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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp
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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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 && SS.getScopeRep()) {
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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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 // typeid is not supported in OpenCL.
533 if (getLangOpts().OpenCLCPlusPlus) {
1
Assuming field 'OpenCLCPlusPlus' is 0
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 field 'CXXTypeInfoDecl' is non-null
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 field 'RTTI' is not equal to 0
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 false
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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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-10~svn373517/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
1137bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1138 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1139 const bool ByCopy) {
1140 // We don't need to capture this in an unevaluated context.
1141 if (isUnevaluatedContext() && !Explicit)
1142 return true;
1143
1144 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1144, __PRETTY_FUNCTION__))
;
1145
1146 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1147 ? *FunctionScopeIndexToStopAt
1148 : FunctionScopes.size() - 1;
1149
1150 // Check that we can capture the *enclosing object* (referred to by '*this')
1151 // by the capturing-entity/closure (lambda/block/etc) at
1152 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1153
1154 // Note: The *enclosing object* can only be captured by-value by a
1155 // closure that is a lambda, using the explicit notation:
1156 // [*this] { ... }.
1157 // Every other capture of the *enclosing object* results in its by-reference
1158 // capture.
1159
1160 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1161 // stack), we can capture the *enclosing object* only if:
1162 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1163 // - or, 'L' has an implicit capture.
1164 // AND
1165 // -- there is no enclosing closure
1166 // -- or, there is some enclosing closure 'E' that has already captured the
1167 // *enclosing object*, and every intervening closure (if any) between 'E'
1168 // and 'L' can implicitly capture the *enclosing object*.
1169 // -- or, every enclosing closure can implicitly capture the
1170 // *enclosing object*
1171
1172
1173 unsigned NumCapturingClosures = 0;
1174 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1175 if (CapturingScopeInfo *CSI =
1176 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1177 if (CSI->CXXThisCaptureIndex != 0) {
1178 // 'this' is already being captured; there isn't anything more to do.
1179 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1180 break;
1181 }
1182 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1183 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1184 // This context can't implicitly capture 'this'; fail out.
1185 if (BuildAndDiagnose)
1186 Diag(Loc, diag::err_this_capture)
1187 << (Explicit && idx == MaxFunctionScopesIndex);
1188 return true;
1189 }
1190 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1191 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1192 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1193 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1194 (Explicit && idx == MaxFunctionScopesIndex)) {
1195 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1196 // iteration through can be an explicit capture, all enclosing closures,
1197 // if any, must perform implicit captures.
1198
1199 // This closure can capture 'this'; continue looking upwards.
1200 NumCapturingClosures++;
1201 continue;
1202 }
1203 // This context can't implicitly capture 'this'; fail out.
1204 if (BuildAndDiagnose)
1205 Diag(Loc, diag::err_this_capture)
1206 << (Explicit && idx == MaxFunctionScopesIndex);
1207 return true;
1208 }
1209 break;
1210 }
1211 if (!BuildAndDiagnose) return false;
1212
1213 // If we got here, then the closure at MaxFunctionScopesIndex on the
1214 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1215 // (including implicit by-reference captures in any enclosing closures).
1216
1217 // In the loop below, respect the ByCopy flag only for the closure requesting
1218 // the capture (i.e. first iteration through the loop below). Ignore it for
1219 // all enclosing closure's up to NumCapturingClosures (since they must be
1220 // implicitly capturing the *enclosing object* by reference (see loop
1221 // above)).
1222 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1225, __PRETTY_FUNCTION__))
1223 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1225, __PRETTY_FUNCTION__))
1224 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1225, __PRETTY_FUNCTION__))
1225 "*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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1225, __PRETTY_FUNCTION__))
;
1226 QualType ThisTy = getCurrentThisType();
1227 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1228 --idx, --NumCapturingClosures) {
1229 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1230
1231 // The type of the corresponding data member (not a 'this' pointer if 'by
1232 // copy').
1233 QualType CaptureType = ThisTy;
1234 if (ByCopy) {
1235 // If we are capturing the object referred to by '*this' by copy, ignore
1236 // any cv qualifiers inherited from the type of the member function for
1237 // the type of the closure-type's corresponding data member and any use
1238 // of 'this'.
1239 CaptureType = ThisTy->getPointeeType();
1240 CaptureType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1241 }
1242
1243 bool isNested = NumCapturingClosures > 1;
1244 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1245 }
1246 return false;
1247}
1248
1249ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1250 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1251 /// is a non-lvalue expression whose value is the address of the object for
1252 /// which the function is called.
1253
1254 QualType ThisTy = getCurrentThisType();
1255 if (ThisTy.isNull())
1256 return Diag(Loc, diag::err_invalid_this_use);
1257 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1258}
1259
1260Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1261 bool IsImplicit) {
1262 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1263 MarkThisReferenced(This);
1264 return This;
1265}
1266
1267void Sema::MarkThisReferenced(CXXThisExpr *This) {
1268 CheckCXXThisCapture(This->getExprLoc());
1269}
1270
1271bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1272 // If we're outside the body of a member function, then we'll have a specified
1273 // type for 'this'.
1274 if (CXXThisTypeOverride.isNull())
1275 return false;
1276
1277 // Determine whether we're looking into a class that's currently being
1278 // defined.
1279 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1280 return Class && Class->isBeingDefined();
1281}
1282
1283/// Parse construction of a specified type.
1284/// Can be interpreted either as function-style casting ("int(x)")
1285/// or class type construction ("ClassType(x,y,z)")
1286/// or creation of a value-initialized type ("int()").
1287ExprResult
1288Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1289 SourceLocation LParenOrBraceLoc,
1290 MultiExprArg exprs,
1291 SourceLocation RParenOrBraceLoc,
1292 bool ListInitialization) {
1293 if (!TypeRep)
1294 return ExprError();
1295
1296 TypeSourceInfo *TInfo;
1297 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1298 if (!TInfo)
1299 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1300
1301 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1302 RParenOrBraceLoc, ListInitialization);
1303 // Avoid creating a non-type-dependent expression that contains typos.
1304 // Non-type-dependent expressions are liable to be discarded without
1305 // checking for embedded typos.
1306 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1307 !Result.get()->isTypeDependent())
1308 Result = CorrectDelayedTyposInExpr(Result.get());
1309 return Result;
1310}
1311
1312ExprResult
1313Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1314 SourceLocation LParenOrBraceLoc,
1315 MultiExprArg Exprs,
1316 SourceLocation RParenOrBraceLoc,
1317 bool ListInitialization) {
1318 QualType Ty = TInfo->getType();
1319 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1320
1321 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1322 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1323 // directly. We work around this by dropping the locations of the braces.
1324 SourceRange Locs = ListInitialization
1325 ? SourceRange()
1326 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1327 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1328 Exprs, Locs.getEnd());
1329 }
1330
1331 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1333, __PRETTY_FUNCTION__))
1332 (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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1333, __PRETTY_FUNCTION__))
1333 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1333, __PRETTY_FUNCTION__))
;
1334 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1335
1336 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1337 InitializationKind Kind =
1338 Exprs.size()
1339 ? ListInitialization
1340 ? InitializationKind::CreateDirectList(
1341 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1342 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1343 RParenOrBraceLoc)
1344 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1345 RParenOrBraceLoc);
1346
1347 // C++1z [expr.type.conv]p1:
1348 // If the type is a placeholder for a deduced class type, [...perform class
1349 // template argument deduction...]
1350 DeducedType *Deduced = Ty->getContainedDeducedType();
1351 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1352 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1353 Kind, Exprs);
1354 if (Ty.isNull())
1355 return ExprError();
1356 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1357 }
1358
1359 // C++ [expr.type.conv]p1:
1360 // If the expression list is a parenthesized single expression, the type
1361 // conversion expression is equivalent (in definedness, and if defined in
1362 // meaning) to the corresponding cast expression.
1363 if (Exprs.size() == 1 && !ListInitialization &&
1364 !isa<InitListExpr>(Exprs[0])) {
1365 Expr *Arg = Exprs[0];
1366 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1367 RParenOrBraceLoc);
1368 }
1369
1370 // For an expression of the form T(), T shall not be an array type.
1371 QualType ElemTy = Ty;
1372 if (Ty->isArrayType()) {
1373 if (!ListInitialization)
1374 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1375 << FullRange);
1376 ElemTy = Context.getBaseElementType(Ty);
1377 }
1378
1379 // There doesn't seem to be an explicit rule against this but sanity demands
1380 // we only construct objects with object types.
1381 if (Ty->isFunctionType())
1382 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1383 << Ty << FullRange);
1384
1385 // C++17 [expr.type.conv]p2:
1386 // If the type is cv void and the initializer is (), the expression is a
1387 // prvalue of the specified type that performs no initialization.
1388 if (!Ty->isVoidType() &&
1389 RequireCompleteType(TyBeginLoc, ElemTy,
1390 diag::err_invalid_incomplete_type_use, FullRange))
1391 return ExprError();
1392
1393 // Otherwise, the expression is a prvalue of the specified type whose
1394 // result object is direct-initialized (11.6) with the initializer.
1395 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1396 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1397
1398 if (Result.isInvalid())
1399 return Result;
1400
1401 Expr *Inner = Result.get();
1402 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1403 Inner = BTE->getSubExpr();
1404 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1405 !isa<CXXScalarValueInitExpr>(Inner)) {
1406 // If we created a CXXTemporaryObjectExpr, that node also represents the
1407 // functional cast. Otherwise, create an explicit cast to represent
1408 // the syntactic form of a functional-style cast that was used here.
1409 //
1410 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1411 // would give a more consistent AST representation than using a
1412 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1413 // is sometimes handled by initialization and sometimes not.
1414 QualType ResultType = Result.get()->getType();
1415 SourceRange Locs = ListInitialization
1416 ? SourceRange()
1417 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1418 Result = CXXFunctionalCastExpr::Create(
1419 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1420 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1421 }
1422
1423 return Result;
1424}
1425
1426bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1427 // [CUDA] Ignore this function, if we can't call it.
1428 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1429 if (getLangOpts().CUDA &&
1430 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1431 return false;
1432
1433 SmallVector<const FunctionDecl*, 4> PreventedBy;
1434 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1435
1436 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1437 return Result;
1438
1439 // In case of CUDA, return true if none of the 1-argument deallocator
1440 // functions are actually callable.
1441 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1442 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1443, __PRETTY_FUNCTION__))
1443 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1443, __PRETTY_FUNCTION__))
;
1444 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1445 });
1446}
1447
1448/// Determine whether the given function is a non-placement
1449/// deallocation function.
1450static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1451 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1452 return S.isUsualDeallocationFunction(Method);
1453
1454 if (FD->getOverloadedOperator() != OO_Delete &&
1455 FD->getOverloadedOperator() != OO_Array_Delete)
1456 return false;
1457
1458 unsigned UsualParams = 1;
1459
1460 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1461 S.Context.hasSameUnqualifiedType(
1462 FD->getParamDecl(UsualParams)->getType(),
1463 S.Context.getSizeType()))
1464 ++UsualParams;
1465
1466 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1467 S.Context.hasSameUnqualifiedType(
1468 FD->getParamDecl(UsualParams)->getType(),
1469 S.Context.getTypeDeclType(S.getStdAlignValT())))
1470 ++UsualParams;
1471
1472 return UsualParams == FD->getNumParams();
1473}
1474
1475namespace {
1476 struct UsualDeallocFnInfo {
1477 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1478 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1479 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1480 Destroying(false), HasSizeT(false), HasAlignValT(false),
1481 CUDAPref(Sema::CFP_Native) {
1482 // A function template declaration is never a usual deallocation function.
1483 if (!FD)
1484 return;
1485 unsigned NumBaseParams = 1;
1486 if (FD->isDestroyingOperatorDelete()) {
1487 Destroying = true;
1488 ++NumBaseParams;
1489 }
1490
1491 if (NumBaseParams < FD->getNumParams() &&
1492 S.Context.hasSameUnqualifiedType(
1493 FD->getParamDecl(NumBaseParams)->getType(),
1494 S.Context.getSizeType())) {
1495 ++NumBaseParams;
1496 HasSizeT = true;
1497 }
1498
1499 if (NumBaseParams < FD->getNumParams() &&
1500 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1501 ++NumBaseParams;
1502 HasAlignValT = true;
1503 }
1504
1505 // In CUDA, determine how much we'd like / dislike to call this.
1506 if (S.getLangOpts().CUDA)
1507 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1508 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1509 }
1510
1511 explicit operator bool() const { return FD; }
1512
1513 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1514 bool WantAlign) const {
1515 // C++ P0722:
1516 // A destroying operator delete is preferred over a non-destroying
1517 // operator delete.
1518 if (Destroying != Other.Destroying)
1519 return Destroying;
1520
1521 // C++17 [expr.delete]p10:
1522 // If the type has new-extended alignment, a function with a parameter
1523 // of type std::align_val_t is preferred; otherwise a function without
1524 // such a parameter is preferred
1525 if (HasAlignValT != Other.HasAlignValT)
1526 return HasAlignValT == WantAlign;
1527
1528 if (HasSizeT != Other.HasSizeT)
1529 return HasSizeT == WantSize;
1530
1531 // Use CUDA call preference as a tiebreaker.
1532 return CUDAPref > Other.CUDAPref;
1533 }
1534
1535 DeclAccessPair Found;
1536 FunctionDecl *FD;
1537 bool Destroying, HasSizeT, HasAlignValT;
1538 Sema::CUDAFunctionPreference CUDAPref;
1539 };
1540}
1541
1542/// Determine whether a type has new-extended alignment. This may be called when
1543/// the type is incomplete (for a delete-expression with an incomplete pointee
1544/// type), in which case it will conservatively return false if the alignment is
1545/// not known.
1546static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1547 return S.getLangOpts().AlignedAllocation &&
1548 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1549 S.getASTContext().getTargetInfo().getNewAlign();
1550}
1551
1552/// Select the correct "usual" deallocation function to use from a selection of
1553/// deallocation functions (either global or class-scope).
1554static UsualDeallocFnInfo resolveDeallocationOverload(
1555 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1556 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1557 UsualDeallocFnInfo Best;
1558
1559 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1560 UsualDeallocFnInfo Info(S, I.getPair());
1561 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1562 Info.CUDAPref == Sema::CFP_Never)
1563 continue;
1564
1565 if (!Best) {
1566 Best = Info;
1567 if (BestFns)
1568 BestFns->push_back(Info);
1569 continue;
1570 }
1571
1572 if (Best.isBetterThan(Info, WantSize, WantAlign))
1573 continue;
1574
1575 // If more than one preferred function is found, all non-preferred
1576 // functions are eliminated from further consideration.
1577 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1578 BestFns->clear();
1579
1580 Best = Info;
1581 if (BestFns)
1582 BestFns->push_back(Info);
1583 }
1584
1585 return Best;
1586}
1587
1588/// Determine whether a given type is a class for which 'delete[]' would call
1589/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1590/// we need to store the array size (even if the type is
1591/// trivially-destructible).
1592static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1593 QualType allocType) {
1594 const RecordType *record =
1595 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1596 if (!record) return false;
1597
1598 // Try to find an operator delete[] in class scope.
1599
1600 DeclarationName deleteName =
1601 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1602 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1603 S.LookupQualifiedName(ops, record->getDecl());
1604
1605 // We're just doing this for information.
1606 ops.suppressDiagnostics();
1607
1608 // Very likely: there's no operator delete[].
1609 if (ops.empty()) return false;
1610
1611 // If it's ambiguous, it should be illegal to call operator delete[]
1612 // on this thing, so it doesn't matter if we allocate extra space or not.
1613 if (ops.isAmbiguous()) return false;
1614
1615 // C++17 [expr.delete]p10:
1616 // If the deallocation functions have class scope, the one without a
1617 // parameter of type std::size_t is selected.
1618 auto Best = resolveDeallocationOverload(
1619 S, ops, /*WantSize*/false,
1620 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1621 return Best && Best.HasSizeT;
1622}
1623
1624/// Parsed a C++ 'new' expression (C++ 5.3.4).
1625///
1626/// E.g.:
1627/// @code new (memory) int[size][4] @endcode
1628/// or
1629/// @code ::new Foo(23, "hello") @endcode
1630///
1631/// \param StartLoc The first location of the expression.
1632/// \param UseGlobal True if 'new' was prefixed with '::'.
1633/// \param PlacementLParen Opening paren of the placement arguments.
1634/// \param PlacementArgs Placement new arguments.
1635/// \param PlacementRParen Closing paren of the placement arguments.
1636/// \param TypeIdParens If the type is in parens, the source range.
1637/// \param D The type to be allocated, as well as array dimensions.
1638/// \param Initializer The initializing expression or initializer-list, or null
1639/// if there is none.
1640ExprResult
1641Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1642 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1643 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1644 Declarator &D, Expr *Initializer) {
1645 Optional<Expr *> ArraySize;
1646 // If the specified type is an array, unwrap it and save the expression.
1647 if (D.getNumTypeObjects() > 0 &&
1648 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1649 DeclaratorChunk &Chunk = D.getTypeObject(0);
1650 if (D.getDeclSpec().hasAutoTypeSpec())
1651 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1652 << D.getSourceRange());
1653 if (Chunk.Arr.hasStatic)
1654 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1655 << D.getSourceRange());
1656 if (!Chunk.Arr.NumElts && !Initializer)
1657 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1658 << D.getSourceRange());
1659
1660 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1661 D.DropFirstTypeObject();
1662 }
1663
1664 // Every dimension shall be of constant size.
1665 if (ArraySize) {
1666 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1667 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1668 break;
1669
1670 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1671 if (Expr *NumElts = (Expr *)Array.NumElts) {
1672 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1673 if (getLangOpts().CPlusPlus14) {
1674 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1675 // shall be a converted constant expression (5.19) of type std::size_t
1676 // and shall evaluate to a strictly positive value.
1677 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1678 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1678, __PRETTY_FUNCTION__))
;
1679 llvm::APSInt Value(IntWidth);
1680 Array.NumElts
1681 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1682 CCEK_NewExpr)
1683 .get();
1684 } else {
1685 Array.NumElts
1686 = VerifyIntegerConstantExpression(NumElts, nullptr,
1687 diag::err_new_array_nonconst)
1688 .get();
1689 }
1690 if (!Array.NumElts)
1691 return ExprError();
1692 }
1693 }
1694 }
1695 }
1696
1697 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1698 QualType AllocType = TInfo->getType();
1699 if (D.isInvalidType())
1700 return ExprError();
1701
1702 SourceRange DirectInitRange;
1703 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1704 DirectInitRange = List->getSourceRange();
1705
1706 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1707 PlacementLParen, PlacementArgs, PlacementRParen,
1708 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1709 Initializer);
1710}
1711
1712static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1713 Expr *Init) {
1714 if (!Init)
1715 return true;
1716 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1717 return PLE->getNumExprs() == 0;
1718 if (isa<ImplicitValueInitExpr>(Init))
1719 return true;
1720 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1721 return !CCE->isListInitialization() &&
1722 CCE->getConstructor()->isDefaultConstructor();
1723 else if (Style == CXXNewExpr::ListInit) {
1724 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1725, __PRETTY_FUNCTION__))
1725 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1725, __PRETTY_FUNCTION__))
;
1726 return true;
1727 }
1728 return false;
1729}
1730
1731bool
1732Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1733 if (!getLangOpts().AlignedAllocationUnavailable)
1734 return false;
1735 if (FD.isDefined())
1736 return false;
1737 bool IsAligned = false;
1738 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1739 return true;
1740 return false;
1741}
1742
1743// Emit a diagnostic if an aligned allocation/deallocation function that is not
1744// implemented in the standard library is selected.
1745void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1746 SourceLocation Loc) {
1747 if (isUnavailableAlignedAllocationFunction(FD)) {
1748 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1749 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1750 getASTContext().getTargetInfo().getPlatformName());
1751
1752 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1753 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1754 Diag(Loc, diag::err_aligned_allocation_unavailable)
1755 << IsDelete << FD.getType().getAsString() << OSName
1756 << alignedAllocMinVersion(T.getOS()).getAsString();
1757 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1758 }
1759}
1760
1761ExprResult
1762Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1763 SourceLocation PlacementLParen,
1764 MultiExprArg PlacementArgs,
1765 SourceLocation PlacementRParen,
1766 SourceRange TypeIdParens,
1767 QualType AllocType,
1768 TypeSourceInfo *AllocTypeInfo,
1769 Optional<Expr *> ArraySize,
1770 SourceRange DirectInitRange,
1771 Expr *Initializer) {
1772 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1773 SourceLocation StartLoc = Range.getBegin();
1774
1775 CXXNewExpr::InitializationStyle initStyle;
1776 if (DirectInitRange.isValid()) {
1777 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1777, __PRETTY_FUNCTION__))
;
1778 initStyle = CXXNewExpr::CallInit;
1779 } else if (Initializer && isa<InitListExpr>(Initializer))
1780 initStyle = CXXNewExpr::ListInit;
1781 else {
1782 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1784, __PRETTY_FUNCTION__))
1783 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1784, __PRETTY_FUNCTION__))
1784 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1784, __PRETTY_FUNCTION__))
;
1785 initStyle = CXXNewExpr::NoInit;
1786 }
1787
1788 Expr **Inits = &Initializer;
1789 unsigned NumInits = Initializer ? 1 : 0;
1790 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1791 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1791, __PRETTY_FUNCTION__))
;
1792 Inits = List->getExprs();
1793 NumInits = List->getNumExprs();
1794 }
1795
1796 // C++11 [expr.new]p15:
1797 // A new-expression that creates an object of type T initializes that
1798 // object as follows:
1799 InitializationKind Kind
1800 // - If the new-initializer is omitted, the object is default-
1801 // initialized (8.5); if no initialization is performed,
1802 // the object has indeterminate value
1803 = initStyle == CXXNewExpr::NoInit
1804 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1805 // - Otherwise, the new-initializer is interpreted according to
1806 // the
1807 // initialization rules of 8.5 for direct-initialization.
1808 : initStyle == CXXNewExpr::ListInit
1809 ? InitializationKind::CreateDirectList(
1810 TypeRange.getBegin(), Initializer->getBeginLoc(),
1811 Initializer->getEndLoc())
1812 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1813 DirectInitRange.getBegin(),
1814 DirectInitRange.getEnd());
1815
1816 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1817 auto *Deduced = AllocType->getContainedDeducedType();
1818 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1819 if (ArraySize)
1820 return ExprError(
1821 Diag(ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
1822 diag::err_deduced_class_template_compound_type)
1823 << /*array*/ 2
1824 << (ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
1825
1826 InitializedEntity Entity
1827 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1828 AllocType = DeduceTemplateSpecializationFromInitializer(
1829 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1830 if (AllocType.isNull())
1831 return ExprError();
1832 } else if (Deduced) {
1833 bool Braced = (initStyle == CXXNewExpr::ListInit);
1834 if (NumInits == 1) {
1835 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1836 Inits = p->getInits();
1837 NumInits = p->getNumInits();
1838 Braced = true;
1839 }
1840 }
1841
1842 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1843 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1844 << AllocType << TypeRange);
1845 if (NumInits > 1) {
1846 Expr *FirstBad = Inits[1];
1847 return ExprError(Diag(FirstBad->getBeginLoc(),
1848 diag::err_auto_new_ctor_multiple_expressions)
1849 << AllocType << TypeRange);
1850 }
1851 if (Braced && !getLangOpts().CPlusPlus17)
1852 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1853 << AllocType << TypeRange;
1854 Expr *Deduce = Inits[0];
1855 QualType DeducedType;
1856 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1857 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1858 << AllocType << Deduce->getType()
1859 << TypeRange << Deduce->getSourceRange());
1860 if (DeducedType.isNull())
1861 return ExprError();
1862 AllocType = DeducedType;
1863 }
1864
1865 // Per C++0x [expr.new]p5, the type being constructed may be a
1866 // typedef of an array type.
1867 if (!ArraySize) {
1868 if (const ConstantArrayType *Array
1869 = Context.getAsConstantArrayType(AllocType)) {
1870 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1871 Context.getSizeType(),
1872 TypeRange.getEnd());
1873 AllocType = Array->getElementType();
1874 }
1875 }
1876
1877 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1878 return ExprError();
1879
1880 // In ARC, infer 'retaining' for the allocated
1881 if (getLangOpts().ObjCAutoRefCount &&
1882 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1883 AllocType->isObjCLifetimeType()) {
1884 AllocType = Context.getLifetimeQualifiedType(AllocType,
1885 AllocType->getObjCARCImplicitLifetime());
1886 }
1887
1888 QualType ResultType = Context.getPointerType(AllocType);
1889
1890 if (ArraySize && *ArraySize &&
1891 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
1892 ExprResult result = CheckPlaceholderExpr(*ArraySize);
1893 if (result.isInvalid()) return ExprError();
1894 ArraySize = result.get();
1895 }
1896 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1897 // integral or enumeration type with a non-negative value."
1898 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1899 // enumeration type, or a class type for which a single non-explicit
1900 // conversion function to integral or unscoped enumeration type exists.
1901 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1902 // std::size_t.
1903 llvm::Optional<uint64_t> KnownArraySize;
1904 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
1905 ExprResult ConvertedSize;
1906 if (getLangOpts().CPlusPlus14) {
1907 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1907, __PRETTY_FUNCTION__))
;
1908
1909 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
1910 AA_Converting);
1911
1912 if (!ConvertedSize.isInvalid() &&
1913 (*ArraySize)->getType()->getAs<RecordType>())
1914 // Diagnose the compatibility of this conversion.
1915 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1916 << (*ArraySize)->getType() << 0 << "'size_t'";
1917 } else {
1918 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1919 protected:
1920 Expr *ArraySize;
1921
1922 public:
1923 SizeConvertDiagnoser(Expr *ArraySize)
1924 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1925 ArraySize(ArraySize) {}
1926
1927 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1928 QualType T) override {
1929 return S.Diag(Loc, diag::err_array_size_not_integral)
1930 << S.getLangOpts().CPlusPlus11 << T;
1931 }
1932
1933 SemaDiagnosticBuilder diagnoseIncomplete(
1934 Sema &S, SourceLocation Loc, QualType T) override {
1935 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1936 << T << ArraySize->getSourceRange();
1937 }
1938
1939 SemaDiagnosticBuilder diagnoseExplicitConv(
1940 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1941 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1942 }
1943
1944 SemaDiagnosticBuilder noteExplicitConv(
1945 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1946 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1947 << ConvTy->isEnumeralType() << ConvTy;
1948 }
1949
1950 SemaDiagnosticBuilder diagnoseAmbiguous(
1951 Sema &S, SourceLocation Loc, QualType T) override {
1952 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1953 }
1954
1955 SemaDiagnosticBuilder noteAmbiguous(
1956 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1957 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1958 << ConvTy->isEnumeralType() << ConvTy;
1959 }
1960
1961 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1962 QualType T,
1963 QualType ConvTy) override {
1964 return S.Diag(Loc,
1965 S.getLangOpts().CPlusPlus11
1966 ? diag::warn_cxx98_compat_array_size_conversion
1967 : diag::ext_array_size_conversion)
1968 << T << ConvTy->isEnumeralType() << ConvTy;
1969 }
1970 } SizeDiagnoser(*ArraySize);
1971
1972 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
1973 SizeDiagnoser);
1974 }
1975 if (ConvertedSize.isInvalid())
1976 return ExprError();
1977
1978 ArraySize = ConvertedSize.get();
1979 QualType SizeType = (*ArraySize)->getType();
1980
1981 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1982 return ExprError();
1983
1984 // C++98 [expr.new]p7:
1985 // The expression in a direct-new-declarator shall have integral type
1986 // with a non-negative value.
1987 //
1988 // Let's see if this is a constant < 0. If so, we reject it out of hand,
1989 // per CWG1464. Otherwise, if it's not a constant, we must have an
1990 // unparenthesized array type.
1991 if (!(*ArraySize)->isValueDependent()) {
1992 llvm::APSInt Value;
1993 // We've already performed any required implicit conversion to integer or
1994 // unscoped enumeration type.
1995 // FIXME: Per CWG1464, we are required to check the value prior to
1996 // converting to size_t. This will never find a negative array size in
1997 // C++14 onwards, because Value is always unsigned here!
1998 if ((*ArraySize)->isIntegerConstantExpr(Value, Context)) {
1999 if (Value.isSigned() && Value.isNegative()) {
2000 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2001 diag::err_typecheck_negative_array_size)
2002 << (*ArraySize)->getSourceRange());
2003 }
2004
2005 if (!AllocType->isDependentType()) {
2006 unsigned ActiveSizeBits =
2007 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
2008 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2009 return ExprError(
2010 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2011 << Value.toString(10) << (*ArraySize)->getSourceRange());
2012 }
2013
2014 KnownArraySize = Value.getZExtValue();
2015 } else if (TypeIdParens.isValid()) {
2016 // Can't have dynamic array size when the type-id is in parentheses.
2017 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2018 << (*ArraySize)->getSourceRange()
2019 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2020 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2021
2022 TypeIdParens = SourceRange();
2023 }
2024 }
2025
2026 // Note that we do *not* convert the argument in any way. It can
2027 // be signed, larger than size_t, whatever.
2028 }
2029
2030 FunctionDecl *OperatorNew = nullptr;
2031 FunctionDecl *OperatorDelete = nullptr;
2032 unsigned Alignment =
2033 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2034 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2035 bool PassAlignment = getLangOpts().AlignedAllocation &&
2036 Alignment > NewAlignment;
2037
2038 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
2039 if (!AllocType->isDependentType() &&
2040 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2041 FindAllocationFunctions(
2042 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2043 AllocType, ArraySize.hasValue(), PassAlignment, PlacementArgs,
2044 OperatorNew, OperatorDelete))
2045 return ExprError();
2046
2047 // If this is an array allocation, compute whether the usual array
2048 // deallocation function for the type has a size_t parameter.
2049 bool UsualArrayDeleteWantsSize = false;
2050 if (ArraySize && !AllocType->isDependentType())
2051 UsualArrayDeleteWantsSize =
2052 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2053
2054 SmallVector<Expr *, 8> AllPlaceArgs;
2055 if (OperatorNew) {
2056 const FunctionProtoType *Proto =
2057 OperatorNew->getType()->getAs<FunctionProtoType>();
2058 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2059 : VariadicDoesNotApply;
2060
2061 // We've already converted the placement args, just fill in any default
2062 // arguments. Skip the first parameter because we don't have a corresponding
2063 // argument. Skip the second parameter too if we're passing in the
2064 // alignment; we've already filled it in.
2065 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2066 PassAlignment ? 2 : 1, PlacementArgs,
2067 AllPlaceArgs, CallType))
2068 return ExprError();
2069
2070 if (!AllPlaceArgs.empty())
2071 PlacementArgs = AllPlaceArgs;
2072
2073 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2074 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2075
2076 // FIXME: Missing call to CheckFunctionCall or equivalent
2077
2078 // Warn if the type is over-aligned and is being allocated by (unaligned)
2079 // global operator new.
2080 if (PlacementArgs.empty() && !PassAlignment &&
2081 (OperatorNew->isImplicit() ||
2082 (OperatorNew->getBeginLoc().isValid() &&
2083 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2084 if (Alignment > NewAlignment)
2085 Diag(StartLoc, diag::warn_overaligned_type)
2086 << AllocType
2087 << unsigned(Alignment / Context.getCharWidth())
2088 << unsigned(NewAlignment / Context.getCharWidth());
2089 }
2090 }
2091
2092 // Array 'new' can't have any initializers except empty parentheses.
2093 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2094 // dialect distinction.
2095 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2096 SourceRange InitRange(Inits[0]->getBeginLoc(),
2097 Inits[NumInits - 1]->getEndLoc());
2098 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2099 return ExprError();
2100 }
2101
2102 // If we can perform the initialization, and we've not already done so,
2103 // do it now.
2104 if (!AllocType->isDependentType() &&
2105 !Expr::hasAnyTypeDependentArguments(
2106 llvm::makeArrayRef(Inits, NumInits))) {
2107 // The type we initialize is the complete type, including the array bound.
2108 QualType InitType;
2109 if (KnownArraySize)
2110 InitType = Context.getConstantArrayType(
2111 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2112 *KnownArraySize),
2113 ArrayType::Normal, 0);
2114 else if (ArraySize)
2115 InitType =
2116 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2117 else
2118 InitType = AllocType;
2119
2120 InitializedEntity Entity
2121 = InitializedEntity::InitializeNew(StartLoc, InitType);
2122 InitializationSequence InitSeq(*this, Entity, Kind,
2123 MultiExprArg(Inits, NumInits));
2124 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2125 MultiExprArg(Inits, NumInits));
2126 if (FullInit.isInvalid())
2127 return ExprError();
2128
2129 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2130 // we don't want the initialized object to be destructed.
2131 // FIXME: We should not create these in the first place.
2132 if (CXXBindTemporaryExpr *Binder =
2133 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2134 FullInit = Binder->getSubExpr();
2135
2136 Initializer = FullInit.get();
2137
2138 // FIXME: If we have a KnownArraySize, check that the array bound of the
2139 // initializer is no greater than that constant value.
2140
2141 if (ArraySize && !*ArraySize) {
2142 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2143 if (CAT) {
2144 // FIXME: Track that the array size was inferred rather than explicitly
2145 // specified.
2146 ArraySize = IntegerLiteral::Create(
2147 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2148 } else {
2149 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2150 << Initializer->getSourceRange();
2151 }
2152 }
2153 }
2154
2155 // Mark the new and delete operators as referenced.
2156 if (OperatorNew) {
2157 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2158 return ExprError();
2159 MarkFunctionReferenced(StartLoc, OperatorNew);
2160 }
2161 if (OperatorDelete) {
2162 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2163 return ExprError();
2164 MarkFunctionReferenced(StartLoc, OperatorDelete);
2165 }
2166
2167 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2168 PassAlignment, UsualArrayDeleteWantsSize,
2169 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2170 Initializer, ResultType, AllocTypeInfo, Range,
2171 DirectInitRange);
2172}
2173
2174/// Checks that a type is suitable as the allocated type
2175/// in a new-expression.
2176bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2177 SourceRange R) {
2178 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2179 // abstract class type or array thereof.
2180 if (AllocType->isFunctionType())
2181 return Diag(Loc, diag::err_bad_new_type)
2182 << AllocType << 0 << R;
2183 else if (AllocType->isReferenceType())
2184 return Diag(Loc, diag::err_bad_new_type)
2185 << AllocType << 1 << R;
2186 else if (!AllocType->isDependentType() &&
2187 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2188 return true;
2189 else if (RequireNonAbstractType(Loc, AllocType,
2190 diag::err_allocation_of_abstract_type))
2191 return true;
2192 else if (AllocType->isVariablyModifiedType())
2193 return Diag(Loc, diag::err_variably_modified_new_type)
2194 << AllocType;
2195 else if (AllocType.getAddressSpace() != LangAS::Default &&
2196 !getLangOpts().OpenCLCPlusPlus)
2197 return Diag(Loc, diag::err_address_space_qualified_new)
2198 << AllocType.getUnqualifiedType()
2199 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2200 else if (getLangOpts().ObjCAutoRefCount) {
2201 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2202 QualType BaseAllocType = Context.getBaseElementType(AT);
2203 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2204 BaseAllocType->isObjCLifetimeType())
2205 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2206 << BaseAllocType;
2207 }
2208 }
2209
2210 return false;
2211}
2212
2213static bool resolveAllocationOverload(
2214 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2215 bool &PassAlignment, FunctionDecl *&Operator,
2216 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2217 OverloadCandidateSet Candidates(R.getNameLoc(),
2218 OverloadCandidateSet::CSK_Normal);
2219 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2220 Alloc != AllocEnd; ++Alloc) {
2221 // Even member operator new/delete are implicitly treated as
2222 // static, so don't use AddMemberCandidate.
2223 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2224
2225 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2226 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2227 /*ExplicitTemplateArgs=*/nullptr, Args,
2228 Candidates,
2229 /*SuppressUserConversions=*/false);
2230 continue;
2231 }
2232
2233 FunctionDecl *Fn = cast<FunctionDecl>(D);
2234 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2235 /*SuppressUserConversions=*/false);
2236 }
2237
2238 // Do the resolution.
2239 OverloadCandidateSet::iterator Best;
2240 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2241 case OR_Success: {
2242 // Got one!
2243 FunctionDecl *FnDecl = Best->Function;
2244 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2245 Best->FoundDecl) == Sema::AR_inaccessible)
2246 return true;
2247
2248 Operator = FnDecl;
2249 return false;
2250 }
2251
2252 case OR_No_Viable_Function:
2253 // C++17 [expr.new]p13:
2254 // If no matching function is found and the allocated object type has
2255 // new-extended alignment, the alignment argument is removed from the
2256 // argument list, and overload resolution is performed again.
2257 if (PassAlignment) {
2258 PassAlignment = false;
2259 AlignArg = Args[1];
2260 Args.erase(Args.begin() + 1);
2261 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2262 Operator, &Candidates, AlignArg,
2263 Diagnose);
2264 }
2265
2266 // MSVC will fall back on trying to find a matching global operator new
2267 // if operator new[] cannot be found. Also, MSVC will leak by not
2268 // generating a call to operator delete or operator delete[], but we
2269 // will not replicate that bug.
2270 // FIXME: Find out how this interacts with the std::align_val_t fallback
2271 // once MSVC implements it.
2272 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2273 S.Context.getLangOpts().MSVCCompat) {
2274 R.clear();
2275 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2276 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2277 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2278 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2279 Operator, /*Candidates=*/nullptr,
2280 /*AlignArg=*/nullptr, Diagnose);
2281 }
2282
2283 if (Diagnose) {
2284 PartialDiagnosticAt PD(R.getNameLoc(), S.PDiag(diag::err_ovl_no_viable_function_in_call)
2285 << R.getLookupName() << Range);
2286
2287 // If we have aligned candidates, only note the align_val_t candidates
2288 // from AlignedCandidates and the non-align_val_t candidates from
2289 // Candidates.
2290 if (AlignedCandidates) {
2291 auto IsAligned = [](OverloadCandidate &C) {
2292 return C.Function->getNumParams() > 1 &&
2293 C.Function->getParamDecl(1)->getType()->isAlignValT();
2294 };
2295 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2296
2297 // This was an overaligned allocation, so list the aligned candidates
2298 // first.
2299 Args.insert(Args.begin() + 1, AlignArg);
2300 AlignedCandidates->NoteCandidates(PD, S, OCD_AllCandidates, Args, "",
2301 R.getNameLoc(), IsAligned);
2302 Args.erase(Args.begin() + 1);
2303 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2304 IsUnaligned);
2305 } else {
2306 Candidates.NoteCandidates(PD, S, OCD_AllCandidates, Args);
2307 }
2308 }
2309 return true;
2310
2311 case OR_Ambiguous:
2312 if (Diagnose) {
2313 Candidates.NoteCandidates(
2314 PartialDiagnosticAt(R.getNameLoc(),
2315 S.PDiag(diag::err_ovl_ambiguous_call)
2316 << R.getLookupName() << Range),
2317 S, OCD_ViableCandidates, Args);
2318 }
2319 return true;
2320
2321 case OR_Deleted: {
2322 if (Diagnose) {
2323 Candidates.NoteCandidates(
2324 PartialDiagnosticAt(R.getNameLoc(),
2325 S.PDiag(diag::err_ovl_deleted_call)
2326 << R.getLookupName() << Range),
2327 S, OCD_AllCandidates, Args);
2328 }
2329 return true;
2330 }
2331 }
2332 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2332)
;
2333}
2334
2335bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2336 AllocationFunctionScope NewScope,
2337 AllocationFunctionScope DeleteScope,
2338 QualType AllocType, bool IsArray,
2339 bool &PassAlignment, MultiExprArg PlaceArgs,
2340 FunctionDecl *&OperatorNew,
2341 FunctionDecl *&OperatorDelete,
2342 bool Diagnose) {
2343 // --- Choosing an allocation function ---
2344 // C++ 5.3.4p8 - 14 & 18
2345 // 1) If looking in AFS_Global scope for allocation functions, only look in
2346 // the global scope. Else, if AFS_Class, only look in the scope of the
2347 // allocated class. If AFS_Both, look in both.
2348 // 2) If an array size is given, look for operator new[], else look for
2349 // operator new.
2350 // 3) The first argument is always size_t. Append the arguments from the
2351 // placement form.
2352
2353 SmallVector<Expr*, 8> AllocArgs;
2354 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2355
2356 // We don't care about the actual value of these arguments.
2357 // FIXME: Should the Sema create the expression and embed it in the syntax
2358 // tree? Or should the consumer just recalculate the value?
2359 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2360 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2361 Context.getTargetInfo().getPointerWidth(0)),
2362 Context.getSizeType(),
2363 SourceLocation());
2364 AllocArgs.push_back(&Size);
2365
2366 QualType AlignValT = Context.VoidTy;
2367 if (PassAlignment) {
2368 DeclareGlobalNewDelete();
2369 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2370 }
2371 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2372 if (PassAlignment)
2373 AllocArgs.push_back(&Align);
2374
2375 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2376
2377 // C++ [expr.new]p8:
2378 // If the allocated type is a non-array type, the allocation
2379 // function's name is operator new and the deallocation function's
2380 // name is operator delete. If the allocated type is an array
2381 // type, the allocation function's name is operator new[] and the
2382 // deallocation function's name is operator delete[].
2383 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2384 IsArray ? OO_Array_New : OO_New);
2385
2386 QualType AllocElemType = Context.getBaseElementType(AllocType);
2387
2388 // Find the allocation function.
2389 {
2390 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2391
2392 // C++1z [expr.new]p9:
2393 // If the new-expression begins with a unary :: operator, the allocation
2394 // function's name is looked up in the global scope. Otherwise, if the
2395 // allocated type is a class type T or array thereof, the allocation
2396 // function's name is looked up in the scope of T.
2397 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2398 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2399
2400 // We can see ambiguity here if the allocation function is found in
2401 // multiple base classes.
2402 if (R.isAmbiguous())
2403 return true;
2404
2405 // If this lookup fails to find the name, or if the allocated type is not
2406 // a class type, the allocation function's name is looked up in the
2407 // global scope.
2408 if (R.empty()) {
2409 if (NewScope == AFS_Class)
2410 return true;
2411
2412 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2413 }
2414
2415 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2416 if (PlaceArgs.empty()) {
2417 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2418 } else {
2419 Diag(StartLoc, diag::err_openclcxx_placement_new);
2420 }
2421 return true;
2422 }
2423
2424 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2424, __PRETTY_FUNCTION__))
;
2425 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2425, __PRETTY_FUNCTION__))
;
2426
2427 // We do our own custom access checks below.
2428 R.suppressDiagnostics();
2429
2430 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2431 OperatorNew, /*Candidates=*/nullptr,
2432 /*AlignArg=*/nullptr, Diagnose))
2433 return true;
2434 }
2435
2436 // We don't need an operator delete if we're running under -fno-exceptions.
2437 if (!getLangOpts().Exceptions) {
2438 OperatorDelete = nullptr;
2439 return false;
2440 }
2441
2442 // Note, the name of OperatorNew might have been changed from array to
2443 // non-array by resolveAllocationOverload.
2444 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2445 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2446 ? OO_Array_Delete
2447 : OO_Delete);
2448
2449 // C++ [expr.new]p19:
2450 //
2451 // If the new-expression begins with a unary :: operator, the
2452 // deallocation function's name is looked up in the global
2453 // scope. Otherwise, if the allocated type is a class type T or an
2454 // array thereof, the deallocation function's name is looked up in
2455 // the scope of T. If this lookup fails to find the name, or if
2456 // the allocated type is not a class type or array thereof, the
2457 // deallocation function's name is looked up in the global scope.
2458 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2459 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2460 CXXRecordDecl *RD
2461 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2462 LookupQualifiedName(FoundDelete, RD);
2463 }
2464 if (FoundDelete.isAmbiguous())
2465 return true; // FIXME: clean up expressions?
2466
2467 bool FoundGlobalDelete = FoundDelete.empty();
2468 if (FoundDelete.empty()) {
2469 if (DeleteScope == AFS_Class)
2470 return true;
2471
2472 DeclareGlobalNewDelete();
2473 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2474 }
2475
2476 FoundDelete.suppressDiagnostics();
2477
2478 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2479
2480 // Whether we're looking for a placement operator delete is dictated
2481 // by whether we selected a placement operator new, not by whether
2482 // we had explicit placement arguments. This matters for things like
2483 // struct A { void *operator new(size_t, int = 0); ... };
2484 // A *a = new A()
2485 //
2486 // We don't have any definition for what a "placement allocation function"
2487 // is, but we assume it's any allocation function whose
2488 // parameter-declaration-clause is anything other than (size_t).
2489 //
2490 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2491 // This affects whether an exception from the constructor of an overaligned
2492 // type uses the sized or non-sized form of aligned operator delete.
2493 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2494 OperatorNew->isVariadic();
2495
2496 if (isPlacementNew) {
2497 // C++ [expr.new]p20:
2498 // A declaration of a placement deallocation function matches the
2499 // declaration of a placement allocation function if it has the
2500 // same number of parameters and, after parameter transformations
2501 // (8.3.5), all parameter types except the first are
2502 // identical. [...]
2503 //
2504 // To perform this comparison, we compute the function type that
2505 // the deallocation function should have, and use that type both
2506 // for template argument deduction and for comparison purposes.
2507 QualType ExpectedFunctionType;
2508 {
2509 const FunctionProtoType *Proto
2510 = OperatorNew->getType()->getAs<FunctionProtoType>();
2511
2512 SmallVector<QualType, 4> ArgTypes;
2513 ArgTypes.push_back(Context.VoidPtrTy);
2514 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2515 ArgTypes.push_back(Proto->getParamType(I));
2516
2517 FunctionProtoType::ExtProtoInfo EPI;
2518 // FIXME: This is not part of the standard's rule.
2519 EPI.Variadic = Proto->isVariadic();
2520
2521 ExpectedFunctionType
2522 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2523 }
2524
2525 for (LookupResult::iterator D = FoundDelete.begin(),
2526 DEnd = FoundDelete.end();
2527 D != DEnd; ++D) {
2528 FunctionDecl *Fn = nullptr;
2529 if (FunctionTemplateDecl *FnTmpl =
2530 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2531 // Perform template argument deduction to try to match the
2532 // expected function type.
2533 TemplateDeductionInfo Info(StartLoc);
2534 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2535 Info))
2536 continue;
2537 } else
2538 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2539
2540 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2541 ExpectedFunctionType,
2542 /*AdjustExcpetionSpec*/true),
2543 ExpectedFunctionType))
2544 Matches.push_back(std::make_pair(D.getPair(), Fn));
2545 }
2546
2547 if (getLangOpts().CUDA)
2548 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2549 } else {
2550 // C++1y [expr.new]p22:
2551 // For a non-placement allocation function, the normal deallocation
2552 // function lookup is used
2553 //
2554 // Per [expr.delete]p10, this lookup prefers a member operator delete
2555 // without a size_t argument, but prefers a non-member operator delete
2556 // with a size_t where possible (which it always is in this case).
2557 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2558 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2559 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2560 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2561 &BestDeallocFns);
2562 if (Selected)
2563 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2564 else {
2565 // If we failed to select an operator, all remaining functions are viable
2566 // but ambiguous.
2567 for (auto Fn : BestDeallocFns)
2568 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2569 }
2570 }
2571
2572 // C++ [expr.new]p20:
2573 // [...] If the lookup finds a single matching deallocation
2574 // function, that function will be called; otherwise, no
2575 // deallocation function will be called.
2576 if (Matches.size() == 1) {
2577 OperatorDelete = Matches[0].second;
2578
2579 // C++1z [expr.new]p23:
2580 // If the lookup finds a usual deallocation function (3.7.4.2)
2581 // with a parameter of type std::size_t and that function, considered
2582 // as a placement deallocation function, would have been
2583 // selected as a match for the allocation function, the program
2584 // is ill-formed.
2585 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2586 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2587 UsualDeallocFnInfo Info(*this,
2588 DeclAccessPair::make(OperatorDelete, AS_public));
2589 // Core issue, per mail to core reflector, 2016-10-09:
2590 // If this is a member operator delete, and there is a corresponding
2591 // non-sized member operator delete, this isn't /really/ a sized
2592 // deallocation function, it just happens to have a size_t parameter.
2593 bool IsSizedDelete = Info.HasSizeT;
2594 if (IsSizedDelete && !FoundGlobalDelete) {
2595 auto NonSizedDelete =
2596 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2597 /*WantAlign*/Info.HasAlignValT);
2598 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2599 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2600 IsSizedDelete = false;
2601 }
2602
2603 if (IsSizedDelete) {
2604 SourceRange R = PlaceArgs.empty()
2605 ? SourceRange()
2606 : SourceRange(PlaceArgs.front()->getBeginLoc(),
2607 PlaceArgs.back()->getEndLoc());
2608 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2609 if (!OperatorDelete->isImplicit())
2610 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2611 << DeleteName;
2612 }
2613 }
2614
2615 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2616 Matches[0].first);
2617 } else if (!Matches.empty()) {
2618 // We found multiple suitable operators. Per [expr.new]p20, that means we
2619 // call no 'operator delete' function, but we should at least warn the user.
2620 // FIXME: Suppress this warning if the construction cannot throw.
2621 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2622 << DeleteName << AllocElemType;
2623
2624 for (auto &Match : Matches)
2625 Diag(Match.second->getLocation(),
2626 diag::note_member_declared_here) << DeleteName;
2627 }
2628
2629 return false;
2630}
2631
2632/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2633/// delete. These are:
2634/// @code
2635/// // C++03:
2636/// void* operator new(std::size_t) throw(std::bad_alloc);
2637/// void* operator new[](std::size_t) throw(std::bad_alloc);
2638/// void operator delete(void *) throw();
2639/// void operator delete[](void *) throw();
2640/// // C++11:
2641/// void* operator new(std::size_t);
2642/// void* operator new[](std::size_t);
2643/// void operator delete(void *) noexcept;
2644/// void operator delete[](void *) noexcept;
2645/// // C++1y:
2646/// void* operator new(std::size_t);
2647/// void* operator new[](std::size_t);
2648/// void operator delete(void *) noexcept;
2649/// void operator delete[](void *) noexcept;
2650/// void operator delete(void *, std::size_t) noexcept;
2651/// void operator delete[](void *, std::size_t) noexcept;
2652/// @endcode
2653/// Note that the placement and nothrow forms of new are *not* implicitly
2654/// declared. Their use requires including \<new\>.
2655void Sema::DeclareGlobalNewDelete() {
2656 if (GlobalNewDeleteDeclared)
2657 return;
2658
2659 // The implicitly declared new and delete operators
2660 // are not supported in OpenCL.
2661 if (getLangOpts().OpenCLCPlusPlus)
2662 return;
2663
2664 // C++ [basic.std.dynamic]p2:
2665 // [...] The following allocation and deallocation functions (18.4) are
2666 // implicitly declared in global scope in each translation unit of a
2667 // program
2668 //
2669 // C++03:
2670 // void* operator new(std::size_t) throw(std::bad_alloc);
2671 // void* operator new[](std::size_t) throw(std::bad_alloc);
2672 // void operator delete(void*) throw();
2673 // void operator delete[](void*) throw();
2674 // C++11:
2675 // void* operator new(std::size_t);
2676 // void* operator new[](std::size_t);
2677 // void operator delete(void*) noexcept;
2678 // void operator delete[](void*) noexcept;
2679 // C++1y:
2680 // void* operator new(std::size_t);
2681 // void* operator new[](std::size_t);
2682 // void operator delete(void*) noexcept;
2683 // void operator delete[](void*) noexcept;
2684 // void operator delete(void*, std::size_t) noexcept;
2685 // void operator delete[](void*, std::size_t) noexcept;
2686 //
2687 // These implicit declarations introduce only the function names operator
2688 // new, operator new[], operator delete, operator delete[].
2689 //
2690 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2691 // "std" or "bad_alloc" as necessary to form the exception specification.
2692 // However, we do not make these implicit declarations visible to name
2693 // lookup.
2694 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2695 // The "std::bad_alloc" class has not yet been declared, so build it
2696 // implicitly.
2697 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2698 getOrCreateStdNamespace(),
2699 SourceLocation(), SourceLocation(),
2700 &PP.getIdentifierTable().get("bad_alloc"),
2701 nullptr);
2702 getStdBadAlloc()->setImplicit(true);
2703 }
2704 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2705 // The "std::align_val_t" enum class has not yet been declared, so build it
2706 // implicitly.
2707 auto *AlignValT = EnumDecl::Create(
2708 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2709 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2710 AlignValT->setIntegerType(Context.getSizeType());
2711 AlignValT->setPromotionType(Context.getSizeType());
2712 AlignValT->setImplicit(true);
2713 StdAlignValT = AlignValT;
2714 }
2715
2716 GlobalNewDeleteDeclared = true;
2717
2718 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2719 QualType SizeT = Context.getSizeType();
2720
2721 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2722 QualType Return, QualType Param) {
2723 llvm::SmallVector<QualType, 3> Params;
2724 Params.push_back(Param);
2725
2726 // Create up to four variants of the function (sized/aligned).
2727 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2728 (Kind == OO_Delete || Kind == OO_Array_Delete);
2729 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2730
2731 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2732 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2733 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2734 if (Sized)
2735 Params.push_back(SizeT);
2736
2737 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2738 if (Aligned)
2739 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2740
2741 DeclareGlobalAllocationFunction(
2742 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2743
2744 if (Aligned)
2745 Params.pop_back();
2746 }
2747 }
2748 };
2749
2750 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2751 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2752 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2753 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2754}
2755
2756/// DeclareGlobalAllocationFunction - Declares a single implicit global
2757/// allocation function if it doesn't already exist.
2758void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2759 QualType Return,
2760 ArrayRef<QualType> Params) {
2761 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2762
2763 // Check if this function is already declared.
2764 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2765 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2766 Alloc != AllocEnd; ++Alloc) {
2767 // Only look at non-template functions, as it is the predefined,
2768 // non-templated allocation function we are trying to declare here.
2769 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2770 if (Func->getNumParams() == Params.size()) {
2771 llvm::SmallVector<QualType, 3> FuncParams;
2772 for (auto *P : Func->parameters())
2773 FuncParams.push_back(
2774 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2775 if (llvm::makeArrayRef(FuncParams) == Params) {
2776 // Make the function visible to name lookup, even if we found it in
2777 // an unimported module. It either is an implicitly-declared global
2778 // allocation function, or is suppressing that function.
2779 Func->setVisibleDespiteOwningModule();
2780 return;
2781 }
2782 }
2783 }
2784 }
2785
2786 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
2787 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
2788
2789 QualType BadAllocType;
2790 bool HasBadAllocExceptionSpec
2791 = (Name.getCXXOverloadedOperator() == OO_New ||
2792 Name.getCXXOverloadedOperator() == OO_Array_New);
2793 if (HasBadAllocExceptionSpec) {
2794 if (!getLangOpts().CPlusPlus11) {
2795 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2796 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2796, __PRETTY_FUNCTION__))
;
2797 EPI.ExceptionSpec.Type = EST_Dynamic;
2798 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2799 }
2800 } else {
2801 EPI.ExceptionSpec =
2802 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2803 }
2804
2805 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2806 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2807 FunctionDecl *Alloc = FunctionDecl::Create(
2808 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2809 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2810 Alloc->setImplicit();
2811 // Global allocation functions should always be visible.
2812 Alloc->setVisibleDespiteOwningModule();
2813
2814 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2815 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2816 ? VisibilityAttr::Hidden
2817 : VisibilityAttr::Default));
2818
2819 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2820 for (QualType T : Params) {
2821 ParamDecls.push_back(ParmVarDecl::Create(
2822 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2823 /*TInfo=*/nullptr, SC_None, nullptr));
2824 ParamDecls.back()->setImplicit();
2825 }
2826 Alloc->setParams(ParamDecls);
2827 if (ExtraAttr)
2828 Alloc->addAttr(ExtraAttr);
2829 Context.getTranslationUnitDecl()->addDecl(Alloc);
2830 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2831 };
2832
2833 if (!LangOpts.CUDA)
2834 CreateAllocationFunctionDecl(nullptr);
2835 else {
2836 // Host and device get their own declaration so each can be
2837 // defined or re-declared independently.
2838 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2839 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2840 }
2841}
2842
2843FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2844 bool CanProvideSize,
2845 bool Overaligned,
2846 DeclarationName Name) {
2847 DeclareGlobalNewDelete();
2848
2849 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2850 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2851
2852 // FIXME: It's possible for this to result in ambiguity, through a
2853 // user-declared variadic operator delete or the enable_if attribute. We
2854 // should probably not consider those cases to be usual deallocation
2855 // functions. But for now we just make an arbitrary choice in that case.
2856 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2857 Overaligned);
2858 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2858, __PRETTY_FUNCTION__))
;
2859 return Result.FD;
2860}
2861
2862FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2863 CXXRecordDecl *RD) {
2864 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2865
2866 FunctionDecl *OperatorDelete = nullptr;
2867 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2868 return nullptr;
2869 if (OperatorDelete)
2870 return OperatorDelete;
2871
2872 // If there's no class-specific operator delete, look up the global
2873 // non-array delete.
2874 return FindUsualDeallocationFunction(
2875 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2876 Name);
2877}
2878
2879bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2880 DeclarationName Name,
2881 FunctionDecl *&Operator, bool Diagnose) {
2882 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2883 // Try to find operator delete/operator delete[] in class scope.
2884 LookupQualifiedName(Found, RD);
2885
2886 if (Found.isAmbiguous())
2887 return true;
2888
2889 Found.suppressDiagnostics();
2890
2891 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2892
2893 // C++17 [expr.delete]p10:
2894 // If the deallocation functions have class scope, the one without a
2895 // parameter of type std::size_t is selected.
2896 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2897 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2898 /*WantAlign*/ Overaligned, &Matches);
2899
2900 // If we could find an overload, use it.
2901 if (Matches.size() == 1) {
2902 Operator = cast<CXXMethodDecl>(Matches[0].FD);
2903
2904 // FIXME: DiagnoseUseOfDecl?
2905 if (Operator->isDeleted()) {
2906 if (Diagnose) {
2907 Diag(StartLoc, diag::err_deleted_function_use);
2908 NoteDeletedFunction(Operator);
2909 }
2910 return true;
2911 }
2912
2913 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2914 Matches[0].Found, Diagnose) == AR_inaccessible)
2915 return true;
2916
2917 return false;
2918 }
2919
2920 // We found multiple suitable operators; complain about the ambiguity.
2921 // FIXME: The standard doesn't say to do this; it appears that the intent
2922 // is that this should never happen.
2923 if (!Matches.empty()) {
2924 if (Diagnose) {
2925 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2926 << Name << RD;
2927 for (auto &Match : Matches)
2928 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2929 }
2930 return true;
2931 }
2932
2933 // We did find operator delete/operator delete[] declarations, but
2934 // none of them were suitable.
2935 if (!Found.empty()) {
2936 if (Diagnose) {
2937 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2938 << Name << RD;
2939
2940 for (NamedDecl *D : Found)
2941 Diag(D->getUnderlyingDecl()->getLocation(),
2942 diag::note_member_declared_here) << Name;
2943 }
2944 return true;
2945 }
2946
2947 Operator = nullptr;
2948 return false;
2949}
2950
2951namespace {
2952/// Checks whether delete-expression, and new-expression used for
2953/// initializing deletee have the same array form.
2954class MismatchingNewDeleteDetector {
2955public:
2956 enum MismatchResult {
2957 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2958 NoMismatch,
2959 /// Indicates that variable is initialized with mismatching form of \a new.
2960 VarInitMismatches,
2961 /// Indicates that member is initialized with mismatching form of \a new.
2962 MemberInitMismatches,
2963 /// Indicates that 1 or more constructors' definitions could not been
2964 /// analyzed, and they will be checked again at the end of translation unit.
2965 AnalyzeLater
2966 };
2967
2968 /// \param EndOfTU True, if this is the final analysis at the end of
2969 /// translation unit. False, if this is the initial analysis at the point
2970 /// delete-expression was encountered.
2971 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2972 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2973 HasUndefinedConstructors(false) {}
2974
2975 /// Checks whether pointee of a delete-expression is initialized with
2976 /// matching form of new-expression.
2977 ///
2978 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2979 /// point where delete-expression is encountered, then a warning will be
2980 /// issued immediately. If return value is \c AnalyzeLater at the point where
2981 /// delete-expression is seen, then member will be analyzed at the end of
2982 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2983 /// couldn't be analyzed. If at least one constructor initializes the member
2984 /// with matching type of new, the return value is \c NoMismatch.
2985 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2986 /// Analyzes a class member.
2987 /// \param Field Class member to analyze.
2988 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2989 /// for deleting the \p Field.
2990 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2991 FieldDecl *Field;
2992 /// List of mismatching new-expressions used for initialization of the pointee
2993 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2994 /// Indicates whether delete-expression was in array form.
2995 bool IsArrayForm;
2996
2997private:
2998 const bool EndOfTU;
2999 /// Indicates that there is at least one constructor without body.
3000 bool HasUndefinedConstructors;
3001 /// Returns \c CXXNewExpr from given initialization expression.
3002 /// \param E Expression used for initializing pointee in delete-expression.
3003 /// E can be a single-element \c InitListExpr consisting of new-expression.
3004 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3005 /// Returns whether member is initialized with mismatching form of
3006 /// \c new either by the member initializer or in-class initialization.
3007 ///
3008 /// If bodies of all constructors are not visible at the end of translation
3009 /// unit or at least one constructor initializes member with the matching
3010 /// form of \c new, mismatch cannot be proven, and this function will return
3011 /// \c NoMismatch.
3012 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3013 /// Returns whether variable is initialized with mismatching form of
3014 /// \c new.
3015 ///
3016 /// If variable is initialized with matching form of \c new or variable is not
3017 /// initialized with a \c new expression, this function will return true.
3018 /// If variable is initialized with mismatching form of \c new, returns false.
3019 /// \param D Variable to analyze.
3020 bool hasMatchingVarInit(const DeclRefExpr *D);
3021 /// Checks whether the constructor initializes pointee with mismatching
3022 /// form of \c new.
3023 ///
3024 /// Returns true, if member is initialized with matching form of \c new in
3025 /// member initializer list. Returns false, if member is initialized with the
3026 /// matching form of \c new in this constructor's initializer or given
3027 /// constructor isn't defined at the point where delete-expression is seen, or
3028 /// member isn't initialized by the constructor.
3029 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3030 /// Checks whether member is initialized with matching form of
3031 /// \c new in member initializer list.
3032 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3033 /// Checks whether member is initialized with mismatching form of \c new by
3034 /// in-class initializer.
3035 MismatchResult analyzeInClassInitializer();
3036};
3037}
3038
3039MismatchingNewDeleteDetector::MismatchResult
3040MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3041 NewExprs.clear();
3042 assert(DE && "Expected delete-expression")((DE && "Expected delete-expression") ? static_cast<
void> (0) : __assert_fail ("DE && \"Expected delete-expression\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3042, __PRETTY_FUNCTION__))
;
3043 IsArrayForm = DE->isArrayForm();
3044 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3045 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3046 return analyzeMemberExpr(ME);
3047 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3048 if (!hasMatchingVarInit(D))
3049 return VarInitMismatches;
3050 }
3051 return NoMismatch;
3052}
3053
3054const CXXNewExpr *
3055MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3056 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3056, __PRETTY_FUNCTION__))
;
3057 E = E->IgnoreParenImpCasts();
3058 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3059 if (ILE->getNumInits() == 1)
3060 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3061 }
3062
3063 return dyn_cast_or_null<const CXXNewExpr>(E);
3064}
3065
3066bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3067 const CXXCtorInitializer *CI) {
3068 const CXXNewExpr *NE = nullptr;
3069 if (Field == CI->getMember() &&
3070 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3071 if (NE->isArray() == IsArrayForm)
3072 return true;
3073 else
3074 NewExprs.push_back(NE);
3075 }
3076 return false;
3077}
3078
3079bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3080 const CXXConstructorDecl *CD) {
3081 if (CD->isImplicit())
3082 return false;
3083 const FunctionDecl *Definition = CD;
3084 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3085 HasUndefinedConstructors = true;
3086 return EndOfTU;
3087 }
3088 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3089 if (hasMatchingNewInCtorInit(CI))
3090 return true;
3091 }
3092 return false;
3093}
3094
3095MismatchingNewDeleteDetector::MismatchResult
3096MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3097 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3097, __PRETTY_FUNCTION__))
;
3098 const Expr *InitExpr = Field->getInClassInitializer();
3099 if (!InitExpr)
3100 return EndOfTU ? NoMismatch : AnalyzeLater;
3101 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3102 if (NE->isArray() != IsArrayForm) {
3103 NewExprs.push_back(NE);
3104 return MemberInitMismatches;
3105 }
3106 }
3107 return NoMismatch;
3108}
3109
3110MismatchingNewDeleteDetector::MismatchResult
3111MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3112 bool DeleteWasArrayForm) {
3113 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3113, __PRETTY_FUNCTION__))
;
3114 this->Field = Field;
3115 IsArrayForm = DeleteWasArrayForm;
3116 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3117 for (const auto *CD : RD->ctors()) {
3118 if (hasMatchingNewInCtor(CD))
3119 return NoMismatch;
3120 }
3121 if (HasUndefinedConstructors)
3122 return EndOfTU ? NoMismatch : AnalyzeLater;
3123 if (!NewExprs.empty())
3124 return MemberInitMismatches;
3125 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3126 : NoMismatch;
3127}
3128
3129MismatchingNewDeleteDetector::MismatchResult
3130MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3131 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3131, __PRETTY_FUNCTION__))
;
3132 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3133 return analyzeField(F, IsArrayForm);
3134 return NoMismatch;
3135}
3136
3137bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3138 const CXXNewExpr *NE = nullptr;
3139 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3140 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3141 NE->isArray() != IsArrayForm) {
3142 NewExprs.push_back(NE);
3143 }
3144 }
3145 return NewExprs.empty();
3146}
3147
3148static void
3149DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3150 const MismatchingNewDeleteDetector &Detector) {
3151 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3152 FixItHint H;
3153 if (!Detector.IsArrayForm)
3154 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3155 else {
3156 SourceLocation RSquare = Lexer::findLocationAfterToken(
3157 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3158 SemaRef.getLangOpts(), true);
3159 if (RSquare.isValid())
3160 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3161 }
3162 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3163 << Detector.IsArrayForm << H;
3164
3165 for (const auto *NE : Detector.NewExprs)
3166 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3167 << Detector.IsArrayForm;
3168}
3169
3170void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3171 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3172 return;
3173 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3174 switch (Detector.analyzeDeleteExpr(DE)) {
3175 case MismatchingNewDeleteDetector::VarInitMismatches:
3176 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3177 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3178 break;
3179 }
3180 case MismatchingNewDeleteDetector::AnalyzeLater: {
3181 DeleteExprs[Detector.Field].push_back(
3182 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3183 break;
3184 }
3185 case MismatchingNewDeleteDetector::NoMismatch:
3186 break;
3187 }
3188}
3189
3190void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3191 bool DeleteWasArrayForm) {
3192 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3193 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3194 case MismatchingNewDeleteDetector::VarInitMismatches:
3195 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3195)
;
3196 case MismatchingNewDeleteDetector::AnalyzeLater:
3197 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3198)
3198 "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3198)
;
3199 case MismatchingNewDeleteDetector::MemberInitMismatches:
3200 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3201 break;
3202 case MismatchingNewDeleteDetector::NoMismatch:
3203 break;
3204 }
3205}
3206
3207/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3208/// @code ::delete ptr; @endcode
3209/// or
3210/// @code delete [] ptr; @endcode
3211ExprResult
3212Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3213 bool ArrayForm, Expr *ExE) {
3214 // C++ [expr.delete]p1:
3215 // The operand shall have a pointer type, or a class type having a single
3216 // non-explicit conversion function to a pointer type. The result has type
3217 // void.
3218 //
3219 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3220
3221 ExprResult Ex = ExE;
3222 FunctionDecl *OperatorDelete = nullptr;
3223 bool ArrayFormAsWritten = ArrayForm;
3224 bool UsualArrayDeleteWantsSize = false;
3225
3226 if (!Ex.get()->isTypeDependent()) {
3227 // Perform lvalue-to-rvalue cast, if needed.
3228 Ex = DefaultLvalueConversion(Ex.get());
3229 if (Ex.isInvalid())
3230 return ExprError();
3231
3232 QualType Type = Ex.get()->getType();
3233
3234 class DeleteConverter : public ContextualImplicitConverter {
3235 public:
3236 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3237
3238 bool match(QualType ConvType) override {
3239 // FIXME: If we have an operator T* and an operator void*, we must pick
3240 // the operator T*.
3241 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3242 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3243 return true;
3244 return false;
3245 }
3246
3247 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3248 QualType T) override {
3249 return S.Diag(Loc, diag::err_delete_operand) << T;
3250 }
3251
3252 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3253 QualType T) override {
3254 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3255 }
3256
3257 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3258 QualType T,
3259 QualType ConvTy) override {
3260 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3261 }
3262
3263 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3264 QualType ConvTy) override {
3265 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3266 << ConvTy;
3267 }
3268
3269 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3270 QualType T) override {
3271 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3272 }
3273
3274 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3275 QualType ConvTy) override {
3276 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3277 << ConvTy;
3278 }
3279
3280 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3281 QualType T,
3282 QualType ConvTy) override {
3283 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3283)
;
3284 }
3285 } Converter;
3286
3287 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3288 if (Ex.isInvalid())
3289 return ExprError();
3290 Type = Ex.get()->getType();
3291 if (!Converter.match(Type))
3292 // FIXME: PerformContextualImplicitConversion should return ExprError
3293 // itself in this case.
3294 return ExprError();
3295
3296 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3297 QualType PointeeElem = Context.getBaseElementType(Pointee);
3298
3299 if (Pointee.getAddressSpace() != LangAS::Default &&
3300 !getLangOpts().OpenCLCPlusPlus)
3301 return Diag(Ex.get()->getBeginLoc(),
3302 diag::err_address_space_qualified_delete)
3303 << Pointee.getUnqualifiedType()
3304 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3305
3306 CXXRecordDecl *PointeeRD = nullptr;
3307 if (Pointee->isVoidType() && !isSFINAEContext()) {
3308 // The C++ standard bans deleting a pointer to a non-object type, which
3309 // effectively bans deletion of "void*". However, most compilers support
3310 // this, so we treat it as a warning unless we're in a SFINAE context.
3311 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3312 << Type << Ex.get()->getSourceRange();
3313 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3314 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3315 << Type << Ex.get()->getSourceRange());
3316 } else if (!Pointee->isDependentType()) {
3317 // FIXME: This can result in errors if the definition was imported from a
3318 // module but is hidden.
3319 if (!RequireCompleteType(StartLoc, Pointee,
3320 diag::warn_delete_incomplete, Ex.get())) {
3321 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3322 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3323 }
3324 }
3325
3326 if (Pointee->isArrayType() && !ArrayForm) {
3327 Diag(StartLoc, diag::warn_delete_array_type)
3328 << Type << Ex.get()->getSourceRange()
3329 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3330 ArrayForm = true;
3331 }
3332
3333 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3334 ArrayForm ? OO_Array_Delete : OO_Delete);
3335
3336 if (PointeeRD) {
3337 if (!UseGlobal &&
3338 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3339 OperatorDelete))
3340 return ExprError();
3341
3342 // If we're allocating an array of records, check whether the
3343 // usual operator delete[] has a size_t parameter.
3344 if (ArrayForm) {
3345 // If the user specifically asked to use the global allocator,
3346 // we'll need to do the lookup into the class.
3347 if (UseGlobal)
3348 UsualArrayDeleteWantsSize =
3349 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3350
3351 // Otherwise, the usual operator delete[] should be the
3352 // function we just found.
3353 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3354 UsualArrayDeleteWantsSize =
3355 UsualDeallocFnInfo(*this,
3356 DeclAccessPair::make(OperatorDelete, AS_public))
3357 .HasSizeT;
3358 }
3359
3360 if (!PointeeRD->hasIrrelevantDestructor())
3361 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3362 MarkFunctionReferenced(StartLoc,
3363 const_cast<CXXDestructorDecl*>(Dtor));
3364 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3365 return ExprError();
3366 }
3367
3368 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3369 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3370 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3371 SourceLocation());
3372 }
3373
3374 if (!OperatorDelete) {
3375 if (getLangOpts().OpenCLCPlusPlus) {
3376 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3377 return ExprError();
3378 }
3379
3380 bool IsComplete = isCompleteType(StartLoc, Pointee);
3381 bool CanProvideSize =
3382 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3383 Pointee.isDestructedType());
3384 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3385
3386 // Look for a global declaration.
3387 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3388 Overaligned, DeleteName);
3389 }
3390
3391 MarkFunctionReferenced(StartLoc, OperatorDelete);
3392
3393 // Check access and ambiguity of destructor if we're going to call it.
3394 // Note that this is required even for a virtual delete.
3395 bool IsVirtualDelete = false;
3396 if (PointeeRD) {
3397 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3398 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3399 PDiag(diag::err_access_dtor) << PointeeElem);
3400 IsVirtualDelete = Dtor->isVirtual();
3401 }
3402 }
3403
3404 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3405
3406 // Convert the operand to the type of the first parameter of operator
3407 // delete. This is only necessary if we selected a destroying operator
3408 // delete that we are going to call (non-virtually); converting to void*
3409 // is trivial and left to AST consumers to handle.
3410 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3411 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3412 Qualifiers Qs = Pointee.getQualifiers();
3413 if (Qs.hasCVRQualifiers()) {
3414 // Qualifiers are irrelevant to this conversion; we're only looking
3415 // for access and ambiguity.
3416 Qs.removeCVRQualifiers();
3417 QualType Unqual = Context.getPointerType(
3418 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3419 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3420 }
3421 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3422 if (Ex.isInvalid())
3423 return ExprError();
3424 }
3425 }
3426
3427 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3428 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3429 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3430 AnalyzeDeleteExprMismatch(Result);
3431 return Result;
3432}
3433
3434static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3435 bool IsDelete,
3436 FunctionDecl *&Operator) {
3437
3438 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3439 IsDelete ? OO_Delete : OO_New);
3440
3441 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3442 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3443 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3443, __PRETTY_FUNCTION__))
;
3444 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3444, __PRETTY_FUNCTION__))
;
3445
3446 // We do our own custom access checks below.
3447 R.suppressDiagnostics();
3448
3449 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3450 OverloadCandidateSet Candidates(R.getNameLoc(),
3451 OverloadCandidateSet::CSK_Normal);
3452 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3453 FnOvl != FnOvlEnd; ++FnOvl) {
3454 // Even member operator new/delete are implicitly treated as
3455 // static, so don't use AddMemberCandidate.
3456 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3457
3458 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3459 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3460 /*ExplicitTemplateArgs=*/nullptr, Args,
3461 Candidates,
3462 /*SuppressUserConversions=*/false);
3463 continue;
3464 }
3465
3466 FunctionDecl *Fn = cast<FunctionDecl>(D);
3467 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3468 /*SuppressUserConversions=*/false);
3469 }
3470
3471 SourceRange Range = TheCall->getSourceRange();
3472
3473 // Do the resolution.
3474 OverloadCandidateSet::iterator Best;
3475 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3476 case OR_Success: {
3477 // Got one!
3478 FunctionDecl *FnDecl = Best->Function;
3479 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3480, __PRETTY_FUNCTION__))
3480 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3480, __PRETTY_FUNCTION__))
;
3481
3482 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3483 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3484 << (IsDelete ? 1 : 0) << Range;
3485 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3486 << R.getLookupName() << FnDecl->getSourceRange();
3487 return true;
3488 }
3489
3490 Operator = FnDecl;
3491 return false;
3492 }
3493
3494 case OR_No_Viable_Function:
3495 Candidates.NoteCandidates(
3496 PartialDiagnosticAt(R.getNameLoc(),
3497 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3498 << R.getLookupName() << Range),
3499 S, OCD_AllCandidates, Args);
3500 return true;
3501
3502 case OR_Ambiguous:
3503 Candidates.NoteCandidates(
3504 PartialDiagnosticAt(R.getNameLoc(),
3505 S.PDiag(diag::err_ovl_ambiguous_call)
3506 << R.getLookupName() << Range),
3507 S, OCD_ViableCandidates, Args);
3508 return true;
3509
3510 case OR_Deleted: {
3511 Candidates.NoteCandidates(
3512 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3513 << R.getLookupName() << Range),
3514 S, OCD_AllCandidates, Args);
3515 return true;
3516 }
3517 }
3518 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3518)
;
3519}
3520
3521ExprResult
3522Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3523 bool IsDelete) {
3524 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3525 if (!getLangOpts().CPlusPlus) {
3526 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3527 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3528 << "C++";
3529 return ExprError();
3530 }
3531 // CodeGen assumes it can find the global new and delete to call,
3532 // so ensure that they are declared.
3533 DeclareGlobalNewDelete();
3534
3535 FunctionDecl *OperatorNewOrDelete = nullptr;
3536 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3537 OperatorNewOrDelete))
3538 return ExprError();
3539 assert(OperatorNewOrDelete && "should be found")((OperatorNewOrDelete && "should be found") ? static_cast
<void> (0) : __assert_fail ("OperatorNewOrDelete && \"should be found\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3539, __PRETTY_FUNCTION__))
;
3540
3541 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3542 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3543
3544 TheCall->setType(OperatorNewOrDelete->getReturnType());
3545 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3546 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3547 InitializedEntity Entity =
3548 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3549 ExprResult Arg = PerformCopyInitialization(
3550 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3551 if (Arg.isInvalid())
3552 return ExprError();
3553 TheCall->setArg(i, Arg.get());
3554 }
3555 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3556 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3557, __PRETTY_FUNCTION__))
3557 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3557, __PRETTY_FUNCTION__))
;
3558 Callee->setType(OperatorNewOrDelete->getType());
3559
3560 return TheCallResult;
3561}
3562
3563void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3564 bool IsDelete, bool CallCanBeVirtual,
3565 bool WarnOnNonAbstractTypes,
3566 SourceLocation DtorLoc) {
3567 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3568 return;
3569
3570 // C++ [expr.delete]p3:
3571 // In the first alternative (delete object), if the static type of the
3572 // object to be deleted is different from its dynamic type, the static
3573 // type shall be a base class of the dynamic type of the object to be
3574 // deleted and the static type shall have a virtual destructor or the
3575 // behavior is undefined.
3576 //
3577 const CXXRecordDecl *PointeeRD = dtor->getParent();
3578 // Note: a final class cannot be derived from, no issue there
3579 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3580 return;
3581
3582 // If the superclass is in a system header, there's nothing that can be done.
3583 // The `delete` (where we emit the warning) can be in a system header,
3584 // what matters for this warning is where the deleted type is defined.
3585 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3586 return;
3587
3588 QualType ClassType = dtor->getThisType()->getPointeeType();
3589 if (PointeeRD->isAbstract()) {
3590 // If the class is abstract, we warn by default, because we're
3591 // sure the code has undefined behavior.
3592 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3593 << ClassType;
3594 } else if (WarnOnNonAbstractTypes) {
3595 // Otherwise, if this is not an array delete, it's a bit suspect,
3596 // but not necessarily wrong.
3597 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3598 << ClassType;
3599 }
3600 if (!IsDelete) {
3601 std::string TypeStr;
3602 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3603 Diag(DtorLoc, diag::note_delete_non_virtual)
3604 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3605 }
3606}
3607
3608Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3609 SourceLocation StmtLoc,
3610 ConditionKind CK) {
3611 ExprResult E =
3612 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3613 if (E.isInvalid())
3614 return ConditionError();
3615 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3616 CK == ConditionKind::ConstexprIf);
3617}
3618
3619/// Check the use of the given variable as a C++ condition in an if,
3620/// while, do-while, or switch statement.
3621ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3622 SourceLocation StmtLoc,
3623 ConditionKind CK) {
3624 if (ConditionVar->isInvalidDecl())
3625 return ExprError();
3626
3627 QualType T = ConditionVar->getType();
3628
3629 // C++ [stmt.select]p2:
3630 // The declarator shall not specify a function or an array.
3631 if (T->isFunctionType())
3632 return ExprError(Diag(ConditionVar->getLocation(),
3633 diag::err_invalid_use_of_function_type)
3634 << ConditionVar->getSourceRange());
3635 else if (T->isArrayType())
3636 return ExprError(Diag(ConditionVar->getLocation(),
3637 diag::err_invalid_use_of_array_type)
3638 << ConditionVar->getSourceRange());
3639
3640 ExprResult Condition = BuildDeclRefExpr(
3641 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3642 ConditionVar->getLocation());
3643
3644 switch (CK) {
3645 case ConditionKind::Boolean:
3646 return CheckBooleanCondition(StmtLoc, Condition.get());
3647
3648 case ConditionKind::ConstexprIf:
3649 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3650
3651 case ConditionKind::Switch:
3652 return CheckSwitchCondition(StmtLoc, Condition.get());
3653 }
3654
3655 llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3655)
;
3656}
3657
3658/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3659ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3660 // C++ 6.4p4:
3661 // The value of a condition that is an initialized declaration in a statement
3662 // other than a switch statement is the value of the declared variable
3663 // implicitly converted to type bool. If that conversion is ill-formed, the
3664 // program is ill-formed.
3665 // The value of a condition that is an expression is the value of the
3666 // expression, implicitly converted to bool.
3667 //
3668 // FIXME: Return this value to the caller so they don't need to recompute it.
3669 llvm::APSInt Value(/*BitWidth*/1);
3670 return (IsConstexpr && !CondExpr->isValueDependent())
3671 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3672 CCEK_ConstexprIf)
3673 : PerformContextuallyConvertToBool(CondExpr);
3674}
3675
3676/// Helper function to determine whether this is the (deprecated) C++
3677/// conversion from a string literal to a pointer to non-const char or
3678/// non-const wchar_t (for narrow and wide string literals,
3679/// respectively).
3680bool
3681Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3682 // Look inside the implicit cast, if it exists.
3683 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3684 From = Cast->getSubExpr();
3685
3686 // A string literal (2.13.4) that is not a wide string literal can
3687 // be converted to an rvalue of type "pointer to char"; a wide
3688 // string literal can be converted to an rvalue of type "pointer
3689 // to wchar_t" (C++ 4.2p2).
3690 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3691 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3692 if (const BuiltinType *ToPointeeType
3693 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3694 // This conversion is considered only when there is an
3695 // explicit appropriate pointer target type (C++ 4.2p2).
3696 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3697 switch (StrLit->getKind()) {
3698 case StringLiteral::UTF8:
3699 case StringLiteral::UTF16:
3700 case StringLiteral::UTF32:
3701 // We don't allow UTF literals to be implicitly converted
3702 break;
3703 case StringLiteral::Ascii:
3704 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3705 ToPointeeType->getKind() == BuiltinType::Char_S);
3706 case StringLiteral::Wide:
3707 return Context.typesAreCompatible(Context.getWideCharType(),
3708 QualType(ToPointeeType, 0));
3709 }
3710 }
3711 }
3712
3713 return false;
3714}
3715
3716static ExprResult BuildCXXCastArgument(Sema &S,
3717 SourceLocation CastLoc,
3718 QualType Ty,
3719 CastKind Kind,
3720 CXXMethodDecl *Method,
3721 DeclAccessPair FoundDecl,
3722 bool HadMultipleCandidates,
3723 Expr *From) {
3724 switch (Kind) {
3725 default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3725)
;
3726 case CK_ConstructorConversion: {
3727 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3728 SmallVector<Expr*, 8> ConstructorArgs;
3729
3730 if (S.RequireNonAbstractType(CastLoc, Ty,
3731 diag::err_allocation_of_abstract_type))
3732 return ExprError();
3733
3734 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3735 return ExprError();
3736
3737 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3738 InitializedEntity::InitializeTemporary(Ty));
3739 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3740 return ExprError();
3741
3742 ExprResult Result = S.BuildCXXConstructExpr(
3743 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3744 ConstructorArgs, HadMultipleCandidates,
3745 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3746 CXXConstructExpr::CK_Complete, SourceRange());
3747 if (Result.isInvalid())
3748 return ExprError();
3749
3750 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3751 }
3752
3753 case CK_UserDefinedConversion: {
3754 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3754, __PRETTY_FUNCTION__))
;
3755
3756 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3757 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3758 return ExprError();
3759
3760 // Create an implicit call expr that calls it.
3761 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3762 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3763 HadMultipleCandidates);
3764 if (Result.isInvalid())
3765 return ExprError();
3766 // Record usage of conversion in an implicit cast.
3767 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3768 CK_UserDefinedConversion, Result.get(),
3769 nullptr, Result.get()->getValueKind());
3770
3771 return S.MaybeBindToTemporary(Result.get());
3772 }
3773 }
3774}
3775
3776/// PerformImplicitConversion - Perform an implicit conversion of the
3777/// expression From to the type ToType using the pre-computed implicit
3778/// conversion sequence ICS. Returns the converted
3779/// expression. Action is the kind of conversion we're performing,
3780/// used in the error message.
3781ExprResult
3782Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3783 const ImplicitConversionSequence &ICS,
3784 AssignmentAction Action,
3785 CheckedConversionKind CCK) {
3786 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3787 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3788 return From;
3789
3790 switch (ICS.getKind()) {
3791 case ImplicitConversionSequence::StandardConversion: {
3792 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3793 Action, CCK);
3794 if (Res.isInvalid())
3795 return ExprError();
3796 From = Res.get();
3797 break;
3798 }
3799
3800 case ImplicitConversionSequence::UserDefinedConversion: {
3801
3802 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3803 CastKind CastKind;
3804 QualType BeforeToType;
3805 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3805, __PRETTY_FUNCTION__))
;
3806 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3807 CastKind = CK_UserDefinedConversion;
3808
3809 // If the user-defined conversion is specified by a conversion function,
3810 // the initial standard conversion sequence converts the source type to
3811 // the implicit object parameter of the conversion function.
3812 BeforeToType = Context.getTagDeclType(Conv->getParent());
3813 } else {
3814 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3815 CastKind = CK_ConstructorConversion;
3816 // Do no conversion if dealing with ... for the first conversion.
3817 if (!ICS.UserDefined.EllipsisConversion) {
3818 // If the user-defined conversion is specified by a constructor, the
3819 // initial standard conversion sequence converts the source type to
3820 // the type required by the argument of the constructor
3821 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3822 }
3823 }
3824 // Watch out for ellipsis conversion.
3825 if (!ICS.UserDefined.EllipsisConversion) {
3826 ExprResult Res =
3827 PerformImplicitConversion(From, BeforeToType,
3828 ICS.UserDefined.Before, AA_Converting,
3829 CCK);
3830 if (Res.isInvalid())
3831 return ExprError();
3832 From = Res.get();
3833 }
3834
3835 ExprResult CastArg = BuildCXXCastArgument(
3836 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3837 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3838 ICS.UserDefined.HadMultipleCandidates, From);
3839
3840 if (CastArg.isInvalid())
3841 return ExprError();
3842
3843 From = CastArg.get();
3844
3845 // C++ [over.match.oper]p7:
3846 // [...] the second standard conversion sequence of a user-defined
3847 // conversion sequence is not applied.
3848 if (CCK == CCK_ForBuiltinOverloadedOp)
3849 return From;
3850
3851 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3852 AA_Converting, CCK);
3853 }
3854
3855 case ImplicitConversionSequence::AmbiguousConversion:
3856 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3857 PDiag(diag::err_typecheck_ambiguous_condition)
3858 << From->getSourceRange());
3859 return ExprError();
3860
3861 case ImplicitConversionSequence::EllipsisConversion:
3862 llvm_unreachable("Cannot perform an ellipsis conversion")::llvm::llvm_unreachable_internal("Cannot perform an ellipsis conversion"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3862)
;
3863
3864 case ImplicitConversionSequence::BadConversion:
3865 bool Diagnosed =
3866 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3867 From->getType(), From, Action);
3868 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3868, __PRETTY_FUNCTION__))
; (void)Diagnosed;
3869 return ExprError();
3870 }
3871
3872 // Everything went well.
3873 return From;
3874}
3875
3876/// PerformImplicitConversion - Perform an implicit conversion of the
3877/// expression From to the type ToType by following the standard
3878/// conversion sequence SCS. Returns the converted
3879/// expression. Flavor is the context in which we're performing this
3880/// conversion, for use in error messages.
3881ExprResult
3882Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3883 const StandardConversionSequence& SCS,
3884 AssignmentAction Action,
3885 CheckedConversionKind CCK) {
3886 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3887
3888 // Overall FIXME: we are recomputing too many types here and doing far too
3889 // much extra work. What this means is that we need to keep track of more
3890 // information that is computed when we try the implicit conversion initially,
3891 // so that we don't need to recompute anything here.
3892 QualType FromType = From->getType();
3893
3894 if (SCS.CopyConstructor) {
3895 // FIXME: When can ToType be a reference type?
3896 assert(!ToType->isReferenceType())((!ToType->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ToType->isReferenceType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3896, __PRETTY_FUNCTION__))
;
3897 if (SCS.Second == ICK_Derived_To_Base) {
3898 SmallVector<Expr*, 8> ConstructorArgs;
3899 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3900 From, /*FIXME:ConstructLoc*/SourceLocation(),
3901 ConstructorArgs))
3902 return ExprError();
3903 return BuildCXXConstructExpr(
3904 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3905 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3906 ConstructorArgs, /*HadMultipleCandidates*/ false,
3907 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3908 CXXConstructExpr::CK_Complete, SourceRange());
3909 }
3910 return BuildCXXConstructExpr(
3911 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3912 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3913 From, /*HadMultipleCandidates*/ false,
3914 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3915 CXXConstructExpr::CK_Complete, SourceRange());
3916 }
3917
3918 // Resolve overloaded function references.
3919 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3920 DeclAccessPair Found;
3921 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3922 true, Found);
3923 if (!Fn)
3924 return ExprError();
3925
3926 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
3927 return ExprError();
3928
3929 From = FixOverloadedFunctionReference(From, Found, Fn);
3930 FromType = From->getType();
3931 }
3932
3933 // If we're converting to an atomic type, first convert to the corresponding
3934 // non-atomic type.
3935 QualType ToAtomicType;
3936 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3937 ToAtomicType = ToType;
3938 ToType = ToAtomic->getValueType();
3939 }
3940
3941 QualType InitialFromType = FromType;
3942 // Perform the first implicit conversion.
3943 switch (SCS.First) {
3944 case ICK_Identity:
3945 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3946 FromType = FromAtomic->getValueType().getUnqualifiedType();
3947 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3948 From, /*BasePath=*/nullptr, VK_RValue);
3949 }
3950 break;
3951
3952 case ICK_Lvalue_To_Rvalue: {
3953 assert(From->getObjectKind() != OK_ObjCProperty)((From->getObjectKind() != OK_ObjCProperty) ? static_cast<
void> (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3953, __PRETTY_FUNCTION__))
;
3954 ExprResult FromRes = DefaultLvalueConversion(From);
3955 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3955, __PRETTY_FUNCTION__))
;
3956 From = FromRes.get();
3957 FromType = From->getType();
3958 break;
3959 }
3960
3961 case ICK_Array_To_Pointer:
3962 FromType = Context.getArrayDecayedType(FromType);
3963 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3964 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3965 break;
3966
3967 case ICK_Function_To_Pointer:
3968 FromType = Context.getPointerType(FromType);
3969 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3970 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3971 break;
3972
3973 default:
3974 llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3974)
;
3975 }
3976
3977 // Perform the second implicit conversion
3978 switch (SCS.Second) {
3979 case ICK_Identity:
3980 // C++ [except.spec]p5:
3981 // [For] assignment to and initialization of pointers to functions,
3982 // pointers to member functions, and references to functions: the
3983 // target entity shall allow at least the exceptions allowed by the
3984 // source value in the assignment or initialization.
3985 switch (Action) {
3986 case AA_Assigning:
3987 case AA_Initializing:
3988 // Note, function argument passing and returning are initialization.
3989 case AA_Passing:
3990 case AA_Returning:
3991 case AA_Sending:
3992 case AA_Passing_CFAudited:
3993 if (CheckExceptionSpecCompatibility(From, ToType))
3994 return ExprError();
3995 break;
3996
3997 case AA_Casting:
3998 case AA_Converting:
3999 // Casts and implicit conversions are not initialization, so are not
4000 // checked for exception specification mismatches.
4001 break;
4002 }
4003 // Nothing else to do.
4004 break;
4005
4006 case ICK_Integral_Promotion:
4007 case ICK_Integral_Conversion:
4008 if (ToType->isBooleanType()) {
4009 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4011, __PRETTY_FUNCTION__))
4010 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4011, __PRETTY_FUNCTION__))
4011 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4011, __PRETTY_FUNCTION__))
;
4012 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
4013 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4014 } else {
4015 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
4016 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4017 }
4018 break;
4019
4020 case ICK_Floating_Promotion:
4021 case ICK_Floating_Conversion:
4022 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
4023 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4024 break;
4025
4026 case ICK_Complex_Promotion:
4027 case ICK_Complex_Conversion: {
4028 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4029 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4030 CastKind CK;
4031 if (FromEl->isRealFloatingType()) {
4032 if (ToEl->isRealFloatingType())
4033 CK = CK_FloatingComplexCast;
4034 else
4035 CK = CK_FloatingComplexToIntegralComplex;
4036 } else if (ToEl->isRealFloatingType()) {
4037 CK = CK_IntegralComplexToFloatingComplex;
4038 } else {
4039 CK = CK_IntegralComplexCast;
4040 }
4041 From = ImpCastExprToType(From, ToType, CK,
4042 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4043 break;
4044 }
4045
4046 case ICK_Floating_Integral:
4047 if (ToType->isRealFloatingType())
4048 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
4049 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4050 else
4051 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
4052 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4053 break;
4054
4055 case ICK_Compatible_Conversion:
4056 From = ImpCastExprToType(From, ToType, CK_NoOp,
4057 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4058 break;
4059
4060 case ICK_Writeback_Conversion:
4061 case ICK_Pointer_Conversion: {
4062 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4063 // Diagnose incompatible Objective-C conversions
4064 if (Action == AA_Initializing || Action == AA_Assigning)
4065 Diag(From->getBeginLoc(),
4066 diag::ext_typecheck_convert_incompatible_pointer)
4067 << ToType << From->getType() << Action << From->getSourceRange()
4068 << 0;
4069 else
4070 Diag(From->getBeginLoc(),
4071 diag::ext_typecheck_convert_incompatible_pointer)
4072 << From->getType() << ToType << Action << From->getSourceRange()
4073 << 0;
4074
4075 if (From->getType()->isObjCObjectPointerType() &&
4076 ToType->isObjCObjectPointerType())
4077 EmitRelatedResultTypeNote(From);
4078 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4079 !CheckObjCARCUnavailableWeakConversion(ToType,
4080 From->getType())) {
4081 if (Action == AA_Initializing)
4082 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4083 else
4084 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4085 << (Action == AA_Casting) << From->getType() << ToType
4086 << From->getSourceRange();
4087 }
4088
4089 CastKind Kind;
4090 CXXCastPath BasePath;
4091 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
4092 return ExprError();
4093
4094 // Make sure we extend blocks if necessary.
4095 // FIXME: doing this here is really ugly.
4096 if (Kind == CK_BlockPointerToObjCPointerCast) {
4097 ExprResult E = From;
4098 (void) PrepareCastToObjCObjectPointer(E);
4099 From = E.get();
4100 }
4101 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4102 CheckObjCConversion(SourceRange(), ToType, From, CCK);
4103 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4104 .get();
4105 break;
4106 }
4107
4108 case ICK_Pointer_Member: {
4109 CastKind Kind;
4110 CXXCastPath BasePath;
4111 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4112 return ExprError();
4113 if (CheckExceptionSpecCompatibility(From, ToType))
4114 return ExprError();
4115
4116 // We may not have been able to figure out what this member pointer resolved
4117 // to up until this exact point. Attempt to lock-in it's inheritance model.
4118 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4119 (void)isCompleteType(From->getExprLoc(), From->getType());
4120 (void)isCompleteType(From->getExprLoc(), ToType);
4121 }
4122
4123 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4124 .get();
4125 break;
4126 }
4127
4128 case ICK_Boolean_Conversion:
4129 // Perform half-to-boolean conversion via float.
4130 if (From->getType()->isHalfType()) {
4131 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4132 FromType = Context.FloatTy;
4133 }
4134
4135 From = ImpCastExprToType(From, Context.BoolTy,
4136 ScalarTypeToBooleanCastKind(FromType),
4137 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4138 break;
4139
4140 case ICK_Derived_To_Base: {
4141 CXXCastPath BasePath;
4142 if (CheckDerivedToBaseConversion(
4143 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4144 From->getSourceRange(), &BasePath, CStyle))
4145 return ExprError();
4146
4147 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4148 CK_DerivedToBase, From->getValueKind(),
4149 &BasePath, CCK).get();
4150 break;
4151 }
4152
4153 case ICK_Vector_Conversion:
4154 From = ImpCastExprToType(From, ToType, CK_BitCast,
4155 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4156 break;
4157
4158 case ICK_Vector_Splat: {
4159 // Vector splat from any arithmetic type to a vector.
4160 Expr *Elem = prepareVectorSplat(ToType, From).get();
4161 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4162 /*BasePath=*/nullptr, CCK).get();
4163 break;
4164 }
4165
4166 case ICK_Complex_Real:
4167 // Case 1. x -> _Complex y
4168 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4169 QualType ElType = ToComplex->getElementType();
4170 bool isFloatingComplex = ElType->isRealFloatingType();
4171
4172 // x -> y
4173 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4174 // do nothing
4175 } else if (From->getType()->isRealFloatingType()) {
4176 From = ImpCastExprToType(From, ElType,
4177 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4178 } else {
4179 assert(From->getType()->isIntegerType())((From->getType()->isIntegerType()) ? static_cast<void
> (0) : __assert_fail ("From->getType()->isIntegerType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4179, __PRETTY_FUNCTION__))
;
4180 From = ImpCastExprToType(From, ElType,
4181 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4182 }
4183 // y -> _Complex y
4184 From = ImpCastExprToType(From, ToType,
4185 isFloatingComplex ? CK_FloatingRealToComplex
4186 : CK_IntegralRealToComplex).get();
4187
4188 // Case 2. _Complex x -> y
4189 } else {
4190 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4191 assert(FromComplex)((FromComplex) ? static_cast<void> (0) : __assert_fail (
"FromComplex", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4191, __PRETTY_FUNCTION__))
;
4192
4193 QualType ElType = FromComplex->getElementType();
4194 bool isFloatingComplex = ElType->isRealFloatingType();
4195
4196 // _Complex x -> x
4197 From = ImpCastExprToType(From, ElType,
4198 isFloatingComplex ? CK_FloatingComplexToReal
4199 : CK_IntegralComplexToReal,
4200 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4201
4202 // x -> y
4203 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4204 // do nothing
4205 } else if (ToType->isRealFloatingType()) {
4206 From = ImpCastExprToType(From, ToType,
4207 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
4208 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4209 } else {
4210 assert(ToType->isIntegerType())((ToType->isIntegerType()) ? static_cast<void> (0) :
__assert_fail ("ToType->isIntegerType()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4210, __PRETTY_FUNCTION__))
;
4211 From = ImpCastExprToType(From, ToType,
4212 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
4213 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4214 }
4215 }
4216 break;
4217
4218 case ICK_Block_Pointer_Conversion: {
4219 LangAS AddrSpaceL =
4220 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4221 LangAS AddrSpaceR =
4222 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4223 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&((Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR
) && "Invalid cast") ? static_cast<void> (0) : __assert_fail
("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4224, __PRETTY_FUNCTION__))
4224 "Invalid cast")((Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR
) && "Invalid cast") ? static_cast<void> (0) : __assert_fail
("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4224, __PRETTY_FUNCTION__))
;
4225 CastKind Kind =
4226 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4227 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4228 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4229 break;
4230 }
4231
4232 case ICK_TransparentUnionConversion: {
4233 ExprResult FromRes = From;
4234 Sema::AssignConvertType ConvTy =
4235 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4236 if (FromRes.isInvalid())
4237 return ExprError();
4238 From = FromRes.get();
4239 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4240, __PRETTY_FUNCTION__))
4240 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4240, __PRETTY_FUNCTION__))
;
4241 (void)ConvTy;
4242 break;
4243 }
4244
4245 case ICK_Zero_Event_Conversion:
4246 case ICK_Zero_Queue_Conversion:
4247 From = ImpCastExprToType(From, ToType,
4248 CK_ZeroToOCLOpaqueType,
4249 From->getValueKind()).get();
4250 break;
4251
4252 case ICK_Lvalue_To_Rvalue:
4253 case ICK_Array_To_Pointer:
4254 case ICK_Function_To_Pointer:
4255 case ICK_Function_Conversion:
4256 case ICK_Qualification:
4257 case ICK_Num_Conversion_Kinds:
4258 case ICK_C_Only_Conversion:
4259 case ICK_Incompatible_Pointer_Conversion:
4260 llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4260)
;
4261 }
4262
4263 switch (SCS.Third) {
4264 case ICK_Identity:
4265 // Nothing to do.
4266 break;
4267
4268 case ICK_Function_Conversion:
4269 // If both sides are functions (or pointers/references to them), there could
4270 // be incompatible exception declarations.
4271 if (CheckExceptionSpecCompatibility(From, ToType))
4272 return ExprError();
4273
4274 From = ImpCastExprToType(From, ToType, CK_NoOp,
4275 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4276 break;
4277
4278 case ICK_Qualification: {
4279 // The qualification keeps the category of the inner expression, unless the
4280 // target type isn't a reference.
4281 ExprValueKind VK =
4282 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4283
4284 CastKind CK = CK_NoOp;
4285
4286 if (ToType->isReferenceType() &&
4287 ToType->getPointeeType().getAddressSpace() !=
4288 From->getType().getAddressSpace())
4289 CK = CK_AddressSpaceConversion;
4290
4291 if (ToType->isPointerType() &&
4292 ToType->getPointeeType().getAddressSpace() !=
4293 From->getType()->getPointeeType().getAddressSpace())
4294 CK = CK_AddressSpaceConversion;
4295
4296 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4297 /*BasePath=*/nullptr, CCK)
4298 .get();
4299
4300 if (SCS.DeprecatedStringLiteralToCharPtr &&
4301 !getLangOpts().WritableStrings) {
4302 Diag(From->getBeginLoc(),
4303 getLangOpts().CPlusPlus11
4304 ? diag::ext_deprecated_string_literal_conversion
4305 : diag::warn_deprecated_string_literal_conversion)
4306 << ToType.getNonReferenceType();
4307 }
4308
4309 break;
4310 }
4311
4312 default:
4313 llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4313)
;
4314 }
4315
4316 // If this conversion sequence involved a scalar -> atomic conversion, perform
4317 // that conversion now.
4318 if (!ToAtomicType.isNull()) {
4319 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4320, __PRETTY_FUNCTION__))
4320 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4320, __PRETTY_FUNCTION__))
;
4321 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4322 VK_RValue, nullptr, CCK).get();
4323 }
4324
4325 // If this conversion sequence succeeded and involved implicitly converting a
4326 // _Nullable type to a _Nonnull one, complain.
4327 if (!isCast(CCK))
4328 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4329 From->getBeginLoc());
4330
4331 return From;
4332}
4333
4334/// Check the completeness of a type in a unary type trait.
4335///
4336/// If the particular type trait requires a complete type, tries to complete
4337/// it. If completing the type fails, a diagnostic is emitted and false
4338/// returned. If completing the type succeeds or no completion was required,
4339/// returns true.
4340static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4341 SourceLocation Loc,
4342 QualType ArgTy) {
4343 // C++0x [meta.unary.prop]p3:
4344 // For all of the class templates X declared in this Clause, instantiating
4345 // that template with a template argument that is a class template
4346 // specialization may result in the implicit instantiation of the template
4347 // argument if and only if the semantics of X require that the argument
4348 // must be a complete type.
4349 // We apply this rule to all the type trait expressions used to implement
4350 // these class templates. We also try to follow any GCC documented behavior
4351 // in these expressions to ensure portability of standard libraries.
4352 switch (UTT) {
4353 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4353)
;
4354 // is_complete_type somewhat obviously cannot require a complete type.
4355 case UTT_IsCompleteType:
4356 // Fall-through
4357
4358 // These traits are modeled on the type predicates in C++0x
4359 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4360 // requiring a complete type, as whether or not they return true cannot be
4361 // impacted by the completeness of the type.
4362 case UTT_IsVoid:
4363 case UTT_IsIntegral:
4364 case UTT_IsFloatingPoint:
4365 case UTT_IsArray:
4366 case UTT_IsPointer:
4367 case UTT_IsLvalueReference:
4368 case UTT_IsRvalueReference:
4369 case UTT_IsMemberFunctionPointer:
4370 case UTT_IsMemberObjectPointer:
4371 case UTT_IsEnum:
4372 case UTT_IsUnion:
4373 case UTT_IsClass:
4374 case UTT_IsFunction:
4375 case UTT_IsReference:
4376 case UTT_IsArithmetic:
4377 case UTT_IsFundamental:
4378 case UTT_IsObject:
4379 case UTT_IsScalar:
4380 case UTT_IsCompound:
4381 case UTT_IsMemberPointer:
4382 // Fall-through
4383
4384 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4385 // which requires some of its traits to have the complete type. However,
4386 // the completeness of the type cannot impact these traits' semantics, and
4387 // so they don't require it. This matches the comments on these traits in
4388 // Table 49.
4389 case UTT_IsConst:
4390 case UTT_IsVolatile:
4391 case UTT_IsSigned:
4392 case UTT_IsUnsigned:
4393
4394 // This type trait always returns false, checking the type is moot.
4395 case UTT_IsInterfaceClass:
4396 return true;
4397
4398 // C++14 [meta.unary.prop]:
4399 // If T is a non-union class type, T shall be a complete type.
4400 case UTT_IsEmpty:
4401 case UTT_IsPolymorphic:
4402 case UTT_IsAbstract:
4403 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4404 if (!RD->isUnion())
4405 return !S.RequireCompleteType(
4406 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4407 return true;
4408
4409 // C++14 [meta.unary.prop]:
4410 // If T is a class type, T shall be a complete type.
4411 case UTT_IsFinal:
4412 case UTT_IsSealed:
4413 if (ArgTy->getAsCXXRecordDecl())
4414 return !S.RequireCompleteType(
4415 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4416 return true;
4417
4418 // C++1z [meta.unary.prop]:
4419 // remove_all_extents_t<T> shall be a complete type or cv void.
4420 case UTT_IsAggregate:
4421 case UTT_IsTrivial:
4422 case UTT_IsTriviallyCopyable:
4423 case UTT_IsStandardLayout:
4424 case UTT_IsPOD:
4425 case UTT_IsLiteral:
4426 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4427 // or an array of unknown bound. But GCC actually imposes the same constraints
4428 // as above.
4429 case UTT_HasNothrowAssign:
4430 case UTT_HasNothrowMoveAssign:
4431 case UTT_HasNothrowConstructor:
4432 case UTT_HasNothrowCopy:
4433 case UTT_HasTrivialAssign:
4434 case UTT_HasTrivialMoveAssign:
4435 case UTT_HasTrivialDefaultConstructor:
4436 case UTT_HasTrivialMoveConstructor:
4437 case UTT_HasTrivialCopy:
4438 case UTT_HasTrivialDestructor:
4439 case UTT_HasVirtualDestructor:
4440 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4441 LLVM_FALLTHROUGH[[gnu::fallthrough]];
4442
4443 // C++1z [meta.unary.prop]:
4444 // T shall be a complete type, cv void, or an array of unknown bound.
4445 case UTT_IsDestructible:
4446 case UTT_IsNothrowDestructible:
4447 case UTT_IsTriviallyDestructible:
4448 case UTT_HasUniqueObjectRepresentations:
4449 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4450 return true;
4451
4452 return !S.RequireCompleteType(
4453 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4454 }
4455}
4456
4457static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4458 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4459 bool (CXXRecordDecl::*HasTrivial)() const,
4460 bool (CXXRecordDecl::*HasNonTrivial)() const,
4461 bool (CXXMethodDecl::*IsDesiredOp)() const)
4462{
4463 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4464 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4465 return true;
4466
4467 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4468 DeclarationNameInfo NameInfo(Name, KeyLoc);
4469 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4470 if (Self.LookupQualifiedName(Res, RD)) {
4471 bool FoundOperator = false;
4472 Res.suppressDiagnostics();
4473 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4474 Op != OpEnd; ++Op) {
4475 if (isa<FunctionTemplateDecl>(*Op))
4476 continue;
4477
4478 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4479 if((Operator->*IsDesiredOp)()) {
4480 FoundOperator = true;
4481 const FunctionProtoType *CPT =
4482 Operator->getType()->getAs<FunctionProtoType>();
4483 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4484 if (!CPT || !CPT->isNothrow())
4485 return false;
4486 }
4487 }
4488 return FoundOperator;
4489 }
4490 return false;
4491}
4492
4493static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4494 SourceLocation KeyLoc, QualType T) {
4495 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4495, __PRETTY_FUNCTION__))
;
4496
4497 ASTContext &C = Self.Context;
4498 switch(UTT) {
4499 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4499)
;
4500 // Type trait expressions corresponding to the primary type category
4501 // predicates in C++0x [meta.unary.cat].
4502 case UTT_IsVoid:
4503 return T->isVoidType();
4504 case UTT_IsIntegral:
4505 return T->isIntegralType(C);
4506 case UTT_IsFloatingPoint:
4507 return T->isFloatingType();
4508 case UTT_IsArray:
4509 return T->isArrayType();
4510 case UTT_IsPointer:
4511 return T->isPointerType();
4512 case UTT_IsLvalueReference:
4513 return T->isLValueReferenceType();
4514 case UTT_IsRvalueReference:
4515 return T->isRValueReferenceType();
4516 case UTT_IsMemberFunctionPointer:
4517 return T->isMemberFunctionPointerType();
4518 case UTT_IsMemberObjectPointer:
4519 return T->isMemberDataPointerType();
4520 case UTT_IsEnum:
4521 return T->isEnumeralType();
4522 case UTT_IsUnion:
4523 return T->isUnionType();
4524 case UTT_IsClass:
4525 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4526 case UTT_IsFunction:
4527 return T->isFunctionType();
4528
4529 // Type trait expressions which correspond to the convenient composition
4530 // predicates in C++0x [meta.unary.comp].
4531 case UTT_IsReference:
4532 return T->isReferenceType();
4533 case UTT_IsArithmetic:
4534 return T->isArithmeticType() && !T->isEnumeralType();
4535 case UTT_IsFundamental:
4536 return T->isFundamentalType();
4537 case UTT_IsObject:
4538 return T->isObjectType();
4539 case UTT_IsScalar:
4540 // Note: semantic analysis depends on Objective-C lifetime types to be
4541 // considered scalar types. However, such types do not actually behave
4542 // like scalar types at run time (since they may require retain/release
4543 // operations), so we report them as non-scalar.
4544 if (T->isObjCLifetimeType()) {
4545 switch (T.getObjCLifetime()) {
4546 case Qualifiers::OCL_None:
4547 case Qualifiers::OCL_ExplicitNone:
4548 return true;
4549
4550 case Qualifiers::OCL_Strong:
4551 case Qualifiers::OCL_Weak:
4552 case Qualifiers::OCL_Autoreleasing:
4553 return false;
4554 }
4555 }
4556
4557 return T->isScalarType();
4558 case UTT_IsCompound:
4559 return T->isCompoundType();
4560 case UTT_IsMemberPointer:
4561 return T->isMemberPointerType();
4562
4563 // Type trait expressions which correspond to the type property predicates
4564 // in C++0x [meta.unary.prop].
4565 case UTT_IsConst:
4566 return T.isConstQualified();
4567 case UTT_IsVolatile:
4568 return T.isVolatileQualified();
4569 case UTT_IsTrivial:
4570 return T.isTrivialType(C);
4571 case UTT_IsTriviallyCopyable:
4572 return T.isTriviallyCopyableType(C);
4573 case UTT_IsStandardLayout:
4574 return T->isStandardLayoutType();
4575 case UTT_IsPOD:
4576 return T.isPODType(C);
4577 case UTT_IsLiteral:
4578 return T->isLiteralType(C);
4579 case UTT_IsEmpty:
4580 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4581 return !RD->isUnion() && RD->isEmpty();
4582 return false;
4583 case UTT_IsPolymorphic:
4584 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4585 return !RD->isUnion() && RD->isPolymorphic();
4586 return false;
4587 case UTT_IsAbstract:
4588 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4589 return !RD->isUnion() && RD->isAbstract();
4590 return false;
4591 case UTT_IsAggregate:
4592 // Report vector extensions and complex types as aggregates because they
4593 // support aggregate initialization. GCC mirrors this behavior for vectors
4594 // but not _Complex.
4595 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4596 T->isAnyComplexType();
4597 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4598 // even then only when it is used with the 'interface struct ...' syntax
4599 // Clang doesn't support /CLR which makes this type trait moot.
4600 case UTT_IsInterfaceClass:
4601 return false;
4602 case UTT_IsFinal:
4603 case UTT_IsSealed:
4604 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4605 return RD->hasAttr<FinalAttr>();
4606 return false;
4607 case UTT_IsSigned:
4608 // Enum types should always return false.
4609 // Floating points should always return true.
4610 return !T->isEnumeralType() && (T->isFloatingType() || T->isSignedIntegerType());
4611 case UTT_IsUnsigned:
4612 return T->isUnsignedIntegerType();
4613
4614 // Type trait expressions which query classes regarding their construction,
4615 // destruction, and copying. Rather than being based directly on the
4616 // related type predicates in the standard, they are specified by both
4617 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4618 // specifications.
4619 //
4620 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4621 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4622 //
4623 // Note that these builtins do not behave as documented in g++: if a class
4624 // has both a trivial and a non-trivial special member of a particular kind,
4625 // they return false! For now, we emulate this behavior.
4626 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4627 // does not correctly compute triviality in the presence of multiple special
4628 // members of the same kind. Revisit this once the g++ bug is fixed.
4629 case UTT_HasTrivialDefaultConstructor:
4630 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4631 // If __is_pod (type) is true then the trait is true, else if type is
4632 // a cv class or union type (or array thereof) with a trivial default
4633 // constructor ([class.ctor]) then the trait is true, else it is false.
4634 if (T.isPODType(C))
4635 return true;
4636 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4637 return RD->hasTrivialDefaultConstructor() &&
4638 !RD->hasNonTrivialDefaultConstructor();
4639 return false;
4640 case UTT_HasTrivialMoveConstructor:
4641 // This trait is implemented by MSVC 2012 and needed to parse the
4642 // standard library headers. Specifically this is used as the logic
4643 // behind std::is_trivially_move_constructible (20.9.4.3).
4644 if (T.isPODType(C))
4645 return true;
4646 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4647 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4648 return false;
4649 case UTT_HasTrivialCopy:
4650 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4651 // If __is_pod (type) is true or type is a reference type then
4652 // the trait is true, else if type is a cv class or union type
4653 // with a trivial copy constructor ([class.copy]) then the trait
4654 // is true, else it is false.
4655 if (T.isPODType(C) || T->isReferenceType())
4656 return true;
4657 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4658 return RD->hasTrivialCopyConstructor() &&
4659 !RD->hasNonTrivialCopyConstructor();
4660 return false;
4661 case UTT_HasTrivialMoveAssign:
4662 // This trait is implemented by MSVC 2012 and needed to parse the
4663 // standard library headers. Specifically it is used as the logic
4664 // behind std::is_trivially_move_assignable (20.9.4.3)
4665 if (T.isPODType(C))
4666 return true;
4667 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4668 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4669 return false;
4670 case UTT_HasTrivialAssign:
4671 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4672 // If type is const qualified or is a reference type then the
4673 // trait is false. Otherwise if __is_pod (type) is true then the
4674 // trait is true, else if type is a cv class or union type with
4675 // a trivial copy assignment ([class.copy]) then the trait is
4676 // true, else it is false.
4677 // Note: the const and reference restrictions are interesting,
4678 // given that const and reference members don't prevent a class
4679 // from having a trivial copy assignment operator (but do cause
4680 // errors if the copy assignment operator is actually used, q.v.
4681 // [class.copy]p12).
4682
4683 if (T.isConstQualified())
4684 return false;
4685 if (T.isPODType(C))
4686 return true;
4687 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4688 return RD->hasTrivialCopyAssignment() &&
4689 !RD->hasNonTrivialCopyAssignment();
4690 return false;
4691 case UTT_IsDestructible:
4692 case UTT_IsTriviallyDestructible:
4693 case UTT_IsNothrowDestructible:
4694 // C++14 [meta.unary.prop]:
4695 // For reference types, is_destructible<T>::value is true.
4696 if (T->isReferenceType())
4697 return true;
4698
4699 // Objective-C++ ARC: autorelease types don't require destruction.
4700 if (T->isObjCLifetimeType() &&
4701 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4702 return true;
4703
4704 // C++14 [meta.unary.prop]:
4705 // For incomplete types and function types, is_destructible<T>::value is
4706 // false.
4707 if (T->isIncompleteType() || T->isFunctionType())
4708 return false;
4709
4710 // A type that requires destruction (via a non-trivial destructor or ARC
4711 // lifetime semantics) is not trivially-destructible.
4712 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4713 return false;
4714
4715 // C++14 [meta.unary.prop]:
4716 // For object types and given U equal to remove_all_extents_t<T>, if the
4717 // expression std::declval<U&>().~U() is well-formed when treated as an
4718 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4719 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4720 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4721 if (!Destructor)
4722 return false;
4723 // C++14 [dcl.fct.def.delete]p2:
4724 // A program that refers to a deleted function implicitly or
4725 // explicitly, other than to declare it, is ill-formed.
4726 if (Destructor->isDeleted())
4727 return false;
4728 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4729 return false;
4730 if (UTT == UTT_IsNothrowDestructible) {
4731 const FunctionProtoType *CPT =
4732 Destructor->getType()->getAs<FunctionProtoType>();
4733 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4734 if (!CPT || !CPT->isNothrow())
4735 return false;
4736 }
4737 }
4738 return true;
4739
4740 case UTT_HasTrivialDestructor:
4741 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4742 // If __is_pod (type) is true or type is a reference type
4743 // then the trait is true, else if type is a cv class or union
4744 // type (or array thereof) with a trivial destructor
4745 // ([class.dtor]) then the trait is true, else it is
4746 // false.
4747 if (T.isPODType(C) || T->isReferenceType())
4748 return true;
4749
4750 // Objective-C++ ARC: autorelease types don't require destruction.
4751 if (T->isObjCLifetimeType() &&
4752 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4753 return true;
4754
4755 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4756 return RD->hasTrivialDestructor();
4757 return false;
4758 // TODO: Propagate nothrowness for implicitly declared special members.
4759 case UTT_HasNothrowAssign:
4760 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4761 // If type is const qualified or is a reference type then the
4762 // trait is false. Otherwise if __has_trivial_assign (type)
4763 // is true then the trait is true, else if type is a cv class
4764 // or union type with copy assignment operators that are known
4765 // not to throw an exception then the trait is true, else it is
4766 // false.
4767 if (C.getBaseElementType(T).isConstQualified())
4768 return false;
4769 if (T->isReferenceType())
4770 return false;
4771 if (T.isPODType(C) || T->isObjCLifetimeType())
4772 return true;
4773
4774 if (const RecordType *RT = T->getAs<RecordType>())
4775 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4776 &CXXRecordDecl::hasTrivialCopyAssignment,
4777 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4778 &CXXMethodDecl::isCopyAssignmentOperator);
4779 return false;
4780 case UTT_HasNothrowMoveAssign:
4781 // This trait is implemented by MSVC 2012 and needed to parse the
4782 // standard library headers. Specifically this is used as the logic
4783 // behind std::is_nothrow_move_assignable (20.9.4.3).
4784 if (T.isPODType(C))
4785 return true;
4786
4787 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4788 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4789 &CXXRecordDecl::hasTrivialMoveAssignment,
4790 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4791 &CXXMethodDecl::isMoveAssignmentOperator);
4792 return false;
4793 case UTT_HasNothrowCopy:
4794 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4795 // If __has_trivial_copy (type) is true then the trait is true, else
4796 // if type is a cv class or union type with copy constructors that are
4797 // known not to throw an exception then the trait is true, else it is
4798 // false.
4799 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4800 return true;
4801 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4802 if (RD->hasTrivialCopyConstructor() &&
4803 !RD->hasNonTrivialCopyConstructor())
4804 return true;
4805
4806 bool FoundConstructor = false;
4807 unsigned FoundTQs;
4808 for (const auto *ND : Self.LookupConstructors(RD)) {
4809 // A template constructor is never a copy constructor.
4810 // FIXME: However, it may actually be selected at the actual overload
4811 // resolution point.
4812 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4813 continue;
4814 // UsingDecl itself is not a constructor
4815 if (isa<UsingDecl>(ND))
4816 continue;
4817 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4818 if (Constructor->isCopyConstructor(FoundTQs)) {
4819 FoundConstructor = true;
4820 const FunctionProtoType *CPT
4821 = Constructor->getType()->getAs<FunctionProtoType>();
4822 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4823 if (!CPT)
4824 return false;
4825 // TODO: check whether evaluating default arguments can throw.
4826 // For now, we'll be conservative and assume that they can throw.
4827 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
4828 return false;
4829 }
4830 }
4831
4832 return FoundConstructor;
4833 }
4834 return false;
4835 case UTT_HasNothrowConstructor:
4836 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4837 // If __has_trivial_constructor (type) is true then the trait is
4838 // true, else if type is a cv class or union type (or array
4839 // thereof) with a default constructor that is known not to
4840 // throw an exception then the trait is true, else it is false.
4841 if (T.isPODType(C) || T->isObjCLifetimeType())
4842 return true;
4843 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4844 if (RD->hasTrivialDefaultConstructor() &&
4845 !RD->hasNonTrivialDefaultConstructor())
4846 return true;
4847
4848 bool FoundConstructor = false;
4849 for (const auto *ND : Self.LookupConstructors(RD)) {
4850 // FIXME: In C++0x, a constructor template can be a default constructor.
4851 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4852 continue;
4853 // UsingDecl itself is not a constructor
4854 if (isa<UsingDecl>(ND))
4855 continue;
4856 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4857 if (Constructor->isDefaultConstructor()) {
4858 FoundConstructor = true;
4859 const FunctionProtoType *CPT
4860 = Constructor->getType()->getAs<FunctionProtoType>();
4861 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4862 if (!CPT)
4863 return false;
4864 // FIXME: check whether evaluating default arguments can throw.
4865 // For now, we'll be conservative and assume that they can throw.
4866 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
4867 return false;
4868 }
4869 }
4870 return FoundConstructor;
4871 }
4872 return false;
4873 case UTT_HasVirtualDestructor:
4874 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4875 // If type is a class type with a virtual destructor ([class.dtor])
4876 // then the trait is true, else it is false.
4877 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4878 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4879 return Destructor->isVirtual();
4880 return false;
4881
4882 // These type trait expressions are modeled on the specifications for the
4883 // Embarcadero C++0x type trait functions:
4884 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4885 case UTT_IsCompleteType:
4886 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4887 // Returns True if and only if T is a complete type at the point of the
4888 // function call.
4889 return !T->isIncompleteType();
4890 case UTT_HasUniqueObjectRepresentations:
4891 return C.hasUniqueObjectRepresentations(T);
4892 }
4893}
4894
4895static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4896 QualType RhsT, SourceLocation KeyLoc);
4897
4898static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4899 ArrayRef<TypeSourceInfo *> Args,
4900 SourceLocation RParenLoc) {
4901 if (Kind <= UTT_Last)
4902 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4903
4904 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4905 // traits to avoid duplication.
4906 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4907 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4908 Args[1]->getType(), RParenLoc);
4909
4910 switch (Kind) {
4911 case clang::BTT_ReferenceBindsToTemporary:
4912 case clang::TT_IsConstructible:
4913 case clang::TT_IsNothrowConstructible:
4914 case clang::TT_IsTriviallyConstructible: {
4915 // C++11 [meta.unary.prop]:
4916 // is_trivially_constructible is defined as:
4917 //
4918 // is_constructible<T, Args...>::value is true and the variable
4919 // definition for is_constructible, as defined below, is known to call
4920 // no operation that is not trivial.
4921 //
4922 // The predicate condition for a template specialization
4923 // is_constructible<T, Args...> shall be satisfied if and only if the
4924 // following variable definition would be well-formed for some invented
4925 // variable t:
4926 //
4927 // T t(create<Args>()...);
4928 assert(!Args.empty())((!Args.empty()) ? static_cast<void> (0) : __assert_fail
("!Args.empty()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4928, __PRETTY_FUNCTION__))
;
4929
4930 // Precondition: T and all types in the parameter pack Args shall be
4931 // complete types, (possibly cv-qualified) void, or arrays of
4932 // unknown bound.
4933 for (const auto *TSI : Args) {
4934 QualType ArgTy = TSI->getType();
4935 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4936 continue;
4937
4938 if (S.RequireCompleteType(KWLoc, ArgTy,
4939 diag::err_incomplete_type_used_in_type_trait_expr))
4940 return false;
4941 }
4942
4943 // Make sure the first argument is not incomplete nor a function type.
4944 QualType T = Args[0]->getType();
4945 if (T->isIncompleteType() || T->isFunctionType())
4946 return false;
4947
4948 // Make sure the first argument is not an abstract type.
4949 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4950 if (RD && RD->isAbstract())
4951 return false;
4952
4953 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4954 SmallVector<Expr *, 2> ArgExprs;
4955 ArgExprs.reserve(Args.size() - 1);
4956 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4957 QualType ArgTy = Args[I]->getType();
4958 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4959 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4960 OpaqueArgExprs.push_back(
4961 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
4962 ArgTy.getNonLValueExprType(S.Context),
4963 Expr::getValueKindForType(ArgTy)));
4964 }
4965 for (Expr &E : OpaqueArgExprs)
4966 ArgExprs.push_back(&E);
4967
4968 // Perform the initialization in an unevaluated context within a SFINAE
4969 // trap at translation unit scope.
4970 EnterExpressionEvaluationContext Unevaluated(
4971 S, Sema::ExpressionEvaluationContext::Unevaluated);
4972 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4973 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4974 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4975 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4976 RParenLoc));
4977 InitializationSequence Init(S, To, InitKind, ArgExprs);
4978 if (Init.Failed())
4979 return false;
4980
4981 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4982 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4983 return false;
4984
4985 if (Kind == clang::TT_IsConstructible)
4986 return true;
4987
4988 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4989 if (!T->isReferenceType())
4990 return false;
4991
4992 return !Init.isDirectReferenceBinding();
4993 }
4994
4995 if (Kind == clang::TT_IsNothrowConstructible)
4996 return S.canThrow(Result.get()) == CT_Cannot;
4997
4998 if (Kind == clang::TT_IsTriviallyConstructible) {
4999 // Under Objective-C ARC and Weak, if the destination has non-trivial
5000 // Objective-C lifetime, this is a non-trivial construction.
5001 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5002 return false;
5003
5004 // The initialization succeeded; now make sure there are no non-trivial
5005 // calls.
5006 return !Result.get()->hasNonTrivialCall(S.Context);
5007 }
5008
5009 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5009)
;
5010 return false;
5011 }
5012 default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5012)
;
5013 }
5014
5015 return false;
5016}
5017
5018ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5019 ArrayRef<TypeSourceInfo *> Args,
5020 SourceLocation RParenLoc) {
5021 QualType ResultType = Context.getLogicalOperationType();
5022
5023 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5024 *this, Kind, KWLoc, Args[0]->getType()))
5025 return ExprError();
5026
5027 bool Dependent = false;
5028 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5029 if (Args[I]->getType()->isDependentType()) {
5030 Dependent = true;
5031 break;
5032 }
5033 }
5034
5035 bool Result = false;
5036 if (!Dependent)
5037 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5038
5039 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5040 RParenLoc, Result);
5041}
5042
5043ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5044 ArrayRef<ParsedType> Args,
5045 SourceLocation RParenLoc) {
5046 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5047 ConvertedArgs.reserve(Args.size());
5048
5049 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5050 TypeSourceInfo *TInfo;
5051 QualType T = GetTypeFromParser(Args[I], &TInfo);
5052 if (!TInfo)
5053 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5054
5055 ConvertedArgs.push_back(TInfo);
5056 }
5057
5058 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5059}
5060
5061static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5062 QualType RhsT, SourceLocation KeyLoc) {
5063 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5064, __PRETTY_FUNCTION__))
5064 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5064, __PRETTY_FUNCTION__))
;
5065
5066 switch(BTT) {
5067 case BTT_IsBaseOf: {
5068 // C++0x [meta.rel]p2
5069 // Base is a base class of Derived without regard to cv-qualifiers or
5070 // Base and Derived are not unions and name the same class type without
5071 // regard to cv-qualifiers.
5072
5073 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5074 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5075 if (!rhsRecord || !lhsRecord) {
5076 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5077 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5078 if (!LHSObjTy || !RHSObjTy)
5079 return false;
5080
5081 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5082 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5083 if (!BaseInterface || !DerivedInterface)
5084 return false;
5085
5086 if (Self.RequireCompleteType(
5087 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5088 return false;
5089
5090 return BaseInterface->isSuperClassOf(DerivedInterface);
5091 }
5092
5093 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5094, __PRETTY_FUNCTION__))
5094 == (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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5094, __PRETTY_FUNCTION__))
;
5095
5096 // Unions are never base classes, and never have base classes.
5097 // It doesn't matter if they are complete or not. See PR#41843
5098 if (lhsRecord && lhsRecord->getDecl()->isUnion())
5099 return false;
5100 if (rhsRecord && rhsRecord->getDecl()->isUnion())
5101 return false;
5102
5103 if (lhsRecord == rhsRecord)
5104 return true;
5105
5106 // C++0x [meta.rel]p2:
5107 // If Base and Derived are class types and are different types
5108 // (ignoring possible cv-qualifiers) then Derived shall be a
5109 // complete type.
5110 if (Self.RequireCompleteType(KeyLoc, RhsT,
5111 diag::err_incomplete_type_used_in_type_trait_expr))
5112 return false;
5113
5114 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5115 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5116 }
5117 case BTT_IsSame:
5118 return Self.Context.hasSameType(LhsT, RhsT);
5119 case BTT_TypeCompatible: {
5120 // GCC ignores cv-qualifiers on arrays for this builtin.
5121 Qualifiers LhsQuals, RhsQuals;
5122 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5123 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5124 return Self.Context.typesAreCompatible(Lhs, Rhs);
5125 }
5126 case BTT_IsConvertible:
5127 case BTT_IsConvertibleTo: {
5128 // C++0x [meta.rel]p4:
5129 // Given the following function prototype:
5130 //
5131 // template <class T>
5132 // typename add_rvalue_reference<T>::type create();
5133 //
5134 // the predicate condition for a template specialization
5135 // is_convertible<From, To> shall be satisfied if and only if
5136 // the return expression in the following code would be
5137 // well-formed, including any implicit conversions to the return
5138 // type of the function:
5139 //
5140 // To test() {
5141 // return create<From>();
5142 // }
5143 //
5144 // Access checking is performed as if in a context unrelated to To and
5145 // From. Only the validity of the immediate context of the expression
5146 // of the return-statement (including conversions to the return type)
5147 // is considered.
5148 //
5149 // We model the initialization as a copy-initialization of a temporary
5150 // of the appropriate type, which for this expression is identical to the
5151 // return statement (since NRVO doesn't apply).
5152
5153 // Functions aren't allowed to return function or array types.
5154 if (RhsT->isFunctionType() || RhsT->isArrayType())
5155 return false;
5156
5157 // A return statement in a void function must have void type.
5158 if (RhsT->isVoidType())
5159 return LhsT->isVoidType();
5160
5161 // A function definition requires a complete, non-abstract return type.
5162 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5163 return false;
5164
5165 // Compute the result of add_rvalue_reference.
5166 if (LhsT->isObjectType() || LhsT->isFunctionType())
5167 LhsT = Self.Context.getRValueReferenceType(LhsT);
5168
5169 // Build a fake source and destination for initialization.
5170 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5171 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5172 Expr::getValueKindForType(LhsT));
5173 Expr *FromPtr = &From;
5174 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5175 SourceLocation()));
5176
5177 // Perform the initialization in an unevaluated context within a SFINAE
5178 // trap at translation unit scope.
5179 EnterExpressionEvaluationContext Unevaluated(
5180 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5181 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5182 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5183 InitializationSequence Init(Self, To, Kind, FromPtr);
5184 if (Init.Failed())
5185 return false;
5186
5187 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5188 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5189 }
5190
5191 case BTT_IsAssignable:
5192 case BTT_IsNothrowAssignable:
5193 case BTT_IsTriviallyAssignable: {
5194 // C++11 [meta.unary.prop]p3:
5195 // is_trivially_assignable is defined as:
5196 // is_assignable<T, U>::value is true and the assignment, as defined by
5197 // is_assignable, is known to call no operation that is not trivial
5198 //
5199 // is_assignable is defined as:
5200 // The expression declval<T>() = declval<U>() is well-formed when
5201 // treated as an unevaluated operand (Clause 5).
5202 //
5203 // For both, T and U shall be complete types, (possibly cv-qualified)
5204 // void, or arrays of unknown bound.
5205 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5206 Self.RequireCompleteType(KeyLoc, LhsT,
5207 diag::err_incomplete_type_used_in_type_trait_expr))
5208 return false;
5209 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5210 Self.RequireCompleteType(KeyLoc, RhsT,
5211 diag::err_incomplete_type_used_in_type_trait_expr))
5212 return false;
5213
5214 // cv void is never assignable.
5215 if (LhsT->isVoidType() || RhsT->isVoidType())
5216 return false;
5217
5218 // Build expressions that emulate the effect of declval<T>() and
5219 // declval<U>().
5220 if (LhsT->isObjectType() || LhsT->isFunctionType())
5221 LhsT = Self.Context.getRValueReferenceType(LhsT);
5222 if (RhsT->isObjectType() || RhsT->isFunctionType())
5223 RhsT = Self.Context.getRValueReferenceType(RhsT);
5224 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5225 Expr::getValueKindForType(LhsT));
5226 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5227 Expr::getValueKindForType(RhsT));
5228
5229 // Attempt the assignment in an unevaluated context within a SFINAE
5230 // trap at translation unit scope.
5231 EnterExpressionEvaluationContext Unevaluated(
5232 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5233 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5234 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5235 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5236 &Rhs);
5237 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5238 return false;
5239
5240 if (BTT == BTT_IsAssignable)
5241 return true;
5242
5243 if (BTT == BTT_IsNothrowAssignable)
5244 return Self.canThrow(Result.get()) == CT_Cannot;
5245
5246 if (BTT == BTT_IsTriviallyAssignable) {
5247 // Under Objective-C ARC and Weak, if the destination has non-trivial
5248 // Objective-C lifetime, this is a non-trivial assignment.
5249 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5250 return false;
5251
5252 return !Result.get()->hasNonTrivialCall(Self.Context);
5253 }
5254
5255 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5255)
;
5256 return false;
5257 }
5258 default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5258)
;
5259 }
5260 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5260)
;
5261}
5262
5263ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5264 SourceLocation KWLoc,
5265 ParsedType Ty,
5266 Expr* DimExpr,
5267 SourceLocation RParen) {
5268 TypeSourceInfo *TSInfo;
5269 QualType T = GetTypeFromParser(Ty, &TSInfo);
5270 if (!TSInfo)
5271 TSInfo = Context.getTrivialTypeSourceInfo(T);
5272
5273 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5274}
5275
5276static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5277 QualType T, Expr *DimExpr,
5278 SourceLocation KeyLoc) {
5279 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5279, __PRETTY_FUNCTION__))
;
5280
5281 switch(ATT) {
5282 case ATT_ArrayRank:
5283 if (T->isArrayType()) {
5284 unsigned Dim = 0;
5285 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5286 ++Dim;
5287 T = AT->getElementType();
5288 }
5289 return Dim;
5290 }
5291 return 0;
5292
5293 case ATT_ArrayExtent: {
5294 llvm::APSInt Value;
5295 uint64_t Dim;
5296 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5297 diag::err_dimension_expr_not_constant_integer,
5298 false).isInvalid())
5299 return 0;
5300 if (Value.isSigned() && Value.isNegative()) {
5301 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5302 << DimExpr->getSourceRange();
5303 return 0;
5304 }
5305 Dim = Value.getLimitedValue();
5306
5307 if (T->isArrayType()) {
5308 unsigned D = 0;
5309 bool Matched = false;
5310 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5311 if (Dim == D) {
5312 Matched = true;
5313 break;
5314 }
5315 ++D;
5316 T = AT->getElementType();
5317 }
5318
5319 if (Matched && T->isArrayType()) {
5320 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5321 return CAT->getSize().getLimitedValue();
5322 }
5323 }
5324 return 0;
5325 }
5326 }
5327 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5327)
;
5328}
5329
5330ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5331 SourceLocation KWLoc,
5332 TypeSourceInfo *TSInfo,
5333 Expr* DimExpr,
5334 SourceLocation RParen) {
5335 QualType T = TSInfo->getType();
5336
5337 // FIXME: This should likely be tracked as an APInt to remove any host
5338 // assumptions about the width of size_t on the target.
5339 uint64_t Value = 0;
5340 if (!T->isDependentType())
5341 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5342
5343 // While the specification for these traits from the Embarcadero C++
5344 // compiler's documentation says the return type is 'unsigned int', Clang
5345 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5346 // compiler, there is no difference. On several other platforms this is an
5347 // important distinction.
5348 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5349 RParen, Context.getSizeType());
5350}
5351
5352ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5353 SourceLocation KWLoc,
5354 Expr *Queried,
5355 SourceLocation RParen) {
5356 // If error parsing the expression, ignore.
5357 if (!Queried)
5358 return ExprError();
5359
5360 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5361
5362 return Result;
5363}
5364
5365static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5366 switch (ET) {
5367 case ET_IsLValueExpr: return E->isLValue();
5368 case ET_IsRValueExpr: return E->isRValue();
5369 }
5370 llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5370)
;
5371}
5372
5373ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5374 SourceLocation KWLoc,
5375 Expr *Queried,
5376 SourceLocation RParen) {
5377 if (Queried->isTypeDependent()) {
5378 // Delay type-checking for type-dependent expressions.
5379 } else if (Queried->getType()->isPlaceholderType()) {
5380 ExprResult PE = CheckPlaceholderExpr(Queried);
5381 if (PE.isInvalid()) return ExprError();
5382 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5383 }
5384
5385 bool Value = EvaluateExpressionTrait(ET, Queried);
5386
5387 return new (Context)
5388 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5389}
5390
5391QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5392 ExprValueKind &VK,
5393 SourceLocation Loc,
5394 bool isIndirect) {
5395 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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5397, __PRETTY_FUNCTION__))
5396 !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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5397, __PRETTY_FUNCTION__))
5397 "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-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5397, __PRETTY_FUNCTION__))
;
5398
5399 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5400 // temporary materialization conversion otherwise.
5401 if (isIndirect)
5402 LHS = DefaultLvalueConversion(LHS.get());
5403 else if (LHS.get()->isRValue())
5404 LHS = TemporaryMaterializationConversion(LHS.get());
5405 if (LHS.isInvalid())
5406 return QualType();
5407
5408 // The RHS always undergoes lvalue conversions.
5409 RHS = DefaultLvalueConversion(RHS.get());
5410 if (RHS.isInvalid()) return QualType();
5411
5412 const char *OpSpelling = isIndirect ? "->*" : ".*";
5413 // C++ 5.5p2
5414 // The binary operator .* [p3: ->*] binds its second operand, which shall
5415 // be of type "pointer to member of T" (where T is a completely-defined
5416 // class type) [...]
5417 QualType RHSType = RHS.get()->getType();
5418 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5419 if (!MemPtr) {
5420 Diag(Loc, diag::err_bad_memptr_rhs)
5421 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5422 return QualType();
5423 }
5424
5425 QualType Class(MemPtr->getClass(), 0);
5426
5427 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5428 // member pointer points must be completely-defined. However, there is no
5429 // reason for this semantic distinction, and the rule is not enforced by
5430 // other compilers. Therefore, we do not check this property, as it is
5431 // likely to be considered a defect.
5432
5433 // C++ 5.5p2
5434 // [...] to its first operand, which shall be of class T or of a class of
5435 // which T is an unambiguous and accessible base class. [p3: a pointer to
5436 // such a class]
5437 QualType LHSType = LHS.get()->getType();
5438 if (isIndirect) {
5439 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5440 LHSType = Ptr->getPointeeType();
5441 else {
5442 Diag(Loc, diag::err_bad_memptr_lhs)
5443 << OpSpelling << 1 << LHSType
5444 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5445 return QualType();
5446 }
5447 }
5448
5449 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5450 // If we want to check the hierarchy, we need a complete type.
5451 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5452 OpSpelling, (int)isIndirect)) {
5453 return QualType();
5454 }
5455
5456 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5457 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5458 << (int)isIndirect << LHS.get()->getType();
5459 return QualType();
5460 }
5461
5462 CXXCastPath BasePath;
5463 if (CheckDerivedToBaseConversion(
5464 LHSType, Class, Loc,
5465 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5466 &BasePath))
5467 return QualType();
5468
5469 // Cast LHS to type of use.
5470 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5471 if (isIndirect)
5472 UseType = Context.getPointerType(UseType);
5473 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5474 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5475 &BasePath);
5476 }
5477
5478 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5479 // Diagnose use of pointer-to-member type which when used as
5480 // the functional cast in a pointer-to-member expression.
5481 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5482 return QualType();
5483 }
5484
5485 // C++ 5.5p2
5486 // The result is an object or a function of the type specified by the
5487 // second operand.
5488 // The cv qualifiers are the union of those in the pointer and the left side,
5489 // in accordance with 5.5p5 and 5.2.5.
5490 QualType Result = MemPtr->getPointeeType();
5491 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5492
5493 // C++0x [expr.mptr.oper]p6:
5494 // In a .* expression whose object expression is an rvalue, the program is
5495 // ill-formed if the second operand is a pointer to member function with
5496 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5497 // expression is an lvalue, the program is ill-formed if the second operand
5498 // is a pointer to member function with ref-qualifier &&.
5499 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5500 switch (Proto->getRefQualifier()) {
5501 case RQ_None:
5502 // Do nothing
5503 break;
5504
5505 case RQ_LValue:
5506 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5507 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5508 // is (exactly) 'const'.
5509 if (Proto->isConst() && !Proto->isVolatile())
5510 Diag(Loc, getLangOpts().CPlusPlus2a
5511 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5512 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5513 else
5514 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5515 << RHSType << 1 << LHS.get()->getSourceRange();
5516 }
5517 break;
5518
5519 case RQ_RValue:
5520 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5521 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5522 << RHSType << 0 << LHS.get()->getSourceRange();
5523 break;
5524 }
5525 }
5526
5527 // C++ [expr.mptr.oper]p6:
5528 // The result of a .* expression whose second operand is a pointer
5529 // to a data member is of the same value category as its
5530 // first operand. The result of a .* expression whose second
5531 // operand is a pointer to a member function is a prvalue. The
5532 // result of an ->* expression is an lvalue if its second operand
5533 // is a pointer to data member and a prvalue otherwise.
5534 if (Result->isFunctionType()) {
5535 VK = VK_RValue;
5536 return Context.BoundMemberTy;
5537 } else if (isIndirect) {
5538 VK = VK_LValue;
5539 } else {
5540 VK = LHS.get()->getValueKind();
5541 }
5542
5543 return Result;
5544}
5545
5546/// Try to convert a type to another according to C++11 5.16p3.
5547///
5548/// This is part of the parameter validation for the ? operator. If either
5549/// value operand is a class type, the two operands are attempted to be
5550/// converted to each other. This function does the conversion in one direction.
5551/// It returns true if the program is ill-formed and has already been diagnosed
5552/// as such.
5553static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5554 SourceLocation QuestionLoc,
5555 bool &HaveConversion,
5556 QualType &ToType) {
5557 HaveConversion = false;
5558 ToType = To->getType();
5559
5560 InitializationKind Kind =
5561 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
5562 // C++11 5.16p3
5563 // The process for determining whether an operand expression E1 of type T1
5564 // can be converted to match an operand expression E2 of type T2 is defined
5565 // as follows:
5566 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5567 // implicitly converted to type "lvalue reference to T2", subject to the
5568 // constraint that in the conversion the reference must bind directly to
5569 // an lvalue.
5570 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5571 // implicitly converted to the type "rvalue reference to R2", subject to
5572 // the constraint that the reference must bind directly.
5573 if (To->isLValue() || To->isXValue()) {
5574 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5575 : Self.Context.getRValueReferenceType(ToType);
5576
5577 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5578
5579 InitializationSequence InitSeq(Self, Entity, Kind, From);
5580 if (InitSeq.isDirectReferenceBinding()) {
5581 ToType = T;
5582 HaveConversion = true;
5583 return false;
5584 }
5585
5586 if (InitSeq.isAmbiguous())
5587 return InitSeq.Diagnose(Self, Entity, Kind, From);
5588 }
5589
5590 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5591 // -- if E1 and E2 have class type, and the underlying class types are
5592 // the same or one is a base class of the other:
5593 QualType FTy = From->getType();
5594 QualType TTy = To->getType();
5595 const RecordType *FRec = FTy->getAs<RecordType>();
5596 const RecordType *TRec = TTy->getAs<RecordType>();
5597 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5598 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5599 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5600 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5601 // E1 can be converted to match E2 if the class of T2 is the
5602 // same type as, or a base class of, the class of T1, and
5603 // [cv2 > cv1].
5604 if (FRec == TRec || FDerivedFromT) {
5605 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5606 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5607 InitializationSequence InitSeq(Self, Entity, Kind, From);
5608 if (InitSeq) {
5609 HaveConversion = true;
5610 return false;
5611 }
5612
5613 if (InitSeq.isAmbiguous())
5614 return InitSeq.Diagnose(Self, Entity, Kind, From);
5615 }
5616 }
5617
5618 return false;
5619 }
5620
5621 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5622 // implicitly converted to the type that expression E2 would have
5623 // if E2 were converted to an rvalue (or the type it has, if E2 is
5624 // an rvalue).
5625 //
5626 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5627 // to the array-to-pointer or function-to-pointer conversions.
5628 TTy = TTy.getNonLValueExprType(Self.Context);
5629
5630 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5631 InitializationSequence InitSeq(Self, Entity, Kind, From);
5632 HaveConversion = !InitSeq.Failed();
5633 ToType = TTy;
5634 if (InitSeq.isAmbiguous())
5635 return InitSeq.Diagnose(Self, Entity, Kind, From);
5636
5637 return false;
5638}
5639
5640/// Try to find a common type for two according to C++0x 5.16p5.
5641///
5642/// This is part of the parameter validation for the ? operator. If either
5643/// value operand is a class type, overload resolution is used to find a
5644/// conversion to a common type.
5645static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5646 SourceLocation QuestionLoc) {
5647 Expr *Args[2] = { LHS.get(), RHS.get() };
5648 OverloadCandidateSet CandidateSet(QuestionLoc,
5649 OverloadCandidateSet::CSK_Operator);
5650 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5651 CandidateSet);
5652
5653 OverloadCandidateSet::iterator Best;
5654 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5655 case OR_Success: {
5656 // We found a match. Perform the conversions on the arguments and move on.
5657 ExprResult LHSRes = Self.PerformImplicitConversion(
5658 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5659 Sema::AA_Converting);
5660 if (LHSRes.isInvalid())
5661 break;
5662 LHS = LHSRes;
5663
5664 ExprResult RHSRes = Self.PerformImplicitConversion(
5665 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5666 Sema::AA_Converting);
5667 if (RHSRes.isInvalid())
5668 break;
5669 RHS = RHSRes;
5670 if (Best->Function)
5671 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5672 return false;
5673 }
5674
5675 case OR_No_Viable_Function:
5676
5677 // Emit a better diagnostic if one of the expressions is a null pointer
5678 // constant and the other is a pointer type. In this case, the user most
5679 // likely forgot to take the address of the other expression.
5680 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5681 return true;
5682
5683 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5684 << LHS.get()->getType() << RHS.get()->getType()
5685 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5686 return true;
5687
5688 case OR_Ambiguous:
5689 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5690 << LHS.get()->getType() << RHS.get()->getType()
5691 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5692 // FIXME: Print the possible common types by printing the return types of
5693 // the viable candidates.
5694 break;
5695
5696 case OR_Deleted:
5697 llvm_unreachable("Conditional operator has only built-in overloads")::llvm::llvm_unreachable_internal("Conditional operator has only built-in overloads"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5697)
;
5698 }
5699 return true;
5700}
5701
5702/// Perform an "extended" implicit conversion as returned by
5703/// TryClassUnification.
5704static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5705 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5706 InitializationKind Kind =
5707 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
5708 Expr *Arg = E.get();
5709 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5710 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5711 if (Result.isInvalid())
5712 return true;
5713
5714 E = Result;
5715 return false;
5716}
5717
5718/// Check the operands of ?: under C++ semantics.
5719///
5720/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5721/// extension. In this case, LHS == Cond. (But they're not aliases.)
5722QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5723 ExprResult &RHS, ExprValueKind &VK,
5724 ExprObjectKind &OK,
5725 SourceLocation QuestionLoc) {
5726 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5727 // interface pointers.
5728
5729 // C++11 [expr.cond]p1
5730 // The first expression is contextually converted to bool.
5731 //
5732 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5733 // a is that of a integer vector with the same number of elements and
5734 // size as the vectors of b and c. If one of either b or c is a scalar
5735 // it is implicitly converted to match the type of the vector.
5736 // Otherwise the expression is ill-formed. If both b and c are scalars,
5737 // then b and c are checked and converted to the type of a if possible.
5738 // Unlike the OpenCL ?: operator, the expression is evaluated as
5739 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5740 if (!Cond.get()->isTypeDependent()) {
5741 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5742 if (CondRes.isInvalid())
5743 return QualType();
5744 Cond = CondRes;
5745 }
5746
5747 // Assume r-value.
5748 VK = VK_RValue;
5749 OK = OK_Ordinary;
5750
5751 // Either of the arguments dependent?
5752 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5753 return Context.DependentTy;
5754
5755 // C++11 [expr.cond]p2
5756 // If either the second or the third operand has type (cv) void, ...
5757 QualType LTy = LHS.get()->getType();
5758 QualType RTy = RHS.get()->getType();
5759 bool LVoid = LTy->isVoidType();
5760 bool RVoid = RTy->isVoidType();
5761 if (LVoid || RVoid) {
5762 // ... one of the following shall hold:
5763 // -- The second or the third operand (but not both) is a (possibly
5764 // parenthesized) throw-expression; the result is of the type
5765 // and value category of the other.
5766 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5767 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5768 if (LThrow != RThrow) {
5769 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5770 VK = NonThrow->getValueKind();
5771 // DR (no number yet): the result is a bit-field if the
5772 // non-throw-expression operand is a bit-field.
5773 OK = NonThrow->getObjectKind();
5774 return NonThrow->getType();
5775 }
5776
5777 // -- Both the second and third operands have type void; the result is of
5778 // type void and is a prvalue.
5779 if (LVoid && RVoid)
5780 return Context.VoidTy;
5781
5782 // Neither holds, error.
5783 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5784 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5785 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5786 return QualType();
5787 }
5788
5789 // Neither is void.
5790
5791 // C++11 [expr.cond]p3
5792 // Otherwise, if the second and third operand have different types, and
5793 // either has (cv) class type [...] an attempt is made to convert each of
5794 // those operands to the type of the other.
5795 if (!Context.hasSameType(LTy, RTy) &&
5796 (LTy->isRecordType() || RTy->isRecordType())) {
5797 // These return true if a single direction is already ambiguous.
5798 QualType L2RType, R2LType;
5799 bool HaveL2R, HaveR2L;
5800 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5801 return QualType();
5802 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5803 return QualType();
5804
5805 // If both can be converted, [...] the program is ill-formed.
5806 if (HaveL2R && HaveR2L) {
5807 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5808 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5809 return QualType();
5810 }
5811
5812 // If exactly one conversion is possible, that conversion is applied to
5813 // the chosen operand and the converted operands are used in place of the
5814 // original operands for the remainder of this section.
5815 if (HaveL2R) {
5816 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5817 return QualType();
5818 LTy = LHS.get()->getType();
5819 } else if (HaveR2L) {
5820 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5821 return QualType();
5822 RTy = RHS.get()->getType();
5823 }
5824 }
5825
5826 // C++11 [expr.cond]p3
5827 // if both are glvalues of the same value category and the same type except
5828 // for cv-qualification, an attempt is made to convert each of those
5829 // operands to the type of the other.
5830 // FIXME:
5831 // Resolving a defect in P0012R1: we extend this to cover all cases where
5832 // one of the operands is reference-compatible with the other, in order
5833 // to support conditionals between functions differing in noexcept.
5834 ExprValueKind LVK = LHS.get()->getValueKind();
5835 ExprValueKind RVK = RHS.get()->getValueKind();
5836 if (!Context.hasSameType(LTy, RTy) &&
5837 LVK == RVK && LVK != VK_RValue) {
5838 // DerivedToBase was already handled by the class-specific case above.
5839 // FIXME: Should we allow ObjC conversions here?
5840 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5841 if (CompareReferenceRelationship(
5842 QuestionLoc, LTy, RTy, DerivedToBase,
5843 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5844 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5845 // [...] subject to the constraint that the reference must bind
5846 // directly [...]
5847 !RHS.get()->refersToBitField() &&
5848 !RHS.get()->refersToVectorElement()) {
5849 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5850 RTy = RHS.get()->getType();
5851 } else if (CompareReferenceRelationship(
5852 QuestionLoc, RTy, LTy, DerivedToBase,
5853 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5854 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5855 !LHS.get()->refersToBitField() &&
5856 !LHS.get()->refersToVectorElement()) {
5857 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5858 LTy = LHS.get()->getType();
5859 }
5860 }
5861
5862 // C++11 [expr.cond]p4
5863 // If the second and third operands are glvalues of the same value
5864 // category and have the same type, the result is of that type and
5865 // value category and it is a bit-field if the second or the third
5866 // operand is a bit-field, or if both are bit-fields.
5867 // We only extend this to bitfields, not to the crazy other kinds of
5868 // l-values.
5869 bool Same = Context.hasSameType(LTy, RTy);
5870 if (Same && LVK == RVK && LVK != VK_RValue &&
5871 LHS.get()->isOrdinaryOrBitFieldObject() &&
5872 RHS.get()->isOrdinaryOrBitFieldObject()) {
5873 VK = LHS.get()->getValueKind();
5874 if (LHS.get()->getObjectKind() == OK_BitField ||
5875 RHS.get()->getObjectKind() == OK_BitField)
5876 OK = OK_BitField;
5877
5878 // If we have function pointer types, unify them anyway to unify their
5879 // exception specifications, if any.
5880 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5881 Qualifiers Qs = LTy.getQualifiers();
5882 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS,
5883 /*ConvertArgs*/false);
5884 LTy = Context.getQualifiedType(LTy, Qs);
5885
5886 assert(!LTy.isNull() && "failed to find composite pointer type for "((!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? static_cast<
void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5887, __PRETTY_FUNCTION__))
5887 "canonically equivalent function ptr types")((!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? static_cast<
void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5887, __PRETTY_FUNCTION__))
;
5888 assert(Context.hasSameType(LTy, RTy) && "bad composite pointer type")((Context.hasSameType(LTy, RTy) && "bad composite pointer type"
) ? static_cast<void> (0) : __assert_fail ("Context.hasSameType(LTy, RTy) && \"bad composite pointer type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5888, __PRETTY_FUNCTION__))
;
5889 }
5890
5891 return LTy;
5892 }
5893
5894 // C++11 [expr.cond]p5
5895 // Otherwise, the result is a prvalue. If the second and third operands
5896 // do not have the same type, and either has (cv) class type, ...
5897 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5898 // ... overload resolution is used to determine the conversions (if any)
5899 // to be applied to the operands. If the overload resolution fails, the
5900 // program is ill-formed.
5901 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5902 return QualType();
5903 }
5904
5905 // C++11 [expr.cond]p6
5906 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5907 // conversions are performed on the second and third operands.
5908 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5909 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5910 if (LHS.isInvalid() || RHS.isInvalid())
5911 return QualType();
5912 LTy = LHS.get()->getType();
5913 RTy = RHS.get()->getType();
5914
5915 // After those conversions, one of the following shall hold:
5916 // -- The second and third operands have the same type; the result
5917 // is of that type. If the operands have class type, the result
5918 // is a prvalue temporary of the result type, which is
5919 // copy-initialized from either the second operand or the third
5920 // operand depending on the value of the first operand.
5921 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5922 if (LTy->isRecordType()) {
5923 // The operands have class type. Make a temporary copy.
5924 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5925
5926 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5927 SourceLocation(),
5928 LHS);
5929 if (LHSCopy.isInvalid())
5930 return QualType();
5931
5932 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5933 SourceLocation(),
5934 RHS);
5935 if (RHSCopy.isInvalid())
5936 return QualType();
5937
5938 LHS = LHSCopy;
5939 RHS = RHSCopy;
5940 }
5941
5942 // If we have function pointer types, unify them anyway to unify their
5943 // exception specifications, if any.
5944 if (LTy->isFunctionPointerType() || LTy->isMemberFunctionPointerType()) {
5945 LTy = FindCompositePointerType(QuestionLoc, LHS, RHS);
5946 assert(!LTy.isNull() && "failed to find composite pointer type for "((!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? static_cast<
void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5947, __PRETTY_FUNCTION__))
5947 "canonically equivalent function ptr types")((!LTy.isNull() && "failed to find composite pointer type for "
"canonically equivalent function ptr types") ? static_cast<
void> (0) : __assert_fail ("!LTy.isNull() && \"failed to find composite pointer type for \" \"canonically equivalent function ptr types\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5947, __PRETTY_FUNCTION__))
;
5948 }
5949
5950 return LTy;
5951 }
5952
5953 // Extension: conditional operator involving vector types.
5954 if (LTy->isVectorType() || RTy->isVectorType())
5955 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5956 /*AllowBothBool*/true,
5957 /*AllowBoolConversions*/false);
5958
5959 // -- The second and third operands have arithmetic or enumeration type;
5960 // the usual arithmetic conversions are performed to bring them to a
5961 // common type, and the result is of that type.
5962 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5963 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5964 if (LHS.isInvalid() || RHS.isInvalid())
5965 return QualType();
5966 if (ResTy.isNull()) {
5967 Diag(QuestionLoc,
5968 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5969 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5970 return QualType();
5971 }
5972
5973 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5974 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5975
5976 return ResTy;
5977 }
5978
5979 // -- The second and third operands have pointer type, or one has pointer
5980 // type and the other is a null pointer constant, or both are null
5981 // pointer constants, at least one of which is non-integral; pointer
5982 // conversions and qualification conversions are performed to bring them
5983 // to their composite pointer type. The result is of the composite
5984 // pointer type.
5985 // -- The second and third operands have pointer to member type, or one has
5986 // pointer to member type and the other is a null pointer constant;
5987 // pointer to member conversions and qualification conversions are
5988 // performed to bring them to a common type, whose cv-qualification
5989 // shall match the cv-qualification of either the second or the third
5990 // operand. The result is of the common type.
5991 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
5992 if (!Composite.isNull())
5993 return Composite;
5994
5995 // Similarly, attempt to find composite type of two objective-c pointers.
5996 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5997 if (!Composite.isNull())
5998 return Composite;
5999
6000 // Check if we are using a null with a non-pointer type.
6001 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6002 return QualType();
6003
6004 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6005 << LHS.get()->getType() << RHS.get()->getType()
6006 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6007 return QualType();
6008}
6009
6010static FunctionProtoType::ExceptionSpecInfo
6011mergeExceptionSpecs(Sema &S, FunctionProtoType::ExceptionSpecInfo ESI1,
6012 FunctionProtoType::ExceptionSpecInfo ESI2,
6013 SmallVectorImpl<QualType> &ExceptionTypeStorage) {
6014 ExceptionSpecificationType EST1 = ESI1.Type;
6015 ExceptionSpecificationType EST2 = ESI2.Type;
6016
6017 // If either of them can throw anything, that is the result.
6018 if (EST1 == EST_None) return ESI1;
6019 if (EST2 == EST_None) return ESI2;
6020 if (EST1 == EST_MSAny) return ESI1;
6021 if (EST2 == EST_MSAny) return ESI2;
6022 if (EST1 == EST_NoexceptFalse) return ESI1;
6023 if (EST2 == EST_NoexceptFalse) return ESI2;
6024
6025 // If either of them is non-throwing, the result is the other.
6026 if (EST1 == EST_NoThrow) return ESI2;
6027 if (EST2 == EST_NoThrow) return ESI1;
6028 if (EST1 == EST_DynamicNone) return ESI2;
6029 if (EST2 == EST_DynamicNone) return ESI1;
6030 if (EST1 == EST_BasicNoexcept) return ESI2;
6031 if (EST2 == EST_BasicNoexcept) return ESI1;
6032 if (EST1 == EST_NoexceptTrue) return ESI2;
6033 if (EST2 == EST_NoexceptTrue) return ESI1;
6034
6035 // If we're left with value-dependent computed noexcept expressions, we're
6036 // stuck. Before C++17, we can just drop the exception specification entirely,
6037 // since it's not actually part of the canonical type. And this should never
6038 // happen in C++17, because it would mean we were computing the composite
6039 // pointer type of dependent types, which should never happen.
6040 if (EST1 == EST_DependentNoexcept || EST2 == EST_DependentNoexcept) {
6041 assert(!S.getLangOpts().CPlusPlus17 &&((!S.getLangOpts().CPlusPlus17 && "computing composite pointer type of dependent types"
) ? static_cast<void> (0) : __assert_fail ("!S.getLangOpts().CPlusPlus17 && \"computing composite pointer type of dependent types\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6042, __PRETTY_FUNCTION__))
6042 "computing composite pointer type of dependent types")((!S.getLangOpts().CPlusPlus17 && "computing composite pointer type of dependent types"
) ? static_cast<void> (0) : __assert_fail ("!S.getLangOpts().CPlusPlus17 && \"computing composite pointer type of dependent types\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6042, __PRETTY_FUNCTION__))
;
6043 return FunctionProtoType::ExceptionSpecInfo();
6044 }
6045
6046 // Switch over the possibilities so that people adding new values know to
6047 // update this function.
6048 switch (EST1) {
6049 case EST_None:
6050 case EST_DynamicNone:
6051 case EST_MSAny:
6052 case EST_BasicNoexcept:
6053 case EST_DependentNoexcept:
6054 case EST_NoexceptFalse:
6055 case EST_NoexceptTrue:
6056 case EST_NoThrow:
6057 llvm_unreachable("handled above")::llvm::llvm_unreachable_internal("handled above", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6057)
;
6058
6059 case EST_Dynamic: {
6060 // This is the fun case: both exception specifications are dynamic. Form
6061 // the union of the two lists.
6062 assert(EST2 == EST_Dynamic && "other cases should already be handled")((EST2 == EST_Dynamic && "other cases should already be handled"
) ? static_cast<void> (0) : __assert_fail ("EST2 == EST_Dynamic && \"other cases should already be handled\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6062, __PRETTY_FUNCTION__))
;
6063 llvm::SmallPtrSet<QualType, 8> Found;
6064 for (auto &Exceptions : {ESI1.Exceptions, ESI2.Exceptions})
6065 for (QualType E : Exceptions)
6066 if (Found.insert(S.Context.getCanonicalType(E)).second)
6067 ExceptionTypeStorage.push_back(E);
6068
6069 FunctionProtoType::ExceptionSpecInfo Result(EST_Dynamic);
6070 Result.Exceptions = ExceptionTypeStorage;
6071 return Result;
6072 }
6073
6074 case EST_Unevaluated:
6075 case EST_Uninstantiated:
6076 case EST_Unparsed:
6077 llvm_unreachable("shouldn't see unresolved exception specifications here")::llvm::llvm_unreachable_internal("shouldn't see unresolved exception specifications here"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6077)
;
6078 }
6079
6080 llvm_unreachable("invalid ExceptionSpecificationType")::llvm::llvm_unreachable_internal("invalid ExceptionSpecificationType"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6080)
;
6081}
6082
6083/// Find a merged pointer type and convert the two expressions to it.
6084///
6085/// This finds the composite pointer type (or member pointer type) for @p E1
6086/// and @p E2 according to C++1z 5p14. It converts both expressions to this
6087/// type and returns it.
6088/// It does not emit diagnostics.
6089///
6090/// \param Loc The location of the operator requiring these two expressions to
6091/// be converted to the composite pointer type.
6092///
6093/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6094QualType Sema::FindCompositePointerType(SourceLocation Loc,
6095 Expr *&E1, Expr *&E2,
6096 bool ConvertArgs) {
6097 assert(getLangOpts().CPlusPlus && "This function assumes C++")((getLangOpts().CPlusPlus && "This function assumes C++"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"This function assumes C++\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6097, __PRETTY_FUNCTION__))
;
6098
6099 // C++1z [expr]p14:
6100 // The composite pointer type of two operands p1 and p2 having types T1
6101 // and T2
6102 QualType T1 = E1->getType(), T2 = E2->getType();
6103
6104 // where at least one is a pointer or pointer to member type or
6105 // std::nullptr_t is:
6106 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6107 T1->isNullPtrType();
6108 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6109 T2->isNullPtrType();
6110 if (!T1IsPointerLike && !T2IsPointerLike)
6111 return QualType();
6112
6113 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6114 // This can't actually happen, following the standard, but we also use this
6115 // to implement the end of [expr.conv], which hits this case.
6116 //
6117 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6118 if (T1IsPointerLike &&
6119 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6120 if (ConvertArgs)
6121 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6122 ? CK_NullToMemberPointer
6123 : CK_NullToPointer).get();
6124 return T1;
6125 }
6126 if (T2IsPointerLike &&
6127 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6128 if (ConvertArgs)
6129 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6130 ? CK_NullToMemberPointer
6131 : CK_NullToPointer).get();
6132 return T2;
6133 }
6134
6135 // Now both have to be pointers or member pointers.
6136 if (!T1IsPointerLike || !T2IsPointerLike)
6137 return QualType();
6138 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&((!T1->isNullPtrType() && !T2->isNullPtrType() &&
"nullptr_t should be a null pointer constant") ? static_cast
<void> (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6139, __PRETTY_FUNCTION__))
6139 "nullptr_t should be a null pointer constant")((!T1->isNullPtrType() && !T2->isNullPtrType() &&
"nullptr_t should be a null pointer constant") ? static_cast
<void> (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6139, __PRETTY_FUNCTION__))
;
6140
6141 // - if T1 or T2 is "pointer to cv1 void" and the other type is
6142 // "pointer to cv2 T", "pointer to cv12 void", where cv12 is
6143 // the union of cv1 and cv2;
6144 // - if T1 or T2 is "pointer to noexcept function" and the other type is
6145 // "pointer to function", where the function types are otherwise the same,
6146 // "pointer to function";
6147 // FIXME: This rule is defective: it should also permit removing noexcept
6148 // from a pointer to member function. As a Clang extension, we also
6149 // permit removing 'noreturn', so we generalize this rule to;
6150 // - [Clang] If T1 and T2 are both of type "pointer to function" or
6151 // "pointer to member function" and the pointee types can be unified
6152 // by a function pointer conversion, that conversion is applied
6153 // before checking the following rules.
6154 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6155 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6156 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6157 // respectively;
6158 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6159 // to member of C2 of type cv2 U2" where C1 is reference-related to C2 or
6160 // C2 is reference-related to C1 (8.6.3), the cv-combined type of T2 and
6161 // T1 or the cv-combined type of T1 and T2, respectively;
6162 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6163 // T2;
6164 //
6165 // If looked at in the right way, these bullets all do the same thing.
6166 // What we do here is, we build the two possible cv-combined types, and try
6167 // the conversions in both directions. If only one works, or if the two
6168 // composite types are the same, we have succeeded.
6169 // FIXME: extended qualifiers?
6170 //
6171 // Note that this will fail to find a composite pointer type for "pointer
6172 // to void" and "pointer to function". We can't actually perform the final
6173 // conversion in this case, even though a composite pointer type formally
6174 // exists.
6175 SmallVector<unsigned, 4> QualifierUnion;
6176 SmallVector<std::pair<const Type *, const Type *>, 4> MemberOfClass;
6177 QualType Composite1 = T1;
6178 QualType Composite2 = T2;
6179 unsigned NeedConstBefore = 0;
6180 while (true) {
6181 const PointerType *Ptr1, *Ptr2;
6182 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6183 (Ptr2 = Composite2->getAs<PointerType>())) {
6184 Composite1 = Ptr1->getPointeeType();
6185 Composite2 = Ptr2->getPointeeType();
6186
6187 // If we're allowed to create a non-standard composite type, keep track
6188 // of where we need to fill in additional 'const' qualifiers.
6189 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
6190 NeedConstBefore = QualifierUnion.size();
6191
6192 QualifierUnion.push_back(
6193 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6194 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
6195 continue;
6196 }
6197
6198 const MemberPointerType *MemPtr1, *MemPtr2;
6199 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6200 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6201 Composite1 = MemPtr1->getPointeeType();
6202 Composite2 = MemPtr2->getPointeeType();
6203
6204 // If we're allowed to create a non-standard composite type, keep track
6205 // of where we need to fill in additional 'const' qualifiers.
6206 if (Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
6207 NeedConstBefore = QualifierUnion.size();
6208
6209 QualifierUnion.push_back(
6210 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
6211 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
6212 MemPtr2->getClass()));
6213 continue;
6214 }
6215
6216 // FIXME: block pointer types?
6217
6218 // Cannot unwrap any more types.
6219 break;
6220 }
6221
6222 // Apply the function pointer conversion to unify the types. We've already
6223 // unwrapped down to the function types, and we want to merge rather than
6224 // just convert, so do this ourselves rather than calling
6225 // IsFunctionConversion.
6226 //
6227 // FIXME: In order to match the standard wording as closely as possible, we
6228 // currently only do this under a single level of pointers. Ideally, we would
6229 // allow this in general, and set NeedConstBefore to the relevant depth on
6230 // the side(s) where we changed anything.
6231 if (QualifierUnion.size() == 1) {
6232 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
6233 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
6234 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
6235 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
6236
6237 // The result is noreturn if both operands are.
6238 bool Noreturn =
6239 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
6240 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
6241 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
6242
6243 // The result is nothrow if both operands are.
6244 SmallVector<QualType, 8> ExceptionTypeStorage;
6245 EPI1.ExceptionSpec = EPI2.ExceptionSpec =
6246 mergeExceptionSpecs(*this, EPI1.ExceptionSpec, EPI2.ExceptionSpec,
6247 ExceptionTypeStorage);
6248
6249 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
6250 FPT1->getParamTypes(), EPI1);
6251 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
6252 FPT2->getParamTypes(), EPI2);
6253 }
6254 }
6255 }
6256
6257 if (NeedConstBefore) {
6258 // Extension: Add 'const' to qualifiers that come before the first qualifier
6259 // mismatch, so that our (non-standard!) composite type meets the
6260 // requirements of C++ [conv.qual]p4 bullet 3.
6261 for (unsigned I = 0; I != NeedConstBefore; ++I)
6262 if ((QualifierUnion[I] & Qualifiers::Const) == 0)
6263 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
6264 }
6265
6266 // Rewrap the composites as pointers or member pointers with the union CVRs.
6267 auto MOC = MemberOfClass.rbegin();
6268 for (unsigned CVR : llvm::reverse(QualifierUnion)) {
6269 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
6270 auto Classes = *MOC++;
6271 if (Classes.first && Classes.second) {
6272 // Rebuild member pointer type
6273 Composite1 = Context.getMemberPointerType(
6274 Context.getQualifiedType(Composite1, Quals), Classes.first);
6275 Composite2 = Context.getMemberPointerType(
6276 Context.getQualifiedType(Composite2, Quals), Classes.second);
6277 } else {
6278 // Rebuild pointer type
6279 Composite1 =
6280 Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
6281 Composite2 =
6282 Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
6283 }
6284 }
6285
6286 struct Conversion {
6287 Sema &S;
6288 Expr *&E1, *&E2;
6289 QualType Composite;
6290 InitializedEntity Entity;
6291 InitializationKind Kind;
6292 InitializationSequence E1ToC, E2ToC;
6293 bool Viable;
6294
6295 Conversion(Sema &S, SourceLocation Loc, Expr *&E1, Expr *&E2,
6296 QualType Composite)
6297 : S(S), E1(E1), E2(E2), Composite(Composite),
6298 Entity(InitializedEntity::InitializeTemporary(Composite)),
6299 Kind(InitializationKind::CreateCopy(Loc, SourceLocation())),
6300 E1ToC(S, Entity, Kind, E1), E2ToC(S, Entity, Kind, E2),
6301 Viable(E1ToC && E2ToC) {}
6302
6303 bool perform() {
6304 ExprResult E1Result = E1ToC.Perform(S, Entity, Kind, E1);
6305 if (E1Result.isInvalid())
6306 return true;
6307 E1 = E1Result.getAs<Expr>();
6308
6309 ExprResult E2Result = E2ToC.Perform(S, Entity, Kind, E2);
6310 if (E2Result.isInvalid())
6311 return true;
6312 E2 = E2Result.getAs<Expr>();
6313
6314 return false;
6315 }
6316 };
6317
6318 // Try to convert to each composite pointer type.
6319 Conversion C1(*this, Loc, E1, E2, Composite1);
6320 if (C1.Viable && Context.hasSameType(Composite1, Composite2)) {
6321 if (ConvertArgs && C1.perform())
6322 return QualType();
6323 return C1.Composite;
6324 }
6325 Conversion C2(*this, Loc, E1, E2, Composite2);
6326
6327 if (C1.Viable == C2.Viable) {
6328 // Either Composite1 and Composite2 are viable and are different, or
6329 // neither is viable.
6330 // FIXME: How both be viable and different?
6331 return QualType();
6332 }
6333
6334 // Convert to the chosen type.
6335 if (ConvertArgs && (C1.Viable ? C1 : C2).perform())
6336 return QualType();
6337
6338 return C1.Viable ? C1.Composite : C2.Composite;
6339}
6340
6341ExprResult Sema::MaybeBindToTemporary(Expr *E) {
6342 if (!E)
6343 return ExprError();
6344
6345 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?")((!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"
) ? static_cast<void> (0) : __assert_fail ("!isa<CXXBindTemporaryExpr>(E) && \"Double-bound temporary?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6345, __PRETTY_FUNCTION__))
;
6346
6347 // If the result is a glvalue, we shouldn't bind it.
6348 if (!E->isRValue())
6349 return E;
6350
6351 // In ARC, calls that return a retainable type can return retained,
6352 // in which case we have to insert a consuming cast.
6353 if (getLangOpts().ObjCAutoRefCount &&
6354 E->getType()->isObjCRetainableType()) {
6355
6356 bool ReturnsRetained;
6357
6358 // For actual calls, we compute this by examining the type of the
6359 // called value.
6360 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
6361 Expr *Callee = Call->getCallee()->IgnoreParens();
6362 QualType T = Callee->getType();
6363
6364 if (T == Context.BoundMemberTy) {
6365 // Handle pointer-to-members.
6366 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
6367 T = BinOp->getRHS()->getType();
6368 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
6369 T = Mem->getMemberDecl()->getType();
6370 }
6371
6372 if (const PointerType *Ptr = T->getAs<PointerType>())
6373 T = Ptr->getPointeeType();
6374 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
6375 T = Ptr->getPointeeType();
6376 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
6377 T = MemPtr->getPointeeType();
6378
6379 const FunctionType *FTy = T->getAs<FunctionType>();
6380 assert(FTy && "call to value not of function type?")((FTy && "call to value not of function type?") ? static_cast
<void> (0) : __assert_fail ("FTy && \"call to value not of function type?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6380, __PRETTY_FUNCTION__))
;
6381 ReturnsRetained = FTy->getExtInfo().getProducesResult();
6382
6383 // ActOnStmtExpr arranges things so that StmtExprs of retainable
6384 // type always produce a +1 object.
6385 } else if (isa<StmtExpr>(E)) {
6386 ReturnsRetained = true;
6387
6388 // We hit this case with the lambda conversion-to-block optimization;
6389 // we don't want any extra casts here.
6390 } else if (isa<CastExpr>(E) &&
6391 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
6392 return E;
6393
6394 // For message sends and property references, we try to find an
6395 // actual method. FIXME: we should infer retention by selector in
6396 // cases where we don't have an actual method.
6397 } else {
6398 ObjCMethodDecl *D = nullptr;
6399 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
6400 D = Send->getMethodDecl();
6401 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
6402 D = BoxedExpr->getBoxingMethod();
6403 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
6404 // Don't do reclaims if we're using the zero-element array
6405 // constant.
6406 if (ArrayLit->getNumElements() == 0 &&
6407 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6408 return E;
6409
6410 D = ArrayLit->getArrayWithObjectsMethod();
6411 } else if (ObjCDictionaryLiteral *DictLit
6412 = dyn_cast<ObjCDictionaryLiteral>(E)) {
6413 // Don't do reclaims if we're using the zero-element dictionary
6414 // constant.
6415 if (DictLit->getNumElements() == 0 &&
6416 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
6417 return E;
6418
6419 D = DictLit->getDictWithObjectsMethod();
6420 }
6421
6422 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
6423
6424 // Don't do reclaims on performSelector calls; despite their
6425 // return type, the invoked method doesn't necessarily actually
6426 // return an object.
6427 if (!ReturnsRetained &&
6428 D && D->getMethodFamily() == OMF_performSelector)
6429 return E;
6430 }
6431
6432 // Don't reclaim an object of Class type.
6433 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
6434 return E;
6435
6436 Cleanup.setExprNeedsCleanups(true);
6437
6438 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
6439 : CK_ARCReclaimReturnedObject);
6440 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
6441 VK_RValue);
6442 }
6443
6444 if (!getLangOpts().CPlusPlus)
6445 return E;
6446
6447 // Search for the base element type (cf. ASTContext::getBaseElementType) with
6448 // a fast path for the common case that the type is directly a RecordType.
6449 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
6450 const RecordType *RT = nullptr;
6451 while (!RT) {
6452 switch (T->getTypeClass()) {
6453 case Type::Record:
6454 RT = cast<RecordType>(T);
6455 break;
6456 case Type::ConstantArray:
6457 case Type::IncompleteArray:
6458 case Type::VariableArray:
6459 case Type::DependentSizedArray:
6460 T = cast<ArrayType>(T)->getElementType().getTypePtr();
6461 break;
6462 default:
6463 return E;
6464 }
6465 }
6466
6467 // That should be enough to guarantee that this type is complete, if we're
6468 // not processing a decltype expression.
6469 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6470 if (RD->isInvalidDecl() || RD->isDependentContext())
6471 return E;
6472
6473 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
6474 ExpressionEvaluationContextRecord::EK_Decltype;
6475 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
6476
6477 if (Destructor) {
6478 MarkFunctionReferenced(E->getExprLoc(), Destructor);
6479 CheckDestructorAccess(E->getExprLoc(), Destructor,
6480 PDiag(diag::err_access_dtor_temp)
6481 << E->getType());
6482 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
6483 return ExprError();
6484
6485 // If destructor is trivial, we can avoid the extra copy.
6486 if (Destructor->isTrivial())
6487 return E;
6488
6489 // We need a cleanup, but we don't need to remember the temporary.
6490 Cleanup.setExprNeedsCleanups(true);
6491 }
6492
6493 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
6494 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
6495
6496 if (IsDecltype)
6497 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
6498
6499 return Bind;
6500}
6501
6502ExprResult
6503Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
6504 if (SubExpr.isInvalid())
6505 return ExprError();
6506
6507 return MaybeCreateExprWithCleanups(SubExpr.get());
6508}
6509
6510Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
6511 assert(SubExpr && "subexpression can't be null!")((SubExpr && "subexpression can't be null!") ? static_cast
<void> (0) : __assert_fail ("SubExpr && \"subexpression can't be null!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6511, __PRETTY_FUNCTION__))
;
6512
6513 CleanupVarDeclMarking();
6514
6515 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
6516 assert(ExprCleanupObjects.size() >= FirstCleanup)((ExprCleanupObjects.size() >= FirstCleanup) ? static_cast
<void> (0) : __assert_fail ("ExprCleanupObjects.size() >= FirstCleanup"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6516, __PRETTY_FUNCTION__))
;
6517 assert(Cleanup.exprNeedsCleanups() ||((Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() ==
FirstCleanup) ? static_cast<void> (0) : __assert_fail (
"Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6518, __PRETTY_FUNCTION__))
6518 ExprCleanupObjects.size() == FirstCleanup)((Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() ==
FirstCleanup) ? static_cast<void> (0) : __assert_fail (
"Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6518, __PRETTY_FUNCTION__))
;
6519 if (!Cleanup.exprNeedsCleanups())
6520 return SubExpr;
6521
6522 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
6523 ExprCleanupObjects.size() - FirstCleanup);
6524
6525 auto *E = ExprWithCleanups::Create(
6526 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
6527 DiscardCleanupsInEvaluationContext();
6528
6529 return E;
6530}
6531
6532Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
6533 assert(SubStmt && "sub-statement can't be null!")((SubStmt && "sub-statement can't be null!") ? static_cast
<void> (0) : __assert_fail ("SubStmt && \"sub-statement can't be null!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6533, __PRETTY_FUNCTION__))
;
6534
6535 CleanupVarDeclMarking();
6536
6537 if (!Cleanup.exprNeedsCleanups())
6538 return SubStmt;
6539
6540 // FIXME: In order to attach the temporaries, wrap the statement into
6541 // a StmtExpr; currently this is only used for asm statements.
6542 // This is hacky, either create a new CXXStmtWithTemporaries statement or
6543 // a new AsmStmtWithTemporaries.
6544 CompoundStmt *CompStmt = CompoundStmt::Create(
6545 Context, SubStmt, SourceLocation(), SourceLocation());
6546 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
6547 SourceLocation());
6548 return MaybeCreateExprWithCleanups(E);
6549}
6550
6551/// Process the expression contained within a decltype. For such expressions,
6552/// certain semantic checks on temporaries are delayed until this point, and
6553/// are omitted for the 'topmost' call in the decltype expression. If the
6554/// topmost call bound a temporary, strip that temporary off the expression.
6555ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
6556 assert(ExprEvalContexts.back().ExprContext ==((ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord
::EK_Decltype && "not in a decltype expression") ? static_cast
<void> (0) : __assert_fail ("ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6558, __PRETTY_FUNCTION__))
6557 ExpressionEvaluationContextRecord::EK_Decltype &&((ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord
::EK_Decltype && "not in a decltype expression") ? static_cast
<void> (0) : __assert_fail ("ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6558, __PRETTY_FUNCTION__))
6558 "not in a decltype expression")((ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord
::EK_Decltype && "not in a decltype expression") ? static_cast
<void> (0) : __assert_fail ("ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 6558, __PRETTY_FUNCTION__))
;
6559
6560 ExprResult Result = CheckPlaceholderExpr(E);
6561 if (Result.isInvalid())
6562 return ExprError();
6563 E = Result.get();
6564
6565 // C++11 [expr.call]p11:
6566 // If a function call is a prvalue of object type,
6567 // -- if the function call is either
6568 // -- the operand of a decltype-specifier, or
6569 // -- the right operand of a comma operator that is the operand of a
6570 // decltype-specifier,
6571 // a temporary object is not introduced for the prvalue.
6572
6573 // Recursively rebuild ParenExprs and comma expressions to strip out the
6574 // outermost CXXBindTemporaryExpr, if any.
6575 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
6576 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
6577 if (SubExpr.isInvalid())
6578 return ExprError();
6579 if (SubExpr.get() == PE->getSubExpr())
6580 return E;
6581 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
6582 }
6583 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6584 if (BO->getOpcode() == BO_Comma) {
6585 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
6586 if (RHS.isInvalid())
6587 return ExprError();
6588 if (RHS.get() == BO->getRHS())
6589 return E;
6590 return new (Context) BinaryOperator(
6591 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
6592 BO->getObjectKind(), BO->getOperatorLoc(), BO->getFPFeatures());
6593 }
6594 }
6595
6596 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
6597 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
6598 : nullptr;
6599 if (TopCall)
6600 E = TopCall;
6601 else
6602 TopBind = nullptr;
6603
6604 // Disable the special decltype handling now.
6605 ExprEvalContexts.back().ExprContext =
6606 ExpressionEvaluationContextRecord::EK_Other;
6607
6608 // In MS mode, don't perform any extra checking of call return types within a
6609 // decltype expression.
6610 if (getLangOpts().MSVCCompat)
6611 return E;
6612
6613 // Perform the semantic checks we delayed until this point.
6614 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
6615 I != N; ++I) {
6616 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
6617 if (Call == TopCall)
6618 continue;
6619
6620 if (CheckCallReturnType(Call->getCallReturnType(Context),
6621 Call->getBeginLoc(), Call, Call->getDirectCallee()))
6622 return ExprError();
6623 }
6624
6625 // Now all relevant types are complete, check the destructors are accessible
6626 // and non-deleted, and annotate them on the temporaries.
6627 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
6628 I != N; ++I) {
6629 CXXBindTemporaryExpr *Bind =
6630 ExprEvalContexts.back().DelayedDecltypeBinds[I];
6631 if (Bind == TopBind)
6632 continue;
6633
6634 CXXTemporary *Temp = Bind->getTemporary();
6635
6636 CXXRecordDecl *RD =
6637 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
6638 CXXDestructorDecl *Destructor = LookupDestructor(RD);
6639 Temp->setDestructor(Destructor);
6640
6641 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
6642 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
6643 PDiag(diag::err_access_dtor_temp)
6644 << Bind->getType());
6645 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
6646 return ExprError();
6647
6648 // We need a cleanup, but we don't need to remember the temporary.
6649 Cleanup.setExprNeedsCleanups(true);
6650 }
6651
6652 // Possibly strip off the top CXXBindTemporaryExpr.
6653 return E;
6654}
6655
6656/// Note a set of 'operator->' functions that were used for a member access.
6657static void noteOperatorArrows(Sema &S,
6658 ArrayRef<FunctionDecl *> OperatorArrows) {
6659 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
6660 // FIXME: Make this configurable?
6661 unsigned Limit = 9;
6662 if (OperatorArrows.size() > Limit) {
6663 // Produce Limit-1 normal notes and one 'skipping' note.
6664 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
6665 SkipCount = OperatorArrows.size() - (Limit - 1);
6666 }
6667
6668 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
6669 if (I == SkipStart) {
6670 S.Diag(OperatorArrows[I]->getLocation(),
6671 diag::note_operator_arrows_suppressed)
6672 << SkipCount;
6673 I += SkipCount;
6674 } else {
6675 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
6676 << OperatorArrows[I]->getCallResultType();
6677 ++I;
6678 }
6679 }
6680}
6681
6682ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
6683 SourceLocation OpLoc,
6684 tok::TokenKind OpKind,
6685 ParsedType &ObjectType,
6686 bool &MayBePseudoDestructor) {
6687 // Since this might be a postfix expression, get rid of ParenListExprs.
6688 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
6689 if (Result.isInvalid()) return ExprError();
6690 Base = Result.get();
6691
6692 Result = CheckPlaceholderExpr(Base);
6693 if (Result.isInvalid()) return ExprError();
6694 Base = Result.get();
6695
6696 QualType BaseType = Base->getType();
6697 MayBePseudoDestructor = false;
6698 if (BaseType->isDependentType()) {
6699 // If we have a pointer to a dependent type and are using the -> operator,
6700 // the object type is the type that the pointer points to. We might still
6701 // have enough information about that type to do something useful.
6702 if (OpKind == tok::arrow)
6703 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
6704 BaseType = Ptr->getPointeeType();
6705
6706 ObjectType = ParsedType::make(BaseType);
6707 MayBePseudoDestructor = true;
6708 return Base;
6709 }
6710
6711 // C++ [over.match.oper]p8:
6712 // [...] When operator->returns, the operator-> is applied to the value
6713 // returned, with the original second operand.
6714 if (OpKind == tok::arrow) {
6715 QualType StartingType = BaseType;
6716 bool NoArrowOperatorFound = false;
6717 bool FirstIteration = true;
6718 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
6719 // The set of types we've considered so far.
6720 llvm::SmallPtrSet<CanQualType,8> CTypes;
6721 SmallVector<FunctionDecl*, 8> OperatorArrows;
6722 CTypes.insert(Context.getCanonicalType(BaseType));
6723
6724 while (BaseType->isRecordType()) {
6725 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
6726 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
6727 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
6728 noteOperatorArrows(*this, OperatorArrows);
6729 Diag(OpLoc, diag::note_operator_arrow_depth)
6730 << getLangOpts().ArrowDepth;
6731 return ExprError();
6732 }
6733
6734 Result = BuildOverloadedArrowExpr(
6735 S, Base, OpLoc,
6736 // When in a template specialization and on the first loop iteration,
6737 // potentially give the default diagnostic (with the fixit in a
6738 // separate note) instead of having the error reported back to here
6739 // and giving a diagnostic with a fixit attached to the error itself.
6740 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
6741 ? nullptr
6742 : &NoArrowOperatorFound);
6743 if (Result.isInvalid()) {
6744 if (NoArrowOperatorFound) {
6745 if (FirstIteration) {
6746 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6747 << BaseType << 1 << Base->getSourceRange()
6748 << FixItHint::CreateReplacement(OpLoc, ".");
6749 OpKind = tok::period;
6750 break;
6751 }
6752 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
6753 << BaseType << Base->getSourceRange();
6754 CallExpr *CE = dyn_cast<CallExpr>(Base);
6755 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
6756 Diag(CD->getBeginLoc(),
6757 diag::note_member_reference_arrow_from_operator_arrow);
6758 }
6759 }
6760 return ExprError();
6761 }
6762 Base = Result.get();
6763 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
6764 OperatorArrows.push_back(OpCall->getDirectCallee());
6765 BaseType = Base->getType();
6766 CanQualType CBaseType = Context.getCanonicalType(BaseType);
6767 if (!CTypes.insert(CBaseType).second) {
6768 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6769 noteOperatorArrows(*this, OperatorArrows);
6770 return ExprError();
6771 }
6772 FirstIteration = false;
6773 }
6774
6775 if (OpKind == tok::arrow) {
6776 if (BaseType->isPointerType())
6777 BaseType = BaseType->getPointeeType();
6778 else if (auto *AT = Context.getAsArrayType(BaseType))
6779 BaseType = AT->getElementType();
6780 }
6781 }
6782
6783 // Objective-C properties allow "." access on Objective-C pointer types,
6784 // so adjust the base type to the object type itself.
6785 if (BaseType->isObjCObjectPointerType())
6786 BaseType = BaseType->getPointeeType();
6787
6788 // C++ [basic.lookup.classref]p2:
6789 // [...] If the type of the object expression is of pointer to scalar
6790 // type, the unqualified-id is looked up in the context of the complete
6791 // postfix-expression.
6792 //
6793 // This also indicates that we could be parsing a pseudo-destructor-name.
6794 // Note that Objective-C class and object types can be pseudo-destructor
6795 // expressions or normal member (ivar or property) access expressions, and
6796 // it's legal for the type to be incomplete if this is a pseudo-destructor
6797 // call. We'll do more incomplete-type checks later in the lookup process,
6798 // so just skip this check for ObjC types.
6799 if (!BaseType->isRecordType()) {
6800 ObjectType = ParsedType::make(BaseType);
6801 MayBePseudoDestructor = true;
6802 return Base;
6803 }
6804
6805 // The object type must be complete (or dependent), or
6806 // C++11 [expr.prim.general]p3:
6807 // Unlike the object expression in other contexts, *this is not required to
6808 // be of complete type for purposes of class member access (5.2.5) outside
6809 // the member function body.
6810 if (!BaseType->isDependentType() &&
6811 !isThisOutsideMemberFunctionBody(BaseType) &&
6812 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6813 return ExprError();
6814
6815 // C++ [basic.lookup.classref]p2:
6816 // If the id-expression in a class member access (5.2.5) is an
6817 // unqualified-id, and the type of the object expression is of a class
6818 // type C (or of pointer to a class type C), the unqualified-id is looked
6819 // up in the scope of class C. [...]
6820 ObjectType = ParsedType::make(BaseType);
6821 return Base;
6822}
6823
6824static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
6825 tok::TokenKind& OpKind, SourceLocation OpLoc) {
6826 if (Base->hasPlaceholderType()) {
6827 ExprResult result = S.CheckPlaceholderExpr(Base);
6828 if (result.isInvalid()) return true;
6829 Base = result.get();
6830 }
6831 ObjectType = Base->getType();
6832
6833 // C++ [expr.pseudo]p2:
6834 // The left-hand side of the dot operator shall be of scalar type. The
6835 // left-hand side of the arrow operator shall be of pointer to scalar type.
6836 // This scalar type is the object type.
6837 // Note that this is rather different from the normal handling for the
6838 // arrow operator.
6839 if (OpKind == tok::arrow) {
6840 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6841 ObjectType = Ptr->getPointeeType();
6842 } else if (!Base->isTypeDependent()) {
6843 // The user wrote "p->" when they probably meant "p."; fix it.
6844 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6845 << ObjectType << true
6846 << FixItHint::CreateReplacement(OpLoc, ".");
6847 if (S.isSFINAEContext())
6848 return true;
6849
6850 OpKind = tok::period;
6851 }
6852 }
6853
6854 return false;
6855}
6856
6857/// Check if it's ok to try and recover dot pseudo destructor calls on
6858/// pointer objects.
6859static bool
6860canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
6861 QualType DestructedType) {
6862 // If this is a record type, check if its destructor is callable.
6863 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
6864 if (RD->hasDefinition())
6865 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
6866 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
6867 return false;
6868 }
6869
6870 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
6871 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
6872 DestructedType->isVectorType();
6873}
6874
6875ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
6876 SourceLocation OpLoc,
6877 tok::TokenKind OpKind,
6878 const CXXScopeSpec &SS,
6879 TypeSourceInfo *ScopeTypeInfo,
6880 SourceLocation CCLoc,
6881 SourceLocation TildeLoc,
6882 PseudoDestructorTypeStorage Destructed) {
6883 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6884
6885 QualType ObjectType;
6886 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6887 return ExprError();
6888
6889 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6890 !ObjectType->isVectorType()) {
6891 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6892 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6893 else {
6894 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6895 << ObjectType << Base->getSourceRange();
6896 return ExprError();
6897 }
6898 }
6899
6900 // C++ [expr.pseudo]p2:
6901 // [...] The cv-unqualified versions of the object type and of the type
6902 // designated by the pseudo-destructor-name shall be the same type.
6903 if (DestructedTypeInfo) {
6904 QualType DestructedType = DestructedTypeInfo->getType();
6905 SourceLocation DestructedTypeStart
6906 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6907 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6908 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6909 // Detect dot pseudo destructor calls on pointer objects, e.g.:
6910 // Foo *foo;
6911 // foo.~Foo();
6912 if (OpKind == tok::period && ObjectType->isPointerType() &&
6913 Context.hasSameUnqualifiedType(DestructedType,
6914 ObjectType->getPointeeType())) {
6915 auto Diagnostic =
6916 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6917 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
6918
6919 // Issue a fixit only when the destructor is valid.
6920 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
6921 *this, DestructedType))
6922 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
6923
6924 // Recover by setting the object type to the destructed type and the
6925 // operator to '->'.
6926 ObjectType = DestructedType;
6927 OpKind = tok::arrow;
6928 } else {
6929 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6930 << ObjectType << DestructedType << Base->getSourceRange()
6931 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6932
6933 // Recover by setting the destructed type to the object type.
6934 DestructedType = ObjectType;
6935 DestructedTypeInfo =
6936 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
6937 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6938 }
6939 } else if (DestructedType.getObjCLifetime() !=
6940 ObjectType.getObjCLifetime()) {
6941
6942 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6943 // Okay: just pretend that the user provided the correctly-qualified
6944 // type.
6945 } else {
6946 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6947 << ObjectType << DestructedType << Base->getSourceRange()
6948 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6949 }
6950
6951 // Recover by setting the destructed type to the object type.
6952 DestructedType = ObjectType;
6953 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6954 DestructedTypeStart);
6955 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6956 }
6957 }
6958 }
6959
6960 // C++ [expr.pseudo]p2:
6961 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6962 // form
6963 //
6964 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6965 //
6966 // shall designate the same scalar type.
6967 if (ScopeTypeInfo) {
6968 QualType ScopeType = ScopeTypeInfo->getType();
6969 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6970 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6971
6972 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6973 diag::err_pseudo_dtor_type_mismatch)
6974 << ObjectType << ScopeType << Base->getSourceRange()
6975 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6976
6977 ScopeType = QualType();
6978 ScopeTypeInfo = nullptr;
6979 }
6980 }
6981
6982 Expr *Result
6983 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6984 OpKind == tok::arrow, OpLoc,
6985 SS.getWithLocInContext(Context),
6986 ScopeTypeInfo,
6987 CCLoc,
6988 TildeLoc,
6989 Destructed);
6990
6991 return Result;
6992}
6993
6994ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6995 SourceLocation OpLoc,
6996 tok::TokenKind OpKind,
6997 CXXScopeSpec &SS,
6998 UnqualifiedId &FirstTypeName,
6999 SourceLocation CCLoc,
7000 SourceLocation TildeLoc,
7001 UnqualifiedId &SecondTypeName) {
7002 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId
|| FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier
) && "Invalid first type name in pseudo-destructor") ?
static_cast<void> (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7004, __PRETTY_FUNCTION__))
7003 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId
|| FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier
) && "Invalid first type name in pseudo-destructor") ?
static_cast<void> (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7004, __PRETTY_FUNCTION__))
7004 "Invalid first type name in pseudo-destructor")(((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId
|| FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier
) && "Invalid first type name in pseudo-destructor") ?
static_cast<void> (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7004, __PRETTY_FUNCTION__))
;
7005 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId
|| SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier
) && "Invalid second type name in pseudo-destructor")
? static_cast<void> (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7007, __PRETTY_FUNCTION__))
7006 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId
|| SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier
) && "Invalid second type name in pseudo-destructor")
? static_cast<void> (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7007, __PRETTY_FUNCTION__))
7007 "Invalid second type name in pseudo-destructor")(((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId
|| SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier
) && "Invalid second type name in pseudo-destructor")
? static_cast<void> (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7007, __PRETTY_FUNCTION__))
;
7008
7009 QualType ObjectType;
7010 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7011 return ExprError();
7012
7013 // Compute the object type that we should use for name lookup purposes. Only
7014 // record types and dependent types matter.
7015 ParsedType ObjectTypePtrForLookup;
7016 if (!SS.isSet()) {
7017 if (ObjectType->isRecordType())
7018 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7019 else if (ObjectType->isDependentType())
7020 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7021 }
7022
7023 // Convert the name of the type being destructed (following the ~) into a
7024 // type (with source-location information).
7025 QualType DestructedType;
7026 TypeSourceInfo *DestructedTypeInfo = nullptr;
7027 PseudoDestructorTypeStorage Destructed;
7028 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7029 ParsedType T = getTypeName(*SecondTypeName.Identifier,
7030 SecondTypeName.StartLocation,
7031 S, &SS, true, false, ObjectTypePtrForLookup,
7032 /*IsCtorOrDtorName*/true);
7033 if (!T &&
7034 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7035 (!SS.isSet() && ObjectType->isDependentType()))) {
7036 // The name of the type being destroyed is a dependent name, and we
7037 // couldn't find anything useful in scope. Just store the identifier and
7038 // it's location, and we'll perform (qualified) name lookup again at
7039 // template instantiation time.
7040 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7041 SecondTypeName.StartLocation);
7042 } else if (!T) {
7043 Diag(SecondTypeName.StartLocation,
7044 diag::err_pseudo_dtor_destructor_non_type)
7045 << SecondTypeName.Identifier << ObjectType;
7046 if (isSFINAEContext())
7047 return ExprError();
7048
7049 // Recover by assuming we had the right type all along.
7050 DestructedType = ObjectType;
7051 } else
7052 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7053 } else {
7054 // Resolve the template-id to a type.
7055 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7056 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7057 TemplateId->NumArgs);
7058 TypeResult T = ActOnTemplateIdType(S,
7059 TemplateId->SS,
7060 TemplateId->TemplateKWLoc,
7061 TemplateId->Template,
7062 TemplateId->Name,
7063 TemplateId->TemplateNameLoc,
7064 TemplateId->LAngleLoc,
7065 TemplateArgsPtr,
7066 TemplateId->RAngleLoc,
7067 /*IsCtorOrDtorName*/true);
7068 if (T.isInvalid() || !T.get()) {
7069 // Recover by assuming we had the right type all along.
7070 DestructedType = ObjectType;
7071 } else
7072 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7073 }
7074
7075 // If we've performed some kind of recovery, (re-)build the type source
7076 // information.
7077 if (!DestructedType.isNull()) {
7078 if (!DestructedTypeInfo)
7079 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7080 SecondTypeName.StartLocation);
7081 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7082 }
7083
7084 // Convert the name of the scope type (the type prior to '::') into a type.
7085 TypeSourceInfo *ScopeTypeInfo = nullptr;
7086 QualType ScopeType;
7087 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7088 FirstTypeName.Identifier) {
7089 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7090 ParsedType T = getTypeName(*FirstTypeName.Identifier,
7091 FirstTypeName.StartLocation,
7092 S, &SS, true, false, ObjectTypePtrForLookup,
7093 /*IsCtorOrDtorName*/true);
7094 if (!T) {
7095 Diag(FirstTypeName.StartLocation,
7096 diag::err_pseudo_dtor_destructor_non_type)
7097 << FirstTypeName.Identifier << ObjectType;
7098
7099 if (isSFINAEContext())
7100 return ExprError();
7101
7102 // Just drop this type. It's unnecessary anyway.
7103 ScopeType = QualType();
7104 } else
7105 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7106 } else {
7107 // Resolve the template-id to a type.
7108 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7109 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7110 TemplateId->NumArgs);
7111 TypeResult T = ActOnTemplateIdType(S,
7112 TemplateId->SS,
7113 TemplateId->TemplateKWLoc,
7114 TemplateId->Template,
7115 TemplateId->Name,
7116 TemplateId->TemplateNameLoc,
7117 TemplateId->LAngleLoc,
7118 TemplateArgsPtr,
7119 TemplateId->RAngleLoc,
7120 /*IsCtorOrDtorName*/true);
7121 if (T.isInvalid() || !T.get()) {
7122 // Recover by dropping this type.
7123 ScopeType = QualType();
7124 } else
7125 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7126 }
7127 }
7128
7129 if (!ScopeType.isNull() && !ScopeTypeInfo)
7130 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7131 FirstTypeName.StartLocation);
7132
7133
7134 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7135 ScopeTypeInfo, CCLoc, TildeLoc,
7136 Destructed);
7137}
7138
7139ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7140 SourceLocation OpLoc,
7141 tok::TokenKind OpKind,
7142 SourceLocation TildeLoc,
7143 const DeclSpec& DS) {
7144 QualType ObjectType;
7145 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7146 return ExprError();
7147
7148 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
7149 false);
7150
7151 TypeLocBuilder TLB;
7152 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7153 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
7154 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7155 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7156
7157 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7158 nullptr, SourceLocation(), TildeLoc,
7159 Destructed);
7160}
7161
7162ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
7163 CXXConversionDecl *Method,
7164 bool HadMultipleCandidates) {
7165 // Convert the expression to match the conversion function's implicit object
7166 // parameter.
7167 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
7168 FoundDecl, Method);
7169 if (Exp.isInvalid())
7170 return true;
7171
7172 if (Method->getParent()->isLambda() &&
7173 Method->getConversionType()->isBlockPointerType()) {
7174 // This is a lambda conversion to block pointer; check if the argument
7175 // was a LambdaExpr.
7176 Expr *SubE = E;
7177 CastExpr *CE = dyn_cast<CastExpr>(SubE);
7178 if (CE && CE->getCastKind() == CK_NoOp)
7179 SubE = CE->getSubExpr();
7180 SubE = SubE->IgnoreParens();
7181 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
7182 SubE = BE->getSubExpr();
7183 if (isa<LambdaExpr>(SubE)) {
7184 // For the conversion to block pointer on a lambda expression, we
7185 // construct a special BlockLiteral instead; this doesn't really make
7186 // a difference in ARC, but outside of ARC the resulting block literal
7187 // follows the normal lifetime rules for block literals instead of being
7188 // autoreleased.
7189 DiagnosticErrorTrap Trap(Diags);
7190 PushExpressionEvaluationContext(
7191 ExpressionEvaluationContext::PotentiallyEvaluated);
7192 ExprResult BlockExp = BuildBlockForLambdaConversion(
7193 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
7194 PopExpressionEvaluationContext();
7195
7196 if (BlockExp.isInvalid())
7197 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
7198 return BlockExp;
7199 }
7200 }
7201
7202 MemberExpr *ME =
7203 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
7204 NestedNameSpecifierLoc(), SourceLocation(), Method,
7205 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
7206 HadMultipleCandidates, DeclarationNameInfo(),
7207 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
7208
7209 QualType ResultType = Method->getReturnType();
7210 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7211 ResultType = ResultType.getNonLValueExprType(Context);
7212
7213 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
7214 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc());
7215
7216 if (CheckFunctionCall(Method, CE,
7217 Method->getType()->castAs<FunctionProtoType>()))
7218 return ExprError();
7219
7220 return CE;
7221}
7222
7223ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
7224 SourceLocation RParen) {
7225 // If the operand is an unresolved lookup expression, the expression is ill-
7226 // formed per [over.over]p1, because overloaded function names cannot be used
7227 // without arguments except in explicit contexts.
7228 ExprResult R = CheckPlaceholderExpr(Operand);
7229 if (R.isInvalid())
7230 return R;
7231
7232 // The operand may have been modified when checking the placeholder type.
7233 Operand = R.get();
7234
7235 if (!inTemplateInstantiation() && Operand->HasSideEffects(Context, false)) {
7236 // The expression operand for noexcept is in an unevaluated expression
7237 // context, so side effects could result in unintended consequences.
7238 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7239 }
7240
7241 CanThrowResult CanThrow = canThrow(Operand);
7242 return new (Context)
7243 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
7244}
7245
7246ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
7247 Expr *Operand, SourceLocation RParen) {
7248 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
7249}
7250
7251static bool IsSpecialDiscardedValue(Expr *E) {
7252 // In C++11, discarded-value expressions of a certain form are special,
7253 // according to [expr]p10:
7254 // The lvalue-to-rvalue conversion (4.1) is applied only if the
7255 // expression is an lvalue of volatile-qualified type and it has
7256 // one of the following forms:
7257 E = E->IgnoreParens();
7258
7259 // - id-expression (5.1.1),
7260 if (isa<DeclRefExpr>(E))
7261 return true;
7262
7263 // - subscripting (5.2.1),
7264 if (isa<ArraySubscriptExpr>(E))
7265 return true;
7266
7267 // - class member access (5.2.5),
7268 if (isa<MemberExpr>(E))
7269 return true;
7270
7271 // - indirection (5.3.1),
7272 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
7273 if (UO->getOpcode() == UO_Deref)
7274 return true;
7275
7276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7277 // - pointer-to-member operation (5.5),
7278 if (BO->isPtrMemOp())
7279 return true;
7280
7281 // - comma expression (5.18) where the right operand is one of the above.
7282 if (BO->getOpcode() == BO_Comma)
7283 return IsSpecialDiscardedValue(BO->getRHS());
7284 }
7285
7286 // - conditional expression (5.16) where both the second and the third
7287 // operands are one of the above, or
7288 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
7289 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
7290 IsSpecialDiscardedValue(CO->getFalseExpr());
7291 // The related edge case of "*x ?: *x".
7292 if (BinaryConditionalOperator *BCO =
7293 dyn_cast<BinaryConditionalOperator>(E)) {
7294 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
7295 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
7296 IsSpecialDiscardedValue(BCO->getFalseExpr());
7297 }
7298
7299 // Objective-C++ extensions to the rule.
7300 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
7301 return true;
7302
7303 return false;
7304}
7305
7306/// Perform the conversions required for an expression used in a
7307/// context that ignores the result.
7308ExprResult Sema::IgnoredValueConversions(Expr *E) {
7309 if (E->hasPlaceholderType()) {
7310 ExprResult result = CheckPlaceholderExpr(E);
7311 if (result.isInvalid()) return E;
7312 E = result.get();
7313 }
7314
7315 // C99 6.3.2.1:
7316 // [Except in specific positions,] an lvalue that does not have
7317 // array type is converted to the value stored in the
7318 // designated object (and is no longer an lvalue).
7319 if (E->isRValue()) {
7320 // In C, function designators (i.e. expressions of function type)
7321 // are r-values, but we still want to do function-to-pointer decay
7322 // on them. This is both technically correct and convenient for
7323 // some clients.
7324 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
7325 return DefaultFunctionArrayConversion(E);
7326
7327 return E;
7328 }
7329
7330 if (getLangOpts().CPlusPlus) {
7331 // The C++11 standard defines the notion of a discarded-value expression;
7332 // normally, we don't need to do anything to handle it, but if it is a
7333 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
7334 // conversion.
7335 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
7336 E->getType().isVolatileQualified() &&
7337 IsSpecialDiscardedValue(E)) {
7338 ExprResult Res = DefaultLvalueConversion(E);
7339 if (Res.isInvalid())
7340 return E;
7341 E = Res.get();
7342 }
7343
7344 // C++1z:
7345 // If the expression is a prvalue after this optional conversion, the
7346 // temporary materialization conversion is applied.
7347 //
7348 // We skip this step: IR generation is able to synthesize the storage for
7349 // itself in the aggregate case, and adding the extra node to the AST is
7350 // just clutter.
7351 // FIXME: We don't emit lifetime markers for the temporaries due to this.
7352 // FIXME: Do any other AST consumers care about this?
7353 return E;
7354 }
7355
7356 // GCC seems to also exclude expressions of incomplete enum type.
7357 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
7358 if (!T->getDecl()->isComplete()) {
7359 // FIXME: stupid workaround for a codegen bug!
7360 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
7361 return E;
7362 }
7363 }
7364
7365 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
7366 if (Res.isInvalid())
7367 return E;
7368 E = Res.get();
7369
7370 if (!E->getType()->isVoidType())
7371 RequireCompleteType(E->getExprLoc(), E->getType(),
7372 diag::err_incomplete_type);
7373 return E;
7374}
7375
7376// If we can unambiguously determine whether Var can never be used
7377// in a constant expression, return true.
7378// - if the variable and its initializer are non-dependent, then
7379// we can unambiguously check if the variable is a constant expression.
7380// - if the initializer is not value dependent - we can determine whether
7381// it can be used to initialize a constant expression. If Init can not
7382// be used to initialize a constant expression we conclude that Var can
7383// never be a constant expression.
7384// - FXIME: if the initializer is dependent, we can still do some analysis and
7385// identify certain cases unambiguously as non-const by using a Visitor:
7386// - such as those that involve odr-use of a ParmVarDecl, involve a new
7387// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
7388static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
7389 ASTContext &Context) {
7390 if (isa<ParmVarDecl>(Var)) return true;
7391 const VarDecl *DefVD = nullptr;
7392
7393 // If there is no initializer - this can not be a constant expression.
7394 if (!Var->getAnyInitializer(DefVD)) return true;
7395 assert(DefVD)((DefVD) ? static_cast<void> (0) : __assert_fail ("DefVD"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7395, __PRETTY_FUNCTION__))
;
7396 if (DefVD->isWeak()) return false;
7397 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
7398
7399 Expr *Init = cast<Expr>(Eval->Value);
7400
7401 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
7402 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
7403 // of value-dependent expressions, and use it here to determine whether the
7404 // initializer is a potential constant expression.
7405 return false;
7406 }
7407
7408 return !Var->isUsableInConstantExpressions(Context);
7409}
7410
7411/// Check if the current lambda has any potential captures
7412/// that must be captured by any of its enclosing lambdas that are ready to
7413/// capture. If there is a lambda that can capture a nested
7414/// potential-capture, go ahead and do so. Also, check to see if any
7415/// variables are uncaptureable or do not involve an odr-use so do not
7416/// need to be captured.
7417
7418static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
7419 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
7420
7421 assert(!S.isUnevaluatedContext())((!S.isUnevaluatedContext()) ? static_cast<void> (0) : __assert_fail
("!S.isUnevaluatedContext()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7421, __PRETTY_FUNCTION__))
;
7422 assert(S.CurContext->isDependentContext())((S.CurContext->isDependentContext()) ? static_cast<void
> (0) : __assert_fail ("S.CurContext->isDependentContext()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7422, __PRETTY_FUNCTION__))
;
7423#ifndef NDEBUG
7424 DeclContext *DC = S.CurContext;
7425 while (DC && isa<CapturedDecl>(DC))
7426 DC = DC->getParent();
7427 assert(((CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext"
) ? static_cast<void> (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7429, __PRETTY_FUNCTION__))
7428 CurrentLSI->CallOperator == DC &&((CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext"
) ? static_cast<void> (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7429, __PRETTY_FUNCTION__))
7429 "The current call operator must be synchronized with Sema's CurContext")((CurrentLSI->CallOperator == DC && "The current call operator must be synchronized with Sema's CurContext"
) ? static_cast<void> (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7429, __PRETTY_FUNCTION__))
;
7430#endif // NDEBUG
7431
7432 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
7433
7434 // All the potentially captureable variables in the current nested
7435 // lambda (within a generic outer lambda), must be captured by an
7436 // outer lambda that is enclosed within a non-dependent context.
7437 CurrentLSI->visitPotentialCaptures([&] (VarDecl *Var, Expr *VarExpr) {
7438 // If the variable is clearly identified as non-odr-used and the full
7439 // expression is not instantiation dependent, only then do we not
7440 // need to check enclosing lambda's for speculative captures.
7441 // For e.g.:
7442 // Even though 'x' is not odr-used, it should be captured.
7443 // int test() {
7444 // const int x = 10;
7445 // auto L = [=](auto a) {
7446 // (void) +x + a;
7447 // };
7448 // }
7449 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
7450 !IsFullExprInstantiationDependent)
7451 return;
7452
7453 // If we have a capture-capable lambda for the variable, go ahead and
7454 // capture the variable in that lambda (and all its enclosing lambdas).
7455 if (const Optional<unsigned> Index =
7456 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7457 S.FunctionScopes, Var, S))
7458 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(),
7459 Index.getValue());
7460 const bool IsVarNeverAConstantExpression =
7461 VariableCanNeverBeAConstantExpression(Var, S.Context);
7462 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
7463 // This full expression is not instantiation dependent or the variable
7464 // can not be used in a constant expression - which means
7465 // this variable must be odr-used here, so diagnose a
7466 // capture violation early, if the variable is un-captureable.
7467 // This is purely for diagnosing errors early. Otherwise, this
7468 // error would get diagnosed when the lambda becomes capture ready.
7469 QualType CaptureType, DeclRefType;
7470 SourceLocation ExprLoc = VarExpr->getExprLoc();
7471 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7472 /*EllipsisLoc*/ SourceLocation(),
7473 /*BuildAndDiagnose*/false, CaptureType,
7474 DeclRefType, nullptr)) {
7475 // We will never be able to capture this variable, and we need
7476 // to be able to in any and all instantiations, so diagnose it.
7477 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
7478 /*EllipsisLoc*/ SourceLocation(),
7479 /*BuildAndDiagnose*/true, CaptureType,
7480 DeclRefType, nullptr);
7481 }
7482 }
7483 });
7484
7485 // Check if 'this' needs to be captured.
7486 if (CurrentLSI->hasPotentialThisCapture()) {
7487 // If we have a capture-capable lambda for 'this', go ahead and capture
7488 // 'this' in that lambda (and all its enclosing lambdas).
7489 if (const Optional<unsigned> Index =
7490 getStackIndexOfNearestEnclosingCaptureCapableLambda(
7491 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
7492 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
7493 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
7494 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
7495 &FunctionScopeIndexOfCapturableLambda);
7496 }
7497 }
7498
7499 // Reset all the potential captures at the end of each full-expression.
7500 CurrentLSI->clearPotentialCaptures();
7501}
7502
7503static ExprResult attemptRecovery(Sema &SemaRef,
7504 const TypoCorrectionConsumer &Consumer,
7505 const TypoCorrection &TC) {
7506 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
7507 Consumer.getLookupResult().getLookupKind());
7508 const CXXScopeSpec *SS = Consumer.getSS();
7509 CXXScopeSpec NewSS;
7510
7511 // Use an approprate CXXScopeSpec for building the expr.
7512 if (auto *NNS = TC.getCorrectionSpecifier())
7513 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
7514 else if (SS && !TC.WillReplaceSpecifier())
7515 NewSS = *SS;
7516
7517 if (auto *ND = TC.getFoundDecl()) {
7518 R.setLookupName(ND->getDeclName());
7519 R.addDecl(ND);
7520 if (ND->isCXXClassMember()) {
7521 // Figure out the correct naming class to add to the LookupResult.
7522 CXXRecordDecl *Record = nullptr;
7523 if (auto *NNS = TC.getCorrectionSpecifier())
7524 Record = NNS->getAsType()->getAsCXXRecordDecl();
7525 if (!Record)
7526 Record =
7527 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
7528 if (Record)
7529 R.setNamingClass(Record);
7530
7531 // Detect and handle the case where the decl might be an implicit
7532 // member.
7533 bool MightBeImplicitMember;
7534 if (!Consumer.isAddressOfOperand())
7535 MightBeImplicitMember = true;
7536 else if (!NewSS.isEmpty())
7537 MightBeImplicitMember = false;
7538 else if (R.isOverloadedResult())
7539 MightBeImplicitMember = false;
7540 else if (R.isUnresolvableResult())
7541 MightBeImplicitMember = true;
7542 else
7543 MightBeImplicitMember = isa<FieldDecl>(ND) ||
7544 isa<IndirectFieldDecl>(ND) ||
7545 isa<MSPropertyDecl>(ND);
7546
7547 if (MightBeImplicitMember)
7548 return SemaRef.BuildPossibleImplicitMemberExpr(
7549 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
7550 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
7551 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
7552 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
7553 Ivar->getIdentifier());
7554 }
7555 }
7556
7557 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
7558 /*AcceptInvalidDecl*/ true);
7559}
7560
7561namespace {
7562class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
7563 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
7564
7565public:
7566 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
7567 : TypoExprs(TypoExprs) {}
7568 bool VisitTypoExpr(TypoExpr *TE) {
7569 TypoExprs.insert(TE);
7570 return true;
7571 }
7572};
7573
7574class TransformTypos : public TreeTransform<TransformTypos> {
7575 typedef TreeTransform<TransformTypos> BaseTransform;
7576
7577 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
7578 // process of being initialized.
7579 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
7580 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
7581 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
7582 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
7583
7584 /// Emit diagnostics for all of the TypoExprs encountered.
7585 ///
7586 /// If the TypoExprs were successfully corrected, then the diagnostics should
7587 /// suggest the corrections. Otherwise the diagnostics will not suggest
7588 /// anything (having been passed an empty TypoCorrection).
7589 ///
7590 /// If we've failed to correct due to ambiguous corrections, we need to
7591 /// be sure to pass empty corrections and replacements. Otherwise it's
7592 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
7593 /// and we don't want to report those diagnostics.
7594 void EmitAllDiagnostics(bool IsAmbiguous) {
7595 for (TypoExpr *TE : TypoExprs) {
7596 auto &State = SemaRef.getTypoExprState(TE);
7597 if (State.DiagHandler) {
7598 TypoCorrection TC = IsAmbiguous
7599 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
7600 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
7601
7602 // Extract the NamedDecl from the transformed TypoExpr and add it to the
7603 // TypoCorrection, replacing the existing decls. This ensures the right
7604 // NamedDecl is used in diagnostics e.g. in the case where overload
7605 // resolution was used to select one from several possible decls that
7606 // had been stored in the TypoCorrection.
7607 if (auto *ND = getDeclFromExpr(
7608 Replacement.isInvalid() ? nullptr : Replacement.get()))
7609 TC.setCorrectionDecl(ND);
7610
7611 State.DiagHandler(TC);
7612 }
7613 SemaRef.clearDelayedTypo(TE);
7614 }
7615 }
7616
7617 /// If corrections for the first TypoExpr have been exhausted for a
7618 /// given combination of the other TypoExprs, retry those corrections against
7619 /// the next combination of substitutions for the other TypoExprs by advancing
7620 /// to the next potential correction of the second TypoExpr. For the second
7621 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
7622 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
7623 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
7624 /// TransformCache). Returns true if there is still any untried combinations
7625 /// of corrections.
7626 bool CheckAndAdvanceTypoExprCorrectionStreams() {
7627 for (auto TE : TypoExprs) {
7628 auto &State = SemaRef.getTypoExprState(TE);
7629 TransformCache.erase(TE);
7630 if (!State.Consumer->finished())
7631 return true;
7632 State.Consumer->resetCorrectionStream();
7633 }
7634 return false;
7635 }
7636
7637 NamedDecl *getDeclFromExpr(Expr *E) {
7638 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
7639 E = OverloadResolution[OE];
7640
7641 if (!E)
7642 return nullptr;
7643 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
7644 return DRE->getFoundDecl();
7645 if (auto *ME = dyn_cast<MemberExpr>(E))
7646 return ME->getFoundDecl();
7647 // FIXME: Add any other expr types that could be be seen by the delayed typo
7648 // correction TreeTransform for which the corresponding TypoCorrection could
7649 // contain multiple decls.
7650 return nullptr;
7651 }
7652
7653 ExprResult TryTransform(Expr *E) {
7654 Sema::SFINAETrap Trap(SemaRef);
7655 ExprResult Res = TransformExpr(E);
7656 if (Trap.hasErrorOccurred() || Res.isInvalid())
7657 return ExprError();
7658
7659 return ExprFilter(Res.get());
7660 }
7661
7662 // Since correcting typos may intoduce new TypoExprs, this function
7663 // checks for new TypoExprs and recurses if it finds any. Note that it will
7664 // only succeed if it is able to correct all typos in the given expression.
7665 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
7666 if (Res.isInvalid()) {
7667 return Res;
7668 }
7669 // Check to see if any new TypoExprs were created. If so, we need to recurse
7670 // to check their validity.
7671 Expr *FixedExpr = Res.get();
7672
7673 auto SavedTypoExprs = std::move(TypoExprs);
7674 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
7675 TypoExprs.clear();
7676 AmbiguousTypoExprs.clear();
7677
7678 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
7679 if (!TypoExprs.empty()) {
7680 // Recurse to handle newly created TypoExprs. If we're not able to
7681 // handle them, discard these TypoExprs.
7682 ExprResult RecurResult =
7683 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
7684 if (RecurResult.isInvalid()) {
7685 Res = ExprError();
7686 // Recursive corrections didn't work, wipe them away and don't add
7687 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
7688 // since we don't want to clear them twice. Note: it's possible the
7689 // TypoExprs were created recursively and thus won't be in our
7690 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
7691 auto &SemaTypoExprs = SemaRef.TypoExprs;
7692 for (auto TE : TypoExprs) {
7693 TransformCache.erase(TE);
7694 SemaRef.clearDelayedTypo(TE);
7695
7696 auto SI = find(SemaTypoExprs, TE);
7697 if (SI != SemaTypoExprs.end()) {
7698 SemaTypoExprs.erase(SI);
7699 }
7700 }
7701 } else {
7702 // TypoExpr is valid: add newly created TypoExprs since we were
7703 // able to correct them.
7704 Res = RecurResult;
7705 SavedTypoExprs.set_union(TypoExprs);
7706 }
7707 }
7708
7709 TypoExprs = std::move(SavedTypoExprs);
7710 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
7711
7712 return Res;
7713 }
7714
7715 // Try to transform the given expression, looping through the correction
7716 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
7717 //
7718 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
7719 // true and this method immediately will return an `ExprError`.
7720 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
7721 ExprResult Res;
7722 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
7723 SemaRef.TypoExprs.clear();
7724
7725 while (true) {
7726 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
7727
7728 // Recursion encountered an ambiguous correction. This means that our
7729 // correction itself is ambiguous, so stop now.
7730 if (IsAmbiguous)
7731 break;
7732
7733 // If the transform is still valid after checking for any new typos,
7734 // it's good to go.
7735 if (!Res.isInvalid())
7736 break;
7737
7738 // The transform was invalid, see if we have any TypoExprs with untried
7739 // correction candidates.
7740 if (!CheckAndAdvanceTypoExprCorrectionStreams())
7741 break;
7742 }
7743
7744 // If we found a valid result, double check to make sure it's not ambiguous.
7745 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
7746 auto SavedTransformCache = std::move(TransformCache);
7747 TransformCache.clear();
7748 // Ensure none of the TypoExprs have multiple typo correction candidates
7749 // with the same edit length that pass all the checks and filters.
7750 while (!AmbiguousTypoExprs.empty()) {
7751 auto TE = AmbiguousTypoExprs.back();
7752
7753 // TryTransform itself can create new Typos, adding them to the TypoExpr map
7754 // and invalidating our TypoExprState, so always fetch it instead of storing.
7755 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
7756
7757 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
7758 TypoCorrection Next;
7759 do {
7760 // Fetch the next correction by erasing the typo from the cache and calling
7761 // `TryTransform` which will iterate through corrections in
7762 // `TransformTypoExpr`.
7763 TransformCache.erase(TE);
7764 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
7765
7766 if (!AmbigRes.isInvalid() || IsAmbiguous) {
7767 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
7768 SavedTransformCache.erase(TE);
7769 Res = ExprError();
7770 IsAmbiguous = true;
7771 break;
7772 }
7773 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
7774 Next.getEditDistance(false) == TC.getEditDistance(false));
7775
7776 if (IsAmbiguous)
7777 break;
7778
7779 AmbiguousTypoExprs.remove(TE);
7780 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
7781 }
7782 TransformCache = std::move(SavedTransformCache);
7783 }
7784
7785 // Wipe away any newly created TypoExprs that we don't know about. Since we
7786 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
7787 // possible if a `TypoExpr` is created during a transformation but then
7788 // fails before we can discover it.
7789 auto &SemaTypoExprs = SemaRef.TypoExprs;
7790 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
7791 auto TE = *Iterator;
7792 auto FI = find(TypoExprs, TE);
7793 if (FI != TypoExprs.end()) {
7794 Iterator++;
7795 continue;
7796 }
7797 SemaRef.clearDelayedTypo(TE);
7798 Iterator = SemaTypoExprs.erase(Iterator);
7799 }
7800 SemaRef.TypoExprs = std::move(SavedTypoExprs);
7801
7802 return Res;
7803 }
7804
7805public:
7806 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
7807 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
7808
7809 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
7810 MultiExprArg Args,
7811 SourceLocation RParenLoc,
7812 Expr *ExecConfig = nullptr) {
7813 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
7814 RParenLoc, ExecConfig);
7815 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
7816 if (Result.isUsable()) {
7817 Expr *ResultCall = Result.get();
7818 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
7819 ResultCall = BE->getSubExpr();
7820 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
7821 OverloadResolution[OE] = CE->getCallee();
7822 }
7823 }
7824 return Result;
7825 }
7826
7827 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
7828
7829 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
7830
7831 ExprResult Transform(Expr *E) {
7832 bool IsAmbiguous = false;
7833 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
7834
7835 if (!Res.isUsable())
7836 FindTypoExprs(TypoExprs).TraverseStmt(E);
7837
7838 EmitAllDiagnostics(IsAmbiguous);
7839
7840 return Res;
7841 }
7842
7843 ExprResult TransformTypoExpr(TypoExpr *E) {
7844 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
7845 // cached transformation result if there is one and the TypoExpr isn't the
7846 // first one that was encountered.
7847 auto &CacheEntry = TransformCache[E];
7848 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
7849 return CacheEntry;
7850 }
7851
7852 auto &State = SemaRef.getTypoExprState(E);
7853 assert(State.Consumer && "Cannot transform a cleared TypoExpr")((State.Consumer && "Cannot transform a cleared TypoExpr"
) ? static_cast<void> (0) : __assert_fail ("State.Consumer && \"Cannot transform a cleared TypoExpr\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7853, __PRETTY_FUNCTION__))
;
7854
7855 // For the first TypoExpr and an uncached TypoExpr, find the next likely
7856 // typo correction and return it.
7857 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
7858 if (InitDecl && TC.getFoundDecl() == InitDecl)
7859 continue;
7860 // FIXME: If we would typo-correct to an invalid declaration, it's
7861 // probably best to just suppress all errors from this typo correction.
7862 ExprResult NE = State.RecoveryHandler ?
7863 State.RecoveryHandler(SemaRef, E, TC) :
7864 attemptRecovery(SemaRef, *State.Consumer, TC);
7865 if (!NE.isInvalid()) {
7866 // Check whether there may be a second viable correction with the same
7867 // edit distance; if so, remember this TypoExpr may have an ambiguous
7868 // correction so it can be more thoroughly vetted later.
7869 TypoCorrection Next;
7870 if ((Next = State.Consumer->peekNextCorrection()) &&
7871 Next.getEditDistance(false) == TC.getEditDistance(false)) {
7872 AmbiguousTypoExprs.insert(E);
7873 } else {
7874 AmbiguousTypoExprs.remove(E);
7875 }
7876 assert(!NE.isUnset() &&((!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult"
) ? static_cast<void> (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7877, __PRETTY_FUNCTION__))
7877 "Typo was transformed into a valid-but-null ExprResult")((!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult"
) ? static_cast<void> (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7877, __PRETTY_FUNCTION__))
;
7878 return CacheEntry = NE;
7879 }
7880 }
7881 return CacheEntry = ExprError();
7882 }
7883};
7884}
7885
7886ExprResult
7887Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
7888 llvm::function_ref<ExprResult(Expr *)> Filter) {
7889 // If the current evaluation context indicates there are uncorrected typos
7890 // and the current expression isn't guaranteed to not have typos, try to
7891 // resolve any TypoExpr nodes that might be in the expression.
7892 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
7893 (E->isTypeDependent() || E->isValueDependent() ||
7894 E->isInstantiationDependent())) {
7895 auto TyposResolved = DelayedTypos.size();
7896 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
7897 TyposResolved -= DelayedTypos.size();
7898 if (Result.isInvalid() || Result.get() != E) {
7899 ExprEvalContexts.back().NumTypos -= TyposResolved;
7900 return Result;
7901 }
7902 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?")((TyposResolved == 0 && "Corrected typo but got same Expr back?"
) ? static_cast<void> (0) : __assert_fail ("TyposResolved == 0 && \"Corrected typo but got same Expr back?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 7902, __PRETTY_FUNCTION__))
;
7903 }
7904 return E;
7905}
7906
7907ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
7908 bool DiscardedValue,
7909 bool IsConstexpr) {
7910 ExprResult FullExpr = FE;
7911
7912 if (!FullExpr.get())
7913 return ExprError();
7914
7915 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
7916 return ExprError();
7917
7918 if (DiscardedValue) {
7919 // Top-level expressions default to 'id' when we're in a debugger.
7920 if (getLangOpts().DebuggerCastResultToId &&
7921 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7922 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7923 if (FullExpr.isInvalid())
7924 return ExprError();
7925 }
7926
7927 FullExpr = CheckPlaceholderExpr(FullExpr.get());
7928 if (FullExpr.isInvalid())
7929 return ExprError();
7930
7931 FullExpr = IgnoredValueConversions(FullExpr.get());
7932 if (FullExpr.isInvalid())
7933 return ExprError();
7934
7935 DiagnoseUnusedExprResult(FullExpr.get());
7936 }
7937
7938 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7939 if (FullExpr.isInvalid())
7940 return ExprError();
7941
7942 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7943
7944 // At the end of this full expression (which could be a deeply nested
7945 // lambda), if there is a potential capture within the nested lambda,
7946 // have the outer capture-able lambda try and capture it.
7947 // Consider the following code:
7948 // void f(int, int);
7949 // void f(const int&, double);
7950 // void foo() {
7951 // const int x = 10, y = 20;
7952 // auto L = [=](auto a) {
7953 // auto M = [=](auto b) {
7954 // f(x, b); <-- requires x to be captured by L and M
7955 // f(y, a); <-- requires y to be captured by L, but not all Ms
7956 // };
7957 // };
7958 // }
7959
7960 // FIXME: Also consider what happens for something like this that involves
7961 // the gnu-extension statement-expressions or even lambda-init-captures:
7962 // void f() {
7963 // const int n = 0;
7964 // auto L = [&](auto a) {
7965 // +n + ({ 0; a; });
7966 // };
7967 // }
7968 //
7969 // Here, we see +n, and then the full-expression 0; ends, so we don't
7970 // capture n (and instead remove it from our list of potential captures),
7971 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7972 // for us to see that we need to capture n after all.
7973
7974 LambdaScopeInfo *const CurrentLSI =
7975 getCurLambda(/*IgnoreCapturedRegions=*/true);
7976 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7977 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7978 // for an example of the code that might cause this asynchrony.
7979 // By ensuring we are in the context of a lambda's call operator
7980 // we can fix the bug (we only need to check whether we need to capture
7981 // if we are within a lambda's body); but per the comments in that
7982 // PR, a proper fix would entail :
7983 // "Alternative suggestion:
7984 // - Add to Sema an integer holding the smallest (outermost) scope
7985 // index that we are *lexically* within, and save/restore/set to
7986 // FunctionScopes.size() in InstantiatingTemplate's
7987 // constructor/destructor.
7988 // - Teach the handful of places that iterate over FunctionScopes to
7989 // stop at the outermost enclosing lexical scope."
7990 DeclContext *DC = CurContext;
7991 while (DC && isa<CapturedDecl>(DC))
7992 DC = DC->getParent();
7993 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
7994 if (IsInLambdaDeclContext && CurrentLSI &&
7995 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7996 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7997 *this);
7998 return MaybeCreateExprWithCleanups(FullExpr);
7999}
8000
8001StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8002 if (!FullStmt) return StmtError();
8003
8004 return MaybeCreateStmtWithCleanups(FullStmt);
8005}
8006
8007Sema::IfExistsResult
8008Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8009 CXXScopeSpec &SS,
8010 const DeclarationNameInfo &TargetNameInfo) {
8011 DeclarationName TargetName = TargetNameInfo.getName();
8012 if (!TargetName)
8013 return IER_DoesNotExist;
8014
8015 // If the name itself is dependent, then the result is dependent.
8016 if (TargetName.isDependentName())
8017 return IER_Dependent;
8018
8019 // Do the redeclaration lookup in the current scope.
8020 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8021 Sema::NotForRedeclaration);
8022 LookupParsedName(R, S, &SS);
8023 R.suppressDiagnostics();
8024
8025 switch (R.getResultKind()) {
8026 case LookupResult::Found:
8027 case LookupResult::FoundOverloaded:
8028 case LookupResult::FoundUnresolvedValue:
8029 case LookupResult::Ambiguous:
8030 return IER_Exists;
8031
8032 case LookupResult::NotFound:
8033 return IER_DoesNotExist;
8034
8035 case LookupResult::NotFoundInCurrentInstantiation:
8036 return IER_Dependent;
8037 }
8038
8039 llvm_unreachable("Invalid LookupResult Kind!")::llvm::llvm_unreachable_internal("Invalid LookupResult Kind!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 8039)
;
8040}
8041
8042Sema::IfExistsResult
8043Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8044 bool IsIfExists, CXXScopeSpec &SS,
8045 UnqualifiedId &Name) {
8046 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8047
8048 // Check for an unexpanded parameter pack.
8049 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8050 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8051 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
8052 return IER_Error;
8053
8054 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8055}