Bug Summary

File:build/source/clang/lib/Sema/SemaExprCXX.cpp
Warning:line 627, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaExprCXX.cpp -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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/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 "TreeTransform.h"
15#include "TypeLocBuilder.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/Basic/AlignedAllocation.h"
27#include "clang/Basic/DiagnosticSema.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Basic/TokenKinds.h"
31#include "clang/Basic/TypeTraits.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/EnterExpressionEvaluationContext.h"
35#include "clang/Sema/Initialization.h"
36#include "clang/Sema/Lookup.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/Scope.h"
39#include "clang/Sema/ScopeInfo.h"
40#include "clang/Sema/SemaInternal.h"
41#include "clang/Sema/SemaLambda.h"
42#include "clang/Sema/Template.h"
43#include "clang/Sema/TemplateDeduction.h"
44#include "llvm/ADT/APInt.h"
45#include "llvm/ADT/STLExtras.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/TypeSize.h"
48#include <optional>
49using namespace clang;
50using namespace sema;
51
52/// Handle the result of the special case name lookup for inheriting
53/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
54/// constructor names in member using declarations, even if 'X' is not the
55/// name of the corresponding type.
56ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
57 SourceLocation NameLoc,
58 IdentifierInfo &Name) {
59 NestedNameSpecifier *NNS = SS.getScopeRep();
60
61 // Convert the nested-name-specifier into a type.
62 QualType Type;
63 switch (NNS->getKind()) {
64 case NestedNameSpecifier::TypeSpec:
65 case NestedNameSpecifier::TypeSpecWithTemplate:
66 Type = QualType(NNS->getAsType(), 0);
67 break;
68
69 case NestedNameSpecifier::Identifier:
70 // Strip off the last layer of the nested-name-specifier and build a
71 // typename type for it.
72 assert(NNS->getAsIdentifier() == &Name && "not a constructor name")(static_cast <bool> (NNS->getAsIdentifier() == &
Name && "not a constructor name") ? void (0) : __assert_fail
("NNS->getAsIdentifier() == &Name && \"not a constructor name\""
, "clang/lib/Sema/SemaExprCXX.cpp", 72, __extension__ __PRETTY_FUNCTION__
))
;
73 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
74 NNS->getAsIdentifier());
75 break;
76
77 case NestedNameSpecifier::Global:
78 case NestedNameSpecifier::Super:
79 case NestedNameSpecifier::Namespace:
80 case NestedNameSpecifier::NamespaceAlias:
81 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"
, "clang/lib/Sema/SemaExprCXX.cpp", 81)
;
82 }
83
84 // This reference to the type is located entirely at the location of the
85 // final identifier in the qualified-id.
86 return CreateParsedType(Type,
87 Context.getTrivialTypeSourceInfo(Type, NameLoc));
88}
89
90ParsedType Sema::getConstructorName(IdentifierInfo &II,
91 SourceLocation NameLoc,
92 Scope *S, CXXScopeSpec &SS,
93 bool EnteringContext) {
94 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
95 assert(CurClass && &II == CurClass->getIdentifier() &&(static_cast <bool> (CurClass && &II == CurClass
->getIdentifier() && "not a constructor name") ? void
(0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\""
, "clang/lib/Sema/SemaExprCXX.cpp", 96, __extension__ __PRETTY_FUNCTION__
))
96 "not a constructor name")(static_cast <bool> (CurClass && &II == CurClass
->getIdentifier() && "not a constructor name") ? void
(0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\""
, "clang/lib/Sema/SemaExprCXX.cpp", 96, __extension__ __PRETTY_FUNCTION__
))
;
97
98 // When naming a constructor as a member of a dependent context (eg, in a
99 // friend declaration or an inherited constructor declaration), form an
100 // unresolved "typename" type.
101 if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) {
102 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
103 return ParsedType::make(T);
104 }
105
106 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
107 return ParsedType();
108
109 // Find the injected-class-name declaration. Note that we make no attempt to
110 // diagnose cases where the injected-class-name is shadowed: the only
111 // declaration that can validly shadow the injected-class-name is a
112 // non-static data member, and if the class contains both a non-static data
113 // member and a constructor then it is ill-formed (we check that in
114 // CheckCompletedCXXClass).
115 CXXRecordDecl *InjectedClassName = nullptr;
116 for (NamedDecl *ND : CurClass->lookup(&II)) {
117 auto *RD = dyn_cast<CXXRecordDecl>(ND);
118 if (RD && RD->isInjectedClassName()) {
119 InjectedClassName = RD;
120 break;
121 }
122 }
123 if (!InjectedClassName) {
124 if (!CurClass->isInvalidDecl()) {
125 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
126 // properly. Work around it here for now.
127 Diag(SS.getLastQualifierNameLoc(),
128 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
129 }
130 return ParsedType();
131 }
132
133 QualType T = Context.getTypeDeclType(InjectedClassName);
134 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
135 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
136
137 return ParsedType::make(T);
138}
139
140ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
141 IdentifierInfo &II,
142 SourceLocation NameLoc,
143 Scope *S, CXXScopeSpec &SS,
144 ParsedType ObjectTypePtr,
145 bool EnteringContext) {
146 // Determine where to perform name lookup.
147
148 // FIXME: This area of the standard is very messy, and the current
149 // wording is rather unclear about which scopes we search for the
150 // destructor name; see core issues 399 and 555. Issue 399 in
151 // particular shows where the current description of destructor name
152 // lookup is completely out of line with existing practice, e.g.,
153 // this appears to be ill-formed:
154 //
155 // namespace N {
156 // template <typename T> struct S {
157 // ~S();
158 // };
159 // }
160 //
161 // void f(N::S<int>* s) {
162 // s->N::S<int>::~S();
163 // }
164 //
165 // See also PR6358 and PR6359.
166 //
167 // For now, we accept all the cases in which the name given could plausibly
168 // be interpreted as a correct destructor name, issuing off-by-default
169 // extension diagnostics on the cases that don't strictly conform to the
170 // C++20 rules. This basically means we always consider looking in the
171 // nested-name-specifier prefix, the complete nested-name-specifier, and
172 // the scope, and accept if we find the expected type in any of the three
173 // places.
174
175 if (SS.isInvalid())
176 return nullptr;
177
178 // Whether we've failed with a diagnostic already.
179 bool Failed = false;
180
181 llvm::SmallVector<NamedDecl*, 8> FoundDecls;
182 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet;
183
184 // If we have an object type, it's because we are in a
185 // pseudo-destructor-expression or a member access expression, and
186 // we know what type we're looking for.
187 QualType SearchType =
188 ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType();
189
190 auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType {
191 auto IsAcceptableResult = [&](NamedDecl *D) -> bool {
192 auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl());
193 if (!Type)
194 return false;
195
196 if (SearchType.isNull() || SearchType->isDependentType())
197 return true;
198
199 QualType T = Context.getTypeDeclType(Type);
200 return Context.hasSameUnqualifiedType(T, SearchType);
201 };
202
203 unsigned NumAcceptableResults = 0;
204 for (NamedDecl *D : Found) {
205 if (IsAcceptableResult(D))
206 ++NumAcceptableResults;
207
208 // Don't list a class twice in the lookup failure diagnostic if it's
209 // found by both its injected-class-name and by the name in the enclosing
210 // scope.
211 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
212 if (RD->isInjectedClassName())
213 D = cast<NamedDecl>(RD->getParent());
214
215 if (FoundDeclSet.insert(D).second)
216 FoundDecls.push_back(D);
217 }
218
219 // As an extension, attempt to "fix" an ambiguity by erasing all non-type
220 // results, and all non-matching results if we have a search type. It's not
221 // clear what the right behavior is if destructor lookup hits an ambiguity,
222 // but other compilers do generally accept at least some kinds of
223 // ambiguity.
224 if (Found.isAmbiguous() && NumAcceptableResults == 1) {
225 Diag(NameLoc, diag::ext_dtor_name_ambiguous);
226 LookupResult::Filter F = Found.makeFilter();
227 while (F.hasNext()) {
228 NamedDecl *D = F.next();
229 if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl()))
230 Diag(D->getLocation(), diag::note_destructor_type_here)
231 << Context.getTypeDeclType(TD);
232 else
233 Diag(D->getLocation(), diag::note_destructor_nontype_here);
234
235 if (!IsAcceptableResult(D))
236 F.erase();
237 }
238 F.done();
239 }
240
241 if (Found.isAmbiguous())
242 Failed = true;
243
244 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
245 if (IsAcceptableResult(Type)) {
246 QualType T = Context.getTypeDeclType(Type);
247 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
248 return CreateParsedType(Context.getElaboratedType(ETK_None, nullptr, T),
249 Context.getTrivialTypeSourceInfo(T, NameLoc));
250 }
251 }
252
253 return nullptr;
254 };
255
256 bool IsDependent = false;
257
258 auto LookupInObjectType = [&]() -> ParsedType {
259 if (Failed || SearchType.isNull())
260 return nullptr;
261
262 IsDependent |= SearchType->isDependentType();
263
264 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
265 DeclContext *LookupCtx = computeDeclContext(SearchType);
266 if (!LookupCtx)
267 return nullptr;
268 LookupQualifiedName(Found, LookupCtx);
269 return CheckLookupResult(Found);
270 };
271
272 auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType {
273 if (Failed)
274 return nullptr;
275
276 IsDependent |= isDependentScopeSpecifier(LookupSS);
277 DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext);
278 if (!LookupCtx)
279 return nullptr;
280
281 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
282 if (RequireCompleteDeclContext(LookupSS, LookupCtx)) {
283 Failed = true;
284 return nullptr;
285 }
286 LookupQualifiedName(Found, LookupCtx);
287 return CheckLookupResult(Found);
288 };
289
290 auto LookupInScope = [&]() -> ParsedType {
291 if (Failed || !S)
292 return nullptr;
293
294 LookupResult Found(*this, &II, NameLoc, LookupDestructorName);
295 LookupName(Found, S);
296 return CheckLookupResult(Found);
297 };
298
299 // C++2a [basic.lookup.qual]p6:
300 // In a qualified-id of the form
301 //
302 // nested-name-specifier[opt] type-name :: ~ type-name
303 //
304 // the second type-name is looked up in the same scope as the first.
305 //
306 // We interpret this as meaning that if you do a dual-scope lookup for the
307 // first name, you also do a dual-scope lookup for the second name, per
308 // C++ [basic.lookup.classref]p4:
309 //
310 // If the id-expression in a class member access is a qualified-id of the
311 // form
312 //
313 // class-name-or-namespace-name :: ...
314 //
315 // the class-name-or-namespace-name following the . or -> is first looked
316 // up in the class of the object expression and the name, if found, is used.
317 // Otherwise, it is looked up in the context of the entire
318 // postfix-expression.
319 //
320 // This looks in the same scopes as for an unqualified destructor name:
321 //
322 // C++ [basic.lookup.classref]p3:
323 // If the unqualified-id is ~ type-name, the type-name is looked up
324 // in the context of the entire postfix-expression. If the type T
325 // of the object expression is of a class type C, the type-name is
326 // also looked up in the scope of class C. At least one of the
327 // lookups shall find a name that refers to cv T.
328 //
329 // FIXME: The intent is unclear here. Should type-name::~type-name look in
330 // the scope anyway if it finds a non-matching name declared in the class?
331 // If both lookups succeed and find a dependent result, which result should
332 // we retain? (Same question for p->~type-name().)
333
334 if (NestedNameSpecifier *Prefix =
335 SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) {
336 // This is
337 //
338 // nested-name-specifier type-name :: ~ type-name
339 //
340 // Look for the second type-name in the nested-name-specifier.
341 CXXScopeSpec PrefixSS;
342 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
343 if (ParsedType T = LookupInNestedNameSpec(PrefixSS))
344 return T;
345 } else {
346 // This is one of
347 //
348 // type-name :: ~ type-name
349 // ~ type-name
350 //
351 // Look in the scope and (if any) the object type.
352 if (ParsedType T = LookupInScope())
353 return T;
354 if (ParsedType T = LookupInObjectType())
355 return T;
356 }
357
358 if (Failed)
359 return nullptr;
360
361 if (IsDependent) {
362 // We didn't find our type, but that's OK: it's dependent anyway.
363
364 // FIXME: What if we have no nested-name-specifier?
365 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
366 SS.getWithLocInContext(Context),
367 II, NameLoc);
368 return ParsedType::make(T);
369 }
370
371 // The remaining cases are all non-standard extensions imitating the behavior
372 // of various other compilers.
373 unsigned NumNonExtensionDecls = FoundDecls.size();
374
375 if (SS.isSet()) {
376 // For compatibility with older broken C++ rules and existing code,
377 //
378 // nested-name-specifier :: ~ type-name
379 //
380 // also looks for type-name within the nested-name-specifier.
381 if (ParsedType T = LookupInNestedNameSpec(SS)) {
382 Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope)
383 << SS.getRange()
384 << FixItHint::CreateInsertion(SS.getEndLoc(),
385 ("::" + II.getName()).str());
386 return T;
387 }
388
389 // For compatibility with other compilers and older versions of Clang,
390 //
391 // nested-name-specifier type-name :: ~ type-name
392 //
393 // also looks for type-name in the scope. Unfortunately, we can't
394 // reasonably apply this fallback for dependent nested-name-specifiers.
395 if (SS.isValid() && SS.getScopeRep()->getPrefix()) {
396 if (ParsedType T = LookupInScope()) {
397 Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope)
398 << FixItHint::CreateRemoval(SS.getRange());
399 Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here)
400 << GetTypeFromParser(T);
401 return T;
402 }
403 }
404 }
405
406 // We didn't find anything matching; tell the user what we did find (if
407 // anything).
408
409 // Don't tell the user about declarations we shouldn't have found.
410 FoundDecls.resize(NumNonExtensionDecls);
411
412 // List types before non-types.
413 std::stable_sort(FoundDecls.begin(), FoundDecls.end(),
414 [](NamedDecl *A, NamedDecl *B) {
415 return isa<TypeDecl>(A->getUnderlyingDecl()) >
416 isa<TypeDecl>(B->getUnderlyingDecl());
417 });
418
419 // Suggest a fixit to properly name the destroyed type.
420 auto MakeFixItHint = [&]{
421 const CXXRecordDecl *Destroyed = nullptr;
422 // FIXME: If we have a scope specifier, suggest its last component?
423 if (!SearchType.isNull())
424 Destroyed = SearchType->getAsCXXRecordDecl();
425 else if (S)
426 Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity());
427 if (Destroyed)
428 return FixItHint::CreateReplacement(SourceRange(NameLoc),
429 Destroyed->getNameAsString());
430 return FixItHint();
431 };
432
433 if (FoundDecls.empty()) {
434 // FIXME: Attempt typo-correction?
435 Diag(NameLoc, diag::err_undeclared_destructor_name)
436 << &II << MakeFixItHint();
437 } else if (!SearchType.isNull() && FoundDecls.size() == 1) {
438 if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) {
439 assert(!SearchType.isNull() &&(static_cast <bool> (!SearchType.isNull() && "should only reject a type result if we have a search type"
) ? void (0) : __assert_fail ("!SearchType.isNull() && \"should only reject a type result if we have a search type\""
, "clang/lib/Sema/SemaExprCXX.cpp", 440, __extension__ __PRETTY_FUNCTION__
))
440 "should only reject a type result if we have a search type")(static_cast <bool> (!SearchType.isNull() && "should only reject a type result if we have a search type"
) ? void (0) : __assert_fail ("!SearchType.isNull() && \"should only reject a type result if we have a search type\""
, "clang/lib/Sema/SemaExprCXX.cpp", 440, __extension__ __PRETTY_FUNCTION__
))
;
441 QualType T = Context.getTypeDeclType(TD);
442 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
443 << T << SearchType << MakeFixItHint();
444 } else {
445 Diag(NameLoc, diag::err_destructor_expr_nontype)
446 << &II << MakeFixItHint();
447 }
448 } else {
449 Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype
450 : diag::err_destructor_expr_mismatch)
451 << &II << SearchType << MakeFixItHint();
452 }
453
454 for (NamedDecl *FoundD : FoundDecls) {
455 if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl()))
456 Diag(FoundD->getLocation(), diag::note_destructor_type_here)
457 << Context.getTypeDeclType(TD);
458 else
459 Diag(FoundD->getLocation(), diag::note_destructor_nontype_here)
460 << FoundD;
461 }
462
463 return nullptr;
464}
465
466ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
467 ParsedType ObjectType) {
468 if (DS.getTypeSpecType() == DeclSpec::TST_error)
469 return nullptr;
470
471 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
472 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
473 return nullptr;
474 }
475
476 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_decltype && "unexpected type in getDestructorType"
) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "clang/lib/Sema/SemaExprCXX.cpp", 477, __extension__ __PRETTY_FUNCTION__
))
477 "unexpected type in getDestructorType")(static_cast <bool> (DS.getTypeSpecType() == DeclSpec::
TST_decltype && "unexpected type in getDestructorType"
) ? void (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "clang/lib/Sema/SemaExprCXX.cpp", 477, __extension__ __PRETTY_FUNCTION__
))
;
478 QualType T = BuildDecltypeType(DS.getRepAsExpr());
479
480 // If we know the type of the object, check that the correct destructor
481 // type was named now; we can give better diagnostics this way.
482 QualType SearchType = GetTypeFromParser(ObjectType);
483 if (!SearchType.isNull() && !SearchType->isDependentType() &&
484 !Context.hasSameUnqualifiedType(T, SearchType)) {
485 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
486 << T << SearchType;
487 return nullptr;
488 }
489
490 return ParsedType::make(T);
491}
492
493bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
494 const UnqualifiedId &Name, bool IsUDSuffix) {
495 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId)(static_cast <bool> (Name.getKind() == UnqualifiedIdKind
::IK_LiteralOperatorId) ? void (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId"
, "clang/lib/Sema/SemaExprCXX.cpp", 495, __extension__ __PRETTY_FUNCTION__
))
;
496 if (!IsUDSuffix) {
497 // [over.literal] p8
498 //
499 // double operator""_Bq(long double); // OK: not a reserved identifier
500 // double operator"" _Bq(long double); // ill-formed, no diagnostic required
501 IdentifierInfo *II = Name.Identifier;
502 ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts());
503 SourceLocation Loc = Name.getEndLoc();
504 if (isReservedInAllContexts(Status) &&
505 !PP.getSourceManager().isInSystemHeader(Loc)) {
506 Diag(Loc, diag::warn_reserved_extern_symbol)
507 << II << static_cast<int>(Status)
508 << FixItHint::CreateReplacement(
509 Name.getSourceRange(),
510 (StringRef("operator\"\"") + II->getName()).str());
511 }
512 }
513
514 if (!SS.isValid())
515 return false;
516
517 switch (SS.getScopeRep()->getKind()) {
518 case NestedNameSpecifier::Identifier:
519 case NestedNameSpecifier::TypeSpec:
520 case NestedNameSpecifier::TypeSpecWithTemplate:
521 // Per C++11 [over.literal]p2, literal operators can only be declared at
522 // namespace scope. Therefore, this unqualified-id cannot name anything.
523 // Reject it early, because we have no AST representation for this in the
524 // case where the scope is dependent.
525 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
526 << SS.getScopeRep();
527 return true;
528
529 case NestedNameSpecifier::Global:
530 case NestedNameSpecifier::Super:
531 case NestedNameSpecifier::Namespace:
532 case NestedNameSpecifier::NamespaceAlias:
533 return false;
534 }
535
536 llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind"
, "clang/lib/Sema/SemaExprCXX.cpp", 536)
;
537}
538
539/// Build a C++ typeid expression with a type operand.
540ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
541 SourceLocation TypeidLoc,
542 TypeSourceInfo *Operand,
543 SourceLocation RParenLoc) {
544 // C++ [expr.typeid]p4:
545 // The top-level cv-qualifiers of the lvalue expression or the type-id
546 // that is the operand of typeid are always ignored.
547 // If the type of the type-id is a class type or a reference to a class
548 // type, the class shall be completely-defined.
549 Qualifiers Quals;
550 QualType T
551 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
552 Quals);
553 if (T->getAs<RecordType>() &&
554 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
555 return ExprError();
556
557 if (T->isVariablyModifiedType())
558 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
559
560 if (CheckQualifiedFunctionForTypeId(T, TypeidLoc))
561 return ExprError();
562
563 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
564 SourceRange(TypeidLoc, RParenLoc));
565}
566
567/// Build a C++ typeid expression with an expression operand.
568ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
569 SourceLocation TypeidLoc,
570 Expr *E,
571 SourceLocation RParenLoc) {
572 bool WasEvaluated = false;
573 if (E && !E->isTypeDependent()) {
13
Assuming 'E' is null
574 if (E->hasPlaceholderType()) {
575 ExprResult result = CheckPlaceholderExpr(E);
576 if (result.isInvalid()) return ExprError();
577 E = result.get();
578 }
579
580 QualType T = E->getType();
581 if (const RecordType *RecordT = T->getAs<RecordType>()) {
582 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
583 // C++ [expr.typeid]p3:
584 // [...] If the type of the expression is a class type, the class
585 // shall be completely-defined.
586 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
587 return ExprError();
588
589 // C++ [expr.typeid]p3:
590 // When typeid is applied to an expression other than an glvalue of a
591 // polymorphic class type [...] [the] expression is an unevaluated
592 // operand. [...]
593 if (RecordD->isPolymorphic() && E->isGLValue()) {
594 if (isUnevaluatedContext()) {
595 // The operand was processed in unevaluated context, switch the
596 // context and recheck the subexpression.
597 ExprResult Result = TransformToPotentiallyEvaluated(E);
598 if (Result.isInvalid())
599 return ExprError();
600 E = Result.get();
601 }
602
603 // We require a vtable to query the type at run time.
604 MarkVTableUsed(TypeidLoc, RecordD);
605 WasEvaluated = true;
606 }
607 }
608
609 ExprResult Result = CheckUnevaluatedOperand(E);
610 if (Result.isInvalid())
611 return ExprError();
612 E = Result.get();
613
614 // C++ [expr.typeid]p4:
615 // [...] If the type of the type-id is a reference to a possibly
616 // cv-qualified type, the result of the typeid expression refers to a
617 // std::type_info object representing the cv-unqualified referenced
618 // type.
619 Qualifiers Quals;
620 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
621 if (!Context.hasSameType(T, UnqualT)) {
622 T = UnqualT;
623 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
624 }
625 }
626
627 if (E->getType()->isVariablyModifiedType())
14
Called C++ object pointer is null
628 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
629 << E->getType());
630 else if (!inTemplateInstantiation() &&
631 E->HasSideEffects(Context, WasEvaluated)) {
632 // The expression operand for typeid is in an unevaluated expression
633 // context, so side effects could result in unintended consequences.
634 Diag(E->getExprLoc(), WasEvaluated
635 ? diag::warn_side_effects_typeid
636 : diag::warn_side_effects_unevaluated_context);
637 }
638
639 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
640 SourceRange(TypeidLoc, RParenLoc));
641}
642
643/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
644ExprResult
645Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
646 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
647 // typeid is not supported in OpenCL.
648 if (getLangOpts().OpenCLCPlusPlus) {
1
Assuming field 'OpenCLCPlusPlus' is 0
2
Taking false branch
649 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
650 << "typeid");
651 }
652
653 // Find the std::type_info type.
654 if (!getStdNamespace())
3
Assuming the condition is false
4
Taking false branch
655 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
656
657 if (!CXXTypeInfoDecl) {
5
Assuming field 'CXXTypeInfoDecl' is non-null
6
Taking false branch
658 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
659 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
660 LookupQualifiedName(R, getStdNamespace());
661 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
662 // Microsoft's typeinfo doesn't have type_info in std but in the global
663 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
664 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
665 LookupQualifiedName(R, Context.getTranslationUnitDecl());
666 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
667 }
668 if (!CXXTypeInfoDecl)
669 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
670 }
671
672 if (!getLangOpts().RTTI) {
7
Assuming field 'RTTI' is not equal to 0
8
Taking false branch
673 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
674 }
675
676 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
677
678 if (isType) {
9
Assuming 'isType' is false
10
Taking false branch
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 BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
690 }
691
692 // The operand is an expression.
693 ExprResult Result =
694 BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc);
11
Passing value via 3rd parameter 'E'
12
Calling 'Sema::BuildCXXTypeId'
695
696 if (!getLangOpts().RTTIData && !Result.isInvalid())
697 if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get()))
698 if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context))
699 Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled)
700 << (getDiagnostics().getDiagnosticOptions().getFormat() ==
701 DiagnosticOptions::MSVC);
702 return Result;
703}
704
705/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
706/// a single GUID.
707static void
708getUuidAttrOfType(Sema &SemaRef, QualType QT,
709 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
710 // Optionally remove one level of pointer, reference or array indirection.
711 const Type *Ty = QT.getTypePtr();
712 if (QT->isPointerType() || QT->isReferenceType())
713 Ty = QT->getPointeeType().getTypePtr();
714 else if (QT->isArrayType())
715 Ty = Ty->getBaseElementTypeUnsafe();
716
717 const auto *TD = Ty->getAsTagDecl();
718 if (!TD)
719 return;
720
721 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
722 UuidAttrs.insert(Uuid);
723 return;
724 }
725
726 // __uuidof can grab UUIDs from template arguments.
727 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
728 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
729 for (const TemplateArgument &TA : TAL.asArray()) {
730 const UuidAttr *UuidForTA = nullptr;
731 if (TA.getKind() == TemplateArgument::Type)
732 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
733 else if (TA.getKind() == TemplateArgument::Declaration)
734 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
735
736 if (UuidForTA)
737 UuidAttrs.insert(UuidForTA);
738 }
739 }
740}
741
742/// Build a Microsoft __uuidof expression with a type operand.
743ExprResult Sema::BuildCXXUuidof(QualType Type,
744 SourceLocation TypeidLoc,
745 TypeSourceInfo *Operand,
746 SourceLocation RParenLoc) {
747 MSGuidDecl *Guid = nullptr;
748 if (!Operand->getType()->isDependentType()) {
749 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
750 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
751 if (UuidAttrs.empty())
752 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
753 if (UuidAttrs.size() > 1)
754 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
755 Guid = UuidAttrs.back()->getGuidDecl();
756 }
757
758 return new (Context)
759 CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc));
760}
761
762/// Build a Microsoft __uuidof expression with an expression operand.
763ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc,
764 Expr *E, SourceLocation RParenLoc) {
765 MSGuidDecl *Guid = nullptr;
766 if (!E->getType()->isDependentType()) {
767 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
768 // A null pointer results in {00000000-0000-0000-0000-000000000000}.
769 Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{});
770 } else {
771 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
772 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
773 if (UuidAttrs.empty())
774 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
775 if (UuidAttrs.size() > 1)
776 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
777 Guid = UuidAttrs.back()->getGuidDecl();
778 }
779 }
780
781 return new (Context)
782 CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc));
783}
784
785/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
786ExprResult
787Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
788 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
789 QualType GuidType = Context.getMSGuidType();
790 GuidType.addConst();
791
792 if (isType) {
793 // The operand is a type; handle it as such.
794 TypeSourceInfo *TInfo = nullptr;
795 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
796 &TInfo);
797 if (T.isNull())
798 return ExprError();
799
800 if (!TInfo)
801 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
802
803 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
804 }
805
806 // The operand is an expression.
807 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
808}
809
810/// ActOnCXXBoolLiteral - Parse {true,false} literals.
811ExprResult
812Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
813 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(static_cast <bool> ((Kind == tok::kw_true || Kind == tok
::kw_false) && "Unknown C++ Boolean value!") ? void (
0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "clang/lib/Sema/SemaExprCXX.cpp", 814, __extension__ __PRETTY_FUNCTION__
))
814 "Unknown C++ Boolean value!")(static_cast <bool> ((Kind == tok::kw_true || Kind == tok
::kw_false) && "Unknown C++ Boolean value!") ? void (
0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "clang/lib/Sema/SemaExprCXX.cpp", 814, __extension__ __PRETTY_FUNCTION__
))
;
815 return new (Context)
816 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
817}
818
819/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
820ExprResult
821Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
822 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
823}
824
825/// ActOnCXXThrow - Parse throw expressions.
826ExprResult
827Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
828 bool IsThrownVarInScope = false;
829 if (Ex) {
830 // C++0x [class.copymove]p31:
831 // When certain criteria are met, an implementation is allowed to omit the
832 // copy/move construction of a class object [...]
833 //
834 // - in a throw-expression, when the operand is the name of a
835 // non-volatile automatic object (other than a function or catch-
836 // clause parameter) whose scope does not extend beyond the end of the
837 // innermost enclosing try-block (if there is one), the copy/move
838 // operation from the operand to the exception object (15.1) can be
839 // omitted by constructing the automatic object directly into the
840 // exception object
841 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
842 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
843 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
844 for( ; S; S = S->getParent()) {
845 if (S->isDeclScope(Var)) {
846 IsThrownVarInScope = true;
847 break;
848 }
849
850 // FIXME: Many of the scope checks here seem incorrect.
851 if (S->getFlags() &
852 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
853 Scope::ObjCMethodScope | Scope::TryScope))
854 break;
855 }
856 }
857 }
858 }
859
860 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
861}
862
863ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
864 bool IsThrownVarInScope) {
865 // Don't report an error if 'throw' is used in system headers.
866 if (!getLangOpts().CXXExceptions &&
867 !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) {
868 // Delay error emission for the OpenMP device code.
869 targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw";
870 }
871
872 // Exceptions aren't allowed in CUDA device code.
873 if (getLangOpts().CUDA)
874 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
875 << "throw" << CurrentCUDATarget();
876
877 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
878 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
879
880 if (Ex && !Ex->isTypeDependent()) {
881 // Initialize the exception result. This implicitly weeds out
882 // abstract types or types with inaccessible copy constructors.
883
884 // C++0x [class.copymove]p31:
885 // When certain criteria are met, an implementation is allowed to omit the
886 // copy/move construction of a class object [...]
887 //
888 // - in a throw-expression, when the operand is the name of a
889 // non-volatile automatic object (other than a function or
890 // catch-clause
891 // parameter) whose scope does not extend beyond the end of the
892 // innermost enclosing try-block (if there is one), the copy/move
893 // operation from the operand to the exception object (15.1) can be
894 // omitted by constructing the automatic object directly into the
895 // exception object
896 NamedReturnInfo NRInfo =
897 IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo();
898
899 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
900 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
901 return ExprError();
902
903 InitializedEntity Entity =
904 InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy);
905 ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex);
906 if (Res.isInvalid())
907 return ExprError();
908 Ex = Res.get();
909 }
910
911 // PPC MMA non-pointer types are not allowed as throw expr types.
912 if (Ex && Context.getTargetInfo().getTriple().isPPC64())
913 CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc());
914
915 return new (Context)
916 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
917}
918
919static void
920collectPublicBases(CXXRecordDecl *RD,
921 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
922 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
923 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
924 bool ParentIsPublic) {
925 for (const CXXBaseSpecifier &BS : RD->bases()) {
926 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
927 bool NewSubobject;
928 // Virtual bases constitute the same subobject. Non-virtual bases are
929 // always distinct subobjects.
930 if (BS.isVirtual())
931 NewSubobject = VBases.insert(BaseDecl).second;
932 else
933 NewSubobject = true;
934
935 if (NewSubobject)
936 ++SubobjectsSeen[BaseDecl];
937
938 // Only add subobjects which have public access throughout the entire chain.
939 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
940 if (PublicPath)
941 PublicSubobjectsSeen.insert(BaseDecl);
942
943 // Recurse on to each base subobject.
944 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
945 PublicPath);
946 }
947}
948
949static void getUnambiguousPublicSubobjects(
950 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
951 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
952 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
953 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
954 SubobjectsSeen[RD] = 1;
955 PublicSubobjectsSeen.insert(RD);
956 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
957 /*ParentIsPublic=*/true);
958
959 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
960 // Skip ambiguous objects.
961 if (SubobjectsSeen[PublicSubobject] > 1)
962 continue;
963
964 Objects.push_back(PublicSubobject);
965 }
966}
967
968/// CheckCXXThrowOperand - Validate the operand of a throw.
969bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
970 QualType ExceptionObjectTy, Expr *E) {
971 // If the type of the exception would be an incomplete type or a pointer
972 // to an incomplete type other than (cv) void the program is ill-formed.
973 QualType Ty = ExceptionObjectTy;
974 bool isPointer = false;
975 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
976 Ty = Ptr->getPointeeType();
977 isPointer = true;
978 }
979 if (!isPointer || !Ty->isVoidType()) {
980 if (RequireCompleteType(ThrowLoc, Ty,
981 isPointer ? diag::err_throw_incomplete_ptr
982 : diag::err_throw_incomplete,
983 E->getSourceRange()))
984 return true;
985
986 if (!isPointer && Ty->isSizelessType()) {
987 Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange();
988 return true;
989 }
990
991 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
992 diag::err_throw_abstract_type, E))
993 return true;
994 }
995
996 // If the exception has class type, we need additional handling.
997 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
998 if (!RD)
999 return false;
1000
1001 // If we are throwing a polymorphic class type or pointer thereof,
1002 // exception handling will make use of the vtable.
1003 MarkVTableUsed(ThrowLoc, RD);
1004
1005 // If a pointer is thrown, the referenced object will not be destroyed.
1006 if (isPointer)
1007 return false;
1008
1009 // If the class has a destructor, we must be able to call it.
1010 if (!RD->hasIrrelevantDestructor()) {
1011 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
1012 MarkFunctionReferenced(E->getExprLoc(), Destructor);
1013 CheckDestructorAccess(E->getExprLoc(), Destructor,
1014 PDiag(diag::err_access_dtor_exception) << Ty);
1015 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
1016 return true;
1017 }
1018 }
1019
1020 // The MSVC ABI creates a list of all types which can catch the exception
1021 // object. This list also references the appropriate copy constructor to call
1022 // if the object is caught by value and has a non-trivial copy constructor.
1023 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1024 // We are only interested in the public, unambiguous bases contained within
1025 // the exception object. Bases which are ambiguous or otherwise
1026 // inaccessible are not catchable types.
1027 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
1028 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
1029
1030 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
1031 // Attempt to lookup the copy constructor. Various pieces of machinery
1032 // will spring into action, like template instantiation, which means this
1033 // cannot be a simple walk of the class's decls. Instead, we must perform
1034 // lookup and overload resolution.
1035 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
1036 if (!CD || CD->isDeleted())
1037 continue;
1038
1039 // Mark the constructor referenced as it is used by this throw expression.
1040 MarkFunctionReferenced(E->getExprLoc(), CD);
1041
1042 // Skip this copy constructor if it is trivial, we don't need to record it
1043 // in the catchable type data.
1044 if (CD->isTrivial())
1045 continue;
1046
1047 // The copy constructor is non-trivial, create a mapping from this class
1048 // type to this constructor.
1049 // N.B. The selection of copy constructor is not sensitive to this
1050 // particular throw-site. Lookup will be performed at the catch-site to
1051 // ensure that the copy constructor is, in fact, accessible (via
1052 // friendship or any other means).
1053 Context.addCopyConstructorForExceptionObject(Subobject, CD);
1054
1055 // We don't keep the instantiated default argument expressions around so
1056 // we must rebuild them here.
1057 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
1058 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
1059 return true;
1060 }
1061 }
1062 }
1063
1064 // Under the Itanium C++ ABI, memory for the exception object is allocated by
1065 // the runtime with no ability for the compiler to request additional
1066 // alignment. Warn if the exception type requires alignment beyond the minimum
1067 // guaranteed by the target C++ runtime.
1068 if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) {
1069 CharUnits TypeAlign = Context.getTypeAlignInChars(Ty);
1070 CharUnits ExnObjAlign = Context.getExnObjectAlignment();
1071 if (ExnObjAlign < TypeAlign) {
1072 Diag(ThrowLoc, diag::warn_throw_underaligned_obj);
1073 Diag(ThrowLoc, diag::note_throw_underaligned_obj)
1074 << Ty << (unsigned)TypeAlign.getQuantity()
1075 << (unsigned)ExnObjAlign.getQuantity();
1076 }
1077 }
1078
1079 return false;
1080}
1081
1082static QualType adjustCVQualifiersForCXXThisWithinLambda(
1083 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
1084 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
1085
1086 QualType ClassType = ThisTy->getPointeeType();
1087 LambdaScopeInfo *CurLSI = nullptr;
1088 DeclContext *CurDC = CurSemaContext;
1089
1090 // Iterate through the stack of lambdas starting from the innermost lambda to
1091 // the outermost lambda, checking if '*this' is ever captured by copy - since
1092 // that could change the cv-qualifiers of the '*this' object.
1093 // The object referred to by '*this' starts out with the cv-qualifiers of its
1094 // member function. We then start with the innermost lambda and iterate
1095 // outward checking to see if any lambda performs a by-copy capture of '*this'
1096 // - and if so, any nested lambda must respect the 'constness' of that
1097 // capturing lamdbda's call operator.
1098 //
1099
1100 // Since the FunctionScopeInfo stack is representative of the lexical
1101 // nesting of the lambda expressions during initial parsing (and is the best
1102 // place for querying information about captures about lambdas that are
1103 // partially processed) and perhaps during instantiation of function templates
1104 // that contain lambda expressions that need to be transformed BUT not
1105 // necessarily during instantiation of a nested generic lambda's function call
1106 // operator (which might even be instantiated at the end of the TU) - at which
1107 // time the DeclContext tree is mature enough to query capture information
1108 // reliably - we use a two pronged approach to walk through all the lexically
1109 // enclosing lambda expressions:
1110 //
1111 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
1112 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
1113 // enclosed by the call-operator of the LSI below it on the stack (while
1114 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
1115 // the stack represents the innermost lambda.
1116 //
1117 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
1118 // represents a lambda's call operator. If it does, we must be instantiating
1119 // a generic lambda's call operator (represented by the Current LSI, and
1120 // should be the only scenario where an inconsistency between the LSI and the
1121 // DeclContext should occur), so climb out the DeclContexts if they
1122 // represent lambdas, while querying the corresponding closure types
1123 // regarding capture information.
1124
1125 // 1) Climb down the function scope info stack.
1126 for (int I = FunctionScopes.size();
1127 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
1128 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
1129 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
1130 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
1131 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1132
1133 if (!CurLSI->isCXXThisCaptured())
1134 continue;
1135
1136 auto C = CurLSI->getCXXThisCapture();
1137
1138 if (C.isCopyCapture()) {
1139 if (!CurLSI->Mutable)
1140 ClassType.addConst();
1141 return ASTCtx.getPointerType(ClassType);
1142 }
1143 }
1144
1145 // 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which
1146 // can happen during instantiation of its nested generic lambda call
1147 // operator); 2. if we're in a lambda scope (lambda body).
1148 if (CurLSI && isLambdaCallOperator(CurDC)) {
1149 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&(static_cast <bool> (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") ? 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\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1153, __extension__ __PRETTY_FUNCTION__
))
1150 "While computing 'this' capture-type for a generic lambda, when we "(static_cast <bool> (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") ? 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\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1153, __extension__ __PRETTY_FUNCTION__
))
1151 "run out of enclosing LSI's, yet the enclosing DC is a "(static_cast <bool> (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") ? 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\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1153, __extension__ __PRETTY_FUNCTION__
))
1152 "lambda-call-operator we must be (i.e. Current LSI) in a generic "(static_cast <bool> (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") ? 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\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1153, __extension__ __PRETTY_FUNCTION__
))
1153 "lambda call oeprator")(static_cast <bool> (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") ? 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\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1153, __extension__ __PRETTY_FUNCTION__
))
;
1154 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))(static_cast <bool> (CurDC == getLambdaAwareParentOfDeclContext
(CurLSI->CallOperator)) ? void (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)"
, "clang/lib/Sema/SemaExprCXX.cpp", 1154, __extension__ __PRETTY_FUNCTION__
))
;
1155
1156 auto IsThisCaptured =
1157 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1158 IsConst = false;
1159 IsByCopy = false;
1160 for (auto &&C : Closure->captures()) {
1161 if (C.capturesThis()) {
1162 if (C.getCaptureKind() == LCK_StarThis)
1163 IsByCopy = true;
1164 if (Closure->getLambdaCallOperator()->isConst())
1165 IsConst = true;
1166 return true;
1167 }
1168 }
1169 return false;
1170 };
1171
1172 bool IsByCopyCapture = false;
1173 bool IsConstCapture = false;
1174 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1175 while (Closure &&
1176 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1177 if (IsByCopyCapture) {
1178 if (IsConstCapture)
1179 ClassType.addConst();
1180 return ASTCtx.getPointerType(ClassType);
1181 }
1182 Closure = isLambdaCallOperator(Closure->getParent())
1183 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1184 : nullptr;
1185 }
1186 }
1187 return ASTCtx.getPointerType(ClassType);
1188}
1189
1190QualType Sema::getCurrentThisType() {
1191 DeclContext *DC = getFunctionLevelDeclContext();
1192 QualType ThisTy = CXXThisTypeOverride;
1193
1194 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1195 if (method && method->isInstance())
1196 ThisTy = method->getThisType();
1197 }
1198
1199 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1200 inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) {
1201
1202 // This is a lambda call operator that is being instantiated as a default
1203 // initializer. DC must point to the enclosing class type, so we can recover
1204 // the 'this' type from it.
1205 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1206 // There are no cv-qualifiers for 'this' within default initializers,
1207 // per [expr.prim.general]p4.
1208 ThisTy = Context.getPointerType(ClassTy);
1209 }
1210
1211 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1212 // might need to be adjusted if the lambda or any of its enclosing lambda's
1213 // captures '*this' by copy.
1214 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1215 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1216 CurContext, Context);
1217 return ThisTy;
1218}
1219
1220Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1221 Decl *ContextDecl,
1222 Qualifiers CXXThisTypeQuals,
1223 bool Enabled)
1224 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1225{
1226 if (!Enabled || !ContextDecl)
1227 return;
1228
1229 CXXRecordDecl *Record = nullptr;
1230 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1231 Record = Template->getTemplatedDecl();
1232 else
1233 Record = cast<CXXRecordDecl>(ContextDecl);
1234
1235 QualType T = S.Context.getRecordType(Record);
1236 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1237
1238 S.CXXThisTypeOverride = S.Context.getPointerType(T);
1239
1240 this->Enabled = true;
1241}
1242
1243
1244Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1245 if (Enabled) {
1246 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1247 }
1248}
1249
1250static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) {
1251 SourceLocation DiagLoc = LSI->IntroducerRange.getEnd();
1252 assert(!LSI->isCXXThisCaptured())(static_cast <bool> (!LSI->isCXXThisCaptured()) ? void
(0) : __assert_fail ("!LSI->isCXXThisCaptured()", "clang/lib/Sema/SemaExprCXX.cpp"
, 1252, __extension__ __PRETTY_FUNCTION__))
;
1253 // [=, this] {}; // until C++20: Error: this when = is the default
1254 if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval &&
1255 !Sema.getLangOpts().CPlusPlus20)
1256 return;
1257 Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit)
1258 << FixItHint::CreateInsertion(
1259 DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this");
1260}
1261
1262bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1263 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1264 const bool ByCopy) {
1265 // We don't need to capture this in an unevaluated context.
1266 if (isUnevaluatedContext() && !Explicit)
1267 return true;
1268
1269 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(static_cast <bool> ((!ByCopy || Explicit) && "cannot implicitly capture *this by value"
) ? void (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1269, __extension__ __PRETTY_FUNCTION__
))
;
1270
1271 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1272 ? *FunctionScopeIndexToStopAt
1273 : FunctionScopes.size() - 1;
1274
1275 // Check that we can capture the *enclosing object* (referred to by '*this')
1276 // by the capturing-entity/closure (lambda/block/etc) at
1277 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1278
1279 // Note: The *enclosing object* can only be captured by-value by a
1280 // closure that is a lambda, using the explicit notation:
1281 // [*this] { ... }.
1282 // Every other capture of the *enclosing object* results in its by-reference
1283 // capture.
1284
1285 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1286 // stack), we can capture the *enclosing object* only if:
1287 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1288 // - or, 'L' has an implicit capture.
1289 // AND
1290 // -- there is no enclosing closure
1291 // -- or, there is some enclosing closure 'E' that has already captured the
1292 // *enclosing object*, and every intervening closure (if any) between 'E'
1293 // and 'L' can implicitly capture the *enclosing object*.
1294 // -- or, every enclosing closure can implicitly capture the
1295 // *enclosing object*
1296
1297
1298 unsigned NumCapturingClosures = 0;
1299 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1300 if (CapturingScopeInfo *CSI =
1301 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1302 if (CSI->CXXThisCaptureIndex != 0) {
1303 // 'this' is already being captured; there isn't anything more to do.
1304 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1305 break;
1306 }
1307 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1308 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1309 // This context can't implicitly capture 'this'; fail out.
1310 if (BuildAndDiagnose) {
1311 Diag(Loc, diag::err_this_capture)
1312 << (Explicit && idx == MaxFunctionScopesIndex);
1313 if (!Explicit)
1314 buildLambdaThisCaptureFixit(*this, LSI);
1315 }
1316 return true;
1317 }
1318 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1319 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1320 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1321 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1322 (Explicit && idx == MaxFunctionScopesIndex)) {
1323 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1324 // iteration through can be an explicit capture, all enclosing closures,
1325 // if any, must perform implicit captures.
1326
1327 // This closure can capture 'this'; continue looking upwards.
1328 NumCapturingClosures++;
1329 continue;
1330 }
1331 // This context can't implicitly capture 'this'; fail out.
1332 if (BuildAndDiagnose)
1333 Diag(Loc, diag::err_this_capture)
1334 << (Explicit && idx == MaxFunctionScopesIndex);
1335
1336 if (!Explicit)
1337 buildLambdaThisCaptureFixit(*this, LSI);
1338 return true;
1339 }
1340 break;
1341 }
1342 if (!BuildAndDiagnose) return false;
1343
1344 // If we got here, then the closure at MaxFunctionScopesIndex on the
1345 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1346 // (including implicit by-reference captures in any enclosing closures).
1347
1348 // In the loop below, respect the ByCopy flag only for the closure requesting
1349 // the capture (i.e. first iteration through the loop below). Ignore it for
1350 // all enclosing closure's up to NumCapturingClosures (since they must be
1351 // implicitly capturing the *enclosing object* by reference (see loop
1352 // above)).
1353 assert((!ByCopy ||(static_cast <bool> ((!ByCopy || isa<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1356, __extension__ __PRETTY_FUNCTION__
))
1354 isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(static_cast <bool> ((!ByCopy || isa<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1356, __extension__ __PRETTY_FUNCTION__
))
1355 "Only a lambda can capture the enclosing object (referred to by "(static_cast <bool> ((!ByCopy || isa<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1356, __extension__ __PRETTY_FUNCTION__
))
1356 "*this) by copy")(static_cast <bool> ((!ByCopy || isa<LambdaScopeInfo
>(FunctionScopes[MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? void (0) : __assert_fail ("(!ByCopy || isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1356, __extension__ __PRETTY_FUNCTION__
))
;
1357 QualType ThisTy = getCurrentThisType();
1358 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1359 --idx, --NumCapturingClosures) {
1360 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1361
1362 // The type of the corresponding data member (not a 'this' pointer if 'by
1363 // copy').
1364 QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy;
1365
1366 bool isNested = NumCapturingClosures > 1;
1367 CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy);
1368 }
1369 return false;
1370}
1371
1372ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1373 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1374 /// is a non-lvalue expression whose value is the address of the object for
1375 /// which the function is called.
1376
1377 QualType ThisTy = getCurrentThisType();
1378 if (ThisTy.isNull())
1379 return Diag(Loc, diag::err_invalid_this_use);
1380 return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1381}
1382
1383Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
1384 bool IsImplicit) {
1385 if (getLangOpts().HLSL && Type.getTypePtr()->isPointerType()) {
1386 auto *This = new (Context)
1387 CXXThisExpr(Loc, Type.getTypePtr()->getPointeeType(), IsImplicit);
1388 This->setValueKind(ExprValueKind::VK_LValue);
1389 MarkThisReferenced(This);
1390 return This;
1391 }
1392 auto *This = new (Context) CXXThisExpr(Loc, Type, IsImplicit);
1393 MarkThisReferenced(This);
1394 return This;
1395}
1396
1397void Sema::MarkThisReferenced(CXXThisExpr *This) {
1398 CheckCXXThisCapture(This->getExprLoc());
1399}
1400
1401bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1402 // If we're outside the body of a member function, then we'll have a specified
1403 // type for 'this'.
1404 if (CXXThisTypeOverride.isNull())
1405 return false;
1406
1407 // Determine whether we're looking into a class that's currently being
1408 // defined.
1409 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1410 return Class && Class->isBeingDefined();
1411}
1412
1413/// Parse construction of a specified type.
1414/// Can be interpreted either as function-style casting ("int(x)")
1415/// or class type construction ("ClassType(x,y,z)")
1416/// or creation of a value-initialized type ("int()").
1417ExprResult
1418Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1419 SourceLocation LParenOrBraceLoc,
1420 MultiExprArg exprs,
1421 SourceLocation RParenOrBraceLoc,
1422 bool ListInitialization) {
1423 if (!TypeRep)
1424 return ExprError();
1425
1426 TypeSourceInfo *TInfo;
1427 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1428 if (!TInfo)
1429 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1430
1431 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1432 RParenOrBraceLoc, ListInitialization);
1433 // Avoid creating a non-type-dependent expression that contains typos.
1434 // Non-type-dependent expressions are liable to be discarded without
1435 // checking for embedded typos.
1436 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1437 !Result.get()->isTypeDependent())
1438 Result = CorrectDelayedTyposInExpr(Result.get());
1439 else if (Result.isInvalid())
1440 Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(),
1441 RParenOrBraceLoc, exprs, Ty);
1442 return Result;
1443}
1444
1445ExprResult
1446Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1447 SourceLocation LParenOrBraceLoc,
1448 MultiExprArg Exprs,
1449 SourceLocation RParenOrBraceLoc,
1450 bool ListInitialization) {
1451 QualType Ty = TInfo->getType();
1452 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1453
1454 assert((!ListInitialization || Exprs.size() == 1) &&(static_cast <bool> ((!ListInitialization || Exprs.size
() == 1) && "List initialization must have exactly one expression."
) ? void (0) : __assert_fail ("(!ListInitialization || Exprs.size() == 1) && \"List initialization must have exactly one expression.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1455, __extension__ __PRETTY_FUNCTION__
))
1455 "List initialization must have exactly one expression.")(static_cast <bool> ((!ListInitialization || Exprs.size
() == 1) && "List initialization must have exactly one expression."
) ? void (0) : __assert_fail ("(!ListInitialization || Exprs.size() == 1) && \"List initialization must have exactly one expression.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1455, __extension__ __PRETTY_FUNCTION__
))
;
1456 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1457
1458 InitializedEntity Entity =
1459 InitializedEntity::InitializeTemporary(Context, TInfo);
1460 InitializationKind Kind =
1461 Exprs.size()
1462 ? ListInitialization
1463 ? InitializationKind::CreateDirectList(
1464 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1465 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1466 RParenOrBraceLoc)
1467 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1468 RParenOrBraceLoc);
1469
1470 // C++17 [expr.type.conv]p1:
1471 // If the type is a placeholder for a deduced class type, [...perform class
1472 // template argument deduction...]
1473 // C++23:
1474 // Otherwise, if the type contains a placeholder type, it is replaced by the
1475 // type determined by placeholder type deduction.
1476 DeducedType *Deduced = Ty->getContainedDeducedType();
1477 if (Deduced && !Deduced->isDeduced() &&
1478 isa<DeducedTemplateSpecializationType>(Deduced)) {
1479 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1480 Kind, Exprs);
1481 if (Ty.isNull())
1482 return ExprError();
1483 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1484 } else if (Deduced && !Deduced->isDeduced()) {
1485 MultiExprArg Inits = Exprs;
1486 if (ListInitialization) {
1487 auto *ILE = cast<InitListExpr>(Exprs[0]);
1488 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
1489 }
1490
1491 if (Inits.empty())
1492 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression)
1493 << Ty << FullRange);
1494 if (Inits.size() > 1) {
1495 Expr *FirstBad = Inits[1];
1496 return ExprError(Diag(FirstBad->getBeginLoc(),
1497 diag::err_auto_expr_init_multiple_expressions)
1498 << Ty << FullRange);
1499 }
1500 if (getLangOpts().CPlusPlus23) {
1501 if (Ty->getAs<AutoType>())
1502 Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange;
1503 }
1504 Expr *Deduce = Inits[0];
1505 if (isa<InitListExpr>(Deduce))
1506 return ExprError(
1507 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
1508 << ListInitialization << Ty << FullRange);
1509 QualType DeducedType;
1510 TemplateDeductionInfo Info(Deduce->getExprLoc());
1511 TemplateDeductionResult Result =
1512 DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info);
1513 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed)
1514 return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure)
1515 << Ty << Deduce->getType() << FullRange
1516 << Deduce->getSourceRange());
1517 if (DeducedType.isNull()) {
1518 assert(Result == TDK_AlreadyDiagnosed)(static_cast <bool> (Result == TDK_AlreadyDiagnosed) ? void
(0) : __assert_fail ("Result == TDK_AlreadyDiagnosed", "clang/lib/Sema/SemaExprCXX.cpp"
, 1518, __extension__ __PRETTY_FUNCTION__))
;
1519 return ExprError();
1520 }
1521
1522 Ty = DeducedType;
1523 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1524 }
1525
1526 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs))
1527 return CXXUnresolvedConstructExpr::Create(
1528 Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs,
1529 RParenOrBraceLoc, ListInitialization);
1530
1531 // C++ [expr.type.conv]p1:
1532 // If the expression list is a parenthesized single expression, the type
1533 // conversion expression is equivalent (in definedness, and if defined in
1534 // meaning) to the corresponding cast expression.
1535 if (Exprs.size() == 1 && !ListInitialization &&
1536 !isa<InitListExpr>(Exprs[0])) {
1537 Expr *Arg = Exprs[0];
1538 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1539 RParenOrBraceLoc);
1540 }
1541
1542 // For an expression of the form T(), T shall not be an array type.
1543 QualType ElemTy = Ty;
1544 if (Ty->isArrayType()) {
1545 if (!ListInitialization)
1546 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1547 << FullRange);
1548 ElemTy = Context.getBaseElementType(Ty);
1549 }
1550
1551 // Only construct objects with object types.
1552 // The standard doesn't explicitly forbid function types here, but that's an
1553 // obvious oversight, as there's no way to dynamically construct a function
1554 // in general.
1555 if (Ty->isFunctionType())
1556 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1557 << Ty << FullRange);
1558
1559 // C++17 [expr.type.conv]p2:
1560 // If the type is cv void and the initializer is (), the expression is a
1561 // prvalue of the specified type that performs no initialization.
1562 if (!Ty->isVoidType() &&
1563 RequireCompleteType(TyBeginLoc, ElemTy,
1564 diag::err_invalid_incomplete_type_use, FullRange))
1565 return ExprError();
1566
1567 // Otherwise, the expression is a prvalue of the specified type whose
1568 // result object is direct-initialized (11.6) with the initializer.
1569 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1570 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1571
1572 if (Result.isInvalid())
1573 return Result;
1574
1575 Expr *Inner = Result.get();
1576 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1577 Inner = BTE->getSubExpr();
1578 if (auto *CE = dyn_cast<ConstantExpr>(Inner);
1579 CE && CE->isImmediateInvocation())
1580 Inner = CE->getSubExpr();
1581 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1582 !isa<CXXScalarValueInitExpr>(Inner)) {
1583 // If we created a CXXTemporaryObjectExpr, that node also represents the
1584 // functional cast. Otherwise, create an explicit cast to represent
1585 // the syntactic form of a functional-style cast that was used here.
1586 //
1587 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1588 // would give a more consistent AST representation than using a
1589 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1590 // is sometimes handled by initialization and sometimes not.
1591 QualType ResultType = Result.get()->getType();
1592 SourceRange Locs = ListInitialization
1593 ? SourceRange()
1594 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1595 Result = CXXFunctionalCastExpr::Create(
1596 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1597 Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(),
1598 Locs.getBegin(), Locs.getEnd());
1599 }
1600
1601 return Result;
1602}
1603
1604bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1605 // [CUDA] Ignore this function, if we can't call it.
1606 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
1607 if (getLangOpts().CUDA) {
1608 auto CallPreference = IdentifyCUDAPreference(Caller, Method);
1609 // If it's not callable at all, it's not the right function.
1610 if (CallPreference < CFP_WrongSide)
1611 return false;
1612 if (CallPreference == CFP_WrongSide) {
1613 // Maybe. We have to check if there are better alternatives.
1614 DeclContext::lookup_result R =
1615 Method->getDeclContext()->lookup(Method->getDeclName());
1616 for (const auto *D : R) {
1617 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1618 if (IdentifyCUDAPreference(Caller, FD) > CFP_WrongSide)
1619 return false;
1620 }
1621 }
1622 // We've found no better variants.
1623 }
1624 }
1625
1626 SmallVector<const FunctionDecl*, 4> PreventedBy;
1627 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1628
1629 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1630 return Result;
1631
1632 // In case of CUDA, return true if none of the 1-argument deallocator
1633 // functions are actually callable.
1634 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1635 assert(FD->getNumParams() == 1 &&(static_cast <bool> (FD->getNumParams() == 1 &&
"Only single-operand functions should be in PreventedBy") ? void
(0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1636, __extension__ __PRETTY_FUNCTION__
))
1636 "Only single-operand functions should be in PreventedBy")(static_cast <bool> (FD->getNumParams() == 1 &&
"Only single-operand functions should be in PreventedBy") ? void
(0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1636, __extension__ __PRETTY_FUNCTION__
))
;
1637 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1638 });
1639}
1640
1641/// Determine whether the given function is a non-placement
1642/// deallocation function.
1643static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1644 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1645 return S.isUsualDeallocationFunction(Method);
1646
1647 if (FD->getOverloadedOperator() != OO_Delete &&
1648 FD->getOverloadedOperator() != OO_Array_Delete)
1649 return false;
1650
1651 unsigned UsualParams = 1;
1652
1653 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1654 S.Context.hasSameUnqualifiedType(
1655 FD->getParamDecl(UsualParams)->getType(),
1656 S.Context.getSizeType()))
1657 ++UsualParams;
1658
1659 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1660 S.Context.hasSameUnqualifiedType(
1661 FD->getParamDecl(UsualParams)->getType(),
1662 S.Context.getTypeDeclType(S.getStdAlignValT())))
1663 ++UsualParams;
1664
1665 return UsualParams == FD->getNumParams();
1666}
1667
1668namespace {
1669 struct UsualDeallocFnInfo {
1670 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1671 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1672 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1673 Destroying(false), HasSizeT(false), HasAlignValT(false),
1674 CUDAPref(Sema::CFP_Native) {
1675 // A function template declaration is never a usual deallocation function.
1676 if (!FD)
1677 return;
1678 unsigned NumBaseParams = 1;
1679 if (FD->isDestroyingOperatorDelete()) {
1680 Destroying = true;
1681 ++NumBaseParams;
1682 }
1683
1684 if (NumBaseParams < FD->getNumParams() &&
1685 S.Context.hasSameUnqualifiedType(
1686 FD->getParamDecl(NumBaseParams)->getType(),
1687 S.Context.getSizeType())) {
1688 ++NumBaseParams;
1689 HasSizeT = true;
1690 }
1691
1692 if (NumBaseParams < FD->getNumParams() &&
1693 FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) {
1694 ++NumBaseParams;
1695 HasAlignValT = true;
1696 }
1697
1698 // In CUDA, determine how much we'd like / dislike to call this.
1699 if (S.getLangOpts().CUDA)
1700 if (auto *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true))
1701 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1702 }
1703
1704 explicit operator bool() const { return FD; }
1705
1706 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1707 bool WantAlign) const {
1708 // C++ P0722:
1709 // A destroying operator delete is preferred over a non-destroying
1710 // operator delete.
1711 if (Destroying != Other.Destroying)
1712 return Destroying;
1713
1714 // C++17 [expr.delete]p10:
1715 // If the type has new-extended alignment, a function with a parameter
1716 // of type std::align_val_t is preferred; otherwise a function without
1717 // such a parameter is preferred
1718 if (HasAlignValT != Other.HasAlignValT)
1719 return HasAlignValT == WantAlign;
1720
1721 if (HasSizeT != Other.HasSizeT)
1722 return HasSizeT == WantSize;
1723
1724 // Use CUDA call preference as a tiebreaker.
1725 return CUDAPref > Other.CUDAPref;
1726 }
1727
1728 DeclAccessPair Found;
1729 FunctionDecl *FD;
1730 bool Destroying, HasSizeT, HasAlignValT;
1731 Sema::CUDAFunctionPreference CUDAPref;
1732 };
1733}
1734
1735/// Determine whether a type has new-extended alignment. This may be called when
1736/// the type is incomplete (for a delete-expression with an incomplete pointee
1737/// type), in which case it will conservatively return false if the alignment is
1738/// not known.
1739static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1740 return S.getLangOpts().AlignedAllocation &&
1741 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1742 S.getASTContext().getTargetInfo().getNewAlign();
1743}
1744
1745/// Select the correct "usual" deallocation function to use from a selection of
1746/// deallocation functions (either global or class-scope).
1747static UsualDeallocFnInfo resolveDeallocationOverload(
1748 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1749 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1750 UsualDeallocFnInfo Best;
1751
1752 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1753 UsualDeallocFnInfo Info(S, I.getPair());
1754 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1755 Info.CUDAPref == Sema::CFP_Never)
1756 continue;
1757
1758 if (!Best) {
1759 Best = Info;
1760 if (BestFns)
1761 BestFns->push_back(Info);
1762 continue;
1763 }
1764
1765 if (Best.isBetterThan(Info, WantSize, WantAlign))
1766 continue;
1767
1768 // If more than one preferred function is found, all non-preferred
1769 // functions are eliminated from further consideration.
1770 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1771 BestFns->clear();
1772
1773 Best = Info;
1774 if (BestFns)
1775 BestFns->push_back(Info);
1776 }
1777
1778 return Best;
1779}
1780
1781/// Determine whether a given type is a class for which 'delete[]' would call
1782/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1783/// we need to store the array size (even if the type is
1784/// trivially-destructible).
1785static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1786 QualType allocType) {
1787 const RecordType *record =
1788 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1789 if (!record) return false;
1790
1791 // Try to find an operator delete[] in class scope.
1792
1793 DeclarationName deleteName =
1794 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1795 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1796 S.LookupQualifiedName(ops, record->getDecl());
1797
1798 // We're just doing this for information.
1799 ops.suppressDiagnostics();
1800
1801 // Very likely: there's no operator delete[].
1802 if (ops.empty()) return false;
1803
1804 // If it's ambiguous, it should be illegal to call operator delete[]
1805 // on this thing, so it doesn't matter if we allocate extra space or not.
1806 if (ops.isAmbiguous()) return false;
1807
1808 // C++17 [expr.delete]p10:
1809 // If the deallocation functions have class scope, the one without a
1810 // parameter of type std::size_t is selected.
1811 auto Best = resolveDeallocationOverload(
1812 S, ops, /*WantSize*/false,
1813 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1814 return Best && Best.HasSizeT;
1815}
1816
1817/// Parsed a C++ 'new' expression (C++ 5.3.4).
1818///
1819/// E.g.:
1820/// @code new (memory) int[size][4] @endcode
1821/// or
1822/// @code ::new Foo(23, "hello") @endcode
1823///
1824/// \param StartLoc The first location of the expression.
1825/// \param UseGlobal True if 'new' was prefixed with '::'.
1826/// \param PlacementLParen Opening paren of the placement arguments.
1827/// \param PlacementArgs Placement new arguments.
1828/// \param PlacementRParen Closing paren of the placement arguments.
1829/// \param TypeIdParens If the type is in parens, the source range.
1830/// \param D The type to be allocated, as well as array dimensions.
1831/// \param Initializer The initializing expression or initializer-list, or null
1832/// if there is none.
1833ExprResult
1834Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1835 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1836 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1837 Declarator &D, Expr *Initializer) {
1838 std::optional<Expr *> ArraySize;
1839 // If the specified type is an array, unwrap it and save the expression.
1840 if (D.getNumTypeObjects() > 0 &&
1841 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1842 DeclaratorChunk &Chunk = D.getTypeObject(0);
1843 if (D.getDeclSpec().hasAutoTypeSpec())
1844 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1845 << D.getSourceRange());
1846 if (Chunk.Arr.hasStatic)
1847 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1848 << D.getSourceRange());
1849 if (!Chunk.Arr.NumElts && !Initializer)
1850 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1851 << D.getSourceRange());
1852
1853 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1854 D.DropFirstTypeObject();
1855 }
1856
1857 // Every dimension shall be of constant size.
1858 if (ArraySize) {
1859 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1860 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1861 break;
1862
1863 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1864 if (Expr *NumElts = (Expr *)Array.NumElts) {
1865 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1866 // FIXME: GCC permits constant folding here. We should either do so consistently
1867 // or not do so at all, rather than changing behavior in C++14 onwards.
1868 if (getLangOpts().CPlusPlus14) {
1869 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1870 // shall be a converted constant expression (5.19) of type std::size_t
1871 // and shall evaluate to a strictly positive value.
1872 llvm::APSInt Value(Context.getIntWidth(Context.getSizeType()));
1873 Array.NumElts
1874 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1875 CCEK_ArrayBound)
1876 .get();
1877 } else {
1878 Array.NumElts =
1879 VerifyIntegerConstantExpression(
1880 NumElts, nullptr, diag::err_new_array_nonconst, AllowFold)
1881 .get();
1882 }
1883 if (!Array.NumElts)
1884 return ExprError();
1885 }
1886 }
1887 }
1888 }
1889
1890 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1891 QualType AllocType = TInfo->getType();
1892 if (D.isInvalidType())
1893 return ExprError();
1894
1895 SourceRange DirectInitRange;
1896 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1897 DirectInitRange = List->getSourceRange();
1898
1899 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1900 PlacementLParen, PlacementArgs, PlacementRParen,
1901 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1902 Initializer);
1903}
1904
1905static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1906 Expr *Init) {
1907 if (!Init)
1908 return true;
1909 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1910 return PLE->getNumExprs() == 0;
1911 if (isa<ImplicitValueInitExpr>(Init))
1912 return true;
1913 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1914 return !CCE->isListInitialization() &&
1915 CCE->getConstructor()->isDefaultConstructor();
1916 else if (Style == CXXNewExpr::ListInit) {
1917 assert(isa<InitListExpr>(Init) &&(static_cast <bool> (isa<InitListExpr>(Init) &&
"Shouldn't create list CXXConstructExprs for arrays.") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1918, __extension__ __PRETTY_FUNCTION__
))
1918 "Shouldn't create list CXXConstructExprs for arrays.")(static_cast <bool> (isa<InitListExpr>(Init) &&
"Shouldn't create list CXXConstructExprs for arrays.") ? void
(0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1918, __extension__ __PRETTY_FUNCTION__
))
;
1919 return true;
1920 }
1921 return false;
1922}
1923
1924bool
1925Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1926 if (!getLangOpts().AlignedAllocationUnavailable)
1927 return false;
1928 if (FD.isDefined())
1929 return false;
1930 std::optional<unsigned> AlignmentParam;
1931 if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) &&
1932 AlignmentParam)
1933 return true;
1934 return false;
1935}
1936
1937// Emit a diagnostic if an aligned allocation/deallocation function that is not
1938// implemented in the standard library is selected.
1939void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1940 SourceLocation Loc) {
1941 if (isUnavailableAlignedAllocationFunction(FD)) {
1942 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1943 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1944 getASTContext().getTargetInfo().getPlatformName());
1945 VersionTuple OSVersion = alignedAllocMinVersion(T.getOS());
1946
1947 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1948 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1949 Diag(Loc, diag::err_aligned_allocation_unavailable)
1950 << IsDelete << FD.getType().getAsString() << OSName
1951 << OSVersion.getAsString() << OSVersion.empty();
1952 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1953 }
1954}
1955
1956ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1957 SourceLocation PlacementLParen,
1958 MultiExprArg PlacementArgs,
1959 SourceLocation PlacementRParen,
1960 SourceRange TypeIdParens, QualType AllocType,
1961 TypeSourceInfo *AllocTypeInfo,
1962 std::optional<Expr *> ArraySize,
1963 SourceRange DirectInitRange, Expr *Initializer) {
1964 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1965 SourceLocation StartLoc = Range.getBegin();
1966
1967 CXXNewExpr::InitializationStyle initStyle;
1968 if (DirectInitRange.isValid()) {
1969 assert(Initializer && "Have parens but no initializer.")(static_cast <bool> (Initializer && "Have parens but no initializer."
) ? void (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1969, __extension__ __PRETTY_FUNCTION__
))
;
1970 initStyle = CXXNewExpr::CallInit;
1971 } else if (Initializer && isa<InitListExpr>(Initializer))
1972 initStyle = CXXNewExpr::ListInit;
1973 else {
1974 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1976, __extension__ __PRETTY_FUNCTION__
))
1975 isa<CXXConstructExpr>(Initializer)) &&(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1976, __extension__ __PRETTY_FUNCTION__
))
1976 "Initializer expression that cannot have been implicitly created.")(static_cast <bool> ((!Initializer || isa<ImplicitValueInitExpr
>(Initializer) || isa<CXXConstructExpr>(Initializer)
) && "Initializer expression that cannot have been implicitly created."
) ? void (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1976, __extension__ __PRETTY_FUNCTION__
))
;
1977 initStyle = CXXNewExpr::NoInit;
1978 }
1979
1980 MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0);
1981 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1982 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")(static_cast <bool> (initStyle == CXXNewExpr::CallInit &&
"paren init for non-call init") ? void (0) : __assert_fail (
"initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\""
, "clang/lib/Sema/SemaExprCXX.cpp", 1982, __extension__ __PRETTY_FUNCTION__
))
;
1983 Exprs = MultiExprArg(List->getExprs(), List->getNumExprs());
1984 }
1985
1986 // C++11 [expr.new]p15:
1987 // A new-expression that creates an object of type T initializes that
1988 // object as follows:
1989 InitializationKind Kind
1990 // - If the new-initializer is omitted, the object is default-
1991 // initialized (8.5); if no initialization is performed,
1992 // the object has indeterminate value
1993 = initStyle == CXXNewExpr::NoInit
1994 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1995 // - Otherwise, the new-initializer is interpreted according to
1996 // the
1997 // initialization rules of 8.5 for direct-initialization.
1998 : initStyle == CXXNewExpr::ListInit
1999 ? InitializationKind::CreateDirectList(
2000 TypeRange.getBegin(), Initializer->getBeginLoc(),
2001 Initializer->getEndLoc())
2002 : InitializationKind::CreateDirect(TypeRange.getBegin(),
2003 DirectInitRange.getBegin(),
2004 DirectInitRange.getEnd());
2005
2006 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
2007 auto *Deduced = AllocType->getContainedDeducedType();
2008 if (Deduced && !Deduced->isDeduced() &&
2009 isa<DeducedTemplateSpecializationType>(Deduced)) {
2010 if (ArraySize)
2011 return ExprError(
2012 Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(),
2013 diag::err_deduced_class_template_compound_type)
2014 << /*array*/ 2
2015 << (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange));
2016
2017 InitializedEntity Entity
2018 = InitializedEntity::InitializeNew(StartLoc, AllocType);
2019 AllocType = DeduceTemplateSpecializationFromInitializer(
2020 AllocTypeInfo, Entity, Kind, Exprs);
2021 if (AllocType.isNull())
2022 return ExprError();
2023 } else if (Deduced && !Deduced->isDeduced()) {
2024 MultiExprArg Inits = Exprs;
2025 bool Braced = (initStyle == CXXNewExpr::ListInit);
2026 if (Braced) {
2027 auto *ILE = cast<InitListExpr>(Exprs[0]);
2028 Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits());
2029 }
2030
2031 if (initStyle == CXXNewExpr::NoInit || Inits.empty())
2032 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
2033 << AllocType << TypeRange);
2034 if (Inits.size() > 1) {
2035 Expr *FirstBad = Inits[1];
2036 return ExprError(Diag(FirstBad->getBeginLoc(),
2037 diag::err_auto_new_ctor_multiple_expressions)
2038 << AllocType << TypeRange);
2039 }
2040 if (Braced && !getLangOpts().CPlusPlus17)
2041 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
2042 << AllocType << TypeRange;
2043 Expr *Deduce = Inits[0];
2044 if (isa<InitListExpr>(Deduce))
2045 return ExprError(
2046 Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces)
2047 << Braced << AllocType << TypeRange);
2048 QualType DeducedType;
2049 TemplateDeductionInfo Info(Deduce->getExprLoc());
2050 TemplateDeductionResult Result =
2051 DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info);
2052 if (Result != TDK_Success && Result != TDK_AlreadyDiagnosed)
2053 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
2054 << AllocType << Deduce->getType() << TypeRange
2055 << Deduce->getSourceRange());
2056 if (DeducedType.isNull()) {
2057 assert(Result == TDK_AlreadyDiagnosed)(static_cast <bool> (Result == TDK_AlreadyDiagnosed) ? void
(0) : __assert_fail ("Result == TDK_AlreadyDiagnosed", "clang/lib/Sema/SemaExprCXX.cpp"
, 2057, __extension__ __PRETTY_FUNCTION__))
;
2058 return ExprError();
2059 }
2060 AllocType = DeducedType;
2061 }
2062
2063 // Per C++0x [expr.new]p5, the type being constructed may be a
2064 // typedef of an array type.
2065 if (!ArraySize) {
2066 if (const ConstantArrayType *Array
2067 = Context.getAsConstantArrayType(AllocType)) {
2068 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
2069 Context.getSizeType(),
2070 TypeRange.getEnd());
2071 AllocType = Array->getElementType();
2072 }
2073 }
2074
2075 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
2076 return ExprError();
2077
2078 if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin()))
2079 return ExprError();
2080
2081 // In ARC, infer 'retaining' for the allocated
2082 if (getLangOpts().ObjCAutoRefCount &&
2083 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2084 AllocType->isObjCLifetimeType()) {
2085 AllocType = Context.getLifetimeQualifiedType(AllocType,
2086 AllocType->getObjCARCImplicitLifetime());
2087 }
2088
2089 QualType ResultType = Context.getPointerType(AllocType);
2090
2091 if (ArraySize && *ArraySize &&
2092 (*ArraySize)->getType()->isNonOverloadPlaceholderType()) {
2093 ExprResult result = CheckPlaceholderExpr(*ArraySize);
2094 if (result.isInvalid()) return ExprError();
2095 ArraySize = result.get();
2096 }
2097 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
2098 // integral or enumeration type with a non-negative value."
2099 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
2100 // enumeration type, or a class type for which a single non-explicit
2101 // conversion function to integral or unscoped enumeration type exists.
2102 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
2103 // std::size_t.
2104 std::optional<uint64_t> KnownArraySize;
2105 if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) {
2106 ExprResult ConvertedSize;
2107 if (getLangOpts().CPlusPlus14) {
2108 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")(static_cast <bool> (Context.getTargetInfo().getIntWidth
() && "Builtin type of size 0?") ? void (0) : __assert_fail
("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\""
, "clang/lib/Sema/SemaExprCXX.cpp", 2108, __extension__ __PRETTY_FUNCTION__
))
;
2109
2110 ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(),
2111 AA_Converting);
2112
2113 if (!ConvertedSize.isInvalid() &&
2114 (*ArraySize)->getType()->getAs<RecordType>())
2115 // Diagnose the compatibility of this conversion.
2116 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
2117 << (*ArraySize)->getType() << 0 << "'size_t'";
2118 } else {
2119 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
2120 protected:
2121 Expr *ArraySize;
2122
2123 public:
2124 SizeConvertDiagnoser(Expr *ArraySize)
2125 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
2126 ArraySize(ArraySize) {}
2127
2128 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
2129 QualType T) override {
2130 return S.Diag(Loc, diag::err_array_size_not_integral)
2131 << S.getLangOpts().CPlusPlus11 << T;
2132 }
2133
2134 SemaDiagnosticBuilder diagnoseIncomplete(
2135 Sema &S, SourceLocation Loc, QualType T) override {
2136 return S.Diag(Loc, diag::err_array_size_incomplete_type)
2137 << T << ArraySize->getSourceRange();
2138 }
2139
2140 SemaDiagnosticBuilder diagnoseExplicitConv(
2141 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
2142 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
2143 }
2144
2145 SemaDiagnosticBuilder noteExplicitConv(
2146 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2147 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2148 << ConvTy->isEnumeralType() << ConvTy;
2149 }
2150
2151 SemaDiagnosticBuilder diagnoseAmbiguous(
2152 Sema &S, SourceLocation Loc, QualType T) override {
2153 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
2154 }
2155
2156 SemaDiagnosticBuilder noteAmbiguous(
2157 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
2158 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
2159 << ConvTy->isEnumeralType() << ConvTy;
2160 }
2161
2162 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2163 QualType T,
2164 QualType ConvTy) override {
2165 return S.Diag(Loc,
2166 S.getLangOpts().CPlusPlus11
2167 ? diag::warn_cxx98_compat_array_size_conversion
2168 : diag::ext_array_size_conversion)
2169 << T << ConvTy->isEnumeralType() << ConvTy;
2170 }
2171 } SizeDiagnoser(*ArraySize);
2172
2173 ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize,
2174 SizeDiagnoser);
2175 }
2176 if (ConvertedSize.isInvalid())
2177 return ExprError();
2178
2179 ArraySize = ConvertedSize.get();
2180 QualType SizeType = (*ArraySize)->getType();
2181
2182 if (!SizeType->isIntegralOrUnscopedEnumerationType())
2183 return ExprError();
2184
2185 // C++98 [expr.new]p7:
2186 // The expression in a direct-new-declarator shall have integral type
2187 // with a non-negative value.
2188 //
2189 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2190 // per CWG1464. Otherwise, if it's not a constant, we must have an
2191 // unparenthesized array type.
2192
2193 // We've already performed any required implicit conversion to integer or
2194 // unscoped enumeration type.
2195 // FIXME: Per CWG1464, we are required to check the value prior to
2196 // converting to size_t. This will never find a negative array size in
2197 // C++14 onwards, because Value is always unsigned here!
2198 if (std::optional<llvm::APSInt> Value =
2199 (*ArraySize)->getIntegerConstantExpr(Context)) {
2200 if (Value->isSigned() && Value->isNegative()) {
2201 return ExprError(Diag((*ArraySize)->getBeginLoc(),
2202 diag::err_typecheck_negative_array_size)
2203 << (*ArraySize)->getSourceRange());
2204 }
2205
2206 if (!AllocType->isDependentType()) {
2207 unsigned ActiveSizeBits =
2208 ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value);
2209 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2210 return ExprError(
2211 Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large)
2212 << toString(*Value, 10) << (*ArraySize)->getSourceRange());
2213 }
2214
2215 KnownArraySize = Value->getZExtValue();
2216 } else if (TypeIdParens.isValid()) {
2217 // Can't have dynamic array size when the type-id is in parentheses.
2218 Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2219 << (*ArraySize)->getSourceRange()
2220 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2221 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2222
2223 TypeIdParens = SourceRange();
2224 }
2225
2226 // Note that we do *not* convert the argument in any way. It can
2227 // be signed, larger than size_t, whatever.
2228 }
2229
2230 FunctionDecl *OperatorNew = nullptr;
2231 FunctionDecl *OperatorDelete = nullptr;
2232 unsigned Alignment =
2233 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2234 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2235 bool PassAlignment = getLangOpts().AlignedAllocation &&
2236 Alignment > NewAlignment;
2237
2238 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
2239 if (!AllocType->isDependentType() &&
2240 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2241 FindAllocationFunctions(
2242 StartLoc, SourceRange(PlacementLParen, PlacementRParen), Scope, Scope,
2243 AllocType, ArraySize.has_value(), PassAlignment, PlacementArgs,
2244 OperatorNew, OperatorDelete))
2245 return ExprError();
2246
2247 // If this is an array allocation, compute whether the usual array
2248 // deallocation function for the type has a size_t parameter.
2249 bool UsualArrayDeleteWantsSize = false;
2250 if (ArraySize && !AllocType->isDependentType())
2251 UsualArrayDeleteWantsSize =
2252 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2253
2254 SmallVector<Expr *, 8> AllPlaceArgs;
2255 if (OperatorNew) {
2256 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2257 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2258 : VariadicDoesNotApply;
2259
2260 // We've already converted the placement args, just fill in any default
2261 // arguments. Skip the first parameter because we don't have a corresponding
2262 // argument. Skip the second parameter too if we're passing in the
2263 // alignment; we've already filled it in.
2264 unsigned NumImplicitArgs = PassAlignment ? 2 : 1;
2265 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2266 NumImplicitArgs, PlacementArgs, AllPlaceArgs,
2267 CallType))
2268 return ExprError();
2269
2270 if (!AllPlaceArgs.empty())
2271 PlacementArgs = AllPlaceArgs;
2272
2273 // We would like to perform some checking on the given `operator new` call,
2274 // but the PlacementArgs does not contain the implicit arguments,
2275 // namely allocation size and maybe allocation alignment,
2276 // so we need to conjure them.
2277
2278 QualType SizeTy = Context.getSizeType();
2279 unsigned SizeTyWidth = Context.getTypeSize(SizeTy);
2280
2281 llvm::APInt SingleEltSize(
2282 SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity());
2283
2284 // How many bytes do we want to allocate here?
2285 std::optional<llvm::APInt> AllocationSize;
2286 if (!ArraySize && !AllocType->isDependentType()) {
2287 // For non-array operator new, we only want to allocate one element.
2288 AllocationSize = SingleEltSize;
2289 } else if (KnownArraySize && !AllocType->isDependentType()) {
2290 // For array operator new, only deal with static array size case.
2291 bool Overflow;
2292 AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize)
2293 .umul_ov(SingleEltSize, Overflow);
2294 (void)Overflow;
2295 assert((static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already."
) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 2297, __extension__ __PRETTY_FUNCTION__
))
2296 !Overflow &&(static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already."
) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 2297, __extension__ __PRETTY_FUNCTION__
))
2297 "Expected that all the overflows would have been handled already.")(static_cast <bool> (!Overflow && "Expected that all the overflows would have been handled already."
) ? void (0) : __assert_fail ("!Overflow && \"Expected that all the overflows would have been handled already.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 2297, __extension__ __PRETTY_FUNCTION__
))
;
2298 }
2299
2300 IntegerLiteral AllocationSizeLiteral(
2301 Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)),
2302 SizeTy, SourceLocation());
2303 // Otherwise, if we failed to constant-fold the allocation size, we'll
2304 // just give up and pass-in something opaque, that isn't a null pointer.
2305 OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue,
2306 OK_Ordinary, /*SourceExpr=*/nullptr);
2307
2308 // Let's synthesize the alignment argument in case we will need it.
2309 // Since we *really* want to allocate these on stack, this is slightly ugly
2310 // because there might not be a `std::align_val_t` type.
2311 EnumDecl *StdAlignValT = getStdAlignValT();
2312 QualType AlignValT =
2313 StdAlignValT ? Context.getTypeDeclType(StdAlignValT) : SizeTy;
2314 IntegerLiteral AlignmentLiteral(
2315 Context,
2316 llvm::APInt(Context.getTypeSize(SizeTy),
2317 Alignment / Context.getCharWidth()),
2318 SizeTy, SourceLocation());
2319 ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT,
2320 CK_IntegralCast, &AlignmentLiteral,
2321 VK_PRValue, FPOptionsOverride());
2322
2323 // Adjust placement args by prepending conjured size and alignment exprs.
2324 llvm::SmallVector<Expr *, 8> CallArgs;
2325 CallArgs.reserve(NumImplicitArgs + PlacementArgs.size());
2326 CallArgs.emplace_back(AllocationSize
2327 ? static_cast<Expr *>(&AllocationSizeLiteral)
2328 : &OpaqueAllocationSize);
2329 if (PassAlignment)
2330 CallArgs.emplace_back(&DesiredAlignment);
2331 CallArgs.insert(CallArgs.end(), PlacementArgs.begin(), PlacementArgs.end());
2332
2333 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs);
2334
2335 checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs,
2336 /*IsMemberFunction=*/false, StartLoc, Range, CallType);
2337
2338 // Warn if the type is over-aligned and is being allocated by (unaligned)
2339 // global operator new.
2340 if (PlacementArgs.empty() && !PassAlignment &&
2341 (OperatorNew->isImplicit() ||
2342 (OperatorNew->getBeginLoc().isValid() &&
2343 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2344 if (Alignment > NewAlignment)
2345 Diag(StartLoc, diag::warn_overaligned_type)
2346 << AllocType
2347 << unsigned(Alignment / Context.getCharWidth())
2348 << unsigned(NewAlignment / Context.getCharWidth());
2349 }
2350 }
2351
2352 // Array 'new' can't have any initializers except empty parentheses.
2353 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2354 // dialect distinction.
2355 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2356 SourceRange InitRange(Exprs.front()->getBeginLoc(),
2357 Exprs.back()->getEndLoc());
2358 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2359 return ExprError();
2360 }
2361
2362 // If we can perform the initialization, and we've not already done so,
2363 // do it now.
2364 if (!AllocType->isDependentType() &&
2365 !Expr::hasAnyTypeDependentArguments(Exprs)) {
2366 // The type we initialize is the complete type, including the array bound.
2367 QualType InitType;
2368 if (KnownArraySize)
2369 InitType = Context.getConstantArrayType(
2370 AllocType,
2371 llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2372 *KnownArraySize),
2373 *ArraySize, ArrayType::Normal, 0);
2374 else if (ArraySize)
2375 InitType =
2376 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2377 else
2378 InitType = AllocType;
2379
2380 InitializedEntity Entity
2381 = InitializedEntity::InitializeNew(StartLoc, InitType);
2382 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
2383 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs);
2384 if (FullInit.isInvalid())
2385 return ExprError();
2386
2387 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2388 // we don't want the initialized object to be destructed.
2389 // FIXME: We should not create these in the first place.
2390 if (CXXBindTemporaryExpr *Binder =
2391 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2392 FullInit = Binder->getSubExpr();
2393
2394 Initializer = FullInit.get();
2395
2396 // FIXME: If we have a KnownArraySize, check that the array bound of the
2397 // initializer is no greater than that constant value.
2398
2399 if (ArraySize && !*ArraySize) {
2400 auto *CAT = Context.getAsConstantArrayType(Initializer->getType());
2401 if (CAT) {
2402 // FIXME: Track that the array size was inferred rather than explicitly
2403 // specified.
2404 ArraySize = IntegerLiteral::Create(
2405 Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd());
2406 } else {
2407 Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init)
2408 << Initializer->getSourceRange();
2409 }
2410 }
2411 }
2412
2413 // Mark the new and delete operators as referenced.
2414 if (OperatorNew) {
2415 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2416 return ExprError();
2417 MarkFunctionReferenced(StartLoc, OperatorNew);
2418 }
2419 if (OperatorDelete) {
2420 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2421 return ExprError();
2422 MarkFunctionReferenced(StartLoc, OperatorDelete);
2423 }
2424
2425 return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete,
2426 PassAlignment, UsualArrayDeleteWantsSize,
2427 PlacementArgs, TypeIdParens, ArraySize, initStyle,
2428 Initializer, ResultType, AllocTypeInfo, Range,
2429 DirectInitRange);
2430}
2431
2432/// Checks that a type is suitable as the allocated type
2433/// in a new-expression.
2434bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2435 SourceRange R) {
2436 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2437 // abstract class type or array thereof.
2438 if (AllocType->isFunctionType())
2439 return Diag(Loc, diag::err_bad_new_type)
2440 << AllocType << 0 << R;
2441 else if (AllocType->isReferenceType())
2442 return Diag(Loc, diag::err_bad_new_type)
2443 << AllocType << 1 << R;
2444 else if (!AllocType->isDependentType() &&
2445 RequireCompleteSizedType(
2446 Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R))
2447 return true;
2448 else if (RequireNonAbstractType(Loc, AllocType,
2449 diag::err_allocation_of_abstract_type))
2450 return true;
2451 else if (AllocType->isVariablyModifiedType())
2452 return Diag(Loc, diag::err_variably_modified_new_type)
2453 << AllocType;
2454 else if (AllocType.getAddressSpace() != LangAS::Default &&
2455 !getLangOpts().OpenCLCPlusPlus)
2456 return Diag(Loc, diag::err_address_space_qualified_new)
2457 << AllocType.getUnqualifiedType()
2458 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2459 else if (getLangOpts().ObjCAutoRefCount) {
2460 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2461 QualType BaseAllocType = Context.getBaseElementType(AT);
2462 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2463 BaseAllocType->isObjCLifetimeType())
2464 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2465 << BaseAllocType;
2466 }
2467 }
2468
2469 return false;
2470}
2471
2472static bool resolveAllocationOverload(
2473 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2474 bool &PassAlignment, FunctionDecl *&Operator,
2475 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2476 OverloadCandidateSet Candidates(R.getNameLoc(),
2477 OverloadCandidateSet::CSK_Normal);
2478 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2479 Alloc != AllocEnd; ++Alloc) {
2480 // Even member operator new/delete are implicitly treated as
2481 // static, so don't use AddMemberCandidate.
2482 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2483
2484 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2485 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2486 /*ExplicitTemplateArgs=*/nullptr, Args,
2487 Candidates,
2488 /*SuppressUserConversions=*/false);
2489 continue;
2490 }
2491
2492 FunctionDecl *Fn = cast<FunctionDecl>(D);
2493 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2494 /*SuppressUserConversions=*/false);
2495 }
2496
2497 // Do the resolution.
2498 OverloadCandidateSet::iterator Best;
2499 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2500 case OR_Success: {
2501 // Got one!
2502 FunctionDecl *FnDecl = Best->Function;
2503 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2504 Best->FoundDecl) == Sema::AR_inaccessible)
2505 return true;
2506
2507 Operator = FnDecl;
2508 return false;
2509 }
2510
2511 case OR_No_Viable_Function:
2512 // C++17 [expr.new]p13:
2513 // If no matching function is found and the allocated object type has
2514 // new-extended alignment, the alignment argument is removed from the
2515 // argument list, and overload resolution is performed again.
2516 if (PassAlignment) {
2517 PassAlignment = false;
2518 AlignArg = Args[1];
2519 Args.erase(Args.begin() + 1);
2520 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2521 Operator, &Candidates, AlignArg,
2522 Diagnose);
2523 }
2524
2525 // MSVC will fall back on trying to find a matching global operator new
2526 // if operator new[] cannot be found. Also, MSVC will leak by not
2527 // generating a call to operator delete or operator delete[], but we
2528 // will not replicate that bug.
2529 // FIXME: Find out how this interacts with the std::align_val_t fallback
2530 // once MSVC implements it.
2531 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2532 S.Context.getLangOpts().MSVCCompat) {
2533 R.clear();
2534 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2535 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2536 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2537 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2538 Operator, /*Candidates=*/nullptr,
2539 /*AlignArg=*/nullptr, Diagnose);
2540 }
2541
2542 if (Diagnose) {
2543 // If this is an allocation of the form 'new (p) X' for some object
2544 // pointer p (or an expression that will decay to such a pointer),
2545 // diagnose the missing inclusion of <new>.
2546 if (!R.isClassLookup() && Args.size() == 2 &&
2547 (Args[1]->getType()->isObjectPointerType() ||
2548 Args[1]->getType()->isArrayType())) {
2549 S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new)
2550 << R.getLookupName() << Range;
2551 // Listing the candidates is unlikely to be useful; skip it.
2552 return true;
2553 }
2554
2555 // Finish checking all candidates before we note any. This checking can
2556 // produce additional diagnostics so can't be interleaved with our
2557 // emission of notes.
2558 //
2559 // For an aligned allocation, separately check the aligned and unaligned
2560 // candidates with their respective argument lists.
2561 SmallVector<OverloadCandidate*, 32> Cands;
2562 SmallVector<OverloadCandidate*, 32> AlignedCands;
2563 llvm::SmallVector<Expr*, 4> AlignedArgs;
2564 if (AlignedCandidates) {
2565 auto IsAligned = [](OverloadCandidate &C) {
2566 return C.Function->getNumParams() > 1 &&
2567 C.Function->getParamDecl(1)->getType()->isAlignValT();
2568 };
2569 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2570
2571 AlignedArgs.reserve(Args.size() + 1);
2572 AlignedArgs.push_back(Args[0]);
2573 AlignedArgs.push_back(AlignArg);
2574 AlignedArgs.append(Args.begin() + 1, Args.end());
2575 AlignedCands = AlignedCandidates->CompleteCandidates(
2576 S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned);
2577
2578 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2579 R.getNameLoc(), IsUnaligned);
2580 } else {
2581 Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args,
2582 R.getNameLoc());
2583 }
2584
2585 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2586 << R.getLookupName() << Range;
2587 if (AlignedCandidates)
2588 AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "",
2589 R.getNameLoc());
2590 Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc());
2591 }
2592 return true;
2593
2594 case OR_Ambiguous:
2595 if (Diagnose) {
2596 Candidates.NoteCandidates(
2597 PartialDiagnosticAt(R.getNameLoc(),
2598 S.PDiag(diag::err_ovl_ambiguous_call)
2599 << R.getLookupName() << Range),
2600 S, OCD_AmbiguousCandidates, Args);
2601 }
2602 return true;
2603
2604 case OR_Deleted: {
2605 if (Diagnose) {
2606 Candidates.NoteCandidates(
2607 PartialDiagnosticAt(R.getNameLoc(),
2608 S.PDiag(diag::err_ovl_deleted_call)
2609 << R.getLookupName() << Range),
2610 S, OCD_AllCandidates, Args);
2611 }
2612 return true;
2613 }
2614 }
2615 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "clang/lib/Sema/SemaExprCXX.cpp", 2615)
;
2616}
2617
2618bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2619 AllocationFunctionScope NewScope,
2620 AllocationFunctionScope DeleteScope,
2621 QualType AllocType, bool IsArray,
2622 bool &PassAlignment, MultiExprArg PlaceArgs,
2623 FunctionDecl *&OperatorNew,
2624 FunctionDecl *&OperatorDelete,
2625 bool Diagnose) {
2626 // --- Choosing an allocation function ---
2627 // C++ 5.3.4p8 - 14 & 18
2628 // 1) If looking in AFS_Global scope for allocation functions, only look in
2629 // the global scope. Else, if AFS_Class, only look in the scope of the
2630 // allocated class. If AFS_Both, look in both.
2631 // 2) If an array size is given, look for operator new[], else look for
2632 // operator new.
2633 // 3) The first argument is always size_t. Append the arguments from the
2634 // placement form.
2635
2636 SmallVector<Expr*, 8> AllocArgs;
2637 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2638
2639 // We don't care about the actual value of these arguments.
2640 // FIXME: Should the Sema create the expression and embed it in the syntax
2641 // tree? Or should the consumer just recalculate the value?
2642 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2643 IntegerLiteral Size(
2644 Context,
2645 llvm::APInt::getZero(
2646 Context.getTargetInfo().getPointerWidth(LangAS::Default)),
2647 Context.getSizeType(), SourceLocation());
2648 AllocArgs.push_back(&Size);
2649
2650 QualType AlignValT = Context.VoidTy;
2651 if (PassAlignment) {
2652 DeclareGlobalNewDelete();
2653 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2654 }
2655 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2656 if (PassAlignment)
2657 AllocArgs.push_back(&Align);
2658
2659 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2660
2661 // C++ [expr.new]p8:
2662 // If the allocated type is a non-array type, the allocation
2663 // function's name is operator new and the deallocation function's
2664 // name is operator delete. If the allocated type is an array
2665 // type, the allocation function's name is operator new[] and the
2666 // deallocation function's name is operator delete[].
2667 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2668 IsArray ? OO_Array_New : OO_New);
2669
2670 QualType AllocElemType = Context.getBaseElementType(AllocType);
2671
2672 // Find the allocation function.
2673 {
2674 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2675
2676 // C++1z [expr.new]p9:
2677 // If the new-expression begins with a unary :: operator, the allocation
2678 // function's name is looked up in the global scope. Otherwise, if the
2679 // allocated type is a class type T or array thereof, the allocation
2680 // function's name is looked up in the scope of T.
2681 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2682 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2683
2684 // We can see ambiguity here if the allocation function is found in
2685 // multiple base classes.
2686 if (R.isAmbiguous())
2687 return true;
2688
2689 // If this lookup fails to find the name, or if the allocated type is not
2690 // a class type, the allocation function's name is looked up in the
2691 // global scope.
2692 if (R.empty()) {
2693 if (NewScope == AFS_Class)
2694 return true;
2695
2696 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2697 }
2698
2699 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2700 if (PlaceArgs.empty()) {
2701 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2702 } else {
2703 Diag(StartLoc, diag::err_openclcxx_placement_new);
2704 }
2705 return true;
2706 }
2707
2708 assert(!R.empty() && "implicitly declared allocation functions not found")(static_cast <bool> (!R.empty() && "implicitly declared allocation functions not found"
) ? void (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "clang/lib/Sema/SemaExprCXX.cpp", 2708, __extension__ __PRETTY_FUNCTION__
))
;
2709 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")(static_cast <bool> (!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "clang/lib/Sema/SemaExprCXX.cpp", 2709, __extension__ __PRETTY_FUNCTION__
))
;
2710
2711 // We do our own custom access checks below.
2712 R.suppressDiagnostics();
2713
2714 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2715 OperatorNew, /*Candidates=*/nullptr,
2716 /*AlignArg=*/nullptr, Diagnose))
2717 return true;
2718 }
2719
2720 // We don't need an operator delete if we're running under -fno-exceptions.
2721 if (!getLangOpts().Exceptions) {
2722 OperatorDelete = nullptr;
2723 return false;
2724 }
2725
2726 // Note, the name of OperatorNew might have been changed from array to
2727 // non-array by resolveAllocationOverload.
2728 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2729 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2730 ? OO_Array_Delete
2731 : OO_Delete);
2732
2733 // C++ [expr.new]p19:
2734 //
2735 // If the new-expression begins with a unary :: operator, the
2736 // deallocation function's name is looked up in the global
2737 // scope. Otherwise, if the allocated type is a class type T or an
2738 // array thereof, the deallocation function's name is looked up in
2739 // the scope of T. If this lookup fails to find the name, or if
2740 // the allocated type is not a class type or array thereof, the
2741 // deallocation function's name is looked up in the global scope.
2742 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2743 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2744 auto *RD =
2745 cast<CXXRecordDecl>(AllocElemType->castAs<RecordType>()->getDecl());
2746 LookupQualifiedName(FoundDelete, RD);
2747 }
2748 if (FoundDelete.isAmbiguous())
2749 return true; // FIXME: clean up expressions?
2750
2751 // Filter out any destroying operator deletes. We can't possibly call such a
2752 // function in this context, because we're handling the case where the object
2753 // was not successfully constructed.
2754 // FIXME: This is not covered by the language rules yet.
2755 {
2756 LookupResult::Filter Filter = FoundDelete.makeFilter();
2757 while (Filter.hasNext()) {
2758 auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl());
2759 if (FD && FD->isDestroyingOperatorDelete())
2760 Filter.erase();
2761 }
2762 Filter.done();
2763 }
2764
2765 bool FoundGlobalDelete = FoundDelete.empty();
2766 if (FoundDelete.empty()) {
2767 FoundDelete.clear(LookupOrdinaryName);
2768
2769 if (DeleteScope == AFS_Class)
2770 return true;
2771
2772 DeclareGlobalNewDelete();
2773 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2774 }
2775
2776 FoundDelete.suppressDiagnostics();
2777
2778 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2779
2780 // Whether we're looking for a placement operator delete is dictated
2781 // by whether we selected a placement operator new, not by whether
2782 // we had explicit placement arguments. This matters for things like
2783 // struct A { void *operator new(size_t, int = 0); ... };
2784 // A *a = new A()
2785 //
2786 // We don't have any definition for what a "placement allocation function"
2787 // is, but we assume it's any allocation function whose
2788 // parameter-declaration-clause is anything other than (size_t).
2789 //
2790 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2791 // This affects whether an exception from the constructor of an overaligned
2792 // type uses the sized or non-sized form of aligned operator delete.
2793 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2794 OperatorNew->isVariadic();
2795
2796 if (isPlacementNew) {
2797 // C++ [expr.new]p20:
2798 // A declaration of a placement deallocation function matches the
2799 // declaration of a placement allocation function if it has the
2800 // same number of parameters and, after parameter transformations
2801 // (8.3.5), all parameter types except the first are
2802 // identical. [...]
2803 //
2804 // To perform this comparison, we compute the function type that
2805 // the deallocation function should have, and use that type both
2806 // for template argument deduction and for comparison purposes.
2807 QualType ExpectedFunctionType;
2808 {
2809 auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>();
2810
2811 SmallVector<QualType, 4> ArgTypes;
2812 ArgTypes.push_back(Context.VoidPtrTy);
2813 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2814 ArgTypes.push_back(Proto->getParamType(I));
2815
2816 FunctionProtoType::ExtProtoInfo EPI;
2817 // FIXME: This is not part of the standard's rule.
2818 EPI.Variadic = Proto->isVariadic();
2819
2820 ExpectedFunctionType
2821 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2822 }
2823
2824 for (LookupResult::iterator D = FoundDelete.begin(),
2825 DEnd = FoundDelete.end();
2826 D != DEnd; ++D) {
2827 FunctionDecl *Fn = nullptr;
2828 if (FunctionTemplateDecl *FnTmpl =
2829 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2830 // Perform template argument deduction to try to match the
2831 // expected function type.
2832 TemplateDeductionInfo Info(StartLoc);
2833 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2834 Info))
2835 continue;
2836 } else
2837 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2838
2839 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2840 ExpectedFunctionType,
2841 /*AdjustExcpetionSpec*/true),
2842 ExpectedFunctionType))
2843 Matches.push_back(std::make_pair(D.getPair(), Fn));
2844 }
2845
2846 if (getLangOpts().CUDA)
2847 EraseUnwantedCUDAMatches(getCurFunctionDecl(/*AllowLambda=*/true),
2848 Matches);
2849 } else {
2850 // C++1y [expr.new]p22:
2851 // For a non-placement allocation function, the normal deallocation
2852 // function lookup is used
2853 //
2854 // Per [expr.delete]p10, this lookup prefers a member operator delete
2855 // without a size_t argument, but prefers a non-member operator delete
2856 // with a size_t where possible (which it always is in this case).
2857 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2858 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2859 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2860 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2861 &BestDeallocFns);
2862 if (Selected)
2863 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2864 else {
2865 // If we failed to select an operator, all remaining functions are viable
2866 // but ambiguous.
2867 for (auto Fn : BestDeallocFns)
2868 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2869 }
2870 }
2871
2872 // C++ [expr.new]p20:
2873 // [...] If the lookup finds a single matching deallocation
2874 // function, that function will be called; otherwise, no
2875 // deallocation function will be called.
2876 if (Matches.size() == 1) {
2877 OperatorDelete = Matches[0].second;
2878
2879 // C++1z [expr.new]p23:
2880 // If the lookup finds a usual deallocation function (3.7.4.2)
2881 // with a parameter of type std::size_t and that function, considered
2882 // as a placement deallocation function, would have been
2883 // selected as a match for the allocation function, the program
2884 // is ill-formed.
2885 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2886 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2887 UsualDeallocFnInfo Info(*this,
2888 DeclAccessPair::make(OperatorDelete, AS_public));
2889 // Core issue, per mail to core reflector, 2016-10-09:
2890 // If this is a member operator delete, and there is a corresponding
2891 // non-sized member operator delete, this isn't /really/ a sized
2892 // deallocation function, it just happens to have a size_t parameter.
2893 bool IsSizedDelete = Info.HasSizeT;
2894 if (IsSizedDelete && !FoundGlobalDelete) {
2895 auto NonSizedDelete =
2896 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2897 /*WantAlign*/Info.HasAlignValT);
2898 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2899 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2900 IsSizedDelete = false;
2901 }
2902
2903 if (IsSizedDelete) {
2904 SourceRange R = PlaceArgs.empty()
2905 ? SourceRange()
2906 : SourceRange(PlaceArgs.front()->getBeginLoc(),
2907 PlaceArgs.back()->getEndLoc());
2908 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2909 if (!OperatorDelete->isImplicit())
2910 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2911 << DeleteName;
2912 }
2913 }
2914
2915 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2916 Matches[0].first);
2917 } else if (!Matches.empty()) {
2918 // We found multiple suitable operators. Per [expr.new]p20, that means we
2919 // call no 'operator delete' function, but we should at least warn the user.
2920 // FIXME: Suppress this warning if the construction cannot throw.
2921 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2922 << DeleteName << AllocElemType;
2923
2924 for (auto &Match : Matches)
2925 Diag(Match.second->getLocation(),
2926 diag::note_member_declared_here) << DeleteName;
2927 }
2928
2929 return false;
2930}
2931
2932/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2933/// delete. These are:
2934/// @code
2935/// // C++03:
2936/// void* operator new(std::size_t) throw(std::bad_alloc);
2937/// void* operator new[](std::size_t) throw(std::bad_alloc);
2938/// void operator delete(void *) throw();
2939/// void operator delete[](void *) throw();
2940/// // C++11:
2941/// void* operator new(std::size_t);
2942/// void* operator new[](std::size_t);
2943/// void operator delete(void *) noexcept;
2944/// void operator delete[](void *) noexcept;
2945/// // C++1y:
2946/// void* operator new(std::size_t);
2947/// void* operator new[](std::size_t);
2948/// void operator delete(void *) noexcept;
2949/// void operator delete[](void *) noexcept;
2950/// void operator delete(void *, std::size_t) noexcept;
2951/// void operator delete[](void *, std::size_t) noexcept;
2952/// @endcode
2953/// Note that the placement and nothrow forms of new are *not* implicitly
2954/// declared. Their use requires including \<new\>.
2955void Sema::DeclareGlobalNewDelete() {
2956 if (GlobalNewDeleteDeclared)
2957 return;
2958
2959 // The implicitly declared new and delete operators
2960 // are not supported in OpenCL.
2961 if (getLangOpts().OpenCLCPlusPlus)
2962 return;
2963
2964 // C++ [basic.stc.dynamic.general]p2:
2965 // The library provides default definitions for the global allocation
2966 // and deallocation functions. Some global allocation and deallocation
2967 // functions are replaceable ([new.delete]); these are attached to the
2968 // global module ([module.unit]).
2969 if (getLangOpts().CPlusPlusModules && getCurrentModule())
2970 PushGlobalModuleFragment(SourceLocation());
2971
2972 // C++ [basic.std.dynamic]p2:
2973 // [...] The following allocation and deallocation functions (18.4) are
2974 // implicitly declared in global scope in each translation unit of a
2975 // program
2976 //
2977 // C++03:
2978 // void* operator new(std::size_t) throw(std::bad_alloc);
2979 // void* operator new[](std::size_t) throw(std::bad_alloc);
2980 // void operator delete(void*) throw();
2981 // void operator delete[](void*) throw();
2982 // C++11:
2983 // void* operator new(std::size_t);
2984 // void* operator new[](std::size_t);
2985 // void operator delete(void*) noexcept;
2986 // void operator delete[](void*) noexcept;
2987 // C++1y:
2988 // void* operator new(std::size_t);
2989 // void* operator new[](std::size_t);
2990 // void operator delete(void*) noexcept;
2991 // void operator delete[](void*) noexcept;
2992 // void operator delete(void*, std::size_t) noexcept;
2993 // void operator delete[](void*, std::size_t) noexcept;
2994 //
2995 // These implicit declarations introduce only the function names operator
2996 // new, operator new[], operator delete, operator delete[].
2997 //
2998 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2999 // "std" or "bad_alloc" as necessary to form the exception specification.
3000 // However, we do not make these implicit declarations visible to name
3001 // lookup.
3002 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
3003 // The "std::bad_alloc" class has not yet been declared, so build it
3004 // implicitly.
3005 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
3006 getOrCreateStdNamespace(),
3007 SourceLocation(), SourceLocation(),
3008 &PP.getIdentifierTable().get("bad_alloc"),
3009 nullptr);
3010 getStdBadAlloc()->setImplicit(true);
3011
3012 // The implicitly declared "std::bad_alloc" should live in global module
3013 // fragment.
3014 if (TheGlobalModuleFragment) {
3015 getStdBadAlloc()->setModuleOwnershipKind(
3016 Decl::ModuleOwnershipKind::ReachableWhenImported);
3017 getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment);
3018 }
3019 }
3020 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
3021 // The "std::align_val_t" enum class has not yet been declared, so build it
3022 // implicitly.
3023 auto *AlignValT = EnumDecl::Create(
3024 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
3025 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
3026
3027 // The implicitly declared "std::align_val_t" should live in global module
3028 // fragment.
3029 if (TheGlobalModuleFragment) {
3030 AlignValT->setModuleOwnershipKind(
3031 Decl::ModuleOwnershipKind::ReachableWhenImported);
3032 AlignValT->setLocalOwningModule(TheGlobalModuleFragment);
3033 }
3034
3035 AlignValT->setIntegerType(Context.getSizeType());
3036 AlignValT->setPromotionType(Context.getSizeType());
3037 AlignValT->setImplicit(true);
3038
3039 StdAlignValT = AlignValT;
3040 }
3041
3042 GlobalNewDeleteDeclared = true;
3043
3044 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
3045 QualType SizeT = Context.getSizeType();
3046
3047 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
3048 QualType Return, QualType Param) {
3049 llvm::SmallVector<QualType, 3> Params;
3050 Params.push_back(Param);
3051
3052 // Create up to four variants of the function (sized/aligned).
3053 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
3054 (Kind == OO_Delete || Kind == OO_Array_Delete);
3055 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
3056
3057 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
3058 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
3059 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
3060 if (Sized)
3061 Params.push_back(SizeT);
3062
3063 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
3064 if (Aligned)
3065 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
3066
3067 DeclareGlobalAllocationFunction(
3068 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
3069
3070 if (Aligned)
3071 Params.pop_back();
3072 }
3073 }
3074 };
3075
3076 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
3077 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
3078 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
3079 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
3080
3081 if (getLangOpts().CPlusPlusModules && getCurrentModule())
3082 PopGlobalModuleFragment();
3083}
3084
3085/// DeclareGlobalAllocationFunction - Declares a single implicit global
3086/// allocation function if it doesn't already exist.
3087void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
3088 QualType Return,
3089 ArrayRef<QualType> Params) {
3090 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
3091
3092 // Check if this function is already declared.
3093 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
3094 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
3095 Alloc != AllocEnd; ++Alloc) {
3096 // Only look at non-template functions, as it is the predefined,
3097 // non-templated allocation function we are trying to declare here.
3098 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
3099 if (Func->getNumParams() == Params.size()) {
3100 llvm::SmallVector<QualType, 3> FuncParams;
3101 for (auto *P : Func->parameters())
3102 FuncParams.push_back(
3103 Context.getCanonicalType(P->getType().getUnqualifiedType()));
3104 if (llvm::ArrayRef(FuncParams) == Params) {
3105 // Make the function visible to name lookup, even if we found it in
3106 // an unimported module. It either is an implicitly-declared global
3107 // allocation function, or is suppressing that function.
3108 Func->setVisibleDespiteOwningModule();
3109 return;
3110 }
3111 }
3112 }
3113 }
3114
3115 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
3116 /*IsVariadic=*/false, /*IsCXXMethod=*/false, /*IsBuiltin=*/true));
3117
3118 QualType BadAllocType;
3119 bool HasBadAllocExceptionSpec
3120 = (Name.getCXXOverloadedOperator() == OO_New ||
3121 Name.getCXXOverloadedOperator() == OO_Array_New);
3122 if (HasBadAllocExceptionSpec) {
3123 if (!getLangOpts().CPlusPlus11) {
3124 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
3125 assert(StdBadAlloc && "Must have std::bad_alloc declared")(static_cast <bool> (StdBadAlloc && "Must have std::bad_alloc declared"
) ? void (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3125, __extension__ __PRETTY_FUNCTION__
))
;
3126 EPI.ExceptionSpec.Type = EST_Dynamic;
3127 EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType);
3128 }
3129 if (getLangOpts().NewInfallible) {
3130 EPI.ExceptionSpec.Type = EST_DynamicNone;
3131 }
3132 } else {
3133 EPI.ExceptionSpec =
3134 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
3135 }
3136
3137 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
3138 QualType FnType = Context.getFunctionType(Return, Params, EPI);
3139 FunctionDecl *Alloc = FunctionDecl::Create(
3140 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType,
3141 /*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false,
3142 true);
3143 Alloc->setImplicit();
3144 // Global allocation functions should always be visible.
3145 Alloc->setVisibleDespiteOwningModule();
3146
3147 if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible)
3148 Alloc->addAttr(
3149 ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation()));
3150
3151 // C++ [basic.stc.dynamic.general]p2:
3152 // The library provides default definitions for the global allocation
3153 // and deallocation functions. Some global allocation and deallocation
3154 // functions are replaceable ([new.delete]); these are attached to the
3155 // global module ([module.unit]).
3156 //
3157 // In the language wording, these functions are attched to the global
3158 // module all the time. But in the implementation, the global module
3159 // is only meaningful when we're in a module unit. So here we attach
3160 // these allocation functions to global module conditionally.
3161 if (TheGlobalModuleFragment) {
3162 Alloc->setModuleOwnershipKind(
3163 Decl::ModuleOwnershipKind::ReachableWhenImported);
3164 Alloc->setLocalOwningModule(TheGlobalModuleFragment);
3165 }
3166
3167 Alloc->addAttr(VisibilityAttr::CreateImplicit(
3168 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
3169 ? VisibilityAttr::Hidden
3170 : VisibilityAttr::Default));
3171
3172 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
3173 for (QualType T : Params) {
3174 ParamDecls.push_back(ParmVarDecl::Create(
3175 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
3176 /*TInfo=*/nullptr, SC_None, nullptr));
3177 ParamDecls.back()->setImplicit();
3178 }
3179 Alloc->setParams(ParamDecls);
3180 if (ExtraAttr)
3181 Alloc->addAttr(ExtraAttr);
3182 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc);
3183 Context.getTranslationUnitDecl()->addDecl(Alloc);
3184 IdResolver.tryAddTopLevelDecl(Alloc, Name);
3185 };
3186
3187 if (!LangOpts.CUDA)
3188 CreateAllocationFunctionDecl(nullptr);
3189 else {
3190 // Host and device get their own declaration so each can be
3191 // defined or re-declared independently.
3192 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
3193 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
3194 }
3195}
3196
3197FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
3198 bool CanProvideSize,
3199 bool Overaligned,
3200 DeclarationName Name) {
3201 DeclareGlobalNewDelete();
3202
3203 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
3204 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
3205
3206 // FIXME: It's possible for this to result in ambiguity, through a
3207 // user-declared variadic operator delete or the enable_if attribute. We
3208 // should probably not consider those cases to be usual deallocation
3209 // functions. But for now we just make an arbitrary choice in that case.
3210 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
3211 Overaligned);
3212 assert(Result.FD && "operator delete missing from global scope?")(static_cast <bool> (Result.FD && "operator delete missing from global scope?"
) ? void (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3212, __extension__ __PRETTY_FUNCTION__
))
;
3213 return Result.FD;
3214}
3215
3216FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
3217 CXXRecordDecl *RD) {
3218 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
3219
3220 FunctionDecl *OperatorDelete = nullptr;
3221 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
3222 return nullptr;
3223 if (OperatorDelete)
3224 return OperatorDelete;
3225
3226 // If there's no class-specific operator delete, look up the global
3227 // non-array delete.
3228 return FindUsualDeallocationFunction(
3229 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
3230 Name);
3231}
3232
3233bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
3234 DeclarationName Name,
3235 FunctionDecl *&Operator, bool Diagnose,
3236 bool WantSize, bool WantAligned) {
3237 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
3238 // Try to find operator delete/operator delete[] in class scope.
3239 LookupQualifiedName(Found, RD);
3240
3241 if (Found.isAmbiguous())
3242 return true;
3243
3244 Found.suppressDiagnostics();
3245
3246 bool Overaligned =
3247 WantAligned || hasNewExtendedAlignment(*this, Context.getRecordType(RD));
3248
3249 // C++17 [expr.delete]p10:
3250 // If the deallocation functions have class scope, the one without a
3251 // parameter of type std::size_t is selected.
3252 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
3253 resolveDeallocationOverload(*this, Found, /*WantSize*/ WantSize,
3254 /*WantAlign*/ Overaligned, &Matches);
3255
3256 // If we could find an overload, use it.
3257 if (Matches.size() == 1) {
3258 Operator = cast<CXXMethodDecl>(Matches[0].FD);
3259
3260 // FIXME: DiagnoseUseOfDecl?
3261 if (Operator->isDeleted()) {
3262 if (Diagnose) {
3263 Diag(StartLoc, diag::err_deleted_function_use);
3264 NoteDeletedFunction(Operator);
3265 }
3266 return true;
3267 }
3268
3269 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
3270 Matches[0].Found, Diagnose) == AR_inaccessible)
3271 return true;
3272
3273 return false;
3274 }
3275
3276 // We found multiple suitable operators; complain about the ambiguity.
3277 // FIXME: The standard doesn't say to do this; it appears that the intent
3278 // is that this should never happen.
3279 if (!Matches.empty()) {
3280 if (Diagnose) {
3281 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
3282 << Name << RD;
3283 for (auto &Match : Matches)
3284 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
3285 }
3286 return true;
3287 }
3288
3289 // We did find operator delete/operator delete[] declarations, but
3290 // none of them were suitable.
3291 if (!Found.empty()) {
3292 if (Diagnose) {
3293 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
3294 << Name << RD;
3295
3296 for (NamedDecl *D : Found)
3297 Diag(D->getUnderlyingDecl()->getLocation(),
3298 diag::note_member_declared_here) << Name;
3299 }
3300 return true;
3301 }
3302
3303 Operator = nullptr;
3304 return false;
3305}
3306
3307namespace {
3308/// Checks whether delete-expression, and new-expression used for
3309/// initializing deletee have the same array form.
3310class MismatchingNewDeleteDetector {
3311public:
3312 enum MismatchResult {
3313 /// Indicates that there is no mismatch or a mismatch cannot be proven.
3314 NoMismatch,
3315 /// Indicates that variable is initialized with mismatching form of \a new.
3316 VarInitMismatches,
3317 /// Indicates that member is initialized with mismatching form of \a new.
3318 MemberInitMismatches,
3319 /// Indicates that 1 or more constructors' definitions could not been
3320 /// analyzed, and they will be checked again at the end of translation unit.
3321 AnalyzeLater
3322 };
3323
3324 /// \param EndOfTU True, if this is the final analysis at the end of
3325 /// translation unit. False, if this is the initial analysis at the point
3326 /// delete-expression was encountered.
3327 explicit MismatchingNewDeleteDetector(bool EndOfTU)
3328 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
3329 HasUndefinedConstructors(false) {}
3330
3331 /// Checks whether pointee of a delete-expression is initialized with
3332 /// matching form of new-expression.
3333 ///
3334 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
3335 /// point where delete-expression is encountered, then a warning will be
3336 /// issued immediately. If return value is \c AnalyzeLater at the point where
3337 /// delete-expression is seen, then member will be analyzed at the end of
3338 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
3339 /// couldn't be analyzed. If at least one constructor initializes the member
3340 /// with matching type of new, the return value is \c NoMismatch.
3341 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
3342 /// Analyzes a class member.
3343 /// \param Field Class member to analyze.
3344 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
3345 /// for deleting the \p Field.
3346 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
3347 FieldDecl *Field;
3348 /// List of mismatching new-expressions used for initialization of the pointee
3349 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3350 /// Indicates whether delete-expression was in array form.
3351 bool IsArrayForm;
3352
3353private:
3354 const bool EndOfTU;
3355 /// Indicates that there is at least one constructor without body.
3356 bool HasUndefinedConstructors;
3357 /// Returns \c CXXNewExpr from given initialization expression.
3358 /// \param E Expression used for initializing pointee in delete-expression.
3359 /// E can be a single-element \c InitListExpr consisting of new-expression.
3360 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3361 /// Returns whether member is initialized with mismatching form of
3362 /// \c new either by the member initializer or in-class initialization.
3363 ///
3364 /// If bodies of all constructors are not visible at the end of translation
3365 /// unit or at least one constructor initializes member with the matching
3366 /// form of \c new, mismatch cannot be proven, and this function will return
3367 /// \c NoMismatch.
3368 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3369 /// Returns whether variable is initialized with mismatching form of
3370 /// \c new.
3371 ///
3372 /// If variable is initialized with matching form of \c new or variable is not
3373 /// initialized with a \c new expression, this function will return true.
3374 /// If variable is initialized with mismatching form of \c new, returns false.
3375 /// \param D Variable to analyze.
3376 bool hasMatchingVarInit(const DeclRefExpr *D);
3377 /// Checks whether the constructor initializes pointee with mismatching
3378 /// form of \c new.
3379 ///
3380 /// Returns true, if member is initialized with matching form of \c new in
3381 /// member initializer list. Returns false, if member is initialized with the
3382 /// matching form of \c new in this constructor's initializer or given
3383 /// constructor isn't defined at the point where delete-expression is seen, or
3384 /// member isn't initialized by the constructor.
3385 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3386 /// Checks whether member is initialized with matching form of
3387 /// \c new in member initializer list.
3388 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3389 /// Checks whether member is initialized with mismatching form of \c new by
3390 /// in-class initializer.
3391 MismatchResult analyzeInClassInitializer();
3392};
3393}
3394
3395MismatchingNewDeleteDetector::MismatchResult
3396MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3397 NewExprs.clear();
3398 assert(DE && "Expected delete-expression")(static_cast <bool> (DE && "Expected delete-expression"
) ? void (0) : __assert_fail ("DE && \"Expected delete-expression\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3398, __extension__ __PRETTY_FUNCTION__
))
;
3399 IsArrayForm = DE->isArrayForm();
3400 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3401 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3402 return analyzeMemberExpr(ME);
3403 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3404 if (!hasMatchingVarInit(D))
3405 return VarInitMismatches;
3406 }
3407 return NoMismatch;
3408}
3409
3410const CXXNewExpr *
3411MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3412 assert(E != nullptr && "Expected a valid initializer expression")(static_cast <bool> (E != nullptr && "Expected a valid initializer expression"
) ? void (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3412, __extension__ __PRETTY_FUNCTION__
))
;
3413 E = E->IgnoreParenImpCasts();
3414 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3415 if (ILE->getNumInits() == 1)
3416 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3417 }
3418
3419 return dyn_cast_or_null<const CXXNewExpr>(E);
3420}
3421
3422bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3423 const CXXCtorInitializer *CI) {
3424 const CXXNewExpr *NE = nullptr;
3425 if (Field == CI->getMember() &&
3426 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3427 if (NE->isArray() == IsArrayForm)
3428 return true;
3429 else
3430 NewExprs.push_back(NE);
3431 }
3432 return false;
3433}
3434
3435bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3436 const CXXConstructorDecl *CD) {
3437 if (CD->isImplicit())
3438 return false;
3439 const FunctionDecl *Definition = CD;
3440 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3441 HasUndefinedConstructors = true;
3442 return EndOfTU;
3443 }
3444 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3445 if (hasMatchingNewInCtorInit(CI))
3446 return true;
3447 }
3448 return false;
3449}
3450
3451MismatchingNewDeleteDetector::MismatchResult
3452MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3453 assert(Field != nullptr && "This should be called only for members")(static_cast <bool> (Field != nullptr && "This should be called only for members"
) ? void (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3453, __extension__ __PRETTY_FUNCTION__
))
;
3454 const Expr *InitExpr = Field->getInClassInitializer();
3455 if (!InitExpr)
3456 return EndOfTU ? NoMismatch : AnalyzeLater;
3457 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3458 if (NE->isArray() != IsArrayForm) {
3459 NewExprs.push_back(NE);
3460 return MemberInitMismatches;
3461 }
3462 }
3463 return NoMismatch;
3464}
3465
3466MismatchingNewDeleteDetector::MismatchResult
3467MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3468 bool DeleteWasArrayForm) {
3469 assert(Field != nullptr && "Analysis requires a valid class member.")(static_cast <bool> (Field != nullptr && "Analysis requires a valid class member."
) ? void (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3469, __extension__ __PRETTY_FUNCTION__
))
;
3470 this->Field = Field;
3471 IsArrayForm = DeleteWasArrayForm;
3472 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3473 for (const auto *CD : RD->ctors()) {
3474 if (hasMatchingNewInCtor(CD))
3475 return NoMismatch;
3476 }
3477 if (HasUndefinedConstructors)
3478 return EndOfTU ? NoMismatch : AnalyzeLater;
3479 if (!NewExprs.empty())
3480 return MemberInitMismatches;
3481 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3482 : NoMismatch;
3483}
3484
3485MismatchingNewDeleteDetector::MismatchResult
3486MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3487 assert(ME != nullptr && "Expected a member expression")(static_cast <bool> (ME != nullptr && "Expected a member expression"
) ? void (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3487, __extension__ __PRETTY_FUNCTION__
))
;
3488 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3489 return analyzeField(F, IsArrayForm);
3490 return NoMismatch;
3491}
3492
3493bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3494 const CXXNewExpr *NE = nullptr;
3495 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3496 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3497 NE->isArray() != IsArrayForm) {
3498 NewExprs.push_back(NE);
3499 }
3500 }
3501 return NewExprs.empty();
3502}
3503
3504static void
3505DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3506 const MismatchingNewDeleteDetector &Detector) {
3507 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3508 FixItHint H;
3509 if (!Detector.IsArrayForm)
3510 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3511 else {
3512 SourceLocation RSquare = Lexer::findLocationAfterToken(
3513 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3514 SemaRef.getLangOpts(), true);
3515 if (RSquare.isValid())
3516 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3517 }
3518 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3519 << Detector.IsArrayForm << H;
3520
3521 for (const auto *NE : Detector.NewExprs)
3522 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3523 << Detector.IsArrayForm;
3524}
3525
3526void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3527 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3528 return;
3529 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3530 switch (Detector.analyzeDeleteExpr(DE)) {
3531 case MismatchingNewDeleteDetector::VarInitMismatches:
3532 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3533 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3534 break;
3535 }
3536 case MismatchingNewDeleteDetector::AnalyzeLater: {
3537 DeleteExprs[Detector.Field].push_back(
3538 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3539 break;
3540 }
3541 case MismatchingNewDeleteDetector::NoMismatch:
3542 break;
3543 }
3544}
3545
3546void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3547 bool DeleteWasArrayForm) {
3548 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3549 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3550 case MismatchingNewDeleteDetector::VarInitMismatches:
3551 llvm_unreachable("This analysis should have been done for class members.")::llvm::llvm_unreachable_internal("This analysis should have been done for class members."
, "clang/lib/Sema/SemaExprCXX.cpp", 3551)
;
3552 case MismatchingNewDeleteDetector::AnalyzeLater:
3553 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.", "clang/lib/Sema/SemaExprCXX.cpp", 3554)
3554 "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "clang/lib/Sema/SemaExprCXX.cpp", 3554)
;
3555 case MismatchingNewDeleteDetector::MemberInitMismatches:
3556 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3557 break;
3558 case MismatchingNewDeleteDetector::NoMismatch:
3559 break;
3560 }
3561}
3562
3563/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3564/// @code ::delete ptr; @endcode
3565/// or
3566/// @code delete [] ptr; @endcode
3567ExprResult
3568Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3569 bool ArrayForm, Expr *ExE) {
3570 // C++ [expr.delete]p1:
3571 // The operand shall have a pointer type, or a class type having a single
3572 // non-explicit conversion function to a pointer type. The result has type
3573 // void.
3574 //
3575 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3576
3577 ExprResult Ex = ExE;
3578 FunctionDecl *OperatorDelete = nullptr;
3579 bool ArrayFormAsWritten = ArrayForm;
3580 bool UsualArrayDeleteWantsSize = false;
3581
3582 if (!Ex.get()->isTypeDependent()) {
3583 // Perform lvalue-to-rvalue cast, if needed.
3584 Ex = DefaultLvalueConversion(Ex.get());
3585 if (Ex.isInvalid())
3586 return ExprError();
3587
3588 QualType Type = Ex.get()->getType();
3589
3590 class DeleteConverter : public ContextualImplicitConverter {
3591 public:
3592 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3593
3594 bool match(QualType ConvType) override {
3595 // FIXME: If we have an operator T* and an operator void*, we must pick
3596 // the operator T*.
3597 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3598 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3599 return true;
3600 return false;
3601 }
3602
3603 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3604 QualType T) override {
3605 return S.Diag(Loc, diag::err_delete_operand) << T;
3606 }
3607
3608 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3609 QualType T) override {
3610 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3611 }
3612
3613 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3614 QualType T,
3615 QualType ConvTy) override {
3616 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3617 }
3618
3619 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3620 QualType ConvTy) override {
3621 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3622 << ConvTy;
3623 }
3624
3625 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3626 QualType T) override {
3627 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3628 }
3629
3630 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3631 QualType ConvTy) override {
3632 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3633 << ConvTy;
3634 }
3635
3636 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3637 QualType T,
3638 QualType ConvTy) override {
3639 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "clang/lib/Sema/SemaExprCXX.cpp", 3639)
;
3640 }
3641 } Converter;
3642
3643 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3644 if (Ex.isInvalid())
3645 return ExprError();
3646 Type = Ex.get()->getType();
3647 if (!Converter.match(Type))
3648 // FIXME: PerformContextualImplicitConversion should return ExprError
3649 // itself in this case.
3650 return ExprError();
3651
3652 QualType Pointee = Type->castAs<PointerType>()->getPointeeType();
3653 QualType PointeeElem = Context.getBaseElementType(Pointee);
3654
3655 if (Pointee.getAddressSpace() != LangAS::Default &&
3656 !getLangOpts().OpenCLCPlusPlus)
3657 return Diag(Ex.get()->getBeginLoc(),
3658 diag::err_address_space_qualified_delete)
3659 << Pointee.getUnqualifiedType()
3660 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3661
3662 CXXRecordDecl *PointeeRD = nullptr;
3663 if (Pointee->isVoidType() && !isSFINAEContext()) {
3664 // The C++ standard bans deleting a pointer to a non-object type, which
3665 // effectively bans deletion of "void*". However, most compilers support
3666 // this, so we treat it as a warning unless we're in a SFINAE context.
3667 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3668 << Type << Ex.get()->getSourceRange();
3669 } else if (Pointee->isFunctionType() || Pointee->isVoidType() ||
3670 Pointee->isSizelessType()) {
3671 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3672 << Type << Ex.get()->getSourceRange());
3673 } else if (!Pointee->isDependentType()) {
3674 // FIXME: This can result in errors if the definition was imported from a
3675 // module but is hidden.
3676 if (!RequireCompleteType(StartLoc, Pointee,
3677 diag::warn_delete_incomplete, Ex.get())) {
3678 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3679 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3680 }
3681 }
3682
3683 if (Pointee->isArrayType() && !ArrayForm) {
3684 Diag(StartLoc, diag::warn_delete_array_type)
3685 << Type << Ex.get()->getSourceRange()
3686 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3687 ArrayForm = true;
3688 }
3689
3690 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3691 ArrayForm ? OO_Array_Delete : OO_Delete);
3692
3693 if (PointeeRD) {
3694 if (!UseGlobal &&
3695 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3696 OperatorDelete))
3697 return ExprError();
3698
3699 // If we're allocating an array of records, check whether the
3700 // usual operator delete[] has a size_t parameter.
3701 if (ArrayForm) {
3702 // If the user specifically asked to use the global allocator,
3703 // we'll need to do the lookup into the class.
3704 if (UseGlobal)
3705 UsualArrayDeleteWantsSize =
3706 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3707
3708 // Otherwise, the usual operator delete[] should be the
3709 // function we just found.
3710 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3711 UsualArrayDeleteWantsSize =
3712 UsualDeallocFnInfo(*this,
3713 DeclAccessPair::make(OperatorDelete, AS_public))
3714 .HasSizeT;
3715 }
3716
3717 if (!PointeeRD->hasIrrelevantDestructor())
3718 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3719 MarkFunctionReferenced(StartLoc,
3720 const_cast<CXXDestructorDecl*>(Dtor));
3721 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3722 return ExprError();
3723 }
3724
3725 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3726 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3727 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3728 SourceLocation());
3729 }
3730
3731 if (!OperatorDelete) {
3732 if (getLangOpts().OpenCLCPlusPlus) {
3733 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3734 return ExprError();
3735 }
3736
3737 bool IsComplete = isCompleteType(StartLoc, Pointee);
3738 bool CanProvideSize =
3739 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3740 Pointee.isDestructedType());
3741 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3742
3743 // Look for a global declaration.
3744 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3745 Overaligned, DeleteName);
3746 }
3747
3748 MarkFunctionReferenced(StartLoc, OperatorDelete);
3749
3750 // Check access and ambiguity of destructor if we're going to call it.
3751 // Note that this is required even for a virtual delete.
3752 bool IsVirtualDelete = false;
3753 if (PointeeRD) {
3754 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3755 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3756 PDiag(diag::err_access_dtor) << PointeeElem);
3757 IsVirtualDelete = Dtor->isVirtual();
3758 }
3759 }
3760
3761 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3762
3763 // Convert the operand to the type of the first parameter of operator
3764 // delete. This is only necessary if we selected a destroying operator
3765 // delete that we are going to call (non-virtually); converting to void*
3766 // is trivial and left to AST consumers to handle.
3767 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3768 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3769 Qualifiers Qs = Pointee.getQualifiers();
3770 if (Qs.hasCVRQualifiers()) {
3771 // Qualifiers are irrelevant to this conversion; we're only looking
3772 // for access and ambiguity.
3773 Qs.removeCVRQualifiers();
3774 QualType Unqual = Context.getPointerType(
3775 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3776 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3777 }
3778 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3779 if (Ex.isInvalid())
3780 return ExprError();
3781 }
3782 }
3783
3784 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3785 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3786 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3787 AnalyzeDeleteExprMismatch(Result);
3788 return Result;
3789}
3790
3791static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3792 bool IsDelete,
3793 FunctionDecl *&Operator) {
3794
3795 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3796 IsDelete ? OO_Delete : OO_New);
3797
3798 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3799 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3800 assert(!R.empty() && "implicitly declared allocation functions not found")(static_cast <bool> (!R.empty() && "implicitly declared allocation functions not found"
) ? void (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3800, __extension__ __PRETTY_FUNCTION__
))
;
3801 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")(static_cast <bool> (!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? void (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3801, __extension__ __PRETTY_FUNCTION__
))
;
3802
3803 // We do our own custom access checks below.
3804 R.suppressDiagnostics();
3805
3806 SmallVector<Expr *, 8> Args(TheCall->arguments());
3807 OverloadCandidateSet Candidates(R.getNameLoc(),
3808 OverloadCandidateSet::CSK_Normal);
3809 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3810 FnOvl != FnOvlEnd; ++FnOvl) {
3811 // Even member operator new/delete are implicitly treated as
3812 // static, so don't use AddMemberCandidate.
3813 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3814
3815 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3816 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3817 /*ExplicitTemplateArgs=*/nullptr, Args,
3818 Candidates,
3819 /*SuppressUserConversions=*/false);
3820 continue;
3821 }
3822
3823 FunctionDecl *Fn = cast<FunctionDecl>(D);
3824 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3825 /*SuppressUserConversions=*/false);
3826 }
3827
3828 SourceRange Range = TheCall->getSourceRange();
3829
3830 // Do the resolution.
3831 OverloadCandidateSet::iterator Best;
3832 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3833 case OR_Success: {
3834 // Got one!
3835 FunctionDecl *FnDecl = Best->Function;
3836 assert(R.getNamingClass() == nullptr &&(static_cast <bool> (R.getNamingClass() == nullptr &&
"class members should not be considered") ? void (0) : __assert_fail
("R.getNamingClass() == nullptr && \"class members should not be considered\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3837, __extension__ __PRETTY_FUNCTION__
))
3837 "class members should not be considered")(static_cast <bool> (R.getNamingClass() == nullptr &&
"class members should not be considered") ? void (0) : __assert_fail
("R.getNamingClass() == nullptr && \"class members should not be considered\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3837, __extension__ __PRETTY_FUNCTION__
))
;
3838
3839 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3840 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3841 << (IsDelete ? 1 : 0) << Range;
3842 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3843 << R.getLookupName() << FnDecl->getSourceRange();
3844 return true;
3845 }
3846
3847 Operator = FnDecl;
3848 return false;
3849 }
3850
3851 case OR_No_Viable_Function:
3852 Candidates.NoteCandidates(
3853 PartialDiagnosticAt(R.getNameLoc(),
3854 S.PDiag(diag::err_ovl_no_viable_function_in_call)
3855 << R.getLookupName() << Range),
3856 S, OCD_AllCandidates, Args);
3857 return true;
3858
3859 case OR_Ambiguous:
3860 Candidates.NoteCandidates(
3861 PartialDiagnosticAt(R.getNameLoc(),
3862 S.PDiag(diag::err_ovl_ambiguous_call)
3863 << R.getLookupName() << Range),
3864 S, OCD_AmbiguousCandidates, Args);
3865 return true;
3866
3867 case OR_Deleted: {
3868 Candidates.NoteCandidates(
3869 PartialDiagnosticAt(R.getNameLoc(), S.PDiag(diag::err_ovl_deleted_call)
3870 << R.getLookupName() << Range),
3871 S, OCD_AllCandidates, Args);
3872 return true;
3873 }
3874 }
3875 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "clang/lib/Sema/SemaExprCXX.cpp", 3875)
;
3876}
3877
3878ExprResult
3879Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3880 bool IsDelete) {
3881 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3882 if (!getLangOpts().CPlusPlus) {
3883 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3884 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3885 << "C++";
3886 return ExprError();
3887 }
3888 // CodeGen assumes it can find the global new and delete to call,
3889 // so ensure that they are declared.
3890 DeclareGlobalNewDelete();
3891
3892 FunctionDecl *OperatorNewOrDelete = nullptr;
3893 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3894 OperatorNewOrDelete))
3895 return ExprError();
3896 assert(OperatorNewOrDelete && "should be found")(static_cast <bool> (OperatorNewOrDelete && "should be found"
) ? void (0) : __assert_fail ("OperatorNewOrDelete && \"should be found\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3896, __extension__ __PRETTY_FUNCTION__
))
;
3897
3898 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3899 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3900
3901 TheCall->setType(OperatorNewOrDelete->getReturnType());
3902 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3903 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3904 InitializedEntity Entity =
3905 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3906 ExprResult Arg = PerformCopyInitialization(
3907 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3908 if (Arg.isInvalid())
3909 return ExprError();
3910 TheCall->setArg(i, Arg.get());
3911 }
3912 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3913 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&(static_cast <bool> (Callee && Callee->getCastKind
() == CK_BuiltinFnToFnPtr && "Callee expected to be implicit cast to a builtin function pointer"
) ? void (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3914, __extension__ __PRETTY_FUNCTION__
))
3914 "Callee expected to be implicit cast to a builtin function pointer")(static_cast <bool> (Callee && Callee->getCastKind
() == CK_BuiltinFnToFnPtr && "Callee expected to be implicit cast to a builtin function pointer"
) ? void (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\""
, "clang/lib/Sema/SemaExprCXX.cpp", 3914, __extension__ __PRETTY_FUNCTION__
))
;
3915 Callee->setType(OperatorNewOrDelete->getType());
3916
3917 return TheCallResult;
3918}
3919
3920void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3921 bool IsDelete, bool CallCanBeVirtual,
3922 bool WarnOnNonAbstractTypes,
3923 SourceLocation DtorLoc) {
3924 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3925 return;
3926
3927 // C++ [expr.delete]p3:
3928 // In the first alternative (delete object), if the static type of the
3929 // object to be deleted is different from its dynamic type, the static
3930 // type shall be a base class of the dynamic type of the object to be
3931 // deleted and the static type shall have a virtual destructor or the
3932 // behavior is undefined.
3933 //
3934 const CXXRecordDecl *PointeeRD = dtor->getParent();
3935 // Note: a final class cannot be derived from, no issue there
3936 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3937 return;
3938
3939 // If the superclass is in a system header, there's nothing that can be done.
3940 // The `delete` (where we emit the warning) can be in a system header,
3941 // what matters for this warning is where the deleted type is defined.
3942 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3943 return;
3944
3945 QualType ClassType = dtor->getThisType()->getPointeeType();
3946 if (PointeeRD->isAbstract()) {
3947 // If the class is abstract, we warn by default, because we're
3948 // sure the code has undefined behavior.
3949 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3950 << ClassType;
3951 } else if (WarnOnNonAbstractTypes) {
3952 // Otherwise, if this is not an array delete, it's a bit suspect,
3953 // but not necessarily wrong.
3954 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3955 << ClassType;
3956 }
3957 if (!IsDelete) {
3958 std::string TypeStr;
3959 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3960 Diag(DtorLoc, diag::note_delete_non_virtual)
3961 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3962 }
3963}
3964
3965Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3966 SourceLocation StmtLoc,
3967 ConditionKind CK) {
3968 ExprResult E =
3969 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3970 if (E.isInvalid())
3971 return ConditionError();
3972 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3973 CK == ConditionKind::ConstexprIf);
3974}
3975
3976/// Check the use of the given variable as a C++ condition in an if,
3977/// while, do-while, or switch statement.
3978ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3979 SourceLocation StmtLoc,
3980 ConditionKind CK) {
3981 if (ConditionVar->isInvalidDecl())
3982 return ExprError();
3983
3984 QualType T = ConditionVar->getType();
3985
3986 // C++ [stmt.select]p2:
3987 // The declarator shall not specify a function or an array.
3988 if (T->isFunctionType())
3989 return ExprError(Diag(ConditionVar->getLocation(),
3990 diag::err_invalid_use_of_function_type)
3991 << ConditionVar->getSourceRange());
3992 else if (T->isArrayType())
3993 return ExprError(Diag(ConditionVar->getLocation(),
3994 diag::err_invalid_use_of_array_type)
3995 << ConditionVar->getSourceRange());
3996
3997 ExprResult Condition = BuildDeclRefExpr(
3998 ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue,
3999 ConditionVar->getLocation());
4000
4001 switch (CK) {
4002 case ConditionKind::Boolean:
4003 return CheckBooleanCondition(StmtLoc, Condition.get());
4004
4005 case ConditionKind::ConstexprIf:
4006 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
4007
4008 case ConditionKind::Switch:
4009 return CheckSwitchCondition(StmtLoc, Condition.get());
4010 }
4011
4012 llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind"
, "clang/lib/Sema/SemaExprCXX.cpp", 4012)
;
4013}
4014
4015/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
4016ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
4017 // C++11 6.4p4:
4018 // The value of a condition that is an initialized declaration in a statement
4019 // other than a switch statement is the value of the declared variable
4020 // implicitly converted to type bool. If that conversion is ill-formed, the
4021 // program is ill-formed.
4022 // The value of a condition that is an expression is the value of the
4023 // expression, implicitly converted to bool.
4024 //
4025 // C++23 8.5.2p2
4026 // If the if statement is of the form if constexpr, the value of the condition
4027 // is contextually converted to bool and the converted expression shall be
4028 // a constant expression.
4029 //
4030
4031 ExprResult E = PerformContextuallyConvertToBool(CondExpr);
4032 if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent())
4033 return E;
4034
4035 // FIXME: Return this value to the caller so they don't need to recompute it.
4036 llvm::APSInt Cond;
4037 E = VerifyIntegerConstantExpression(
4038 E.get(), &Cond,
4039 diag::err_constexpr_if_condition_expression_is_not_constant);
4040 return E;
4041}
4042
4043/// Helper function to determine whether this is the (deprecated) C++
4044/// conversion from a string literal to a pointer to non-const char or
4045/// non-const wchar_t (for narrow and wide string literals,
4046/// respectively).
4047bool
4048Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
4049 // Look inside the implicit cast, if it exists.
4050 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
4051 From = Cast->getSubExpr();
4052
4053 // A string literal (2.13.4) that is not a wide string literal can
4054 // be converted to an rvalue of type "pointer to char"; a wide
4055 // string literal can be converted to an rvalue of type "pointer
4056 // to wchar_t" (C++ 4.2p2).
4057 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
4058 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
4059 if (const BuiltinType *ToPointeeType
4060 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
4061 // This conversion is considered only when there is an
4062 // explicit appropriate pointer target type (C++ 4.2p2).
4063 if (!ToPtrType->getPointeeType().hasQualifiers()) {
4064 switch (StrLit->getKind()) {
4065 case StringLiteral::UTF8:
4066 case StringLiteral::UTF16:
4067 case StringLiteral::UTF32:
4068 // We don't allow UTF literals to be implicitly converted
4069 break;
4070 case StringLiteral::Ordinary:
4071 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
4072 ToPointeeType->getKind() == BuiltinType::Char_S);
4073 case StringLiteral::Wide:
4074 return Context.typesAreCompatible(Context.getWideCharType(),
4075 QualType(ToPointeeType, 0));
4076 }
4077 }
4078 }
4079
4080 return false;
4081}
4082
4083static ExprResult BuildCXXCastArgument(Sema &S,
4084 SourceLocation CastLoc,
4085 QualType Ty,
4086 CastKind Kind,
4087 CXXMethodDecl *Method,
4088 DeclAccessPair FoundDecl,
4089 bool HadMultipleCandidates,
4090 Expr *From) {
4091 switch (Kind) {
4092 default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "clang/lib/Sema/SemaExprCXX.cpp"
, 4092)
;
4093 case CK_ConstructorConversion: {
4094 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
4095 SmallVector<Expr*, 8> ConstructorArgs;
4096
4097 if (S.RequireNonAbstractType(CastLoc, Ty,
4098 diag::err_allocation_of_abstract_type))
4099 return ExprError();
4100
4101 if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc,
4102 ConstructorArgs))
4103 return ExprError();
4104
4105 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
4106 InitializedEntity::InitializeTemporary(Ty));
4107 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4108 return ExprError();
4109
4110 ExprResult Result = S.BuildCXXConstructExpr(
4111 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
4112 ConstructorArgs, HadMultipleCandidates,
4113 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4114 CXXConstructExpr::CK_Complete, SourceRange());
4115 if (Result.isInvalid())
4116 return ExprError();
4117
4118 return S.MaybeBindToTemporary(Result.getAs<Expr>());
4119 }
4120
4121 case CK_UserDefinedConversion: {
4122 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")(static_cast <bool> (!From->getType()->isPointerType
() && "Arg can't have pointer type!") ? void (0) : __assert_fail
("!From->getType()->isPointerType() && \"Arg can't have pointer type!\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4122, __extension__ __PRETTY_FUNCTION__
))
;
4123
4124 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
4125 if (S.DiagnoseUseOfDecl(Method, CastLoc))
4126 return ExprError();
4127
4128 // Create an implicit call expr that calls it.
4129 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
4130 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
4131 HadMultipleCandidates);
4132 if (Result.isInvalid())
4133 return ExprError();
4134 // Record usage of conversion in an implicit cast.
4135 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
4136 CK_UserDefinedConversion, Result.get(),
4137 nullptr, Result.get()->getValueKind(),
4138 S.CurFPFeatureOverrides());
4139
4140 return S.MaybeBindToTemporary(Result.get());
4141 }
4142 }
4143}
4144
4145/// PerformImplicitConversion - Perform an implicit conversion of the
4146/// expression From to the type ToType using the pre-computed implicit
4147/// conversion sequence ICS. Returns the converted
4148/// expression. Action is the kind of conversion we're performing,
4149/// used in the error message.
4150ExprResult
4151Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4152 const ImplicitConversionSequence &ICS,
4153 AssignmentAction Action,
4154 CheckedConversionKind CCK) {
4155 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
4156 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
4157 return From;
4158
4159 switch (ICS.getKind()) {
4160 case ImplicitConversionSequence::StandardConversion: {
4161 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
4162 Action, CCK);
4163 if (Res.isInvalid())
4164 return ExprError();
4165 From = Res.get();
4166 break;
4167 }
4168
4169 case ImplicitConversionSequence::UserDefinedConversion: {
4170
4171 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
4172 CastKind CastKind;
4173 QualType BeforeToType;
4174 assert(FD && "no conversion function for user-defined conversion seq")(static_cast <bool> (FD && "no conversion function for user-defined conversion seq"
) ? void (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4174, __extension__ __PRETTY_FUNCTION__
))
;
4175 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
4176 CastKind = CK_UserDefinedConversion;
4177
4178 // If the user-defined conversion is specified by a conversion function,
4179 // the initial standard conversion sequence converts the source type to
4180 // the implicit object parameter of the conversion function.
4181 BeforeToType = Context.getTagDeclType(Conv->getParent());
4182 } else {
4183 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
4184 CastKind = CK_ConstructorConversion;
4185 // Do no conversion if dealing with ... for the first conversion.
4186 if (!ICS.UserDefined.EllipsisConversion) {
4187 // If the user-defined conversion is specified by a constructor, the
4188 // initial standard conversion sequence converts the source type to
4189 // the type required by the argument of the constructor
4190 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
4191 }
4192 }
4193 // Watch out for ellipsis conversion.
4194 if (!ICS.UserDefined.EllipsisConversion) {
4195 ExprResult Res =
4196 PerformImplicitConversion(From, BeforeToType,
4197 ICS.UserDefined.Before, AA_Converting,
4198 CCK);
4199 if (Res.isInvalid())
4200 return ExprError();
4201 From = Res.get();
4202 }
4203
4204 ExprResult CastArg = BuildCXXCastArgument(
4205 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
4206 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
4207 ICS.UserDefined.HadMultipleCandidates, From);
4208
4209 if (CastArg.isInvalid())
4210 return ExprError();
4211
4212 From = CastArg.get();
4213
4214 // C++ [over.match.oper]p7:
4215 // [...] the second standard conversion sequence of a user-defined
4216 // conversion sequence is not applied.
4217 if (CCK == CCK_ForBuiltinOverloadedOp)
4218 return From;
4219
4220 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
4221 AA_Converting, CCK);
4222 }
4223
4224 case ImplicitConversionSequence::AmbiguousConversion:
4225 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
4226 PDiag(diag::err_typecheck_ambiguous_condition)
4227 << From->getSourceRange());
4228 return ExprError();
4229
4230 case ImplicitConversionSequence::EllipsisConversion:
4231 case ImplicitConversionSequence::StaticObjectArgumentConversion:
4232 llvm_unreachable("bad conversion")::llvm::llvm_unreachable_internal("bad conversion", "clang/lib/Sema/SemaExprCXX.cpp"
, 4232)
;
4233
4234 case ImplicitConversionSequence::BadConversion:
4235 Sema::AssignConvertType ConvTy =
4236 CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType());
4237 bool Diagnosed = DiagnoseAssignmentResult(
4238 ConvTy == Compatible ? Incompatible : ConvTy, From->getExprLoc(),
4239 ToType, From->getType(), From, Action);
4240 assert(Diagnosed && "failed to diagnose bad conversion")(static_cast <bool> (Diagnosed && "failed to diagnose bad conversion"
) ? void (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4240, __extension__ __PRETTY_FUNCTION__
))
; (void)Diagnosed;
4241 return ExprError();
4242 }
4243
4244 // Everything went well.
4245 return From;
4246}
4247
4248/// PerformImplicitConversion - Perform an implicit conversion of the
4249/// expression From to the type ToType by following the standard
4250/// conversion sequence SCS. Returns the converted
4251/// expression. Flavor is the context in which we're performing this
4252/// conversion, for use in error messages.
4253ExprResult
4254Sema::PerformImplicitConversion(Expr *From, QualType ToType,
4255 const StandardConversionSequence& SCS,
4256 AssignmentAction Action,
4257 CheckedConversionKind CCK) {
4258 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
4259
4260 // Overall FIXME: we are recomputing too many types here and doing far too
4261 // much extra work. What this means is that we need to keep track of more
4262 // information that is computed when we try the implicit conversion initially,
4263 // so that we don't need to recompute anything here.
4264 QualType FromType = From->getType();
4265
4266 if (SCS.CopyConstructor) {
4267 // FIXME: When can ToType be a reference type?
4268 assert(!ToType->isReferenceType())(static_cast <bool> (!ToType->isReferenceType()) ? void
(0) : __assert_fail ("!ToType->isReferenceType()", "clang/lib/Sema/SemaExprCXX.cpp"
, 4268, __extension__ __PRETTY_FUNCTION__))
;
4269 if (SCS.Second == ICK_Derived_To_Base) {
4270 SmallVector<Expr*, 8> ConstructorArgs;
4271 if (CompleteConstructorCall(
4272 cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From,
4273 /*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs))
4274 return ExprError();
4275 return BuildCXXConstructExpr(
4276 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4277 SCS.FoundCopyConstructor, SCS.CopyConstructor,
4278 ConstructorArgs, /*HadMultipleCandidates*/ false,
4279 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4280 CXXConstructExpr::CK_Complete, SourceRange());
4281 }
4282 return BuildCXXConstructExpr(
4283 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
4284 SCS.FoundCopyConstructor, SCS.CopyConstructor,
4285 From, /*HadMultipleCandidates*/ false,
4286 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
4287 CXXConstructExpr::CK_Complete, SourceRange());
4288 }
4289
4290 // Resolve overloaded function references.
4291 if (Context.hasSameType(FromType, Context.OverloadTy)) {
4292 DeclAccessPair Found;
4293 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
4294 true, Found);
4295 if (!Fn)
4296 return ExprError();
4297
4298 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
4299 return ExprError();
4300
4301 From = FixOverloadedFunctionReference(From, Found, Fn);
4302
4303 // We might get back another placeholder expression if we resolved to a
4304 // builtin.
4305 ExprResult Checked = CheckPlaceholderExpr(From);
4306 if (Checked.isInvalid())
4307 return ExprError();
4308
4309 From = Checked.get();
4310 FromType = From->getType();
4311 }
4312
4313 // If we're converting to an atomic type, first convert to the corresponding
4314 // non-atomic type.
4315 QualType ToAtomicType;
4316 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
4317 ToAtomicType = ToType;
4318 ToType = ToAtomic->getValueType();
4319 }
4320
4321 QualType InitialFromType = FromType;
4322 // Perform the first implicit conversion.
4323 switch (SCS.First) {
4324 case ICK_Identity:
4325 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
4326 FromType = FromAtomic->getValueType().getUnqualifiedType();
4327 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
4328 From, /*BasePath=*/nullptr, VK_PRValue,
4329 FPOptionsOverride());
4330 }
4331 break;
4332
4333 case ICK_Lvalue_To_Rvalue: {
4334 assert(From->getObjectKind() != OK_ObjCProperty)(static_cast <bool> (From->getObjectKind() != OK_ObjCProperty
) ? void (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty"
, "clang/lib/Sema/SemaExprCXX.cpp", 4334, __extension__ __PRETTY_FUNCTION__
))
;
4335 ExprResult FromRes = DefaultLvalueConversion(From);
4336 if (FromRes.isInvalid())
4337 return ExprError();
4338
4339 From = FromRes.get();
4340 FromType = From->getType();
4341 break;
4342 }
4343
4344 case ICK_Array_To_Pointer:
4345 FromType = Context.getArrayDecayedType(FromType);
4346 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue,
4347 /*BasePath=*/nullptr, CCK)
4348 .get();
4349 break;
4350
4351 case ICK_Function_To_Pointer:
4352 FromType = Context.getPointerType(FromType);
4353 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
4354 VK_PRValue, /*BasePath=*/nullptr, CCK)
4355 .get();
4356 break;
4357
4358 default:
4359 llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion"
, "clang/lib/Sema/SemaExprCXX.cpp", 4359)
;
4360 }
4361
4362 // Perform the second implicit conversion
4363 switch (SCS.Second) {
4364 case ICK_Identity:
4365 // C++ [except.spec]p5:
4366 // [For] assignment to and initialization of pointers to functions,
4367 // pointers to member functions, and references to functions: the
4368 // target entity shall allow at least the exceptions allowed by the
4369 // source value in the assignment or initialization.
4370 switch (Action) {
4371 case AA_Assigning:
4372 case AA_Initializing:
4373 // Note, function argument passing and returning are initialization.
4374 case AA_Passing:
4375 case AA_Returning:
4376 case AA_Sending:
4377 case AA_Passing_CFAudited:
4378 if (CheckExceptionSpecCompatibility(From, ToType))
4379 return ExprError();
4380 break;
4381
4382 case AA_Casting:
4383 case AA_Converting:
4384 // Casts and implicit conversions are not initialization, so are not
4385 // checked for exception specification mismatches.
4386 break;
4387 }
4388 // Nothing else to do.
4389 break;
4390
4391 case ICK_Integral_Promotion:
4392 case ICK_Integral_Conversion:
4393 if (ToType->isBooleanType()) {
4394 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4396, __extension__ __PRETTY_FUNCTION__
))
4395 SCS.Second == ICK_Integral_Promotion &&(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4396, __extension__ __PRETTY_FUNCTION__
))
4396 "only enums with fixed underlying type can promote to bool")(static_cast <bool> (FromType->castAs<EnumType>
()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion
&& "only enums with fixed underlying type can promote to bool"
) ? void (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4396, __extension__ __PRETTY_FUNCTION__
))
;
4397 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue,
4398 /*BasePath=*/nullptr, CCK)
4399 .get();
4400 } else {
4401 From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue,
4402 /*BasePath=*/nullptr, CCK)
4403 .get();
4404 }
4405 break;
4406
4407 case ICK_Floating_Promotion:
4408 case ICK_Floating_Conversion:
4409 From = ImpCastExprToType(From, ToType, CK_FloatingCast, VK_PRValue,
4410 /*BasePath=*/nullptr, CCK)
4411 .get();
4412 break;
4413
4414 case ICK_Complex_Promotion:
4415 case ICK_Complex_Conversion: {
4416 QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType();
4417 QualType ToEl = ToType->castAs<ComplexType>()->getElementType();
4418 CastKind CK;
4419 if (FromEl->isRealFloatingType()) {
4420 if (ToEl->isRealFloatingType())
4421 CK = CK_FloatingComplexCast;
4422 else
4423 CK = CK_FloatingComplexToIntegralComplex;
4424 } else if (ToEl->isRealFloatingType()) {
4425 CK = CK_IntegralComplexToFloatingComplex;
4426 } else {
4427 CK = CK_IntegralComplexCast;
4428 }
4429 From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr,
4430 CCK)
4431 .get();
4432 break;
4433 }
4434
4435 case ICK_Floating_Integral:
4436 if (ToType->isRealFloatingType())
4437 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating, VK_PRValue,
4438 /*BasePath=*/nullptr, CCK)
4439 .get();
4440 else
4441 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue,
4442 /*BasePath=*/nullptr, CCK)
4443 .get();
4444 break;
4445
4446 case ICK_Compatible_Conversion:
4447 From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(),
4448 /*BasePath=*/nullptr, CCK).get();
4449 break;
4450
4451 case ICK_Writeback_Conversion:
4452 case ICK_Pointer_Conversion: {
4453 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4454 // Diagnose incompatible Objective-C conversions
4455 if (Action == AA_Initializing || Action == AA_Assigning)
4456 Diag(From->getBeginLoc(),
4457 diag::ext_typecheck_convert_incompatible_pointer)
4458 << ToType << From->getType() << Action << From->getSourceRange()
4459 << 0;
4460 else
4461 Diag(From->getBeginLoc(),
4462 diag::ext_typecheck_convert_incompatible_pointer)
4463 << From->getType() << ToType << Action << From->getSourceRange()
4464 << 0;
4465
4466 if (From->getType()->isObjCObjectPointerType() &&
4467 ToType->isObjCObjectPointerType())
4468 EmitRelatedResultTypeNote(From);
4469 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4470 !CheckObjCARCUnavailableWeakConversion(ToType,
4471 From->getType())) {
4472 if (Action == AA_Initializing)
4473 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4474 else
4475 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4476 << (Action == AA_Casting) << From->getType() << ToType
4477 << From->getSourceRange();
4478 }
4479
4480 // Defer address space conversion to the third conversion.
4481 QualType FromPteeType = From->getType()->getPointeeType();
4482 QualType ToPteeType = ToType->getPointeeType();
4483 QualType NewToType = ToType;
4484 if (!FromPteeType.isNull() && !ToPteeType.isNull() &&
4485 FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) {
4486 NewToType = Context.removeAddrSpaceQualType(ToPteeType);
4487 NewToType = Context.getAddrSpaceQualType(NewToType,
4488 FromPteeType.getAddressSpace());
4489 if (ToType->isObjCObjectPointerType())
4490 NewToType = Context.getObjCObjectPointerType(NewToType);
4491 else if (ToType->isBlockPointerType())
4492 NewToType = Context.getBlockPointerType(NewToType);
4493 else
4494 NewToType = Context.getPointerType(NewToType);
4495 }
4496
4497 CastKind Kind;
4498 CXXCastPath BasePath;
4499 if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle))
4500 return ExprError();
4501
4502 // Make sure we extend blocks if necessary.
4503 // FIXME: doing this here is really ugly.
4504 if (Kind == CK_BlockPointerToObjCPointerCast) {
4505 ExprResult E = From;
4506 (void) PrepareCastToObjCObjectPointer(E);
4507 From = E.get();
4508 }
4509 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4510 CheckObjCConversion(SourceRange(), NewToType, From, CCK);
4511 From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK)
4512 .get();
4513 break;
4514 }
4515
4516 case ICK_Pointer_Member: {
4517 CastKind Kind;
4518 CXXCastPath BasePath;
4519 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4520 return ExprError();
4521 if (CheckExceptionSpecCompatibility(From, ToType))
4522 return ExprError();
4523
4524 // We may not have been able to figure out what this member pointer resolved
4525 // to up until this exact point. Attempt to lock-in it's inheritance model.
4526 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4527 (void)isCompleteType(From->getExprLoc(), From->getType());
4528 (void)isCompleteType(From->getExprLoc(), ToType);
4529 }
4530
4531 From =
4532 ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get();
4533 break;
4534 }
4535
4536 case ICK_Boolean_Conversion:
4537 // Perform half-to-boolean conversion via float.
4538 if (From->getType()->isHalfType()) {
4539 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4540 FromType = Context.FloatTy;
4541 }
4542
4543 From = ImpCastExprToType(From, Context.BoolTy,
4544 ScalarTypeToBooleanCastKind(FromType), VK_PRValue,
4545 /*BasePath=*/nullptr, CCK)
4546 .get();
4547 break;
4548
4549 case ICK_Derived_To_Base: {
4550 CXXCastPath BasePath;
4551 if (CheckDerivedToBaseConversion(
4552 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4553 From->getSourceRange(), &BasePath, CStyle))
4554 return ExprError();
4555
4556 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4557 CK_DerivedToBase, From->getValueKind(),
4558 &BasePath, CCK).get();
4559 break;
4560 }
4561
4562 case ICK_Vector_Conversion:
4563 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4564 /*BasePath=*/nullptr, CCK)
4565 .get();
4566 break;
4567
4568 case ICK_SVE_Vector_Conversion:
4569 case ICK_RVV_Vector_Conversion:
4570 From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue,
4571 /*BasePath=*/nullptr, CCK)
4572 .get();
4573 break;
4574
4575 case ICK_Vector_Splat: {
4576 // Vector splat from any arithmetic type to a vector.
4577 Expr *Elem = prepareVectorSplat(ToType, From).get();
4578 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue,
4579 /*BasePath=*/nullptr, CCK)
4580 .get();
4581 break;
4582 }
4583
4584 case ICK_Complex_Real:
4585 // Case 1. x -> _Complex y
4586 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4587 QualType ElType = ToComplex->getElementType();
4588 bool isFloatingComplex = ElType->isRealFloatingType();
4589
4590 // x -> y
4591 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4592 // do nothing
4593 } else if (From->getType()->isRealFloatingType()) {
4594 From = ImpCastExprToType(From, ElType,
4595 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4596 } else {
4597 assert(From->getType()->isIntegerType())(static_cast <bool> (From->getType()->isIntegerType
()) ? void (0) : __assert_fail ("From->getType()->isIntegerType()"
, "clang/lib/Sema/SemaExprCXX.cpp", 4597, __extension__ __PRETTY_FUNCTION__
))
;
4598 From = ImpCastExprToType(From, ElType,
4599 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4600 }
4601 // y -> _Complex y
4602 From = ImpCastExprToType(From, ToType,
4603 isFloatingComplex ? CK_FloatingRealToComplex
4604 : CK_IntegralRealToComplex).get();
4605
4606 // Case 2. _Complex x -> y
4607 } else {
4608 auto *FromComplex = From->getType()->castAs<ComplexType>();
4609 QualType ElType = FromComplex->getElementType();
4610 bool isFloatingComplex = ElType->isRealFloatingType();
4611
4612 // _Complex x -> x
4613 From = ImpCastExprToType(From, ElType,
4614 isFloatingComplex ? CK_FloatingComplexToReal
4615 : CK_IntegralComplexToReal,
4616 VK_PRValue, /*BasePath=*/nullptr, CCK)
4617 .get();
4618
4619 // x -> y
4620 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4621 // do nothing
4622 } else if (ToType->isRealFloatingType()) {
4623 From = ImpCastExprToType(From, ToType,
4624 isFloatingComplex ? CK_FloatingCast
4625 : CK_IntegralToFloating,
4626 VK_PRValue, /*BasePath=*/nullptr, CCK)
4627 .get();
4628 } else {
4629 assert(ToType->isIntegerType())(static_cast <bool> (ToType->isIntegerType()) ? void
(0) : __assert_fail ("ToType->isIntegerType()", "clang/lib/Sema/SemaExprCXX.cpp"
, 4629, __extension__ __PRETTY_FUNCTION__))
;
4630 From = ImpCastExprToType(From, ToType,
4631 isFloatingComplex ? CK_FloatingToIntegral
4632 : CK_IntegralCast,
4633 VK_PRValue, /*BasePath=*/nullptr, CCK)
4634 .get();
4635 }
4636 }
4637 break;
4638
4639 case ICK_Block_Pointer_Conversion: {
4640 LangAS AddrSpaceL =
4641 ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4642 LangAS AddrSpaceR =
4643 FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace();
4644 assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) &&(static_cast <bool> (Qualifiers::isAddressSpaceSupersetOf
(AddrSpaceL, AddrSpaceR) && "Invalid cast") ? void (0
) : __assert_fail ("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4645, __extension__ __PRETTY_FUNCTION__
))
4645 "Invalid cast")(static_cast <bool> (Qualifiers::isAddressSpaceSupersetOf
(AddrSpaceL, AddrSpaceR) && "Invalid cast") ? void (0
) : __assert_fail ("Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR) && \"Invalid cast\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4645, __extension__ __PRETTY_FUNCTION__
))
;
4646 CastKind Kind =
4647 AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
4648 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind,
4649 VK_PRValue, /*BasePath=*/nullptr, CCK)
4650 .get();
4651 break;
4652 }
4653
4654 case ICK_TransparentUnionConversion: {
4655 ExprResult FromRes = From;
4656 Sema::AssignConvertType ConvTy =
4657 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4658 if (FromRes.isInvalid())
4659 return ExprError();
4660 From = FromRes.get();
4661 assert ((ConvTy == Sema::Compatible) &&(static_cast <bool> ((ConvTy == Sema::Compatible) &&
"Improper transparent union conversion") ? void (0) : __assert_fail
("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4662, __extension__ __PRETTY_FUNCTION__
))
4662 "Improper transparent union conversion")(static_cast <bool> ((ConvTy == Sema::Compatible) &&
"Improper transparent union conversion") ? void (0) : __assert_fail
("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4662, __extension__ __PRETTY_FUNCTION__
))
;
4663 (void)ConvTy;
4664 break;
4665 }
4666
4667 case ICK_Zero_Event_Conversion:
4668 case ICK_Zero_Queue_Conversion:
4669 From = ImpCastExprToType(From, ToType,
4670 CK_ZeroToOCLOpaqueType,
4671 From->getValueKind()).get();
4672 break;
4673
4674 case ICK_Lvalue_To_Rvalue:
4675 case ICK_Array_To_Pointer:
4676 case ICK_Function_To_Pointer:
4677 case ICK_Function_Conversion:
4678 case ICK_Qualification:
4679 case ICK_Num_Conversion_Kinds:
4680 case ICK_C_Only_Conversion:
4681 case ICK_Incompatible_Pointer_Conversion:
4682 llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion"
, "clang/lib/Sema/SemaExprCXX.cpp", 4682)
;
4683 }
4684
4685 switch (SCS.Third) {
4686 case ICK_Identity:
4687 // Nothing to do.
4688 break;
4689
4690 case ICK_Function_Conversion:
4691 // If both sides are functions (or pointers/references to them), there could
4692 // be incompatible exception declarations.
4693 if (CheckExceptionSpecCompatibility(From, ToType))
4694 return ExprError();
4695
4696 From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue,
4697 /*BasePath=*/nullptr, CCK)
4698 .get();
4699 break;
4700
4701 case ICK_Qualification: {
4702 ExprValueKind VK = From->getValueKind();
4703 CastKind CK = CK_NoOp;
4704
4705 if (ToType->isReferenceType() &&
4706 ToType->getPointeeType().getAddressSpace() !=
4707 From->getType().getAddressSpace())
4708 CK = CK_AddressSpaceConversion;
4709
4710 if (ToType->isPointerType() &&
4711 ToType->getPointeeType().getAddressSpace() !=
4712 From->getType()->getPointeeType().getAddressSpace())
4713 CK = CK_AddressSpaceConversion;
4714
4715 if (!isCast(CCK) &&
4716 !ToType->getPointeeType().getQualifiers().hasUnaligned() &&
4717 From->getType()->getPointeeType().getQualifiers().hasUnaligned()) {
4718 Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned)
4719 << InitialFromType << ToType;
4720 }
4721
4722 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4723 /*BasePath=*/nullptr, CCK)
4724 .get();
4725
4726 if (SCS.DeprecatedStringLiteralToCharPtr &&
4727 !getLangOpts().WritableStrings) {
4728 Diag(From->getBeginLoc(),
4729 getLangOpts().CPlusPlus11
4730 ? diag::ext_deprecated_string_literal_conversion
4731 : diag::warn_deprecated_string_literal_conversion)
4732 << ToType.getNonReferenceType();
4733 }
4734
4735 break;
4736 }
4737
4738 default:
4739 llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion"
, "clang/lib/Sema/SemaExprCXX.cpp", 4739)
;
4740 }
4741
4742 // If this conversion sequence involved a scalar -> atomic conversion, perform
4743 // that conversion now.
4744 if (!ToAtomicType.isNull()) {
4745 assert(Context.hasSameType((static_cast <bool> (Context.hasSameType( ToAtomicType->
castAs<AtomicType>()->getValueType(), From->getType
())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "clang/lib/Sema/SemaExprCXX.cpp", 4746, __extension__ __PRETTY_FUNCTION__
))
4746 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))(static_cast <bool> (Context.hasSameType( ToAtomicType->
castAs<AtomicType>()->getValueType(), From->getType
())) ? void (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "clang/lib/Sema/SemaExprCXX.cpp", 4746, __extension__ __PRETTY_FUNCTION__
))
;
4747 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4748 VK_PRValue, nullptr, CCK)
4749 .get();
4750 }
4751
4752 // Materialize a temporary if we're implicitly converting to a reference
4753 // type. This is not required by the C++ rules but is necessary to maintain
4754 // AST invariants.
4755 if (ToType->isReferenceType() && From->isPRValue()) {
4756 ExprResult Res = TemporaryMaterializationConversion(From);
4757 if (Res.isInvalid())
4758 return ExprError();
4759 From = Res.get();
4760 }
4761
4762 // If this conversion sequence succeeded and involved implicitly converting a
4763 // _Nullable type to a _Nonnull one, complain.
4764 if (!isCast(CCK))
4765 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4766 From->getBeginLoc());
4767
4768 return From;
4769}
4770
4771/// Check the completeness of a type in a unary type trait.
4772///
4773/// If the particular type trait requires a complete type, tries to complete
4774/// it. If completing the type fails, a diagnostic is emitted and false
4775/// returned. If completing the type succeeds or no completion was required,
4776/// returns true.
4777static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4778 SourceLocation Loc,
4779 QualType ArgTy) {
4780 // C++0x [meta.unary.prop]p3:
4781 // For all of the class templates X declared in this Clause, instantiating
4782 // that template with a template argument that is a class template
4783 // specialization may result in the implicit instantiation of the template
4784 // argument if and only if the semantics of X require that the argument
4785 // must be a complete type.
4786 // We apply this rule to all the type trait expressions used to implement
4787 // these class templates. We also try to follow any GCC documented behavior
4788 // in these expressions to ensure portability of standard libraries.
4789 switch (UTT) {
4790 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "clang/lib/Sema/SemaExprCXX.cpp"
, 4790)
;
4791 // is_complete_type somewhat obviously cannot require a complete type.
4792 case UTT_IsCompleteType:
4793 // Fall-through
4794
4795 // These traits are modeled on the type predicates in C++0x
4796 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4797 // requiring a complete type, as whether or not they return true cannot be
4798 // impacted by the completeness of the type.
4799 case UTT_IsVoid:
4800 case UTT_IsIntegral:
4801 case UTT_IsFloatingPoint:
4802 case UTT_IsArray:
4803 case UTT_IsBoundedArray:
4804 case UTT_IsPointer:
4805 case UTT_IsNullPointer:
4806 case UTT_IsReferenceable:
4807 case UTT_IsLvalueReference:
4808 case UTT_IsRvalueReference:
4809 case UTT_IsMemberFunctionPointer:
4810 case UTT_IsMemberObjectPointer:
4811 case UTT_IsEnum:
4812 case UTT_IsScopedEnum:
4813 case UTT_IsUnion:
4814 case UTT_IsClass:
4815 case UTT_IsFunction:
4816 case UTT_IsReference:
4817 case UTT_IsArithmetic:
4818 case UTT_IsFundamental:
4819 case UTT_IsObject:
4820 case UTT_IsScalar:
4821 case UTT_IsCompound:
4822 case UTT_IsMemberPointer:
4823 // Fall-through
4824
4825 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4826 // which requires some of its traits to have the complete type. However,
4827 // the completeness of the type cannot impact these traits' semantics, and
4828 // so they don't require it. This matches the comments on these traits in
4829 // Table 49.
4830 case UTT_IsConst:
4831 case UTT_IsVolatile:
4832 case UTT_IsSigned:
4833 case UTT_IsUnboundedArray:
4834 case UTT_IsUnsigned:
4835
4836 // This type trait always returns false, checking the type is moot.
4837 case UTT_IsInterfaceClass:
4838 return true;
4839
4840 // C++14 [meta.unary.prop]:
4841 // If T is a non-union class type, T shall be a complete type.
4842 case UTT_IsEmpty:
4843 case UTT_IsPolymorphic:
4844 case UTT_IsAbstract:
4845 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4846 if (!RD->isUnion())
4847 return !S.RequireCompleteType(
4848 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4849 return true;
4850
4851 // C++14 [meta.unary.prop]:
4852 // If T is a class type, T shall be a complete type.
4853 case UTT_IsFinal:
4854 case UTT_IsSealed:
4855 if (ArgTy->getAsCXXRecordDecl())
4856 return !S.RequireCompleteType(
4857 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4858 return true;
4859
4860 // LWG3823: T shall be an array type, a complete type, or cv void.
4861 case UTT_IsAggregate:
4862 if (ArgTy->isArrayType() || ArgTy->isVoidType())
4863 return true;
4864
4865 return !S.RequireCompleteType(
4866 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4867
4868 // C++1z [meta.unary.prop]:
4869 // remove_all_extents_t<T> shall be a complete type or cv void.
4870 case UTT_IsTrivial:
4871 case UTT_IsTriviallyCopyable:
4872 case UTT_IsStandardLayout:
4873 case UTT_IsPOD:
4874 case UTT_IsLiteral:
4875 // By analogy, is_trivially_relocatable and is_trivially_equality_comparable
4876 // impose the same constraints.
4877 case UTT_IsTriviallyRelocatable:
4878 case UTT_IsTriviallyEqualityComparable:
4879 case UTT_CanPassInRegs:
4880 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4881 // or an array of unknown bound. But GCC actually imposes the same constraints
4882 // as above.
4883 case UTT_HasNothrowAssign:
4884 case UTT_HasNothrowMoveAssign:
4885 case UTT_HasNothrowConstructor:
4886 case UTT_HasNothrowCopy:
4887 case UTT_HasTrivialAssign:
4888 case UTT_HasTrivialMoveAssign:
4889 case UTT_HasTrivialDefaultConstructor:
4890 case UTT_HasTrivialMoveConstructor:
4891 case UTT_HasTrivialCopy:
4892 case UTT_HasTrivialDestructor:
4893 case UTT_HasVirtualDestructor:
4894 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4895 [[fallthrough]];
4896
4897 // C++1z [meta.unary.prop]:
4898 // T shall be a complete type, cv void, or an array of unknown bound.
4899 case UTT_IsDestructible:
4900 case UTT_IsNothrowDestructible:
4901 case UTT_IsTriviallyDestructible:
4902 case UTT_HasUniqueObjectRepresentations:
4903 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4904 return true;
4905
4906 return !S.RequireCompleteType(
4907 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4908 }
4909}
4910
4911static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4912 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4913 bool (CXXRecordDecl::*HasTrivial)() const,
4914 bool (CXXRecordDecl::*HasNonTrivial)() const,
4915 bool (CXXMethodDecl::*IsDesiredOp)() const)
4916{
4917 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4918 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4919 return true;
4920
4921 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4922 DeclarationNameInfo NameInfo(Name, KeyLoc);
4923 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4924 if (Self.LookupQualifiedName(Res, RD)) {
4925 bool FoundOperator = false;
4926 Res.suppressDiagnostics();
4927 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4928 Op != OpEnd; ++Op) {
4929 if (isa<FunctionTemplateDecl>(*Op))
4930 continue;
4931
4932 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4933 if((Operator->*IsDesiredOp)()) {
4934 FoundOperator = true;
4935 auto *CPT = Operator->getType()->castAs<FunctionProtoType>();
4936 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4937 if (!CPT || !CPT->isNothrow())
4938 return false;
4939 }
4940 }
4941 return FoundOperator;
4942 }
4943 return false;
4944}
4945
4946static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4947 SourceLocation KeyLoc, QualType T) {
4948 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() &&
"Cannot evaluate traits of dependent type") ? void (0) : __assert_fail
("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "clang/lib/Sema/SemaExprCXX.cpp", 4948, __extension__ __PRETTY_FUNCTION__
))
;
4949
4950 ASTContext &C = Self.Context;
4951 switch(UTT) {
4952 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "clang/lib/Sema/SemaExprCXX.cpp"
, 4952)
;
4953 // Type trait expressions corresponding to the primary type category
4954 // predicates in C++0x [meta.unary.cat].
4955 case UTT_IsVoid:
4956 return T->isVoidType();
4957 case UTT_IsIntegral:
4958 return T->isIntegralType(C);
4959 case UTT_IsFloatingPoint:
4960 return T->isFloatingType();
4961 case UTT_IsArray:
4962 return T->isArrayType();
4963 case UTT_IsBoundedArray:
4964 if (!T->isVariableArrayType()) {
4965 return T->isArrayType() && !T->isIncompleteArrayType();
4966 }
4967
4968 Self.Diag(KeyLoc, diag::err_vla_unsupported)
4969 << 1 << tok::kw___is_bounded_array;
4970 return false;
4971 case UTT_IsUnboundedArray:
4972 if (!T->isVariableArrayType()) {
4973 return T->isIncompleteArrayType();
4974 }
4975
4976 Self.Diag(KeyLoc, diag::err_vla_unsupported)
4977 << 1 << tok::kw___is_unbounded_array;
4978 return false;
4979 case UTT_IsPointer:
4980 return T->isAnyPointerType();
4981 case UTT_IsNullPointer:
4982 return T->isNullPtrType();
4983 case UTT_IsLvalueReference:
4984 return T->isLValueReferenceType();
4985 case UTT_IsRvalueReference:
4986 return T->isRValueReferenceType();
4987 case UTT_IsMemberFunctionPointer:
4988 return T->isMemberFunctionPointerType();
4989 case UTT_IsMemberObjectPointer:
4990 return T->isMemberDataPointerType();
4991 case UTT_IsEnum:
4992 return T->isEnumeralType();
4993 case UTT_IsScopedEnum:
4994 return T->isScopedEnumeralType();
4995 case UTT_IsUnion:
4996 return T->isUnionType();
4997 case UTT_IsClass:
4998 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4999 case UTT_IsFunction:
5000 return T->isFunctionType();
5001
5002 // Type trait expressions which correspond to the convenient composition
5003 // predicates in C++0x [meta.unary.comp].
5004 case UTT_IsReference:
5005 return T->isReferenceType();
5006 case UTT_IsArithmetic:
5007 return T->isArithmeticType() && !T->isEnumeralType();
5008 case UTT_IsFundamental:
5009 return T->isFundamentalType();
5010 case UTT_IsObject:
5011 return T->isObjectType();
5012 case UTT_IsScalar:
5013 // Note: semantic analysis depends on Objective-C lifetime types to be
5014 // considered scalar types. However, such types do not actually behave
5015 // like scalar types at run time (since they may require retain/release
5016 // operations), so we report them as non-scalar.
5017 if (T->isObjCLifetimeType()) {
5018 switch (T.getObjCLifetime()) {
5019 case Qualifiers::OCL_None:
5020 case Qualifiers::OCL_ExplicitNone:
5021 return true;
5022
5023 case Qualifiers::OCL_Strong:
5024 case Qualifiers::OCL_Weak:
5025 case Qualifiers::OCL_Autoreleasing:
5026 return false;
5027 }
5028 }
5029
5030 return T->isScalarType();
5031 case UTT_IsCompound:
5032 return T->isCompoundType();
5033 case UTT_IsMemberPointer:
5034 return T->isMemberPointerType();
5035
5036 // Type trait expressions which correspond to the type property predicates
5037 // in C++0x [meta.unary.prop].
5038 case UTT_IsConst:
5039 return T.isConstQualified();
5040 case UTT_IsVolatile:
5041 return T.isVolatileQualified();
5042 case UTT_IsTrivial:
5043 return T.isTrivialType(C);
5044 case UTT_IsTriviallyCopyable:
5045 return T.isTriviallyCopyableType(C);
5046 case UTT_IsStandardLayout:
5047 return T->isStandardLayoutType();
5048 case UTT_IsPOD:
5049 return T.isPODType(C);
5050 case UTT_IsLiteral:
5051 return T->isLiteralType(C);
5052 case UTT_IsEmpty:
5053 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5054 return !RD->isUnion() && RD->isEmpty();
5055 return false;
5056 case UTT_IsPolymorphic:
5057 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5058 return !RD->isUnion() && RD->isPolymorphic();
5059 return false;
5060 case UTT_IsAbstract:
5061 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5062 return !RD->isUnion() && RD->isAbstract();
5063 return false;
5064 case UTT_IsAggregate:
5065 // Report vector extensions and complex types as aggregates because they
5066 // support aggregate initialization. GCC mirrors this behavior for vectors
5067 // but not _Complex.
5068 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
5069 T->isAnyComplexType();
5070 // __is_interface_class only returns true when CL is invoked in /CLR mode and
5071 // even then only when it is used with the 'interface struct ...' syntax
5072 // Clang doesn't support /CLR which makes this type trait moot.
5073 case UTT_IsInterfaceClass:
5074 return false;
5075 case UTT_IsFinal:
5076 case UTT_IsSealed:
5077 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5078 return RD->hasAttr<FinalAttr>();
5079 return false;
5080 case UTT_IsSigned:
5081 // Enum types should always return false.
5082 // Floating points should always return true.
5083 return T->isFloatingType() ||
5084 (T->isSignedIntegerType() && !T->isEnumeralType());
5085 case UTT_IsUnsigned:
5086 // Enum types should always return false.
5087 return T->isUnsignedIntegerType() && !T->isEnumeralType();
5088
5089 // Type trait expressions which query classes regarding their construction,
5090 // destruction, and copying. Rather than being based directly on the
5091 // related type predicates in the standard, they are specified by both
5092 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
5093 // specifications.
5094 //
5095 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
5096 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5097 //
5098 // Note that these builtins do not behave as documented in g++: if a class
5099 // has both a trivial and a non-trivial special member of a particular kind,
5100 // they return false! For now, we emulate this behavior.
5101 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
5102 // does not correctly compute triviality in the presence of multiple special
5103 // members of the same kind. Revisit this once the g++ bug is fixed.
5104 case UTT_HasTrivialDefaultConstructor:
5105 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5106 // If __is_pod (type) is true then the trait is true, else if type is
5107 // a cv class or union type (or array thereof) with a trivial default
5108 // constructor ([class.ctor]) then the trait is true, else it is false.
5109 if (T.isPODType(C))
5110 return true;
5111 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5112 return RD->hasTrivialDefaultConstructor() &&
5113 !RD->hasNonTrivialDefaultConstructor();
5114 return false;
5115 case UTT_HasTrivialMoveConstructor:
5116 // This trait is implemented by MSVC 2012 and needed to parse the
5117 // standard library headers. Specifically this is used as the logic
5118 // behind std::is_trivially_move_constructible (20.9.4.3).
5119 if (T.isPODType(C))
5120 return true;
5121 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5122 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
5123 return false;
5124 case UTT_HasTrivialCopy:
5125 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5126 // If __is_pod (type) is true or type is a reference type then
5127 // the trait is true, else if type is a cv class or union type
5128 // with a trivial copy constructor ([class.copy]) then the trait
5129 // is true, else it is false.
5130 if (T.isPODType(C) || T->isReferenceType())
5131 return true;
5132 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5133 return RD->hasTrivialCopyConstructor() &&
5134 !RD->hasNonTrivialCopyConstructor();
5135 return false;
5136 case UTT_HasTrivialMoveAssign:
5137 // This trait is implemented by MSVC 2012 and needed to parse the
5138 // standard library headers. Specifically it is used as the logic
5139 // behind std::is_trivially_move_assignable (20.9.4.3)
5140 if (T.isPODType(C))
5141 return true;
5142 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5143 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
5144 return false;
5145 case UTT_HasTrivialAssign:
5146 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5147 // If type is const qualified or is a reference type then the
5148 // trait is false. Otherwise if __is_pod (type) is true then the
5149 // trait is true, else if type is a cv class or union type with
5150 // a trivial copy assignment ([class.copy]) then the trait is
5151 // true, else it is false.
5152 // Note: the const and reference restrictions are interesting,
5153 // given that const and reference members don't prevent a class
5154 // from having a trivial copy assignment operator (but do cause
5155 // errors if the copy assignment operator is actually used, q.v.
5156 // [class.copy]p12).
5157
5158 if (T.isConstQualified())
5159 return false;
5160 if (T.isPODType(C))
5161 return true;
5162 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5163 return RD->hasTrivialCopyAssignment() &&
5164 !RD->hasNonTrivialCopyAssignment();
5165 return false;
5166 case UTT_IsDestructible:
5167 case UTT_IsTriviallyDestructible:
5168 case UTT_IsNothrowDestructible:
5169 // C++14 [meta.unary.prop]:
5170 // For reference types, is_destructible<T>::value is true.
5171 if (T->isReferenceType())
5172 return true;
5173
5174 // Objective-C++ ARC: autorelease types don't require destruction.
5175 if (T->isObjCLifetimeType() &&
5176 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5177 return true;
5178
5179 // C++14 [meta.unary.prop]:
5180 // For incomplete types and function types, is_destructible<T>::value is
5181 // false.
5182 if (T->isIncompleteType() || T->isFunctionType())
5183 return false;
5184
5185 // A type that requires destruction (via a non-trivial destructor or ARC
5186 // lifetime semantics) is not trivially-destructible.
5187 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
5188 return false;
5189
5190 // C++14 [meta.unary.prop]:
5191 // For object types and given U equal to remove_all_extents_t<T>, if the
5192 // expression std::declval<U&>().~U() is well-formed when treated as an
5193 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
5194 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5195 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
5196 if (!Destructor)
5197 return false;
5198 // C++14 [dcl.fct.def.delete]p2:
5199 // A program that refers to a deleted function implicitly or
5200 // explicitly, other than to declare it, is ill-formed.
5201 if (Destructor->isDeleted())
5202 return false;
5203 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
5204 return false;
5205 if (UTT == UTT_IsNothrowDestructible) {
5206 auto *CPT = Destructor->getType()->castAs<FunctionProtoType>();
5207 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5208 if (!CPT || !CPT->isNothrow())
5209 return false;
5210 }
5211 }
5212 return true;
5213
5214 case UTT_HasTrivialDestructor:
5215 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5216 // If __is_pod (type) is true or type is a reference type
5217 // then the trait is true, else if type is a cv class or union
5218 // type (or array thereof) with a trivial destructor
5219 // ([class.dtor]) then the trait is true, else it is
5220 // false.
5221 if (T.isPODType(C) || T->isReferenceType())
5222 return true;
5223
5224 // Objective-C++ ARC: autorelease types don't require destruction.
5225 if (T->isObjCLifetimeType() &&
5226 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
5227 return true;
5228
5229 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
5230 return RD->hasTrivialDestructor();
5231 return false;
5232 // TODO: Propagate nothrowness for implicitly declared special members.
5233 case UTT_HasNothrowAssign:
5234 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5235 // If type is const qualified or is a reference type then the
5236 // trait is false. Otherwise if __has_trivial_assign (type)
5237 // is true then the trait is true, else if type is a cv class
5238 // or union type with copy assignment operators that are known
5239 // not to throw an exception then the trait is true, else it is
5240 // false.
5241 if (C.getBaseElementType(T).isConstQualified())
5242 return false;
5243 if (T->isReferenceType())
5244 return false;
5245 if (T.isPODType(C) || T->isObjCLifetimeType())
5246 return true;
5247
5248 if (const RecordType *RT = T->getAs<RecordType>())
5249 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5250 &CXXRecordDecl::hasTrivialCopyAssignment,
5251 &CXXRecordDecl::hasNonTrivialCopyAssignment,
5252 &CXXMethodDecl::isCopyAssignmentOperator);
5253 return false;
5254 case UTT_HasNothrowMoveAssign:
5255 // This trait is implemented by MSVC 2012 and needed to parse the
5256 // standard library headers. Specifically this is used as the logic
5257 // behind std::is_nothrow_move_assignable (20.9.4.3).
5258 if (T.isPODType(C))
5259 return true;
5260
5261 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
5262 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
5263 &CXXRecordDecl::hasTrivialMoveAssignment,
5264 &CXXRecordDecl::hasNonTrivialMoveAssignment,
5265 &CXXMethodDecl::isMoveAssignmentOperator);
5266 return false;
5267 case UTT_HasNothrowCopy:
5268 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5269 // If __has_trivial_copy (type) is true then the trait is true, else
5270 // if type is a cv class or union type with copy constructors that are
5271 // known not to throw an exception then the trait is true, else it is
5272 // false.
5273 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
5274 return true;
5275 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
5276 if (RD->hasTrivialCopyConstructor() &&
5277 !RD->hasNonTrivialCopyConstructor())
5278 return true;
5279
5280 bool FoundConstructor = false;
5281 unsigned FoundTQs;
5282 for (const auto *ND : Self.LookupConstructors(RD)) {
5283 // A template constructor is never a copy constructor.
5284 // FIXME: However, it may actually be selected at the actual overload
5285 // resolution point.
5286 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5287 continue;
5288 // UsingDecl itself is not a constructor
5289 if (isa<UsingDecl>(ND))
5290 continue;
5291 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5292 if (Constructor->isCopyConstructor(FoundTQs)) {
5293 FoundConstructor = true;
5294 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5295 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5296 if (!CPT)
5297 return false;
5298 // TODO: check whether evaluating default arguments can throw.
5299 // For now, we'll be conservative and assume that they can throw.
5300 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
5301 return false;
5302 }
5303 }
5304
5305 return FoundConstructor;
5306 }
5307 return false;
5308 case UTT_HasNothrowConstructor:
5309 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
5310 // If __has_trivial_constructor (type) is true then the trait is
5311 // true, else if type is a cv class or union type (or array
5312 // thereof) with a default constructor that is known not to
5313 // throw an exception then the trait is true, else it is false.
5314 if (T.isPODType(C) || T->isObjCLifetimeType())
5315 return true;
5316 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
5317 if (RD->hasTrivialDefaultConstructor() &&
5318 !RD->hasNonTrivialDefaultConstructor())
5319 return true;
5320
5321 bool FoundConstructor = false;
5322 for (const auto *ND : Self.LookupConstructors(RD)) {
5323 // FIXME: In C++0x, a constructor template can be a default constructor.
5324 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
5325 continue;
5326 // UsingDecl itself is not a constructor
5327 if (isa<UsingDecl>(ND))
5328 continue;
5329 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
5330 if (Constructor->isDefaultConstructor()) {
5331 FoundConstructor = true;
5332 auto *CPT = Constructor->getType()->castAs<FunctionProtoType>();
5333 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
5334 if (!CPT)
5335 return false;
5336 // FIXME: check whether evaluating default arguments can throw.
5337 // For now, we'll be conservative and assume that they can throw.
5338 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
5339 return false;
5340 }
5341 }
5342 return FoundConstructor;
5343 }
5344 return false;
5345 case UTT_HasVirtualDestructor:
5346 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
5347 // If type is a class type with a virtual destructor ([class.dtor])
5348 // then the trait is true, else it is false.
5349 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
5350 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
5351 return Destructor->isVirtual();
5352 return false;
5353
5354 // These type trait expressions are modeled on the specifications for the
5355 // Embarcadero C++0x type trait functions:
5356 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
5357 case UTT_IsCompleteType:
5358 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
5359 // Returns True if and only if T is a complete type at the point of the
5360 // function call.
5361 return !T->isIncompleteType();
5362 case UTT_HasUniqueObjectRepresentations:
5363 return C.hasUniqueObjectRepresentations(T);
5364 case UTT_IsTriviallyRelocatable:
5365 return T.isTriviallyRelocatableType(C);
5366 case UTT_IsReferenceable:
5367 return T.isReferenceable();
5368 case UTT_CanPassInRegs:
5369 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl(); RD && !T.hasQualifiers())
5370 return RD->canPassInRegisters();
5371 Self.Diag(KeyLoc, diag::err_builtin_pass_in_regs_non_class) << T;
5372 return false;
5373 case UTT_IsTriviallyEqualityComparable:
5374 return T.isTriviallyEqualityComparableType(C);
5375 }
5376}
5377
5378static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5379 QualType RhsT, SourceLocation KeyLoc);
5380
5381static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
5382 ArrayRef<TypeSourceInfo *> Args,
5383 SourceLocation RParenLoc) {
5384 if (Kind <= UTT_Last)
5385 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
5386
5387 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
5388 // traits to avoid duplication.
5389 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
5390 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
5391 Args[1]->getType(), RParenLoc);
5392
5393 switch (Kind) {
5394 case clang::BTT_ReferenceBindsToTemporary:
5395 case clang::TT_IsConstructible:
5396 case clang::TT_IsNothrowConstructible:
5397 case clang::TT_IsTriviallyConstructible: {
5398 // C++11 [meta.unary.prop]:
5399 // is_trivially_constructible is defined as:
5400 //
5401 // is_constructible<T, Args...>::value is true and the variable
5402 // definition for is_constructible, as defined below, is known to call
5403 // no operation that is not trivial.
5404 //
5405 // The predicate condition for a template specialization
5406 // is_constructible<T, Args...> shall be satisfied if and only if the
5407 // following variable definition would be well-formed for some invented
5408 // variable t:
5409 //
5410 // T t(create<Args>()...);
5411 assert(!Args.empty())(static_cast <bool> (!Args.empty()) ? void (0) : __assert_fail
("!Args.empty()", "clang/lib/Sema/SemaExprCXX.cpp", 5411, __extension__
__PRETTY_FUNCTION__))
;
5412
5413 // Precondition: T and all types in the parameter pack Args shall be
5414 // complete types, (possibly cv-qualified) void, or arrays of
5415 // unknown bound.
5416 for (const auto *TSI : Args) {
5417 QualType ArgTy = TSI->getType();
5418 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
5419 continue;
5420
5421 if (S.RequireCompleteType(KWLoc, ArgTy,
5422 diag::err_incomplete_type_used_in_type_trait_expr))
5423 return false;
5424 }
5425
5426 // Make sure the first argument is not incomplete nor a function type.
5427 QualType T = Args[0]->getType();
5428 if (T->isIncompleteType() || T->isFunctionType())
5429 return false;
5430
5431 // Make sure the first argument is not an abstract type.
5432 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5433 if (RD && RD->isAbstract())
5434 return false;
5435
5436 llvm::BumpPtrAllocator OpaqueExprAllocator;
5437 SmallVector<Expr *, 2> ArgExprs;
5438 ArgExprs.reserve(Args.size() - 1);
5439 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
5440 QualType ArgTy = Args[I]->getType();
5441 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
5442 ArgTy = S.Context.getRValueReferenceType(ArgTy);
5443 ArgExprs.push_back(
5444 new (OpaqueExprAllocator.Allocate<OpaqueValueExpr>())
5445 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
5446 ArgTy.getNonLValueExprType(S.Context),
5447 Expr::getValueKindForType(ArgTy)));
5448 }
5449
5450 // Perform the initialization in an unevaluated context within a SFINAE
5451 // trap at translation unit scope.
5452 EnterExpressionEvaluationContext Unevaluated(
5453 S, Sema::ExpressionEvaluationContext::Unevaluated);
5454 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
5455 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
5456 InitializedEntity To(
5457 InitializedEntity::InitializeTemporary(S.Context, Args[0]));
5458 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
5459 RParenLoc));
5460 InitializationSequence Init(S, To, InitKind, ArgExprs);
5461 if (Init.Failed())
5462 return false;
5463
5464 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
5465 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5466 return false;
5467
5468 if (Kind == clang::TT_IsConstructible)
5469 return true;
5470
5471 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
5472 if (!T->isReferenceType())
5473 return false;
5474
5475 return !Init.isDirectReferenceBinding();
5476 }
5477
5478 if (Kind == clang::TT_IsNothrowConstructible)
5479 return S.canThrow(Result.get()) == CT_Cannot;
5480
5481 if (Kind == clang::TT_IsTriviallyConstructible) {
5482 // Under Objective-C ARC and Weak, if the destination has non-trivial
5483 // Objective-C lifetime, this is a non-trivial construction.
5484 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
5485 return false;
5486
5487 // The initialization succeeded; now make sure there are no non-trivial
5488 // calls.
5489 return !Result.get()->hasNonTrivialCall(S.Context);
5490 }
5491
5492 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "clang/lib/Sema/SemaExprCXX.cpp"
, 5492)
;
5493 return false;
5494 }
5495 default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "clang/lib/Sema/SemaExprCXX.cpp"
, 5495)
;
5496 }
5497
5498 return false;
5499}
5500
5501namespace {
5502void DiagnoseBuiltinDeprecation(Sema& S, TypeTrait Kind,
5503 SourceLocation KWLoc) {
5504 TypeTrait Replacement;
5505 switch (Kind) {
5506 case UTT_HasNothrowAssign:
5507 case UTT_HasNothrowMoveAssign:
5508 Replacement = BTT_IsNothrowAssignable;
5509 break;
5510 case UTT_HasNothrowCopy:
5511 case UTT_HasNothrowConstructor:
5512 Replacement = TT_IsNothrowConstructible;
5513 break;
5514 case UTT_HasTrivialAssign:
5515 case UTT_HasTrivialMoveAssign:
5516 Replacement = BTT_IsTriviallyAssignable;
5517 break;
5518 case UTT_HasTrivialCopy:
5519 Replacement = UTT_IsTriviallyCopyable;
5520 break;
5521 case UTT_HasTrivialDefaultConstructor:
5522 case UTT_HasTrivialMoveConstructor:
5523 Replacement = TT_IsTriviallyConstructible;
5524 break;
5525 case UTT_HasTrivialDestructor:
5526 Replacement = UTT_IsTriviallyDestructible;
5527 break;
5528 default:
5529 return;
5530 }
5531 S.Diag(KWLoc, diag::warn_deprecated_builtin)
5532 << getTraitSpelling(Kind) << getTraitSpelling(Replacement);
5533}
5534}
5535
5536bool Sema::CheckTypeTraitArity(unsigned Arity, SourceLocation Loc, size_t N) {
5537 if (Arity && N != Arity) {
5538 Diag(Loc, diag::err_type_trait_arity)
5539 << Arity << 0 << (Arity > 1) << (int)N << SourceRange(Loc);
5540 return false;
5541 }
5542
5543 if (!Arity && N == 0) {
5544 Diag(Loc, diag::err_type_trait_arity)
5545 << 1 << 1 << 1 << (int)N << SourceRange(Loc);
5546 return false;
5547 }
5548 return true;
5549}
5550
5551ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5552 ArrayRef<TypeSourceInfo *> Args,
5553 SourceLocation RParenLoc) {
5554 if (!CheckTypeTraitArity(getTypeTraitArity(Kind), KWLoc, Args.size()))
5555 return ExprError();
5556 QualType ResultType = Context.getLogicalOperationType();
5557
5558 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5559 *this, Kind, KWLoc, Args[0]->getType()))
5560 return ExprError();
5561
5562 DiagnoseBuiltinDeprecation(*this, Kind, KWLoc);
5563
5564 bool Dependent = false;
5565 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5566 if (Args[I]->getType()->isDependentType()) {
5567 Dependent = true;
5568 break;
5569 }
5570 }
5571
5572 bool Result = false;
5573 if (!Dependent)
5574 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5575
5576 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5577 RParenLoc, Result);
5578}
5579
5580ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5581 ArrayRef<ParsedType> Args,
5582 SourceLocation RParenLoc) {
5583 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5584 ConvertedArgs.reserve(Args.size());
5585
5586 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5587 TypeSourceInfo *TInfo;
5588 QualType T = GetTypeFromParser(Args[I], &TInfo);
5589 if (!TInfo)
5590 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5591
5592 ConvertedArgs.push_back(TInfo);
5593 }
5594
5595 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5596}
5597
5598static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5599 QualType RhsT, SourceLocation KeyLoc) {
5600 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&(static_cast <bool> (!LhsT->isDependentType() &&
!RhsT->isDependentType() && "Cannot evaluate traits of dependent types"
) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "clang/lib/Sema/SemaExprCXX.cpp", 5601, __extension__ __PRETTY_FUNCTION__
))
5601 "Cannot evaluate traits of dependent types")(static_cast <bool> (!LhsT->isDependentType() &&
!RhsT->isDependentType() && "Cannot evaluate traits of dependent types"
) ? void (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "clang/lib/Sema/SemaExprCXX.cpp", 5601, __extension__ __PRETTY_FUNCTION__
))
;
5602
5603 switch(BTT) {
5604 case BTT_IsBaseOf: {
5605 // C++0x [meta.rel]p2
5606 // Base is a base class of Derived without regard to cv-qualifiers or
5607 // Base and Derived are not unions and name the same class type without
5608 // regard to cv-qualifiers.
5609
5610 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5611 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5612 if (!rhsRecord || !lhsRecord) {
5613 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5614 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5615 if (!LHSObjTy || !RHSObjTy)
5616 return false;
5617
5618 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5619 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5620 if (!BaseInterface || !DerivedInterface)
5621 return false;
5622
5623 if (Self.RequireCompleteType(
5624 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5625 return false;
5626
5627 return BaseInterface->isSuperClassOf(DerivedInterface);
5628 }
5629
5630 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)(static_cast <bool> (Self.Context.hasSameUnqualifiedType
(LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "clang/lib/Sema/SemaExprCXX.cpp", 5631, __extension__ __PRETTY_FUNCTION__
))
5631 == (lhsRecord == rhsRecord))(static_cast <bool> (Self.Context.hasSameUnqualifiedType
(LhsT, RhsT) == (lhsRecord == rhsRecord)) ? void (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "clang/lib/Sema/SemaExprCXX.cpp", 5631, __extension__ __PRETTY_FUNCTION__
))
;
5632
5633 // Unions are never base classes, and never have base classes.
5634 // It doesn't matter if they are complete or not. See PR#41843
5635 if (lhsRecord && lhsRecord->getDecl()->isUnion())
5636 return false;
5637 if (rhsRecord && rhsRecord->getDecl()->isUnion())
5638 return false;
5639
5640 if (lhsRecord == rhsRecord)
5641 return true;
5642
5643 // C++0x [meta.rel]p2:
5644 // If Base and Derived are class types and are different types
5645 // (ignoring possible cv-qualifiers) then Derived shall be a
5646 // complete type.
5647 if (Self.RequireCompleteType(KeyLoc, RhsT,
5648 diag::err_incomplete_type_used_in_type_trait_expr))
5649 return false;
5650
5651 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5652 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5653 }
5654 case BTT_IsSame:
5655 return Self.Context.hasSameType(LhsT, RhsT);
5656 case BTT_TypeCompatible: {
5657 // GCC ignores cv-qualifiers on arrays for this builtin.
5658 Qualifiers LhsQuals, RhsQuals;
5659 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5660 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5661 return Self.Context.typesAreCompatible(Lhs, Rhs);
5662 }
5663 case BTT_IsConvertible:
5664 case BTT_IsConvertibleTo: {
5665 // C++0x [meta.rel]p4:
5666 // Given the following function prototype:
5667 //
5668 // template <class T>
5669 // typename add_rvalue_reference<T>::type create();
5670 //
5671 // the predicate condition for a template specialization
5672 // is_convertible<From, To> shall be satisfied if and only if
5673 // the return expression in the following code would be
5674 // well-formed, including any implicit conversions to the return
5675 // type of the function:
5676 //
5677 // To test() {
5678 // return create<From>();
5679 // }
5680 //
5681 // Access checking is performed as if in a context unrelated to To and
5682 // From. Only the validity of the immediate context of the expression
5683 // of the return-statement (including conversions to the return type)
5684 // is considered.
5685 //
5686 // We model the initialization as a copy-initialization of a temporary
5687 // of the appropriate type, which for this expression is identical to the
5688 // return statement (since NRVO doesn't apply).
5689
5690 // Functions aren't allowed to return function or array types.
5691 if (RhsT->isFunctionType() || RhsT->isArrayType())
5692 return false;
5693
5694 // A return statement in a void function must have void type.
5695 if (RhsT->isVoidType())
5696 return LhsT->isVoidType();
5697
5698 // A function definition requires a complete, non-abstract return type.
5699 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5700 return false;
5701
5702 // Compute the result of add_rvalue_reference.
5703 if (LhsT->isObjectType() || LhsT->isFunctionType())
5704 LhsT = Self.Context.getRValueReferenceType(LhsT);
5705
5706 // Build a fake source and destination for initialization.
5707 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5708 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5709 Expr::getValueKindForType(LhsT));
5710 Expr *FromPtr = &From;
5711 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5712 SourceLocation()));
5713
5714 // Perform the initialization in an unevaluated context within a SFINAE
5715 // trap at translation unit scope.
5716 EnterExpressionEvaluationContext Unevaluated(
5717 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5718 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5719 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5720 InitializationSequence Init(Self, To, Kind, FromPtr);
5721 if (Init.Failed())
5722 return false;
5723
5724 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5725 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5726 }
5727
5728 case BTT_IsAssignable:
5729 case BTT_IsNothrowAssignable:
5730 case BTT_IsTriviallyAssignable: {
5731 // C++11 [meta.unary.prop]p3:
5732 // is_trivially_assignable is defined as:
5733 // is_assignable<T, U>::value is true and the assignment, as defined by
5734 // is_assignable, is known to call no operation that is not trivial
5735 //
5736 // is_assignable is defined as:
5737 // The expression declval<T>() = declval<U>() is well-formed when
5738 // treated as an unevaluated operand (Clause 5).
5739 //
5740 // For both, T and U shall be complete types, (possibly cv-qualified)
5741 // void, or arrays of unknown bound.
5742 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5743 Self.RequireCompleteType(KeyLoc, LhsT,
5744 diag::err_incomplete_type_used_in_type_trait_expr))
5745 return false;
5746 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5747 Self.RequireCompleteType(KeyLoc, RhsT,
5748 diag::err_incomplete_type_used_in_type_trait_expr))
5749 return false;
5750
5751 // cv void is never assignable.
5752 if (LhsT->isVoidType() || RhsT->isVoidType())
5753 return false;
5754
5755 // Build expressions that emulate the effect of declval<T>() and
5756 // declval<U>().
5757 if (LhsT->isObjectType() || LhsT->isFunctionType())
5758 LhsT = Self.Context.getRValueReferenceType(LhsT);
5759 if (RhsT->isObjectType() || RhsT->isFunctionType())
5760 RhsT = Self.Context.getRValueReferenceType(RhsT);
5761 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5762 Expr::getValueKindForType(LhsT));
5763 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5764 Expr::getValueKindForType(RhsT));
5765
5766 // Attempt the assignment in an unevaluated context within a SFINAE
5767 // trap at translation unit scope.
5768 EnterExpressionEvaluationContext Unevaluated(
5769 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5770 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5771 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5772 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5773 &Rhs);
5774 if (Result.isInvalid())
5775 return false;
5776
5777 // Treat the assignment as unused for the purpose of -Wdeprecated-volatile.
5778 Self.CheckUnusedVolatileAssignment(Result.get());
5779
5780 if (SFINAE.hasErrorOccurred())
5781 return false;
5782
5783 if (BTT == BTT_IsAssignable)
5784 return true;
5785
5786 if (BTT == BTT_IsNothrowAssignable)
5787 return Self.canThrow(Result.get()) == CT_Cannot;
5788
5789 if (BTT == BTT_IsTriviallyAssignable) {
5790 // Under Objective-C ARC and Weak, if the destination has non-trivial
5791 // Objective-C lifetime, this is a non-trivial assignment.
5792 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5793 return false;
5794
5795 return !Result.get()->hasNonTrivialCall(Self.Context);
5796 }
5797
5798 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "clang/lib/Sema/SemaExprCXX.cpp"
, 5798)
;
5799 return false;
5800 }
5801 default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "clang/lib/Sema/SemaExprCXX.cpp"
, 5801)
;
5802 }
5803 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "clang/lib/Sema/SemaExprCXX.cpp", 5803)
;
5804}
5805
5806ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5807 SourceLocation KWLoc,
5808 ParsedType Ty,
5809 Expr* DimExpr,
5810 SourceLocation RParen) {
5811 TypeSourceInfo *TSInfo;
5812 QualType T = GetTypeFromParser(Ty, &TSInfo);
5813 if (!TSInfo)
5814 TSInfo = Context.getTrivialTypeSourceInfo(T);
5815
5816 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5817}
5818
5819static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5820 QualType T, Expr *DimExpr,
5821 SourceLocation KeyLoc) {
5822 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")(static_cast <bool> (!T->isDependentType() &&
"Cannot evaluate traits of dependent type") ? void (0) : __assert_fail
("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "clang/lib/Sema/SemaExprCXX.cpp", 5822, __extension__ __PRETTY_FUNCTION__
))
;
5823
5824 switch(ATT) {
5825 case ATT_ArrayRank:
5826 if (T->isArrayType()) {
5827 unsigned Dim = 0;
5828 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5829 ++Dim;
5830 T = AT->getElementType();
5831 }
5832 return Dim;
5833 }
5834 return 0;
5835
5836 case ATT_ArrayExtent: {
5837 llvm::APSInt Value;
5838 uint64_t Dim;
5839 if (Self.VerifyIntegerConstantExpression(
5840 DimExpr, &Value, diag::err_dimension_expr_not_constant_integer)
5841 .isInvalid())
5842 return 0;
5843 if (Value.isSigned() && Value.isNegative()) {
5844 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5845 << DimExpr->getSourceRange();
5846 return 0;
5847 }
5848 Dim = Value.getLimitedValue();
5849
5850 if (T->isArrayType()) {
5851 unsigned D = 0;
5852 bool Matched = false;
5853 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5854 if (Dim == D) {
5855 Matched = true;
5856 break;
5857 }
5858 ++D;
5859 T = AT->getElementType();
5860 }
5861
5862 if (Matched && T->isArrayType()) {
5863 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5864 return CAT->getSize().getLimitedValue();
5865 }
5866 }
5867 return 0;
5868 }
5869 }
5870 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "clang/lib/Sema/SemaExprCXX.cpp", 5870)
;
5871}
5872
5873ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5874 SourceLocation KWLoc,
5875 TypeSourceInfo *TSInfo,
5876 Expr* DimExpr,
5877 SourceLocation RParen) {
5878 QualType T = TSInfo->getType();
5879
5880 // FIXME: This should likely be tracked as an APInt to remove any host
5881 // assumptions about the width of size_t on the target.
5882 uint64_t Value = 0;
5883 if (!T->isDependentType())
5884 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5885
5886 // While the specification for these traits from the Embarcadero C++
5887 // compiler's documentation says the return type is 'unsigned int', Clang
5888 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5889 // compiler, there is no difference. On several other platforms this is an
5890 // important distinction.
5891 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5892 RParen, Context.getSizeType());
5893}
5894
5895ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5896 SourceLocation KWLoc,
5897 Expr *Queried,
5898 SourceLocation RParen) {
5899 // If error parsing the expression, ignore.
5900 if (!Queried)
5901 return ExprError();
5902
5903 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5904
5905 return Result;
5906}
5907
5908static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5909 switch (ET) {
5910 case ET_IsLValueExpr: return E->isLValue();
5911 case ET_IsRValueExpr:
5912 return E->isPRValue();
5913 }
5914 llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch"
, "clang/lib/Sema/SemaExprCXX.cpp", 5914)
;
5915}
5916
5917ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5918 SourceLocation KWLoc,
5919 Expr *Queried,
5920 SourceLocation RParen) {
5921 if (Queried->isTypeDependent()) {
5922 // Delay type-checking for type-dependent expressions.
5923 } else if (Queried->hasPlaceholderType()) {
5924 ExprResult PE = CheckPlaceholderExpr(Queried);
5925 if (PE.isInvalid()) return ExprError();
5926 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5927 }
5928
5929 bool Value = EvaluateExpressionTrait(ET, Queried);
5930
5931 return new (Context)
5932 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5933}
5934
5935QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5936 ExprValueKind &VK,
5937 SourceLocation Loc,
5938 bool isIndirect) {
5939 assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() &&(static_cast <bool> (!LHS.get()->hasPlaceholderType(
) && !RHS.get()->hasPlaceholderType() && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() && \"placeholders should have been weeded out by now\""
, "clang/lib/Sema/SemaExprCXX.cpp", 5940, __extension__ __PRETTY_FUNCTION__
))
5940 "placeholders should have been weeded out by now")(static_cast <bool> (!LHS.get()->hasPlaceholderType(
) && !RHS.get()->hasPlaceholderType() && "placeholders should have been weeded out by now"
) ? void (0) : __assert_fail ("!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() && \"placeholders should have been weeded out by now\""
, "clang/lib/Sema/SemaExprCXX.cpp", 5940, __extension__ __PRETTY_FUNCTION__
))
;
5941
5942 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5943 // temporary materialization conversion otherwise.
5944 if (isIndirect)
5945 LHS = DefaultLvalueConversion(LHS.get());
5946 else if (LHS.get()->isPRValue())
5947 LHS = TemporaryMaterializationConversion(LHS.get());
5948 if (LHS.isInvalid())
5949 return QualType();
5950
5951 // The RHS always undergoes lvalue conversions.
5952 RHS = DefaultLvalueConversion(RHS.get());
5953 if (RHS.isInvalid()) return QualType();
5954
5955 const char *OpSpelling = isIndirect ? "->*" : ".*";
5956 // C++ 5.5p2
5957 // The binary operator .* [p3: ->*] binds its second operand, which shall
5958 // be of type "pointer to member of T" (where T is a completely-defined
5959 // class type) [...]
5960 QualType RHSType = RHS.get()->getType();
5961 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5962 if (!MemPtr) {
5963 Diag(Loc, diag::err_bad_memptr_rhs)
5964 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5965 return QualType();
5966 }
5967
5968 QualType Class(MemPtr->getClass(), 0);
5969
5970 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5971 // member pointer points must be completely-defined. However, there is no
5972 // reason for this semantic distinction, and the rule is not enforced by
5973 // other compilers. Therefore, we do not check this property, as it is
5974 // likely to be considered a defect.
5975
5976 // C++ 5.5p2
5977 // [...] to its first operand, which shall be of class T or of a class of
5978 // which T is an unambiguous and accessible base class. [p3: a pointer to
5979 // such a class]
5980 QualType LHSType = LHS.get()->getType();
5981 if (isIndirect) {
5982 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5983 LHSType = Ptr->getPointeeType();
5984 else {
5985 Diag(Loc, diag::err_bad_memptr_lhs)
5986 << OpSpelling << 1 << LHSType
5987 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5988 return QualType();
5989 }
5990 }
5991
5992 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5993 // If we want to check the hierarchy, we need a complete type.
5994 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5995 OpSpelling, (int)isIndirect)) {
5996 return QualType();
5997 }
5998
5999 if (!IsDerivedFrom(Loc, LHSType, Class)) {
6000 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
6001 << (int)isIndirect << LHS.get()->getType();
6002 return QualType();
6003 }
6004
6005 CXXCastPath BasePath;
6006 if (CheckDerivedToBaseConversion(
6007 LHSType, Class, Loc,
6008 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
6009 &BasePath))
6010 return QualType();
6011
6012 // Cast LHS to type of use.
6013 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
6014 if (isIndirect)
6015 UseType = Context.getPointerType(UseType);
6016 ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind();
6017 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
6018 &BasePath);
6019 }
6020
6021 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
6022 // Diagnose use of pointer-to-member type which when used as
6023 // the functional cast in a pointer-to-member expression.
6024 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
6025 return QualType();
6026 }
6027
6028 // C++ 5.5p2
6029 // The result is an object or a function of the type specified by the
6030 // second operand.
6031 // The cv qualifiers are the union of those in the pointer and the left side,
6032 // in accordance with 5.5p5 and 5.2.5.
6033 QualType Result = MemPtr->getPointeeType();
6034 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
6035
6036 // C++0x [expr.mptr.oper]p6:
6037 // In a .* expression whose object expression is an rvalue, the program is
6038 // ill-formed if the second operand is a pointer to member function with
6039 // ref-qualifier &. In a ->* expression or in a .* expression whose object
6040 // expression is an lvalue, the program is ill-formed if the second operand
6041 // is a pointer to member function with ref-qualifier &&.
6042 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
6043 switch (Proto->getRefQualifier()) {
6044 case RQ_None:
6045 // Do nothing
6046 break;
6047
6048 case RQ_LValue:
6049 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
6050 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
6051 // is (exactly) 'const'.
6052 if (Proto->isConst() && !Proto->isVolatile())
6053 Diag(Loc, getLangOpts().CPlusPlus20
6054 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
6055 : diag::ext_pointer_to_const_ref_member_on_rvalue);
6056 else
6057 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6058 << RHSType << 1 << LHS.get()->getSourceRange();
6059 }
6060 break;
6061
6062 case RQ_RValue:
6063 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
6064 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
6065 << RHSType << 0 << LHS.get()->getSourceRange();
6066 break;
6067 }
6068 }
6069
6070 // C++ [expr.mptr.oper]p6:
6071 // The result of a .* expression whose second operand is a pointer
6072 // to a data member is of the same value category as its
6073 // first operand. The result of a .* expression whose second
6074 // operand is a pointer to a member function is a prvalue. The
6075 // result of an ->* expression is an lvalue if its second operand
6076 // is a pointer to data member and a prvalue otherwise.
6077 if (Result->isFunctionType()) {
6078 VK = VK_PRValue;
6079 return Context.BoundMemberTy;
6080 } else if (isIndirect) {
6081 VK = VK_LValue;
6082 } else {
6083 VK = LHS.get()->getValueKind();
6084 }
6085
6086 return Result;
6087}
6088
6089/// Try to convert a type to another according to C++11 5.16p3.
6090///
6091/// This is part of the parameter validation for the ? operator. If either
6092/// value operand is a class type, the two operands are attempted to be
6093/// converted to each other. This function does the conversion in one direction.
6094/// It returns true if the program is ill-formed and has already been diagnosed
6095/// as such.
6096static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
6097 SourceLocation QuestionLoc,
6098 bool &HaveConversion,
6099 QualType &ToType) {
6100 HaveConversion = false;
6101 ToType = To->getType();
6102
6103 InitializationKind Kind =
6104 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
6105 // C++11 5.16p3
6106 // The process for determining whether an operand expression E1 of type T1
6107 // can be converted to match an operand expression E2 of type T2 is defined
6108 // as follows:
6109 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
6110 // implicitly converted to type "lvalue reference to T2", subject to the
6111 // constraint that in the conversion the reference must bind directly to
6112 // an lvalue.
6113 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
6114 // implicitly converted to the type "rvalue reference to R2", subject to
6115 // the constraint that the reference must bind directly.
6116 if (To->isGLValue()) {
6117 QualType T = Self.Context.getReferenceQualifiedType(To);
6118 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
6119
6120 InitializationSequence InitSeq(Self, Entity, Kind, From);
6121 if (InitSeq.isDirectReferenceBinding()) {
6122 ToType = T;
6123 HaveConversion = true;
6124 return false;
6125 }
6126
6127 if (InitSeq.isAmbiguous())
6128 return InitSeq.Diagnose(Self, Entity, Kind, From);
6129 }
6130
6131 // -- If E2 is an rvalue, or if the conversion above cannot be done:
6132 // -- if E1 and E2 have class type, and the underlying class types are
6133 // the same or one is a base class of the other:
6134 QualType FTy = From->getType();
6135 QualType TTy = To->getType();
6136 const RecordType *FRec = FTy->getAs<RecordType>();
6137 const RecordType *TRec = TTy->getAs<RecordType>();
6138 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
6139 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
6140 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
6141 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
6142 // E1 can be converted to match E2 if the class of T2 is the
6143 // same type as, or a base class of, the class of T1, and
6144 // [cv2 > cv1].
6145 if (FRec == TRec || FDerivedFromT) {
6146 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
6147 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
6148 InitializationSequence InitSeq(Self, Entity, Kind, From);
6149 if (InitSeq) {
6150 HaveConversion = true;
6151 return false;
6152 }
6153
6154 if (InitSeq.isAmbiguous())
6155 return InitSeq.Diagnose(Self, Entity, Kind, From);
6156 }
6157 }
6158
6159 return false;
6160 }
6161
6162 // -- Otherwise: E1 can be converted to match E2 if E1 can be
6163 // implicitly converted to the type that expression E2 would have
6164 // if E2 were converted to an rvalue (or the type it has, if E2 is
6165 // an rvalue).
6166 //
6167 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
6168 // to the array-to-pointer or function-to-pointer conversions.
6169 TTy = TTy.getNonLValueExprType(Self.Context);
6170
6171 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
6172 InitializationSequence InitSeq(Self, Entity, Kind, From);
6173 HaveConversion = !InitSeq.Failed();
6174 ToType = TTy;
6175 if (InitSeq.isAmbiguous())
6176 return InitSeq.Diagnose(Self, Entity, Kind, From);
6177
6178 return false;
6179}
6180
6181/// Try to find a common type for two according to C++0x 5.16p5.
6182///
6183/// This is part of the parameter validation for the ? operator. If either
6184/// value operand is a class type, overload resolution is used to find a
6185/// conversion to a common type.
6186static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
6187 SourceLocation QuestionLoc) {
6188 Expr *Args[2] = { LHS.get(), RHS.get() };
6189 OverloadCandidateSet CandidateSet(QuestionLoc,
6190 OverloadCandidateSet::CSK_Operator);
6191 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
6192 CandidateSet);
6193
6194 OverloadCandidateSet::iterator Best;
6195 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
6196 case OR_Success: {
6197 // We found a match. Perform the conversions on the arguments and move on.
6198 ExprResult LHSRes = Self.PerformImplicitConversion(
6199 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
6200 Sema::AA_Converting);
6201 if (LHSRes.isInvalid())
6202 break;
6203 LHS = LHSRes;
6204
6205 ExprResult RHSRes = Self.PerformImplicitConversion(
6206 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
6207 Sema::AA_Converting);
6208 if (RHSRes.isInvalid())
6209 break;
6210 RHS = RHSRes;
6211 if (Best->Function)
6212 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
6213 return false;
6214 }
6215
6216 case OR_No_Viable_Function:
6217
6218 // Emit a better diagnostic if one of the expressions is a null pointer
6219 // constant and the other is a pointer type. In this case, the user most
6220 // likely forgot to take the address of the other expression.
6221 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6222 return true;
6223
6224 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6225 << LHS.get()->getType() << RHS.get()->getType()
6226 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6227 return true;
6228
6229 case OR_Ambiguous:
6230 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
6231 << LHS.get()->getType() << RHS.get()->getType()
6232 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6233 // FIXME: Print the possible common types by printing the return types of
6234 // the viable candidates.
6235 break;
6236
6237 case OR_Deleted:
6238 llvm_unreachable("Conditional operator has only built-in overloads")::llvm::llvm_unreachable_internal("Conditional operator has only built-in overloads"
, "clang/lib/Sema/SemaExprCXX.cpp", 6238)
;
6239 }
6240 return true;
6241}
6242
6243/// Perform an "extended" implicit conversion as returned by
6244/// TryClassUnification.
6245static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
6246 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
6247 InitializationKind Kind =
6248 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
6249 Expr *Arg = E.get();
6250 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
6251 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
6252 if (Result.isInvalid())
6253 return true;
6254
6255 E = Result;
6256 return false;
6257}
6258
6259// Check the condition operand of ?: to see if it is valid for the GCC
6260// extension.
6261static bool isValidVectorForConditionalCondition(ASTContext &Ctx,
6262 QualType CondTy) {
6263 if (!CondTy->isVectorType() && !CondTy->isExtVectorType())
6264 return false;
6265 const QualType EltTy =
6266 cast<VectorType>(CondTy.getCanonicalType())->getElementType();
6267 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types")(static_cast <bool> (!EltTy->isEnumeralType() &&
"Vectors cant be enum types") ? void (0) : __assert_fail ("!EltTy->isEnumeralType() && \"Vectors cant be enum types\""
, "clang/lib/Sema/SemaExprCXX.cpp", 6267, __extension__ __PRETTY_FUNCTION__
))
;
6268 return EltTy->isIntegralType(Ctx);
6269}
6270
6271static bool isValidSizelessVectorForConditionalCondition(ASTContext &Ctx,
6272 QualType CondTy) {
6273 if (!CondTy->isVLSTBuiltinType())
6274 return false;
6275 const QualType EltTy =
6276 cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx);
6277 assert(!EltTy->isEnumeralType() && "Vectors cant be enum types")(static_cast <bool> (!EltTy->isEnumeralType() &&
"Vectors cant be enum types") ? void (0) : __assert_fail ("!EltTy->isEnumeralType() && \"Vectors cant be enum types\""
, "clang/lib/Sema/SemaExprCXX.cpp", 6277, __extension__ __PRETTY_FUNCTION__
))
;
6278 return EltTy->isIntegralType(Ctx);
6279}
6280
6281QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS,
6282 ExprResult &RHS,
6283 SourceLocation QuestionLoc) {
6284 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6285 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6286
6287 QualType CondType = Cond.get()->getType();
6288 const auto *CondVT = CondType->castAs<VectorType>();
6289 QualType CondElementTy = CondVT->getElementType();
6290 unsigned CondElementCount = CondVT->getNumElements();
6291 QualType LHSType = LHS.get()->getType();
6292 const auto *LHSVT = LHSType->getAs<VectorType>();
6293 QualType RHSType = RHS.get()->getType();
6294 const auto *RHSVT = RHSType->getAs<VectorType>();
6295
6296 QualType ResultType;
6297
6298
6299 if (LHSVT && RHSVT) {
6300 if (isa<ExtVectorType>(CondVT) != isa<ExtVectorType>(LHSVT)) {
6301 Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch)
6302 << /*isExtVector*/ isa<ExtVectorType>(CondVT);
6303 return {};
6304 }
6305
6306 // If both are vector types, they must be the same type.
6307 if (!Context.hasSameType(LHSType, RHSType)) {
6308 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6309 << LHSType << RHSType;
6310 return {};
6311 }
6312 ResultType = Context.getCommonSugaredType(LHSType, RHSType);
6313 } else if (LHSVT || RHSVT) {
6314 ResultType = CheckVectorOperands(
6315 LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true,
6316 /*AllowBoolConversions*/ false,
6317 /*AllowBoolOperation*/ true,
6318 /*ReportInvalid*/ true);
6319 if (ResultType.isNull())
6320 return {};
6321 } else {
6322 // Both are scalar.
6323 LHSType = LHSType.getUnqualifiedType();
6324 RHSType = RHSType.getUnqualifiedType();
6325 QualType ResultElementTy =
6326 Context.hasSameType(LHSType, RHSType)
6327 ? Context.getCommonSugaredType(LHSType, RHSType)
6328 : UsualArithmeticConversions(LHS, RHS, QuestionLoc,
6329 ACK_Conditional);
6330
6331 if (ResultElementTy->isEnumeralType()) {
6332 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6333 << ResultElementTy;
6334 return {};
6335 }
6336 if (CondType->isExtVectorType())
6337 ResultType =
6338 Context.getExtVectorType(ResultElementTy, CondVT->getNumElements());
6339 else
6340 ResultType = Context.getVectorType(
6341 ResultElementTy, CondVT->getNumElements(), VectorType::GenericVector);
6342
6343 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6344 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6345 }
6346
6347 assert(!ResultType.isNull() && ResultType->isVectorType() &&(static_cast <bool> (!ResultType.isNull() && ResultType
->isVectorType() && (!CondType->isExtVectorType
() || ResultType->isExtVectorType()) && "Result should have been a vector type"
) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVectorType() && (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && \"Result should have been a vector type\""
, "clang/lib/Sema/SemaExprCXX.cpp", 6349, __extension__ __PRETTY_FUNCTION__
))
6348 (!CondType->isExtVectorType() || ResultType->isExtVectorType()) &&(static_cast <bool> (!ResultType.isNull() && ResultType
->isVectorType() && (!CondType->isExtVectorType
() || ResultType->isExtVectorType()) && "Result should have been a vector type"
) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVectorType() && (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && \"Result should have been a vector type\""
, "clang/lib/Sema/SemaExprCXX.cpp", 6349, __extension__ __PRETTY_FUNCTION__
))
6349 "Result should have been a vector type")(static_cast <bool> (!ResultType.isNull() && ResultType
->isVectorType() && (!CondType->isExtVectorType
() || ResultType->isExtVectorType()) && "Result should have been a vector type"
) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVectorType() && (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && \"Result should have been a vector type\""
, "clang/lib/Sema/SemaExprCXX.cpp", 6349, __extension__ __PRETTY_FUNCTION__
))
;
6350 auto *ResultVectorTy = ResultType->castAs<VectorType>();
6351 QualType ResultElementTy = ResultVectorTy->getElementType();
6352 unsigned ResultElementCount = ResultVectorTy->getNumElements();
6353
6354 if (ResultElementCount != CondElementCount) {
6355 Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType
6356 << ResultType;
6357 return {};
6358 }
6359
6360 if (Context.getTypeSize(ResultElementTy) !=
6361 Context.getTypeSize(CondElementTy)) {
6362 Diag(QuestionLoc, diag::err_conditional_vector_element_size) << CondType
6363 << ResultType;
6364 return {};
6365 }
6366
6367 return ResultType;
6368}
6369
6370QualType Sema::CheckSizelessVectorConditionalTypes(ExprResult &Cond,
6371 ExprResult &LHS,
6372 ExprResult &RHS,
6373 SourceLocation QuestionLoc) {
6374 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6375 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6376
6377 QualType CondType = Cond.get()->getType();
6378 const auto *CondBT = CondType->castAs<BuiltinType>();
6379 QualType CondElementTy = CondBT->getSveEltType(Context);
6380 llvm::ElementCount CondElementCount =
6381 Context.getBuiltinVectorTypeInfo(CondBT).EC;
6382
6383 QualType LHSType = LHS.get()->getType();
6384 const auto *LHSBT =
6385 LHSType->isVLSTBuiltinType() ? LHSType->getAs<BuiltinType>() : nullptr;
6386 QualType RHSType = RHS.get()->getType();
6387 const auto *RHSBT =
6388 RHSType->isVLSTBuiltinType() ? RHSType->getAs<BuiltinType>() : nullptr;
6389
6390 QualType ResultType;
6391
6392 if (LHSBT && RHSBT) {
6393 // If both are sizeless vector types, they must be the same type.
6394 if (!Context.hasSameType(LHSType, RHSType)) {
6395 Diag(QuestionLoc, diag::err_conditional_vector_mismatched)
6396 << LHSType << RHSType;
6397 return QualType();
6398 }
6399 ResultType = LHSType;
6400 } else if (LHSBT || RHSBT) {
6401 ResultType = CheckSizelessVectorOperands(
6402 LHS, RHS, QuestionLoc, /*IsCompAssign*/ false, ACK_Conditional);
6403 if (ResultType.isNull())
6404 return QualType();
6405 } else {
6406 // Both are scalar so splat
6407 QualType ResultElementTy;
6408 LHSType = LHSType.getCanonicalType().getUnqualifiedType();
6409 RHSType = RHSType.getCanonicalType().getUnqualifiedType();
6410
6411 if (Context.hasSameType(LHSType, RHSType))
6412 ResultElementTy = LHSType;
6413 else
6414 ResultElementTy =
6415 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6416
6417 if (ResultElementTy->isEnumeralType()) {
6418 Diag(QuestionLoc, diag::err_conditional_vector_operand_type)
6419 << ResultElementTy;
6420 return QualType();
6421 }
6422
6423 ResultType = Context.getScalableVectorType(
6424 ResultElementTy, CondElementCount.getKnownMinValue());
6425
6426 LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat);
6427 RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat);
6428 }
6429
6430 assert(!ResultType.isNull() && ResultType->isVLSTBuiltinType() &&(static_cast <bool> (!ResultType.isNull() && ResultType
->isVLSTBuiltinType() && "Result should have been a vector type"
) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVLSTBuiltinType() && \"Result should have been a vector type\""
, "clang/lib/Sema/SemaExprCXX.cpp", 6431, __extension__ __PRETTY_FUNCTION__
))
6431 "Result should have been a vector type")(static_cast <bool> (!ResultType.isNull() && ResultType
->isVLSTBuiltinType() && "Result should have been a vector type"
) ? void (0) : __assert_fail ("!ResultType.isNull() && ResultType->isVLSTBuiltinType() && \"Result should have been a vector type\""
, "clang/lib/Sema/SemaExprCXX.cpp", 6431, __extension__ __PRETTY_FUNCTION__
))
;
6432 auto *ResultBuiltinTy = ResultType->castAs<BuiltinType>();
6433 QualType ResultElementTy = ResultBuiltinTy->getSveEltType(Context);
6434 llvm::ElementCount ResultElementCount =
6435 Context.getBuiltinVectorTypeInfo(ResultBuiltinTy).EC;
6436
6437 if (ResultElementCount != CondElementCount) {
6438 Diag(QuestionLoc, diag::err_conditional_vector_size)
6439 << CondType << ResultType;
6440 return QualType();
6441 }
6442
6443 if (Context.getTypeSize(ResultElementTy) !=
6444 Context.getTypeSize(CondElementTy)) {
6445 Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6446 << CondType << ResultType;
6447 return QualType();
6448 }
6449
6450 return ResultType;
6451}
6452
6453/// Check the operands of ?: under C++ semantics.
6454///
6455/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
6456/// extension. In this case, LHS == Cond. (But they're not aliases.)
6457///
6458/// This function also implements GCC's vector extension and the
6459/// OpenCL/ext_vector_type extension for conditionals. The vector extensions
6460/// permit the use of a?b:c where the type of a is that of a integer vector with
6461/// the same number of elements and size as the vectors of b and c. If one of
6462/// either b or c is a scalar it is implicitly converted to match the type of
6463/// the vector. Otherwise the expression is ill-formed. If both b and c are
6464/// scalars, then b and c are checked and converted to the type of a if
6465/// possible.
6466///
6467/// The expressions are evaluated differently for GCC's and OpenCL's extensions.
6468/// For the GCC extension, the ?: operator is evaluated as
6469/// (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
6470/// For the OpenCL extensions, the ?: operator is evaluated as
6471/// (most-significant-bit-set(a[0]) ? b[0] : c[0], .. ,
6472/// most-significant-bit-set(a[n]) ? b[n] : c[n]).
6473QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6474 ExprResult &RHS, ExprValueKind &VK,
6475 ExprObjectKind &OK,
6476 SourceLocation QuestionLoc) {
6477 // FIXME: Handle C99's complex types, block pointers and Obj-C++ interface
6478 // pointers.
6479
6480 // Assume r-value.
6481 VK = VK_PRValue;
6482 OK = OK_Ordinary;
6483 bool IsVectorConditional =
6484 isValidVectorForConditionalCondition(Context, Cond.get()->getType());
6485
6486 bool IsSizelessVectorConditional =
6487 isValidSizelessVectorForConditionalCondition(Context,
6488 Cond.get()->getType());
6489
6490 // C++11 [expr.cond]p1
6491 // The first expression is contextually converted to bool.
6492 if (!Cond.get()->isTypeDependent()) {
6493 ExprResult CondRes = IsVectorConditional || IsSizelessVectorConditional
6494 ? DefaultFunctionArrayLvalueConversion(Cond.get())
6495 : CheckCXXBooleanCondition(Cond.get());
6496 if (CondRes.isInvalid())
6497 return QualType();
6498 Cond = CondRes;
6499 } else {
6500 // To implement C++, the first expression typically doesn't alter the result
6501 // type of the conditional, however the GCC compatible vector extension
6502 // changes the result type to be that of the conditional. Since we cannot
6503 // know if this is a vector extension here, delay the conversion of the
6504 // LHS/RHS below until later.
6505 return Context.DependentTy;
6506 }
6507
6508
6509 // Either of the arguments dependent?
6510 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
6511 return Context.DependentTy;
6512
6513 // C++11 [expr.cond]p2
6514 // If either the second or the third operand has type (cv) void, ...
6515 QualType LTy = LHS.get()->getType();
6516 QualType RTy = RHS.get()->getType();
6517 bool LVoid = LTy->isVoidType();
6518 bool RVoid = RTy->isVoidType();
6519 if (LVoid || RVoid) {
6520 // ... one of the following shall hold:
6521 // -- The second or the third operand (but not both) is a (possibly
6522 // parenthesized) throw-expression; the result is of the type
6523 // and value category of the other.
6524 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
6525 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
6526
6527 // Void expressions aren't legal in the vector-conditional expressions.
6528 if (IsVectorConditional) {
6529 SourceRange DiagLoc =
6530 LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange();
6531 bool IsThrow = LVoid ? LThrow : RThrow;
6532 Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void)
6533 << DiagLoc << IsThrow;
6534 return QualType();
6535 }
6536
6537 if (LThrow != RThrow) {
6538 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
6539 VK = NonThrow->getValueKind();
6540 // DR (no number yet): the result is a bit-field if the
6541 // non-throw-expression operand is a bit-field.
6542 OK = NonThrow->getObjectKind();
6543 return NonThrow->getType();
6544 }
6545
6546 // -- Both the second and third operands have type void; the result is of
6547 // type void and is a prvalue.
6548 if (LVoid && RVoid)
6549 return Context.getCommonSugaredType(LTy, RTy);
6550
6551 // Neither holds, error.
6552 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
6553 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
6554 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6555 return QualType();
6556 }
6557
6558 // Neither is void.
6559 if (IsVectorConditional)
6560 return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6561
6562 if (IsSizelessVectorConditional)
6563 return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc);
6564
6565 // C++11 [expr.cond]p3
6566 // Otherwise, if the second and third operand have different types, and
6567 // either has (cv) class type [...] an attempt is made to convert each of
6568 // those operands to the type of the other.
6569 if (!Context.hasSameType(LTy, RTy) &&
6570 (LTy->isRecordType() || RTy->isRecordType())) {
6571 // These return true if a single direction is already ambiguous.
6572 QualType L2RType, R2LType;
6573 bool HaveL2R, HaveR2L;
6574 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
6575 return QualType();
6576 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
6577 return QualType();
6578
6579 // If both can be converted, [...] the program is ill-formed.
6580 if (HaveL2R && HaveR2L) {
6581 Diag(QuestionLoc, diag::err_conditional_ambiguous)
6582 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6583 return QualType();
6584 }
6585
6586 // If exactly one conversion is possible, that conversion is applied to
6587 // the chosen operand and the converted operands are used in place of the
6588 // original operands for the remainder of this section.
6589 if (HaveL2R) {
6590 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
6591 return QualType();
6592 LTy = LHS.get()->getType();
6593 } else if (HaveR2L) {
6594 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
6595 return QualType();
6596 RTy = RHS.get()->getType();
6597 }
6598 }
6599
6600 // C++11 [expr.cond]p3
6601 // if both are glvalues of the same value category and the same type except
6602 // for cv-qualification, an attempt is made to convert each of those
6603 // operands to the type of the other.
6604 // FIXME:
6605 // Resolving a defect in P0012R1: we extend this to cover all cases where
6606 // one of the operands is reference-compatible with the other, in order
6607 // to support conditionals between functions differing in noexcept. This
6608 // will similarly cover difference in array bounds after P0388R4.
6609 // FIXME: If LTy and RTy have a composite pointer type, should we convert to
6610 // that instead?
6611 ExprValueKind LVK = LHS.get()->getValueKind();
6612 ExprValueKind RVK = RHS.get()->getValueKind();
6613 if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) {
6614 // DerivedToBase was already handled by the class-specific case above.
6615 // FIXME: Should we allow ObjC conversions here?
6616 const ReferenceConversions AllowedConversions =
6617 ReferenceConversions::Qualification |
6618 ReferenceConversions::NestedQualification |
6619 ReferenceConversions::Function;
6620
6621 ReferenceConversions RefConv;
6622 if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) ==
6623 Ref_Compatible &&
6624 !(RefConv & ~AllowedConversions) &&
6625 // [...] subject to the constraint that the reference must bind
6626 // directly [...]
6627 !RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) {
6628 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
6629 RTy = RHS.get()->getType();
6630 } else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) ==
6631 Ref_Compatible &&
6632 !(RefConv & ~AllowedConversions) &&
6633 !LHS.get()->refersToBitField() &&
6634 !LHS.get()->refersToVectorElement()) {
6635 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
6636 LTy = LHS.get()->getType();
6637 }
6638 }
6639
6640 // C++11 [expr.cond]p4
6641 // If the second and third operands are glvalues of the same value
6642 // category and have the same type, the result is of that type and
6643 // value category and it is a bit-field if the second or the third
6644 // operand is a bit-field, or if both are bit-fields.
6645 // We only extend this to bitfields, not to the crazy other kinds of
6646 // l-values.
6647 bool Same = Context.hasSameType(LTy, RTy);
6648 if (Same && LVK == RVK && LVK != VK_PRValue &&
6649 LHS.get()->isOrdinaryOrBitFieldObject() &&
6650 RHS.get()->isOrdinaryOrBitFieldObject()) {
6651 VK = LHS.get()->getValueKind();
6652 if (LHS.get()->getObjectKind() == OK_BitField ||
6653 RHS.get()->getObjectKind() == OK_BitField)
6654 OK = OK_BitField;
6655 return Context.getCommonSugaredType(LTy, RTy);
6656 }
6657
6658 // C++11 [expr.cond]p5
6659 // Otherwise, the result is a prvalue. If the second and third operands
6660 // do not have the same type, and either has (cv) class type, ...
6661 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
6662 // ... overload resolution is used to determine the conversions (if any)
6663 // to be applied to the operands. If the overload resolution fails, the
6664 // program is ill-formed.
6665 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
6666 return QualType();
6667 }
6668
6669 // C++11 [expr.cond]p6
6670 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
6671 // conversions are performed on the second and third operands.
6672 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6673 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6674 if (LHS.isInvalid() || RHS.isInvalid())
6675 return QualType();
6676 LTy = LHS.get()->getType();
6677 RTy = RHS.get()->getType();
6678
6679 // After those conversions, one of the following shall hold:
6680 // -- The second and third operands have the same type; the result
6681 // is of that type. If the operands have class type, the result
6682 // is a prvalue temporary of the result type, which is
6683 // copy-initialized from either the second operand or the third
6684 // operand depending on the value of the first operand.
6685 if (Context.hasSameType(LTy, RTy)) {
6686 if (LTy->isRecordType()) {
6687 // The operands have class type. Make a temporary copy.
6688 ExprResult LHSCopy = PerformCopyInitialization(
6689 InitializedEntity::InitializeTemporary(LTy), SourceLocation(), LHS);
6690 if (LHSCopy.isInvalid())
6691 return QualType();
6692
6693 ExprResult RHSCopy = PerformCopyInitialization(
6694 InitializedEntity::InitializeTemporary(RTy), SourceLocation(), RHS);
6695 if (RHSCopy.isInvalid())
6696 return QualType();
6697
6698 LHS = LHSCopy;
6699 RHS = RHSCopy;
6700 }
6701 return Context.getCommonSugaredType(LTy, RTy);
6702 }
6703
6704 // Extension: conditional operator involving vector types.
6705 if (LTy->isVectorType() || RTy->isVectorType())
6706 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false,
6707 /*AllowBothBool*/ true,
6708 /*AllowBoolConversions*/ false,
6709 /*AllowBoolOperation*/ false,
6710 /*ReportInvalid*/ true);
6711
6712 // -- The second and third operands have arithmetic or enumeration type;
6713 // the usual arithmetic conversions are performed to bring them to a
6714 // common type, and the result is of that type.
6715 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
6716 QualType ResTy =
6717 UsualArithmeticConversions(LHS, RHS, QuestionLoc, ACK_Conditional);
6718 if (LHS.isInvalid() || RHS.isInvalid())
6719 return QualType();
6720 if (ResTy.isNull()) {
6721 Diag(QuestionLoc,
6722 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
6723 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6724 return QualType();
6725 }
6726
6727 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6728 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6729
6730 return ResTy;
6731 }
6732
6733 // -- The second and third operands have pointer type, or one has pointer
6734 // type and the other is a null pointer constant, or both are null
6735 // pointer constants, at least one of which is non-integral; pointer
6736 // conversions and qualification conversions are performed to bring them
6737 // to their composite pointer type. The result is of the composite
6738 // pointer type.
6739 // -- The second and third operands have pointer to member type, or one has
6740 // pointer to member type and the other is a null pointer constant;
6741 // pointer to member conversions and qualification conversions are
6742 // performed to bring them to a common type, whose cv-qualification
6743 // shall match the cv-qualification of either the second or the third
6744 // operand. The result is of the common type.
6745 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS);
6746 if (!Composite.isNull())
6747 return Composite;
6748
6749 // Similarly, attempt to find composite type of two objective-c pointers.
6750 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
6751 if (LHS.isInvalid() || RHS.isInvalid())
6752 return QualType();
6753 if (!Composite.isNull())
6754 return Composite;
6755
6756 // Check if we are using a null with a non-pointer type.
6757 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6758 return QualType();
6759
6760 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6761 << LHS.get()->getType() << RHS.get()->getType()
6762 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6763 return QualType();
6764}
6765
6766/// Find a merged pointer type and convert the two expressions to it.
6767///
6768/// This finds the composite pointer type for \p E1 and \p E2 according to
6769/// C++2a [expr.type]p3. It converts both expressions to this type and returns
6770/// it. It does not emit diagnostics (FIXME: that's not true if \p ConvertArgs
6771/// is \c true).
6772///
6773/// \param Loc The location of the operator requiring these two expressions to
6774/// be converted to the composite pointer type.
6775///
6776/// \param ConvertArgs If \c false, do not convert E1 and E2 to the target type.
6777QualType Sema::FindCompositePointerType(SourceLocation Loc,
6778 Expr *&E1, Expr *&E2,
6779 bool ConvertArgs) {
6780 assert(getLangOpts().CPlusPlus && "This function assumes C++")(static_cast <bool> (getLangOpts().CPlusPlus &&
"This function assumes C++") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"This function assumes C++\""
, "clang/lib/Sema/SemaExprCXX.cpp", 6780, __extension__ __PRETTY_FUNCTION__
))
;
6781
6782 // C++1z [expr]p14:
6783 // The composite pointer type of two operands p1 and p2 having types T1
6784 // and T2
6785 QualType T1 = E1->getType(), T2 = E2->getType();
6786
6787 // where at least one is a pointer or pointer to member type or
6788 // std::nullptr_t is:
6789 bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() ||
6790 T1->isNullPtrType();
6791 bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() ||
6792 T2->isNullPtrType();
6793 if (!T1IsPointerLike && !T2IsPointerLike)
6794 return QualType();
6795
6796 // - if both p1 and p2 are null pointer constants, std::nullptr_t;
6797 // This can't actually happen, following the standard, but we also use this
6798 // to implement the end of [expr.conv], which hits this case.
6799 //
6800 // - if either p1 or p2 is a null pointer constant, T2 or T1, respectively;
6801 if (T1IsPointerLike &&
6802 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6803 if (ConvertArgs)
6804 E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType()
6805 ? CK_NullToMemberPointer
6806 : CK_NullToPointer).get();
6807 return T1;
6808 }
6809 if (T2IsPointerLike &&
6810 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
6811 if (ConvertArgs)
6812 E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType()
6813 ? CK_NullToMemberPointer
6814 : CK_NullToPointer).get();
6815 return T2;
6816 }
6817
6818 // Now both have to be pointers or member pointers.
6819 if (!T1IsPointerLike || !T2IsPointerLike)
6820 return QualType();
6821 assert(!T1->isNullPtrType() && !T2->isNullPtrType() &&(static_cast <bool> (!T1->isNullPtrType() &&
!T2->isNullPtrType() && "nullptr_t should be a null pointer constant"
) ? void (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\""
, "clang/lib/Sema/SemaExprCXX.cpp", 6822, __extension__ __PRETTY_FUNCTION__
))
6822 "nullptr_t should be a null pointer constant")(static_cast <bool> (!T1->isNullPtrType() &&
!T2->isNullPtrType() && "nullptr_t should be a null pointer constant"
) ? void (0) : __assert_fail ("!T1->isNullPtrType() && !T2->isNullPtrType() && \"nullptr_t should be a null pointer constant\""
, "clang/lib/Sema/SemaExprCXX.cpp", 6822, __extension__ __PRETTY_FUNCTION__
))
;
6823
6824 struct Step {
6825 enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K;
6826 // Qualifiers to apply under the step kind.
6827 Qualifiers Quals;
6828 /// The class for a pointer-to-member; a constant array type with a bound
6829 /// (if any) for an array.
6830 const Type *ClassOrBound;
6831
6832 Step(Kind K, const Type *ClassOrBound = nullptr)
6833 : K(K), ClassOrBound(ClassOrBound) {}
6834 QualType rebuild(ASTContext &Ctx, QualType T) const {
6835 T = Ctx.getQualifiedType(T, Quals);
6836 switch (K) {
6837 case Pointer:
6838 return Ctx.getPointerType(T);
6839 case MemberPointer:
6840 return Ctx.getMemberPointerType(T, ClassOrBound);
6841 case ObjCPointer:
6842 return Ctx.getObjCObjectPointerType(T);
6843 case Array:
6844 if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound))
6845 return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr,
6846 ArrayType::Normal, 0);
6847 else
6848 return Ctx.getIncompleteArrayType(T, ArrayType::Normal, 0);
6849 }
6850 llvm_unreachable("unknown step kind")::llvm::llvm_unreachable_internal("unknown step kind", "clang/lib/Sema/SemaExprCXX.cpp"
, 6850)
;
6851 }
6852 };
6853
6854 SmallVector<Step, 8> Steps;
6855
6856 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
6857 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
6858 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1,
6859 // respectively;
6860 // - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer
6861 // to member of C2 of type cv2 U2" for some non-function type U, where
6862 // C1 is reference-related to C2 or C2 is reference-related to C1, the
6863 // cv-combined type of T2 and T1 or the cv-combined type of T1 and T2,
6864 // respectively;
6865 // - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and
6866 // T2;
6867 //
6868 // Dismantle T1 and T2 to simultaneously determine whether they are similar
6869 // and to prepare to form the cv-combined type if so.
6870 QualType Composite1 = T1;
6871 QualType Composite2 = T2;
6872 unsigned NeedConstBefore = 0;
6873 while (true) {
6874 assert(!Composite1.isNull() && !Composite2.isNull())(static_cast <bool> (!Composite1.isNull() && !Composite2
.isNull()) ? void (0) : __assert_fail ("!Composite1.isNull() && !Composite2.isNull()"
, "clang/lib/Sema/SemaExprCXX.cpp", 6874, __extension__ __PRETTY_FUNCTION__
))
;
6875
6876 Qualifiers Q1, Q2;
6877 Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1);
6878 Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2);
6879
6880 // Top-level qualifiers are ignored. Merge at all lower levels.
6881 if (!Steps.empty()) {
6882 // Find the qualifier union: (approximately) the unique minimal set of
6883 // qualifiers that is compatible with both types.
6884 Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() |
6885 Q2.getCVRUQualifiers());
6886
6887 // Under one level of pointer or pointer-to-member, we can change to an
6888 // unambiguous compatible address space.
6889 if (Q1.getAddressSpace() == Q2.getAddressSpace()) {
6890 Quals.setAddressSpace(Q1.getAddressSpace());
6891 } else if (Steps.size() == 1) {
6892 bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2);
6893 bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1);
6894 if (MaybeQ1 == MaybeQ2) {
6895 // Exception for ptr size address spaces. Should be able to choose
6896 // either address space during comparison.
6897 if (isPtrSizeAddressSpace(Q1.getAddressSpace()) ||
6898 isPtrSizeAddressSpace(Q2.getAddressSpace()))
6899 MaybeQ1 = true;
6900 else
6901 return QualType(); // No unique best address space.
6902 }
6903 Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace()
6904 : Q2.getAddressSpace());
6905 } else {
6906 return QualType();
6907 }
6908
6909 // FIXME: In C, we merge __strong and none to __strong at the top level.
6910 if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr())
6911 Quals.setObjCGCAttr(Q1.getObjCGCAttr());
6912 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6913 assert(Steps.size() == 1)(static_cast <bool> (Steps.size() == 1) ? void (0) : __assert_fail
("Steps.size() == 1", "clang/lib/Sema/SemaExprCXX.cpp", 6913
, __extension__ __PRETTY_FUNCTION__))
;
6914 else
6915 return QualType();
6916
6917 // Mismatched lifetime qualifiers never compatibly include each other.
6918 if (Q1.getObjCLifetime() == Q2.getObjCLifetime())
6919 Quals.setObjCLifetime(Q1.getObjCLifetime());
6920 else if (T1->isVoidPointerType() || T2->isVoidPointerType())
6921 assert(Steps.size() == 1)(static_cast <bool> (Steps.size() == 1) ? void (0) : __assert_fail
("Steps.size() == 1", "clang/lib/Sema/SemaExprCXX.cpp", 6921
, __extension__ __PRETTY_FUNCTION__))
;
6922 else
6923 return QualType();
6924
6925 Steps.back().Quals = Quals;
6926 if (Q1 != Quals || Q2 != Quals)
6927 NeedConstBefore = Steps.size() - 1;
6928 }
6929
6930 // FIXME: Can we unify the following with UnwrapSimilarTypes?
6931
6932 const ArrayType *Arr1, *Arr2;
6933 if ((Arr1 = Context.getAsArrayType(Composite1)) &&
6934 (Arr2 = Context.getAsArrayType(Composite2))) {
6935 auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1);
6936 auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2);
6937 if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) {
6938 Composite1 = Arr1->getElementType();
6939 Composite2 = Arr2->getElementType();
6940 Steps.emplace_back(Step::Array, CAT1);
6941 continue;
6942 }
6943 bool IAT1 = isa<IncompleteArrayType>(Arr1);
6944 bool IAT2 = isa<IncompleteArrayType>(Arr2);
6945 if ((IAT1 && IAT2) ||
6946 (getLangOpts().CPlusPlus20 && (IAT1 != IAT2) &&
6947 ((bool)CAT1 != (bool)CAT2) &&
6948 (Steps.empty() || Steps.back().K != Step::Array))) {
6949 // In C++20 onwards, we can unify an array of N T with an array of
6950 // a different or unknown bound. But we can't form an array whose
6951 // element type is an array of unknown bound by doing so.
6952 Composite1 = Arr1->getElementType();
6953 Composite2 = Arr2->getElementType();
6954 Steps.emplace_back(Step::Array);
6955 if (CAT1 || CAT2)
6956 NeedConstBefore = Steps.size();
6957 continue;
6958 }
6959 }
6960
6961 const PointerType *Ptr1, *Ptr2;
6962 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
6963 (Ptr2 = Composite2->getAs<PointerType>())) {
6964 Composite1 = Ptr1->getPointeeType();
6965 Composite2 = Ptr2->getPointeeType();
6966 Steps.emplace_back(Step::Pointer);
6967 continue;
6968 }
6969
6970 const ObjCObjectPointerType *ObjPtr1, *ObjPtr2;
6971 if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) &&
6972 (ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) {
6973 Composite1 = ObjPtr1->getPointeeType();
6974 Composite2 = ObjPtr2->getPointeeType();
6975 Steps.emplace_back(Step::ObjCPointer);
6976 continue;
6977 }
6978
6979 const MemberPointerType *MemPtr1, *MemPtr2;
6980 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
6981 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
6982 Composite1 = MemPtr1->getPointeeType();
6983 Composite2 = MemPtr2->getPointeeType();
6984
6985 // At the top level, we can perform a base-to-derived pointer-to-member
6986 // conversion:
6987 //
6988 // - [...] where C1 is reference-related to C2 or C2 is
6989 // reference-related to C1
6990 //
6991 // (Note that the only kinds of reference-relatedness in scope here are
6992 // "same type or derived from".) At any other level, the class must
6993 // exactly match.
6994 const Type *Class = nullptr;
6995 QualType Cls1(MemPtr1->getClass(), 0);
6996 QualType Cls2(MemPtr2->getClass(), 0);
6997 if (Context.hasSameType(Cls1, Cls2))
6998 Class = MemPtr1->getClass();
6999 else if (Steps.empty())
7000 Class = IsDerivedFrom(Loc, Cls1, Cls2) ? MemPtr1->getClass() :
7001 IsDerivedFrom(Loc, Cls2, Cls1) ? MemPtr2->getClass() : nullptr;
7002 if (!Class)
7003 return QualType();
7004
7005 Steps.emplace_back(Step::MemberPointer, Class);
7006 continue;
7007 }
7008
7009 // Special case: at the top level, we can decompose an Objective-C pointer
7010 // and a 'cv void *'. Unify the qualifiers.
7011 if (Steps.empty() && ((Composite1->isVoidPointerType() &&
7012 Composite2->isObjCObjectPointerType()) ||
7013 (Composite1->isObjCObjectPointerType() &&
7014 Composite2->isVoidPointerType()))) {
7015 Composite1 = Composite1->getPointeeType();
7016 Composite2 = Composite2->getPointeeType();
7017 Steps.emplace_back(Step::Pointer);
7018 continue;
7019 }
7020
7021 // FIXME: block pointer types?
7022
7023 // Cannot unwrap any more types.
7024 break;
7025 }
7026
7027 // - if T1 or T2 is "pointer to noexcept function" and the other type is
7028 // "pointer to function", where the function types are otherwise the same,
7029 // "pointer to function";
7030 // - if T1 or T2 is "pointer to member of C1 of type function", the other
7031 // type is "pointer to member of C2 of type noexcept function", and C1
7032 // is reference-related to C2 or C2 is reference-related to C1, where
7033 // the function types are otherwise the same, "pointer to member of C2 of
7034 // type function" or "pointer to member of C1 of type function",
7035 // respectively;
7036 //
7037 // We also support 'noreturn' here, so as a Clang extension we generalize the
7038 // above to:
7039 //
7040 // - [Clang] If T1 and T2 are both of type "pointer to function" or
7041 // "pointer to member function" and the pointee types can be unified
7042 // by a function pointer conversion, that conversion is applied
7043 // before checking the following rules.
7044 //
7045 // We've already unwrapped down to the function types, and we want to merge
7046 // rather than just convert, so do this ourselves rather than calling
7047 // IsFunctionConversion.
7048 //
7049 // FIXME: In order to match the standard wording as closely as possible, we
7050 // currently only do this under a single level of pointers. Ideally, we would
7051 // allow this in general, and set NeedConstBefore to the relevant depth on
7052 // the side(s) where we changed anything. If we permit that, we should also
7053 // consider this conversion when determining type similarity and model it as
7054 // a qualification conversion.
7055 if (Steps.size() == 1) {
7056 if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) {
7057 if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) {
7058 FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo();
7059 FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo();
7060
7061 // The result is noreturn if both operands are.
7062 bool Noreturn =
7063 EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn();
7064 EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn);
7065 EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn);
7066
7067 // The result is nothrow if both operands are.
7068 SmallVector<QualType, 8> ExceptionTypeStorage;
7069 EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs(
7070 EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage,
7071 getLangOpts().CPlusPlus17);
7072
7073 Composite1 = Context.getFunctionType(FPT1->getReturnType(),
7074 FPT1->getParamTypes(), EPI1);
7075 Composite2 = Context.getFunctionType(FPT2->getReturnType(),
7076 FPT2->getParamTypes(), EPI2);
7077 }
7078 }
7079 }
7080
7081 // There are some more conversions we can perform under exactly one pointer.
7082 if (Steps.size() == 1 && Steps.front().K == Step::Pointer &&
7083 !Context.hasSameType(Composite1, Composite2)) {
7084 // - if T1 or T2 is "pointer to cv1 void" and the other type is
7085 // "pointer to cv2 T", where T is an object type or void,
7086 // "pointer to cv12 void", where cv12 is the union of cv1 and cv2;
7087 if (Composite1->isVoidType() && Composite2->isObjectType())
7088 Composite2 = Composite1;
7089 else if (Composite2->isVoidType() && Composite1->isObjectType())
7090 Composite1 = Composite2;
7091 // - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1
7092 // is reference-related to C2 or C2 is reference-related to C1 (8.6.3),
7093 // the cv-combined type of T1 and T2 or the cv-combined type of T2 and
7094 // T1, respectively;
7095 //
7096 // The "similar type" handling covers all of this except for the "T1 is a
7097 // base class of T2" case in the definition of reference-related.
7098 else if (IsDerivedFrom(Loc, Composite1, Composite2))
7099 Composite1 = Composite2;
7100 else if (IsDerivedFrom(Loc, Composite2, Composite1))
7101 Composite2 = Composite1;
7102 }
7103
7104 // At this point, either the inner types are the same or we have failed to
7105 // find a composite pointer type.
7106 if (!Context.hasSameType(Composite1, Composite2))
7107 return QualType();
7108
7109 // Per C++ [conv.qual]p3, add 'const' to every level before the last
7110 // differing qualifier.
7111 for (unsigned I = 0; I != NeedConstBefore; ++I)
7112 Steps[I].Quals.addConst();
7113
7114 // Rebuild the composite type.
7115 QualType Composite = Context.getCommonSugaredType(Composite1, Composite2);
7116 for (auto &S : llvm::reverse(Steps))
7117 Composite = S.rebuild(Context, Composite);
7118
7119 if (ConvertArgs) {
7120 // Convert the expressions to the composite pointer type.
7121 InitializedEntity Entity =
7122 InitializedEntity::InitializeTemporary(Composite);
7123 InitializationKind Kind =
7124 InitializationKind::CreateCopy(Loc, SourceLocation());
7125
7126 InitializationSequence E1ToC(*this, Entity, Kind, E1);
7127 if (!E1ToC)
7128 return QualType();
7129
7130 InitializationSequence E2ToC(*this, Entity, Kind, E2);
7131 if (!E2ToC)
7132 return QualType();
7133
7134 // FIXME: Let the caller know if these fail to avoid duplicate diagnostics.
7135 ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1);
7136 if (E1Result.isInvalid())
7137 return QualType();
7138 E1 = E1Result.get();
7139
7140 ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2);
7141 if (E2Result.isInvalid())
7142 return QualType();
7143 E2 = E2Result.get();
7144 }
7145
7146 return Composite;
7147}
7148
7149ExprResult Sema::MaybeBindToTemporary(Expr *E) {
7150 if (!E)
7151 return ExprError();
7152
7153 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?")(static_cast <bool> (!isa<CXXBindTemporaryExpr>(E
) && "Double-bound temporary?") ? void (0) : __assert_fail
("!isa<CXXBindTemporaryExpr>(E) && \"Double-bound temporary?\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7153, __extension__ __PRETTY_FUNCTION__
))
;
7154
7155 // If the result is a glvalue, we shouldn't bind it.
7156 if (E->isGLValue())
7157 return E;
7158
7159 // In ARC, calls that return a retainable type can return retained,
7160 // in which case we have to insert a consuming cast.
7161 if (getLangOpts().ObjCAutoRefCount &&
7162 E->getType()->isObjCRetainableType()) {
7163
7164 bool ReturnsRetained;
7165
7166 // For actual calls, we compute this by examining the type of the
7167 // called value.
7168 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
7169 Expr *Callee = Call->getCallee()->IgnoreParens();
7170 QualType T = Callee->getType();
7171
7172 if (T == Context.BoundMemberTy) {
7173 // Handle pointer-to-members.
7174 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
7175 T = BinOp->getRHS()->getType();
7176 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
7177 T = Mem->getMemberDecl()->getType();
7178 }
7179
7180 if (const PointerType *Ptr = T->getAs<PointerType>())
7181 T = Ptr->getPointeeType();
7182 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
7183 T = Ptr->getPointeeType();
7184 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
7185 T = MemPtr->getPointeeType();
7186
7187 auto *FTy = T->castAs<FunctionType>();
7188 ReturnsRetained = FTy->getExtInfo().getProducesResult();
7189
7190 // ActOnStmtExpr arranges things so that StmtExprs of retainable
7191 // type always produce a +1 object.
7192 } else if (isa<StmtExpr>(E)) {
7193 ReturnsRetained = true;
7194
7195 // We hit this case with the lambda conversion-to-block optimization;
7196 // we don't want any extra casts here.
7197 } else if (isa<CastExpr>(E) &&
7198 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
7199 return E;
7200
7201 // For message sends and property references, we try to find an
7202 // actual method. FIXME: we should infer retention by selector in
7203 // cases where we don't have an actual method.
7204 } else {
7205 ObjCMethodDecl *D = nullptr;
7206 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
7207 D = Send->getMethodDecl();
7208 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
7209 D = BoxedExpr->getBoxingMethod();
7210 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
7211 // Don't do reclaims if we're using the zero-element array
7212 // constant.
7213 if (ArrayLit->getNumElements() == 0 &&
7214 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7215 return E;
7216
7217 D = ArrayLit->getArrayWithObjectsMethod();
7218 } else if (ObjCDictionaryLiteral *DictLit
7219 = dyn_cast<ObjCDictionaryLiteral>(E)) {
7220 // Don't do reclaims if we're using the zero-element dictionary
7221 // constant.
7222 if (DictLit->getNumElements() == 0 &&
7223 Context.getLangOpts().ObjCRuntime.hasEmptyCollections())
7224 return E;
7225
7226 D = DictLit->getDictWithObjectsMethod();
7227 }
7228
7229 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
7230
7231 // Don't do reclaims on performSelector calls; despite their
7232 // return type, the invoked method doesn't necessarily actually
7233 // return an object.
7234 if (!ReturnsRetained &&
7235 D && D->getMethodFamily() == OMF_performSelector)
7236 return E;
7237 }
7238
7239 // Don't reclaim an object of Class type.
7240 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
7241 return E;
7242
7243 Cleanup.setExprNeedsCleanups(true);
7244
7245 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
7246 : CK_ARCReclaimReturnedObject);
7247 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
7248 VK_PRValue, FPOptionsOverride());
7249 }
7250
7251 if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
7252 Cleanup.setExprNeedsCleanups(true);
7253
7254 if (!getLangOpts().CPlusPlus)
7255 return E;
7256
7257 // Search for the base element type (cf. ASTContext::getBaseElementType) with
7258 // a fast path for the common case that the type is directly a RecordType.
7259 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
7260 const RecordType *RT = nullptr;
7261 while (!RT) {
7262 switch (T->getTypeClass()) {
7263 case Type::Record:
7264 RT = cast<RecordType>(T);
7265 break;
7266 case Type::ConstantArray:
7267 case Type::IncompleteArray:
7268 case Type::VariableArray:
7269 case Type::DependentSizedArray:
7270 T = cast<ArrayType>(T)->getElementType().getTypePtr();
7271 break;
7272 default:
7273 return E;
7274 }
7275 }
7276
7277 // That should be enough to guarantee that this type is complete, if we're
7278 // not processing a decltype expression.
7279 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7280 if (RD->isInvalidDecl() || RD->isDependentContext())
7281 return E;
7282
7283 bool IsDecltype = ExprEvalContexts.back().ExprContext ==
7284 ExpressionEvaluationContextRecord::EK_Decltype;
7285 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
7286
7287 if (Destructor) {
7288 MarkFunctionReferenced(E->getExprLoc(), Destructor);
7289 CheckDestructorAccess(E->getExprLoc(), Destructor,
7290 PDiag(diag::err_access_dtor_temp)
7291 << E->getType());
7292 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
7293 return ExprError();
7294
7295 // If destructor is trivial, we can avoid the extra copy.
7296 if (Destructor->isTrivial())
7297 return E;
7298
7299 // We need a cleanup, but we don't need to remember the temporary.
7300 Cleanup.setExprNeedsCleanups(true);
7301 }
7302
7303 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
7304 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
7305
7306 if (IsDecltype)
7307 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
7308
7309 return Bind;
7310}
7311
7312ExprResult
7313Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
7314 if (SubExpr.isInvalid())
7315 return ExprError();
7316
7317 return MaybeCreateExprWithCleanups(SubExpr.get());
7318}
7319
7320Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
7321 assert(SubExpr && "subexpression can't be null!")(static_cast <bool> (SubExpr && "subexpression can't be null!"
) ? void (0) : __assert_fail ("SubExpr && \"subexpression can't be null!\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7321, __extension__ __PRETTY_FUNCTION__
))
;
7322
7323 CleanupVarDeclMarking();
7324
7325 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
7326 assert(ExprCleanupObjects.size() >= FirstCleanup)(static_cast <bool> (ExprCleanupObjects.size() >= FirstCleanup
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() >= FirstCleanup"
, "clang/lib/Sema/SemaExprCXX.cpp", 7326, __extension__ __PRETTY_FUNCTION__
))
;
7327 assert(Cleanup.exprNeedsCleanups() ||(static_cast <bool> (Cleanup.exprNeedsCleanups() || ExprCleanupObjects
.size() == FirstCleanup) ? void (0) : __assert_fail ("Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup"
, "clang/lib/Sema/SemaExprCXX.cpp", 7328, __extension__ __PRETTY_FUNCTION__
))
7328 ExprCleanupObjects.size() == FirstCleanup)(static_cast <bool> (Cleanup.exprNeedsCleanups() || ExprCleanupObjects
.size() == FirstCleanup) ? void (0) : __assert_fail ("Cleanup.exprNeedsCleanups() || ExprCleanupObjects.size() == FirstCleanup"
, "clang/lib/Sema/SemaExprCXX.cpp", 7328, __extension__ __PRETTY_FUNCTION__
))
;
7329 if (!Cleanup.exprNeedsCleanups())
7330 return SubExpr;
7331
7332 auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
7333 ExprCleanupObjects.size() - FirstCleanup);
7334
7335 auto *E = ExprWithCleanups::Create(
7336 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
7337 DiscardCleanupsInEvaluationContext();
7338
7339 return E;
7340}
7341
7342Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
7343 assert(SubStmt && "sub-statement can't be null!")(static_cast <bool> (SubStmt && "sub-statement can't be null!"
) ? void (0) : __assert_fail ("SubStmt && \"sub-statement can't be null!\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7343, __extension__ __PRETTY_FUNCTION__
))
;
7344
7345 CleanupVarDeclMarking();
7346
7347 if (!Cleanup.exprNeedsCleanups())
7348 return SubStmt;
7349
7350 // FIXME: In order to attach the temporaries, wrap the statement into
7351 // a StmtExpr; currently this is only used for asm statements.
7352 // This is hacky, either create a new CXXStmtWithTemporaries statement or
7353 // a new AsmStmtWithTemporaries.
7354 CompoundStmt *CompStmt =
7355 CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(),
7356 SourceLocation(), SourceLocation());
7357 Expr *E = new (Context)
7358 StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(),
7359 /*FIXME TemplateDepth=*/0);
7360 return MaybeCreateExprWithCleanups(E);
7361}
7362
7363/// Process the expression contained within a decltype. For such expressions,
7364/// certain semantic checks on temporaries are delayed until this point, and
7365/// are omitted for the 'topmost' call in the decltype expression. If the
7366/// topmost call bound a temporary, strip that temporary off the expression.
7367ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
7368 assert(ExprEvalContexts.back().ExprContext ==(static_cast <bool> (ExprEvalContexts.back().ExprContext
== ExpressionEvaluationContextRecord::EK_Decltype &&
"not in a decltype expression") ? void (0) : __assert_fail (
"ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7370, __extension__ __PRETTY_FUNCTION__
))
7369 ExpressionEvaluationContextRecord::EK_Decltype &&(static_cast <bool> (ExprEvalContexts.back().ExprContext
== ExpressionEvaluationContextRecord::EK_Decltype &&
"not in a decltype expression") ? void (0) : __assert_fail (
"ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7370, __extension__ __PRETTY_FUNCTION__
))
7370 "not in a decltype expression")(static_cast <bool> (ExprEvalContexts.back().ExprContext
== ExpressionEvaluationContextRecord::EK_Decltype &&
"not in a decltype expression") ? void (0) : __assert_fail (
"ExprEvalContexts.back().ExprContext == ExpressionEvaluationContextRecord::EK_Decltype && \"not in a decltype expression\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7370, __extension__ __PRETTY_FUNCTION__
))
;
7371
7372 ExprResult Result = CheckPlaceholderExpr(E);
7373 if (Result.isInvalid())
7374 return ExprError();
7375 E = Result.get();
7376
7377 // C++11 [expr.call]p11:
7378 // If a function call is a prvalue of object type,
7379 // -- if the function call is either
7380 // -- the operand of a decltype-specifier, or
7381 // -- the right operand of a comma operator that is the operand of a
7382 // decltype-specifier,
7383 // a temporary object is not introduced for the prvalue.
7384
7385 // Recursively rebuild ParenExprs and comma expressions to strip out the
7386 // outermost CXXBindTemporaryExpr, if any.
7387 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
7388 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
7389 if (SubExpr.isInvalid())
7390 return ExprError();
7391 if (SubExpr.get() == PE->getSubExpr())
7392 return E;
7393 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
7394 }
7395 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
7396 if (BO->getOpcode() == BO_Comma) {
7397 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
7398 if (RHS.isInvalid())
7399 return ExprError();
7400 if (RHS.get() == BO->getRHS())
7401 return E;
7402 return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma,
7403 BO->getType(), BO->getValueKind(),
7404 BO->getObjectKind(), BO->getOperatorLoc(),
7405 BO->getFPFeatures());
7406 }
7407 }
7408
7409 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
7410 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
7411 : nullptr;
7412 if (TopCall)
7413 E = TopCall;
7414 else
7415 TopBind = nullptr;
7416
7417 // Disable the special decltype handling now.
7418 ExprEvalContexts.back().ExprContext =
7419 ExpressionEvaluationContextRecord::EK_Other;
7420
7421 Result = CheckUnevaluatedOperand(E);
7422 if (Result.isInvalid())
7423 return ExprError();
7424 E = Result.get();
7425
7426 // In MS mode, don't perform any extra checking of call return types within a
7427 // decltype expression.
7428 if (getLangOpts().MSVCCompat)
7429 return E;
7430
7431 // Perform the semantic checks we delayed until this point.
7432 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
7433 I != N; ++I) {
7434 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
7435 if (Call == TopCall)
7436 continue;
7437
7438 if (CheckCallReturnType(Call->getCallReturnType(Context),
7439 Call->getBeginLoc(), Call, Call->getDirectCallee()))
7440 return ExprError();
7441 }
7442
7443 // Now all relevant types are complete, check the destructors are accessible
7444 // and non-deleted, and annotate them on the temporaries.
7445 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
7446 I != N; ++I) {
7447 CXXBindTemporaryExpr *Bind =
7448 ExprEvalContexts.back().DelayedDecltypeBinds[I];
7449 if (Bind == TopBind)
7450 continue;
7451
7452 CXXTemporary *Temp = Bind->getTemporary();
7453
7454 CXXRecordDecl *RD =
7455 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7456 CXXDestructorDecl *Destructor = LookupDestructor(RD);
7457 Temp->setDestructor(Destructor);
7458
7459 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
7460 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
7461 PDiag(diag::err_access_dtor_temp)
7462 << Bind->getType());
7463 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
7464 return ExprError();
7465
7466 // We need a cleanup, but we don't need to remember the temporary.
7467 Cleanup.setExprNeedsCleanups(true);
7468 }
7469
7470 // Possibly strip off the top CXXBindTemporaryExpr.
7471 return E;
7472}
7473
7474/// Note a set of 'operator->' functions that were used for a member access.
7475static void noteOperatorArrows(Sema &S,
7476 ArrayRef<FunctionDecl *> OperatorArrows) {
7477 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
7478 // FIXME: Make this configurable?
7479 unsigned Limit = 9;
7480 if (OperatorArrows.size() > Limit) {
7481 // Produce Limit-1 normal notes and one 'skipping' note.
7482 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
7483 SkipCount = OperatorArrows.size() - (Limit - 1);
7484 }
7485
7486 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
7487 if (I == SkipStart) {
7488 S.Diag(OperatorArrows[I]->getLocation(),
7489 diag::note_operator_arrows_suppressed)
7490 << SkipCount;
7491 I += SkipCount;
7492 } else {
7493 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
7494 << OperatorArrows[I]->getCallResultType();
7495 ++I;
7496 }
7497 }
7498}
7499
7500ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
7501 SourceLocation OpLoc,
7502 tok::TokenKind OpKind,
7503 ParsedType &ObjectType,
7504 bool &MayBePseudoDestructor) {
7505 // Since this might be a postfix expression, get rid of ParenListExprs.
7506 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
7507 if (Result.isInvalid()) return ExprError();
7508 Base = Result.get();
7509
7510 Result = CheckPlaceholderExpr(Base);
7511 if (Result.isInvalid()) return ExprError();
7512 Base = Result.get();
7513
7514 QualType BaseType = Base->getType();
7515 MayBePseudoDestructor = false;
7516 if (BaseType->isDependentType()) {
7517 // If we have a pointer to a dependent type and are using the -> operator,
7518 // the object type is the type that the pointer points to. We might still
7519 // have enough information about that type to do something useful.
7520 if (OpKind == tok::arrow)
7521 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
7522 BaseType = Ptr->getPointeeType();
7523
7524 ObjectType = ParsedType::make(BaseType);
7525 MayBePseudoDestructor = true;
7526 return Base;
7527 }
7528
7529 // C++ [over.match.oper]p8:
7530 // [...] When operator->returns, the operator-> is applied to the value
7531 // returned, with the original second operand.
7532 if (OpKind == tok::arrow) {
7533 QualType StartingType = BaseType;
7534 bool NoArrowOperatorFound = false;
7535 bool FirstIteration = true;
7536 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
7537 // The set of types we've considered so far.
7538 llvm::SmallPtrSet<CanQualType,8> CTypes;
7539 SmallVector<FunctionDecl*, 8> OperatorArrows;
7540 CTypes.insert(Context.getCanonicalType(BaseType));
7541
7542 while (BaseType->isRecordType()) {
7543 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
7544 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
7545 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
7546 noteOperatorArrows(*this, OperatorArrows);
7547 Diag(OpLoc, diag::note_operator_arrow_depth)
7548 << getLangOpts().ArrowDepth;
7549 return ExprError();
7550 }
7551
7552 Result = BuildOverloadedArrowExpr(
7553 S, Base, OpLoc,
7554 // When in a template specialization and on the first loop iteration,
7555 // potentially give the default diagnostic (with the fixit in a
7556 // separate note) instead of having the error reported back to here
7557 // and giving a diagnostic with a fixit attached to the error itself.
7558 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
7559 ? nullptr
7560 : &NoArrowOperatorFound);
7561 if (Result.isInvalid()) {
7562 if (NoArrowOperatorFound) {
7563 if (FirstIteration) {
7564 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7565 << BaseType << 1 << Base->getSourceRange()
7566 << FixItHint::CreateReplacement(OpLoc, ".");
7567 OpKind = tok::period;
7568 break;
7569 }
7570 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
7571 << BaseType << Base->getSourceRange();
7572 CallExpr *CE = dyn_cast<CallExpr>(Base);
7573 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
7574 Diag(CD->getBeginLoc(),
7575 diag::note_member_reference_arrow_from_operator_arrow);
7576 }
7577 }
7578 return ExprError();
7579 }
7580 Base = Result.get();
7581 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
7582 OperatorArrows.push_back(OpCall->getDirectCallee());
7583 BaseType = Base->getType();
7584 CanQualType CBaseType = Context.getCanonicalType(BaseType);
7585 if (!CTypes.insert(CBaseType).second) {
7586 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
7587 noteOperatorArrows(*this, OperatorArrows);
7588 return ExprError();
7589 }
7590 FirstIteration = false;
7591 }
7592
7593 if (OpKind == tok::arrow) {
7594 if (BaseType->isPointerType())
7595 BaseType = BaseType->getPointeeType();
7596 else if (auto *AT = Context.getAsArrayType(BaseType))
7597 BaseType = AT->getElementType();
7598 }
7599 }
7600
7601 // Objective-C properties allow "." access on Objective-C pointer types,
7602 // so adjust the base type to the object type itself.
7603 if (BaseType->isObjCObjectPointerType())
7604 BaseType = BaseType->getPointeeType();
7605
7606 // C++ [basic.lookup.classref]p2:
7607 // [...] If the type of the object expression is of pointer to scalar
7608 // type, the unqualified-id is looked up in the context of the complete
7609 // postfix-expression.
7610 //
7611 // This also indicates that we could be parsing a pseudo-destructor-name.
7612 // Note that Objective-C class and object types can be pseudo-destructor
7613 // expressions or normal member (ivar or property) access expressions, and
7614 // it's legal for the type to be incomplete if this is a pseudo-destructor
7615 // call. We'll do more incomplete-type checks later in the lookup process,
7616 // so just skip this check for ObjC types.
7617 if (!BaseType->isRecordType()) {
7618 ObjectType = ParsedType::make(BaseType);
7619 MayBePseudoDestructor = true;
7620 return Base;
7621 }
7622
7623 // The object type must be complete (or dependent), or
7624 // C++11 [expr.prim.general]p3:
7625 // Unlike the object expression in other contexts, *this is not required to
7626 // be of complete type for purposes of class member access (5.2.5) outside
7627 // the member function body.
7628 if (!BaseType->isDependentType() &&
7629 !isThisOutsideMemberFunctionBody(BaseType) &&
7630 RequireCompleteType(OpLoc, BaseType,
7631 diag::err_incomplete_member_access)) {
7632 return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base});
7633 }
7634
7635 // C++ [basic.lookup.classref]p2:
7636 // If the id-expression in a class member access (5.2.5) is an
7637 // unqualified-id, and the type of the object expression is of a class
7638 // type C (or of pointer to a class type C), the unqualified-id is looked
7639 // up in the scope of class C. [...]
7640 ObjectType = ParsedType::make(BaseType);
7641 return Base;
7642}
7643
7644static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base,
7645 tok::TokenKind &OpKind, SourceLocation OpLoc) {
7646 if (Base->hasPlaceholderType()) {
7647 ExprResult result = S.CheckPlaceholderExpr(Base);
7648 if (result.isInvalid()) return true;
7649 Base = result.get();
7650 }
7651 ObjectType = Base->getType();
7652
7653 // C++ [expr.pseudo]p2:
7654 // The left-hand side of the dot operator shall be of scalar type. The
7655 // left-hand side of the arrow operator shall be of pointer to scalar type.
7656 // This scalar type is the object type.
7657 // Note that this is rather different from the normal handling for the
7658 // arrow operator.
7659 if (OpKind == tok::arrow) {
7660 // The operator requires a prvalue, so perform lvalue conversions.
7661 // Only do this if we might plausibly end with a pointer, as otherwise
7662 // this was likely to be intended to be a '.'.
7663 if (ObjectType->isPointerType() || ObjectType->isArrayType() ||
7664 ObjectType->isFunctionType()) {
7665 ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base);
7666 if (BaseResult.isInvalid())
7667 return true;
7668 Base = BaseResult.get();
7669 ObjectType = Base->getType();
7670 }
7671
7672 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
7673 ObjectType = Ptr->getPointeeType();
7674 } else if (!Base->isTypeDependent()) {
7675 // The user wrote "p->" when they probably meant "p."; fix it.
7676 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7677 << ObjectType << true
7678 << FixItHint::CreateReplacement(OpLoc, ".");
7679 if (S.isSFINAEContext())
7680 return true;
7681
7682 OpKind = tok::period;
7683 }
7684 }
7685
7686 return false;
7687}
7688
7689/// Check if it's ok to try and recover dot pseudo destructor calls on
7690/// pointer objects.
7691static bool
7692canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef,
7693 QualType DestructedType) {
7694 // If this is a record type, check if its destructor is callable.
7695 if (auto *RD = DestructedType->getAsCXXRecordDecl()) {
7696 if (RD->hasDefinition())
7697 if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD))
7698 return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false);
7699 return false;
7700 }
7701
7702 // Otherwise, check if it's a type for which it's valid to use a pseudo-dtor.
7703 return DestructedType->isDependentType() || DestructedType->isScalarType() ||
7704 DestructedType->isVectorType();
7705}
7706
7707ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
7708 SourceLocation OpLoc,
7709 tok::TokenKind OpKind,
7710 const CXXScopeSpec &SS,
7711 TypeSourceInfo *ScopeTypeInfo,
7712 SourceLocation CCLoc,
7713 SourceLocation TildeLoc,
7714 PseudoDestructorTypeStorage Destructed) {
7715 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
7716
7717 QualType ObjectType;
7718 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7719 return ExprError();
7720
7721 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
7722 !ObjectType->isVectorType()) {
7723 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
7724 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
7725 else {
7726 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
7727 << ObjectType << Base->getSourceRange();
7728 return ExprError();
7729 }
7730 }
7731
7732 // C++ [expr.pseudo]p2:
7733 // [...] The cv-unqualified versions of the object type and of the type
7734 // designated by the pseudo-destructor-name shall be the same type.
7735 if (DestructedTypeInfo) {
7736 QualType DestructedType = DestructedTypeInfo->getType();
7737 SourceLocation DestructedTypeStart =
7738 DestructedTypeInfo->getTypeLoc().getBeginLoc();
7739 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
7740 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
7741 // Detect dot pseudo destructor calls on pointer objects, e.g.:
7742 // Foo *foo;
7743 // foo.~Foo();
7744 if (OpKind == tok::period && ObjectType->isPointerType() &&
7745 Context.hasSameUnqualifiedType(DestructedType,
7746 ObjectType->getPointeeType())) {
7747 auto Diagnostic =
7748 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
7749 << ObjectType << /*IsArrow=*/0 << Base->getSourceRange();
7750
7751 // Issue a fixit only when the destructor is valid.
7752 if (canRecoverDotPseudoDestructorCallsOnPointerObjects(
7753 *this, DestructedType))
7754 Diagnostic << FixItHint::CreateReplacement(OpLoc, "->");
7755
7756 // Recover by setting the object type to the destructed type and the
7757 // operator to '->'.
7758 ObjectType = DestructedType;
7759 OpKind = tok::arrow;
7760 } else {
7761 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
7762 << ObjectType << DestructedType << Base->getSourceRange()
7763 << DestructedTypeInfo->getTypeLoc().getSourceRange();
7764
7765 // Recover by setting the destructed type to the object type.
7766 DestructedType = ObjectType;
7767 DestructedTypeInfo =
7768 Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart);
7769 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7770 }
7771 } else if (DestructedType.getObjCLifetime() !=
7772 ObjectType.getObjCLifetime()) {
7773
7774 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
7775 // Okay: just pretend that the user provided the correctly-qualified
7776 // type.
7777 } else {
7778 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
7779 << ObjectType << DestructedType << Base->getSourceRange()
7780 << DestructedTypeInfo->getTypeLoc().getSourceRange();
7781 }
7782
7783 // Recover by setting the destructed type to the object type.
7784 DestructedType = ObjectType;
7785 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
7786 DestructedTypeStart);
7787 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7788 }
7789 }
7790 }
7791
7792 // C++ [expr.pseudo]p2:
7793 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
7794 // form
7795 //
7796 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
7797 //
7798 // shall designate the same scalar type.
7799 if (ScopeTypeInfo) {
7800 QualType ScopeType = ScopeTypeInfo->getType();
7801 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
7802 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
7803
7804 Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(),
7805 diag::err_pseudo_dtor_type_mismatch)
7806 << ObjectType << ScopeType << Base->getSourceRange()
7807 << ScopeTypeInfo->getTypeLoc().getSourceRange();
7808
7809 ScopeType = QualType();
7810 ScopeTypeInfo = nullptr;
7811 }
7812 }
7813
7814 Expr *Result
7815 = new (Context) CXXPseudoDestructorExpr(Context, Base,
7816 OpKind == tok::arrow, OpLoc,
7817 SS.getWithLocInContext(Context),
7818 ScopeTypeInfo,
7819 CCLoc,
7820 TildeLoc,
7821 Destructed);
7822
7823 return Result;
7824}
7825
7826ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7827 SourceLocation OpLoc,
7828 tok::TokenKind OpKind,
7829 CXXScopeSpec &SS,
7830 UnqualifiedId &FirstTypeName,
7831 SourceLocation CCLoc,
7832 SourceLocation TildeLoc,
7833 UnqualifiedId &SecondTypeName) {
7834 assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid first type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7836, __extension__ __PRETTY_FUNCTION__
))
7835 FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid first type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7836, __extension__ __PRETTY_FUNCTION__
))
7836 "Invalid first type name in pseudo-destructor")(static_cast <bool> ((FirstTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid first type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid first type name in pseudo-destructor\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7836, __extension__ __PRETTY_FUNCTION__
))
;
7837 assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid second type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7839, __extension__ __PRETTY_FUNCTION__
))
7838 SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) &&(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid second type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7839, __extension__ __PRETTY_FUNCTION__
))
7839 "Invalid second type name in pseudo-destructor")(static_cast <bool> ((SecondTypeName.getKind() == UnqualifiedIdKind
::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind
::IK_Identifier) && "Invalid second type name in pseudo-destructor"
) ? void (0) : __assert_fail ("(SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && \"Invalid second type name in pseudo-destructor\""
, "clang/lib/Sema/SemaExprCXX.cpp", 7839, __extension__ __PRETTY_FUNCTION__
))
;
7840
7841 QualType ObjectType;
7842 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7843 return ExprError();
7844
7845 // Compute the object type that we should use for name lookup purposes. Only
7846 // record types and dependent types matter.
7847 ParsedType ObjectTypePtrForLookup;
7848 if (!SS.isSet()) {
7849 if (ObjectType->isRecordType())
7850 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
7851 else if (ObjectType->isDependentType())
7852 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
7853 }
7854
7855 // Convert the name of the type being destructed (following the ~) into a
7856 // type (with source-location information).
7857 QualType DestructedType;
7858 TypeSourceInfo *DestructedTypeInfo = nullptr;
7859 PseudoDestructorTypeStorage Destructed;
7860 if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7861 ParsedType T = getTypeName(*SecondTypeName.Identifier,
7862 SecondTypeName.StartLocation,
7863 S, &SS, true, false, ObjectTypePtrForLookup,
7864 /*IsCtorOrDtorName*/true);
7865 if (!T &&
7866 ((SS.isSet() && !computeDeclContext(SS, false)) ||
7867 (!SS.isSet() && ObjectType->isDependentType()))) {
7868 // The name of the type being destroyed is a dependent name, and we
7869 // couldn't find anything useful in scope. Just store the identifier and
7870 // it's location, and we'll perform (qualified) name lookup again at
7871 // template instantiation time.
7872 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
7873 SecondTypeName.StartLocation);
7874 } else if (!T) {
7875 Diag(SecondTypeName.StartLocation,
7876 diag::err_pseudo_dtor_destructor_non_type)
7877 << SecondTypeName.Identifier << ObjectType;
7878 if (isSFINAEContext())
7879 return ExprError();
7880
7881 // Recover by assuming we had the right type all along.
7882 DestructedType = ObjectType;
7883 } else
7884 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
7885 } else {
7886 // Resolve the template-id to a type.
7887 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
7888 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7889 TemplateId->NumArgs);
7890 TypeResult T = ActOnTemplateIdType(S,
7891 SS,
7892 TemplateId->TemplateKWLoc,
7893 TemplateId->Template,
7894 TemplateId->Name,
7895 TemplateId->TemplateNameLoc,
7896 TemplateId->LAngleLoc,
7897 TemplateArgsPtr,
7898 TemplateId->RAngleLoc,
7899 /*IsCtorOrDtorName*/true);
7900 if (T.isInvalid() || !T.get()) {
7901 // Recover by assuming we had the right type all along.
7902 DestructedType = ObjectType;
7903 } else
7904 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
7905 }
7906
7907 // If we've performed some kind of recovery, (re-)build the type source
7908 // information.
7909 if (!DestructedType.isNull()) {
7910 if (!DestructedTypeInfo)
7911 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
7912 SecondTypeName.StartLocation);
7913 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
7914 }
7915
7916 // Convert the name of the scope type (the type prior to '::') into a type.
7917 TypeSourceInfo *ScopeTypeInfo = nullptr;
7918 QualType ScopeType;
7919 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId ||
7920 FirstTypeName.Identifier) {
7921 if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) {
7922 ParsedType T = getTypeName(*FirstTypeName.Identifier,
7923 FirstTypeName.StartLocation,
7924 S, &SS, true, false, ObjectTypePtrForLookup,
7925 /*IsCtorOrDtorName*/true);
7926 if (!T) {
7927 Diag(FirstTypeName.StartLocation,
7928 diag::err_pseudo_dtor_destructor_non_type)
7929 << FirstTypeName.Identifier << ObjectType;
7930
7931 if (isSFINAEContext())
7932 return ExprError();
7933
7934 // Just drop this type. It's unnecessary anyway.
7935 ScopeType = QualType();
7936 } else
7937 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
7938 } else {
7939 // Resolve the template-id to a type.
7940 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
7941 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7942 TemplateId->NumArgs);
7943 TypeResult T = ActOnTemplateIdType(S,
7944 SS,
7945 TemplateId->TemplateKWLoc,
7946 TemplateId->Template,
7947 TemplateId->Name,
7948 TemplateId->TemplateNameLoc,
7949 TemplateId->LAngleLoc,
7950 TemplateArgsPtr,
7951 TemplateId->RAngleLoc,
7952 /*IsCtorOrDtorName*/true);
7953 if (T.isInvalid() || !T.get()) {
7954 // Recover by dropping this type.
7955 ScopeType = QualType();
7956 } else
7957 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
7958 }
7959 }
7960
7961 if (!ScopeType.isNull() && !ScopeTypeInfo)
7962 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
7963 FirstTypeName.StartLocation);
7964
7965
7966 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
7967 ScopeTypeInfo, CCLoc, TildeLoc,
7968 Destructed);
7969}
7970
7971ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
7972 SourceLocation OpLoc,
7973 tok::TokenKind OpKind,
7974 SourceLocation TildeLoc,
7975 const DeclSpec& DS) {
7976 QualType ObjectType;
7977 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
7978 return ExprError();
7979
7980 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
7981 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
7982 return true;
7983 }
7984
7985 QualType T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false);
7986
7987 TypeLocBuilder TLB;
7988 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
7989 DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
7990 DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd());
7991 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
7992 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
7993
7994 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
7995 nullptr, SourceLocation(), TildeLoc,
7996 Destructed);
7997}
7998
7999ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
8000 CXXConversionDecl *Method,
8001 bool HadMultipleCandidates) {
8002 // Convert the expression to match the conversion function's implicit object
8003 // parameter.
8004 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
8005 FoundDecl, Method);
8006 if (Exp.isInvalid())
8007 return true;
8008
8009 if (Method->getParent()->isLambda() &&
8010 Method->getConversionType()->isBlockPointerType()) {
8011 // This is a lambda conversion to block pointer; check if the argument
8012 // was a LambdaExpr.
8013 Expr *SubE = E;
8014 CastExpr *CE = dyn_cast<CastExpr>(SubE);
8015 if (CE && CE->getCastKind() == CK_NoOp)
8016 SubE = CE->getSubExpr();
8017 SubE = SubE->IgnoreParens();
8018 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
8019 SubE = BE->getSubExpr();
8020 if (isa<LambdaExpr>(SubE)) {
8021 // For the conversion to block pointer on a lambda expression, we
8022 // construct a special BlockLiteral instead; this doesn't really make
8023 // a difference in ARC, but outside of ARC the resulting block literal
8024 // follows the normal lifetime rules for block literals instead of being
8025 // autoreleased.
8026 PushExpressionEvaluationContext(
8027 ExpressionEvaluationContext::PotentiallyEvaluated);
8028 ExprResult BlockExp = BuildBlockForLambdaConversion(
8029 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
8030 PopExpressionEvaluationContext();
8031
8032 // FIXME: This note should be produced by a CodeSynthesisContext.
8033 if (BlockExp.isInvalid())
8034 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
8035 return BlockExp;
8036 }
8037 }
8038
8039 MemberExpr *ME =
8040 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
8041 NestedNameSpecifierLoc(), SourceLocation(), Method,
8042 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
8043 HadMultipleCandidates, DeclarationNameInfo(),
8044 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
8045
8046 QualType ResultType = Method->getReturnType();
8047 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8048 ResultType = ResultType.getNonLValueExprType(Context);
8049
8050 CXXMemberCallExpr *CE = CXXMemberCallExpr::Create(
8051 Context, ME, /*Args=*/{}, ResultType, VK, Exp.get()->getEndLoc(),
8052 CurFPFeatureOverrides());
8053
8054 if (CheckFunctionCall(Method, CE,
8055 Method->getType()->castAs<FunctionProtoType>()))
8056 return ExprError();
8057
8058 return CheckForImmediateInvocation(CE, CE->getMethodDecl());
8059}
8060
8061ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
8062 SourceLocation RParen) {
8063 // If the operand is an unresolved lookup expression, the expression is ill-
8064 // formed per [over.over]p1, because overloaded function names cannot be used
8065 // without arguments except in explicit contexts.
8066 ExprResult R = CheckPlaceholderExpr(Operand);
8067 if (R.isInvalid())
8068 return R;
8069
8070 R = CheckUnevaluatedOperand(R.get());
8071 if (R.isInvalid())
8072 return ExprError();
8073
8074 Operand = R.get();
8075
8076 if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() &&
8077 Operand->HasSideEffects(Context, false)) {
8078 // The expression operand for noexcept is in an unevaluated expression
8079 // context, so side effects could result in unintended consequences.
8080 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
8081 }
8082
8083 CanThrowResult CanThrow = canThrow(Operand);
8084 return new (Context)
8085 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
8086}
8087
8088ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
8089 Expr *Operand, SourceLocation RParen) {
8090 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
8091}
8092
8093static void MaybeDecrementCount(
8094 Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) {
8095 DeclRefExpr *LHS = nullptr;
8096 bool IsCompoundAssign = false;
8097 bool isIncrementDecrementUnaryOp = false;
8098 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8099 if (BO->getLHS()->getType()->isDependentType() ||
8100 BO->getRHS()->getType()->isDependentType()) {
8101 if (BO->getOpcode() != BO_Assign)
8102 return;
8103 } else if (!BO->isAssignmentOp())
8104 return;
8105 else
8106 IsCompoundAssign = BO->isCompoundAssignmentOp();
8107 LHS = dyn_cast<DeclRefExpr>(BO->getLHS());
8108 } else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8109 if (COCE->getOperator() != OO_Equal)
8110 return;
8111 LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0));
8112 } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
8113 if (!UO->isIncrementDecrementOp())
8114 return;
8115 isIncrementDecrementUnaryOp = true;
8116 LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr());
8117 }
8118 if (!LHS)
8119 return;
8120 VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl());
8121 if (!VD)
8122 return;
8123 // Don't decrement RefsMinusAssignments if volatile variable with compound
8124 // assignment (+=, ...) or increment/decrement unary operator to avoid
8125 // potential unused-but-set-variable warning.
8126 if ((IsCompoundAssign || isIncrementDecrementUnaryOp) &&
8127 VD->getType().isVolatileQualified())
8128 return;
8129 auto iter = RefsMinusAssignments.find(VD);
8130 if (iter == RefsMinusAssignments.end())
8131 return;
8132 iter->getSecond()--;
8133}
8134
8135/// Perform the conversions required for an expression used in a
8136/// context that ignores the result.
8137ExprResult Sema::IgnoredValueConversions(Expr *E) {
8138 MaybeDecrementCount(E, RefsMinusAssignments);
8139
8140 if (E->hasPlaceholderType()) {
8141 ExprResult result = CheckPlaceholderExpr(E);
8142 if (result.isInvalid()) return E;
8143 E = result.get();
8144 }
8145
8146 // C99 6.3.2.1:
8147 // [Except in specific positions,] an lvalue that does not have
8148 // array type is converted to the value stored in the
8149 // designated object (and is no longer an lvalue).
8150 if (E->isPRValue()) {
8151 // In C, function designators (i.e. expressions of function type)
8152 // are r-values, but we still want to do function-to-pointer decay
8153 // on them. This is both technically correct and convenient for
8154 // some clients.
8155 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
8156 return DefaultFunctionArrayConversion(E);
8157
8158 return E;
8159 }
8160
8161 if (getLangOpts().CPlusPlus) {
8162 // The C++11 standard defines the notion of a discarded-value expression;
8163 // normally, we don't need to do anything to handle it, but if it is a
8164 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
8165 // conversion.
8166 if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) {
8167 ExprResult Res = DefaultLvalueConversion(E);
8168 if (Res.isInvalid())
8169 return E;
8170 E = Res.get();
8171 } else {
8172 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8173 // it occurs as a discarded-value expression.
8174 CheckUnusedVolatileAssignment(E);
8175 }
8176
8177 // C++1z:
8178 // If the expression is a prvalue after this optional conversion, the
8179 // temporary materialization conversion is applied.
8180 //
8181 // We skip this step: IR generation is able to synthesize the storage for
8182 // itself in the aggregate case, and adding the extra node to the AST is
8183 // just clutter.
8184 // FIXME: We don't emit lifetime markers for the temporaries due to this.
8185 // FIXME: Do any other AST consumers care about this?
8186 return E;
8187 }
8188
8189 // GCC seems to also exclude expressions of incomplete enum type.
8190 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
8191 if (!T->getDecl()->isComplete()) {
8192 // FIXME: stupid workaround for a codegen bug!
8193 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
8194 return E;
8195 }
8196 }
8197
8198 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
8199 if (Res.isInvalid())
8200 return E;
8201 E = Res.get();
8202
8203 if (!E->getType()->isVoidType())
8204 RequireCompleteType(E->getExprLoc(), E->getType(),
8205 diag::err_incomplete_type);
8206 return E;
8207}
8208
8209ExprResult Sema::CheckUnevaluatedOperand(Expr *E) {
8210 // Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if
8211 // it occurs as an unevaluated operand.
8212 CheckUnusedVolatileAssignment(E);
8213
8214 return E;
8215}
8216
8217// If we can unambiguously determine whether Var can never be used
8218// in a constant expression, return true.
8219// - if the variable and its initializer are non-dependent, then
8220// we can unambiguously check if the variable is a constant expression.
8221// - if the initializer is not value dependent - we can determine whether
8222// it can be used to initialize a constant expression. If Init can not
8223// be used to initialize a constant expression we conclude that Var can
8224// never be a constant expression.
8225// - FXIME: if the initializer is dependent, we can still do some analysis and
8226// identify certain cases unambiguously as non-const by using a Visitor:
8227// - such as those that involve odr-use of a ParmVarDecl, involve a new
8228// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
8229static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
8230 ASTContext &Context) {
8231 if (isa<ParmVarDecl>(Var)) return true;
8232 const VarDecl *DefVD = nullptr;
8233
8234 // If there is no initializer - this can not be a constant expression.
8235 const Expr *Init = Var->getAnyInitializer(DefVD);
8236 if (!Init)
8237 return true;
8238 assert(DefVD)(static_cast <bool> (DefVD) ? void (0) : __assert_fail (
"DefVD", "clang/lib/Sema/SemaExprCXX.cpp", 8238, __extension__
__PRETTY_FUNCTION__))
;
8239 if (DefVD->isWeak())
8240 return false;
8241
8242 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
8243 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
8244 // of value-dependent expressions, and use it here to determine whether the
8245 // initializer is a potential constant expression.
8246 return false;
8247 }
8248
8249 return !Var->isUsableInConstantExpressions(Context);
8250}
8251
8252/// Check if the current lambda has any potential captures
8253/// that must be captured by any of its enclosing lambdas that are ready to
8254/// capture. If there is a lambda that can capture a nested
8255/// potential-capture, go ahead and do so. Also, check to see if any
8256/// variables are uncaptureable or do not involve an odr-use so do not
8257/// need to be captured.
8258
8259static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
8260 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
8261
8262 assert(!S.isUnevaluatedContext())(static_cast <bool> (!S.isUnevaluatedContext()) ? void (
0) : __assert_fail ("!S.isUnevaluatedContext()", "clang/lib/Sema/SemaExprCXX.cpp"
, 8262, __extension__ __PRETTY_FUNCTION__))
;
8263 assert(S.CurContext->isDependentContext())(static_cast <bool> (S.CurContext->isDependentContext
()) ? void (0) : __assert_fail ("S.CurContext->isDependentContext()"
, "clang/lib/Sema/SemaExprCXX.cpp", 8263, __extension__ __PRETTY_FUNCTION__
))
;
8264#ifndef NDEBUG
8265 DeclContext *DC = S.CurContext;
8266 while (DC && isa<CapturedDecl>(DC))
8267 DC = DC->getParent();
8268 assert((static_cast <bool> (CurrentLSI->CallOperator == DC &&
"The current call operator must be synchronized with Sema's CurContext"
) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "clang/lib/Sema/SemaExprCXX.cpp", 8270, __extension__ __PRETTY_FUNCTION__
))
8269 CurrentLSI->CallOperator == DC &&(static_cast <bool> (CurrentLSI->CallOperator == DC &&
"The current call operator must be synchronized with Sema's CurContext"
) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "clang/lib/Sema/SemaExprCXX.cpp", 8270, __extension__ __PRETTY_FUNCTION__
))
8270 "The current call operator must be synchronized with Sema's CurContext")(static_cast <bool> (CurrentLSI->CallOperator == DC &&
"The current call operator must be synchronized with Sema's CurContext"
) ? void (0) : __assert_fail ("CurrentLSI->CallOperator == DC && \"The current call operator must be synchronized with Sema's CurContext\""
, "clang/lib/Sema/SemaExprCXX.cpp", 8270, __extension__ __PRETTY_FUNCTION__
))
;
8271#endif // NDEBUG
8272
8273 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
8274
8275 // All the potentially captureable variables in the current nested
8276 // lambda (within a generic outer lambda), must be captured by an
8277 // outer lambda that is enclosed within a non-dependent context.
8278 CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) {
8279 // If the variable is clearly identified as non-odr-used and the full
8280 // expression is not instantiation dependent, only then do we not
8281 // need to check enclosing lambda's for speculative captures.
8282 // For e.g.:
8283 // Even though 'x' is not odr-used, it should be captured.
8284 // int test() {
8285 // const int x = 10;
8286 // auto L = [=](auto a) {
8287 // (void) +x + a;
8288 // };
8289 // }
8290 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
8291 !IsFullExprInstantiationDependent)
8292 return;
8293
8294 VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl();
8295 if (!UnderlyingVar)
8296 return;
8297
8298 // If we have a capture-capable lambda for the variable, go ahead and
8299 // capture the variable in that lambda (and all its enclosing lambdas).
8300 if (const std::optional<unsigned> Index =
8301 getStackIndexOfNearestEnclosingCaptureCapableLambda(
8302 S.FunctionScopes, Var, S))
8303 S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index);
8304 const bool IsVarNeverAConstantExpression =
8305 VariableCanNeverBeAConstantExpression(UnderlyingVar, S.Context);
8306 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
8307 // This full expression is not instantiation dependent or the variable
8308 // can not be used in a constant expression - which means
8309 // this variable must be odr-used here, so diagnose a
8310 // capture violation early, if the variable is un-captureable.
8311 // This is purely for diagnosing errors early. Otherwise, this
8312 // error would get diagnosed when the lambda becomes capture ready.
8313 QualType CaptureType, DeclRefType;
8314 SourceLocation ExprLoc = VarExpr->getExprLoc();
8315 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8316 /*EllipsisLoc*/ SourceLocation(),
8317 /*BuildAndDiagnose*/false, CaptureType,
8318 DeclRefType, nullptr)) {
8319 // We will never be able to capture this variable, and we need
8320 // to be able to in any and all instantiations, so diagnose it.
8321 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
8322 /*EllipsisLoc*/ SourceLocation(),
8323 /*BuildAndDiagnose*/true, CaptureType,
8324 DeclRefType, nullptr);
8325 }
8326 }
8327 });
8328
8329 // Check if 'this' needs to be captured.
8330 if (CurrentLSI->hasPotentialThisCapture()) {
8331 // If we have a capture-capable lambda for 'this', go ahead and capture
8332 // 'this' in that lambda (and all its enclosing lambdas).
8333 if (const std::optional<unsigned> Index =
8334 getStackIndexOfNearestEnclosingCaptureCapableLambda(
8335 S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) {
8336 const unsigned FunctionScopeIndexOfCapturableLambda = *Index;
8337 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
8338 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
8339 &FunctionScopeIndexOfCapturableLambda);
8340 }
8341 }
8342
8343 // Reset all the potential captures at the end of each full-expression.
8344 CurrentLSI->clearPotentialCaptures();
8345}
8346
8347static ExprResult attemptRecovery(Sema &SemaRef,
8348 const TypoCorrectionConsumer &Consumer,
8349 const TypoCorrection &TC) {
8350 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
8351 Consumer.getLookupResult().getLookupKind());
8352 const CXXScopeSpec *SS = Consumer.getSS();
8353 CXXScopeSpec NewSS;
8354
8355 // Use an approprate CXXScopeSpec for building the expr.
8356 if (auto *NNS = TC.getCorrectionSpecifier())
8357 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
8358 else if (SS && !TC.WillReplaceSpecifier())
8359 NewSS = *SS;
8360
8361 if (auto *ND = TC.getFoundDecl()) {
8362 R.setLookupName(ND->getDeclName());
8363 R.addDecl(ND);
8364 if (ND->isCXXClassMember()) {
8365 // Figure out the correct naming class to add to the LookupResult.
8366 CXXRecordDecl *Record = nullptr;
8367 if (auto *NNS = TC.getCorrectionSpecifier())
8368 Record = NNS->getAsType()->getAsCXXRecordDecl();
8369 if (!Record)
8370 Record =
8371 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
8372 if (Record)
8373 R.setNamingClass(Record);
8374
8375 // Detect and handle the case where the decl might be an implicit
8376 // member.
8377 bool MightBeImplicitMember;
8378 if (!Consumer.isAddressOfOperand())
8379 MightBeImplicitMember = true;
8380 else if (!NewSS.isEmpty())
8381 MightBeImplicitMember = false;
8382 else if (R.isOverloadedResult())
8383 MightBeImplicitMember = false;
8384 else if (R.isUnresolvableResult())
8385 MightBeImplicitMember = true;
8386 else
8387 MightBeImplicitMember = isa<FieldDecl>(ND) ||
8388 isa<IndirectFieldDecl>(ND) ||
8389 isa<MSPropertyDecl>(ND);
8390
8391 if (MightBeImplicitMember)
8392 return SemaRef.BuildPossibleImplicitMemberExpr(
8393 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
8394 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
8395 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
8396 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
8397 Ivar->getIdentifier());
8398 }
8399 }
8400
8401 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
8402 /*AcceptInvalidDecl*/ true);
8403}
8404
8405namespace {
8406class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
8407 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
8408
8409public:
8410 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
8411 : TypoExprs(TypoExprs) {}
8412 bool VisitTypoExpr(TypoExpr *TE) {
8413 TypoExprs.insert(TE);
8414 return true;
8415 }
8416};
8417
8418class TransformTypos : public TreeTransform<TransformTypos> {
8419 typedef TreeTransform<TransformTypos> BaseTransform;
8420
8421 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
8422 // process of being initialized.
8423 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
8424 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
8425 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
8426 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
8427
8428 /// Emit diagnostics for all of the TypoExprs encountered.
8429 ///
8430 /// If the TypoExprs were successfully corrected, then the diagnostics should
8431 /// suggest the corrections. Otherwise the diagnostics will not suggest
8432 /// anything (having been passed an empty TypoCorrection).
8433 ///
8434 /// If we've failed to correct due to ambiguous corrections, we need to
8435 /// be sure to pass empty corrections and replacements. Otherwise it's
8436 /// possible that the Consumer has a TypoCorrection that failed to ambiguity
8437 /// and we don't want to report those diagnostics.
8438 void EmitAllDiagnostics(bool IsAmbiguous) {
8439 for (TypoExpr *TE : TypoExprs) {
8440 auto &State = SemaRef.getTypoExprState(TE);
8441 if (State.DiagHandler) {
8442 TypoCorrection TC = IsAmbiguous
8443 ? TypoCorrection() : State.Consumer->getCurrentCorrection();
8444 ExprResult Replacement = IsAmbiguous ? ExprError() : TransformCache[TE];
8445
8446 // Extract the NamedDecl from the transformed TypoExpr and add it to the
8447 // TypoCorrection, replacing the existing decls. This ensures the right
8448 // NamedDecl is used in diagnostics e.g. in the case where overload
8449 // resolution was used to select one from several possible decls that
8450 // had been stored in the TypoCorrection.
8451 if (auto *ND = getDeclFromExpr(
8452 Replacement.isInvalid() ? nullptr : Replacement.get()))
8453 TC.setCorrectionDecl(ND);
8454
8455 State.DiagHandler(TC);
8456 }
8457 SemaRef.clearDelayedTypo(TE);
8458 }
8459 }
8460
8461 /// Try to advance the typo correction state of the first unfinished TypoExpr.
8462 /// We allow advancement of the correction stream by removing it from the
8463 /// TransformCache which allows `TransformTypoExpr` to advance during the
8464 /// next transformation attempt.
8465 ///
8466 /// Any substitution attempts for the previous TypoExprs (which must have been
8467 /// finished) will need to be retried since it's possible that they will now
8468 /// be invalid given the latest advancement.
8469 ///
8470 /// We need to be sure that we're making progress - it's possible that the
8471 /// tree is so malformed that the transform never makes it to the
8472 /// `TransformTypoExpr`.
8473 ///
8474 /// Returns true if there are any untried correction combinations.
8475 bool CheckAndAdvanceTypoExprCorrectionStreams() {
8476 for (auto *TE : TypoExprs) {
8477 auto &State = SemaRef.getTypoExprState(TE);
8478 TransformCache.erase(TE);
8479 if (!State.Consumer->hasMadeAnyCorrectionProgress())
8480 return false;
8481 if (!State.Consumer->finished())
8482 return true;
8483 State.Consumer->resetCorrectionStream();
8484 }
8485 return false;
8486 }
8487
8488 NamedDecl *getDeclFromExpr(Expr *E) {
8489 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
8490 E = OverloadResolution[OE];
8491
8492 if (!E)
8493 return nullptr;
8494 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
8495 return DRE->getFoundDecl();
8496 if (auto *ME = dyn_cast<MemberExpr>(E))
8497 return ME->getFoundDecl();
8498 // FIXME: Add any other expr types that could be seen by the delayed typo
8499 // correction TreeTransform for which the corresponding TypoCorrection could
8500 // contain multiple decls.
8501 return nullptr;
8502 }
8503
8504 ExprResult TryTransform(Expr *E) {
8505 Sema::SFINAETrap Trap(SemaRef);
8506 ExprResult Res = TransformExpr(E);
8507 if (Trap.hasErrorOccurred() || Res.isInvalid())
8508 return ExprError();
8509
8510 return ExprFilter(Res.get());
8511 }
8512
8513 // Since correcting typos may intoduce new TypoExprs, this function
8514 // checks for new TypoExprs and recurses if it finds any. Note that it will
8515 // only succeed if it is able to correct all typos in the given expression.
8516 ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) {
8517 if (Res.isInvalid()) {
8518 return Res;
8519 }
8520 // Check to see if any new TypoExprs were created. If so, we need to recurse
8521 // to check their validity.
8522 Expr *FixedExpr = Res.get();
8523
8524 auto SavedTypoExprs = std::move(TypoExprs);
8525 auto SavedAmbiguousTypoExprs = std::move(AmbiguousTypoExprs);
8526 TypoExprs.clear();
8527 AmbiguousTypoExprs.clear();
8528
8529 FindTypoExprs(TypoExprs).TraverseStmt(FixedExpr);
8530 if (!TypoExprs.empty()) {
8531 // Recurse to handle newly created TypoExprs. If we're not able to
8532 // handle them, discard these TypoExprs.
8533 ExprResult RecurResult =
8534 RecursiveTransformLoop(FixedExpr, IsAmbiguous);
8535 if (RecurResult.isInvalid()) {
8536 Res = ExprError();
8537 // Recursive corrections didn't work, wipe them away and don't add
8538 // them to the TypoExprs set. Remove them from Sema's TypoExpr list
8539 // since we don't want to clear them twice. Note: it's possible the
8540 // TypoExprs were created recursively and thus won't be in our
8541 // Sema's TypoExprs - they were created in our `RecursiveTransformLoop`.
8542 auto &SemaTypoExprs = SemaRef.TypoExprs;
8543 for (auto *TE : TypoExprs) {
8544 TransformCache.erase(TE);
8545 SemaRef.clearDelayedTypo(TE);
8546
8547 auto SI = find(SemaTypoExprs, TE);
8548 if (SI != SemaTypoExprs.end()) {
8549 SemaTypoExprs.erase(SI);
8550 }
8551 }
8552 } else {
8553 // TypoExpr is valid: add newly created TypoExprs since we were
8554 // able to correct them.
8555 Res = RecurResult;
8556 SavedTypoExprs.set_union(TypoExprs);
8557 }
8558 }
8559
8560 TypoExprs = std::move(SavedTypoExprs);
8561 AmbiguousTypoExprs = std::move(SavedAmbiguousTypoExprs);
8562
8563 return Res;
8564 }
8565
8566 // Try to transform the given expression, looping through the correction
8567 // candidates with `CheckAndAdvanceTypoExprCorrectionStreams`.
8568 //
8569 // If valid ambiguous typo corrections are seen, `IsAmbiguous` is set to
8570 // true and this method immediately will return an `ExprError`.
8571 ExprResult RecursiveTransformLoop(Expr *E, bool &IsAmbiguous) {
8572 ExprResult Res;
8573 auto SavedTypoExprs = std::move(SemaRef.TypoExprs);
8574 SemaRef.TypoExprs.clear();
8575
8576 while (true) {
8577 Res = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8578
8579 // Recursion encountered an ambiguous correction. This means that our
8580 // correction itself is ambiguous, so stop now.
8581 if (IsAmbiguous)
8582 break;
8583
8584 // If the transform is still valid after checking for any new typos,
8585 // it's good to go.
8586 if (!Res.isInvalid())
8587 break;
8588
8589 // The transform was invalid, see if we have any TypoExprs with untried
8590 // correction candidates.
8591 if (!CheckAndAdvanceTypoExprCorrectionStreams())
8592 break;
8593 }
8594
8595 // If we found a valid result, double check to make sure it's not ambiguous.
8596 if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) {
8597 auto SavedTransformCache =
8598 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache);
8599
8600 // Ensure none of the TypoExprs have multiple typo correction candidates
8601 // with the same edit length that pass all the checks and filters.
8602 while (!AmbiguousTypoExprs.empty()) {
8603 auto TE = AmbiguousTypoExprs.back();
8604
8605 // TryTransform itself can create new Typos, adding them to the TypoExpr map
8606 // and invalidating our TypoExprState, so always fetch it instead of storing.
8607 SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition();
8608
8609 TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection();
8610 TypoCorrection Next;
8611 do {
8612 // Fetch the next correction by erasing the typo from the cache and calling
8613 // `TryTransform` which will iterate through corrections in
8614 // `TransformTypoExpr`.
8615 TransformCache.erase(TE);
8616 ExprResult AmbigRes = CheckForRecursiveTypos(TryTransform(E), IsAmbiguous);
8617
8618 if (!AmbigRes.isInvalid() || IsAmbiguous) {
8619 SemaRef.getTypoExprState(TE).Consumer->resetCorrectionStream();
8620 SavedTransformCache.erase(TE);
8621 Res = ExprError();
8622 IsAmbiguous = true;
8623 break;
8624 }
8625 } while ((Next = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection()) &&
8626 Next.getEditDistance(false) == TC.getEditDistance(false));
8627
8628 if (IsAmbiguous)
8629 break;
8630
8631 AmbiguousTypoExprs.remove(TE);
8632 SemaRef.getTypoExprState(TE).Consumer->restoreSavedPosition();
8633 TransformCache[TE] = SavedTransformCache[TE];
8634 }
8635 TransformCache = std::move(SavedTransformCache);
8636 }
8637
8638 // Wipe away any newly created TypoExprs that we don't know about. Since we
8639 // clear any invalid TypoExprs in `CheckForRecursiveTypos`, this is only
8640 // possible if a `TypoExpr` is created during a transformation but then
8641 // fails before we can discover it.
8642 auto &SemaTypoExprs = SemaRef.TypoExprs;
8643 for (auto Iterator = SemaTypoExprs.begin(); Iterator != SemaTypoExprs.end();) {
8644 auto TE = *Iterator;
8645 auto FI = find(TypoExprs, TE);
8646 if (FI != TypoExprs.end()) {
8647 Iterator++;
8648 continue;
8649 }
8650 SemaRef.clearDelayedTypo(TE);
8651 Iterator = SemaTypoExprs.erase(Iterator);
8652 }
8653 SemaRef.TypoExprs = std::move(SavedTypoExprs);
8654
8655 return Res;
8656 }
8657
8658public:
8659 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
8660 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
8661
8662 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
8663 MultiExprArg Args,
8664 SourceLocation RParenLoc,
8665 Expr *ExecConfig = nullptr) {
8666 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
8667 RParenLoc, ExecConfig);
8668 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
8669 if (Result.isUsable()) {
8670 Expr *ResultCall = Result.get();
8671 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
8672 ResultCall = BE->getSubExpr();
8673 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
8674 OverloadResolution[OE] = CE->getCallee();
8675 }
8676 }
8677 return Result;
8678 }
8679
8680 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
8681
8682 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
8683
8684 ExprResult Transform(Expr *E) {
8685 bool IsAmbiguous = false;
8686 ExprResult Res = RecursiveTransformLoop(E, IsAmbiguous);
8687
8688 if (!Res.isUsable())
8689 FindTypoExprs(TypoExprs).TraverseStmt(E);
8690
8691 EmitAllDiagnostics(IsAmbiguous);
8692
8693 return Res;
8694 }
8695
8696 ExprResult TransformTypoExpr(TypoExpr *E) {
8697 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
8698 // cached transformation result if there is one and the TypoExpr isn't the
8699 // first one that was encountered.
8700 auto &CacheEntry = TransformCache[E];
8701 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
8702 return CacheEntry;
8703 }
8704
8705 auto &State = SemaRef.getTypoExprState(E);
8706 assert(State.Consumer && "Cannot transform a cleared TypoExpr")(static_cast <bool> (State.Consumer && "Cannot transform a cleared TypoExpr"
) ? void (0) : __assert_fail ("State.Consumer && \"Cannot transform a cleared TypoExpr\""
, "clang/lib/Sema/SemaExprCXX.cpp", 8706, __extension__ __PRETTY_FUNCTION__
))
;
8707
8708 // For the first TypoExpr and an uncached TypoExpr, find the next likely
8709 // typo correction and return it.
8710 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
8711 if (InitDecl && TC.getFoundDecl() == InitDecl)
8712 continue;
8713 // FIXME: If we would typo-correct to an invalid declaration, it's
8714 // probably best to just suppress all errors from this typo correction.
8715 ExprResult NE = State.RecoveryHandler ?
8716 State.RecoveryHandler(SemaRef, E, TC) :
8717 attemptRecovery(SemaRef, *State.Consumer, TC);
8718 if (!NE.isInvalid()) {
8719 // Check whether there may be a second viable correction with the same
8720 // edit distance; if so, remember this TypoExpr may have an ambiguous
8721 // correction so it can be more thoroughly vetted later.
8722 TypoCorrection Next;
8723 if ((Next = State.Consumer->peekNextCorrection()) &&
8724 Next.getEditDistance(false) == TC.getEditDistance(false)) {
8725 AmbiguousTypoExprs.insert(E);
8726 } else {
8727 AmbiguousTypoExprs.remove(E);
8728 }
8729 assert(!NE.isUnset() &&(static_cast <bool> (!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult"
) ? void (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\""
, "clang/lib/Sema/SemaExprCXX.cpp", 8730, __extension__ __PRETTY_FUNCTION__
))
8730 "Typo was transformed into a valid-but-null ExprResult")(static_cast <bool> (!NE.isUnset() && "Typo was transformed into a valid-but-null ExprResult"
) ? void (0) : __assert_fail ("!NE.isUnset() && \"Typo was transformed into a valid-but-null ExprResult\""
, "clang/lib/Sema/SemaExprCXX.cpp", 8730, __extension__ __PRETTY_FUNCTION__
))
;
8731 return CacheEntry = NE;
8732 }
8733 }
8734 return CacheEntry = ExprError();
8735 }
8736};
8737}
8738
8739ExprResult
8740Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
8741 bool RecoverUncorrectedTypos,
8742 llvm::function_ref<ExprResult(Expr *)> Filter) {
8743 // If the current evaluation context indicates there are uncorrected typos
8744 // and the current expression isn't guaranteed to not have typos, try to
8745 // resolve any TypoExpr nodes that might be in the expression.
8746 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
8747 (E->isTypeDependent() || E->isValueDependent() ||
8748 E->isInstantiationDependent())) {
8749 auto TyposResolved = DelayedTypos.size();
8750 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
8751 TyposResolved -= DelayedTypos.size();
8752 if (Result.isInvalid() || Result.get() != E) {
8753 ExprEvalContexts.back().NumTypos -= TyposResolved;
8754 if (Result.isInvalid() && RecoverUncorrectedTypos) {
8755 struct TyposReplace : TreeTransform<TyposReplace> {
8756 TyposReplace(Sema &SemaRef) : TreeTransform(SemaRef) {}
8757 ExprResult TransformTypoExpr(clang::TypoExpr *E) {
8758 return this->SemaRef.CreateRecoveryExpr(E->getBeginLoc(),
8759 E->getEndLoc(), {});
8760 }
8761 } TT(*this);
8762 return TT.TransformExpr(E);
8763 }
8764 return Result;
8765 }
8766 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?")(static_cast <bool> (TyposResolved == 0 && "Corrected typo but got same Expr back?"
) ? void (0) : __assert_fail ("TyposResolved == 0 && \"Corrected typo but got same Expr back?\""
, "clang/lib/Sema/SemaExprCXX.cpp", 8766, __extension__ __PRETTY_FUNCTION__
))
;
8767 }
8768 return E;
8769}
8770
8771ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
8772 bool DiscardedValue, bool IsConstexpr,
8773 bool IsTemplateArgument) {
8774 ExprResult FullExpr = FE;
8775
8776 if (!FullExpr.get())
8777 return ExprError();
8778
8779 if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get()))
8780 return ExprError();
8781
8782 if (DiscardedValue) {
8783 // Top-level expressions default to 'id' when we're in a debugger.
8784 if (getLangOpts().DebuggerCastResultToId &&
8785 FullExpr.get()->getType() == Context.UnknownAnyTy) {
8786 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
8787 if (FullExpr.isInvalid())
8788 return ExprError();
8789 }
8790
8791 FullExpr = CheckPlaceholderExpr(FullExpr.get());
8792 if (FullExpr.isInvalid())
8793 return ExprError();
8794
8795 FullExpr = IgnoredValueConversions(FullExpr.get());
8796 if (FullExpr.isInvalid())
8797 return ExprError();
8798
8799 DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr);
8800 }
8801
8802 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get(), /*InitDecl=*/nullptr,
8803 /*RecoverUncorrectedTypos=*/true);
8804 if (FullExpr.isInvalid())
8805 return ExprError();
8806
8807 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
8808
8809 // At the end of this full expression (which could be a deeply nested
8810 // lambda), if there is a potential capture within the nested lambda,
8811 // have the outer capture-able lambda try and capture it.
8812 // Consider the following code:
8813 // void f(int, int);
8814 // void f(const int&, double);
8815 // void foo() {
8816 // const int x = 10, y = 20;
8817 // auto L = [=](auto a) {
8818 // auto M = [=](auto b) {
8819 // f(x, b); <-- requires x to be captured by L and M
8820 // f(y, a); <-- requires y to be captured by L, but not all Ms
8821 // };
8822 // };
8823 // }
8824
8825 // FIXME: Also consider what happens for something like this that involves
8826 // the gnu-extension statement-expressions or even lambda-init-captures:
8827 // void f() {
8828 // const int n = 0;
8829 // auto L = [&](auto a) {
8830 // +n + ({ 0; a; });
8831 // };
8832 // }
8833 //
8834 // Here, we see +n, and then the full-expression 0; ends, so we don't
8835 // capture n (and instead remove it from our list of potential captures),
8836 // and then the full-expression +n + ({ 0; }); ends, but it's too late
8837 // for us to see that we need to capture n after all.
8838
8839 LambdaScopeInfo *const CurrentLSI =
8840 getCurLambda(/*IgnoreCapturedRegions=*/true);
8841 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
8842 // even if CurContext is not a lambda call operator. Refer to that Bug Report
8843 // for an example of the code that might cause this asynchrony.
8844 // By ensuring we are in the context of a lambda's call operator
8845 // we can fix the bug (we only need to check whether we need to capture
8846 // if we are within a lambda's body); but per the comments in that
8847 // PR, a proper fix would entail :
8848 // "Alternative suggestion:
8849 // - Add to Sema an integer holding the smallest (outermost) scope
8850 // index that we are *lexically* within, and save/restore/set to
8851 // FunctionScopes.size() in InstantiatingTemplate's
8852 // constructor/destructor.
8853 // - Teach the handful of places that iterate over FunctionScopes to
8854 // stop at the outermost enclosing lexical scope."
8855 DeclContext *DC = CurContext;
8856 while (DC && isa<CapturedDecl>(DC))
8857 DC = DC->getParent();
8858 const bool IsInLambdaDeclContext = isLambdaCallOperator(DC);
8859 if (IsInLambdaDeclContext && CurrentLSI &&
8860 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
8861 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
8862 *this);
8863 return MaybeCreateExprWithCleanups(FullExpr);
8864}
8865
8866StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
8867 if (!FullStmt) return StmtError();
8868
8869 return MaybeCreateStmtWithCleanups(FullStmt);
8870}
8871
8872Sema::IfExistsResult
8873Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
8874 CXXScopeSpec &SS,
8875 const DeclarationNameInfo &TargetNameInfo) {
8876 DeclarationName TargetName = TargetNameInfo.getName();
8877 if (!TargetName)
8878 return IER_DoesNotExist;
8879
8880 // If the name itself is dependent, then the result is dependent.
8881 if (TargetName.isDependentName())
8882 return IER_Dependent;
8883
8884 // Do the redeclaration lookup in the current scope.
8885 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
8886 Sema::NotForRedeclaration);
8887 LookupParsedName(R, S, &SS);
8888 R.suppressDiagnostics();
8889
8890 switch (R.getResultKind()) {
8891 case LookupResult::Found:
8892 case LookupResult::FoundOverloaded:
8893 case LookupResult::FoundUnresolvedValue:
8894 case LookupResult::Ambiguous:
8895 return IER_Exists;
8896
8897 case LookupResult::NotFound:
8898 return IER_DoesNotExist;
8899
8900 case LookupResult::NotFoundInCurrentInstantiation:
8901 return IER_Dependent;
8902 }
8903
8904 llvm_unreachable("Invalid LookupResult Kind!")::llvm::llvm_unreachable_internal("Invalid LookupResult Kind!"
, "clang/lib/Sema/SemaExprCXX.cpp", 8904)
;
8905}
8906
8907Sema::IfExistsResult
8908Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
8909 bool IsIfExists, CXXScopeSpec &SS,
8910 UnqualifiedId &Name) {
8911 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
8912
8913 // Check for an unexpanded parameter pack.
8914 auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists;
8915 if (DiagnoseUnexpandedParameterPack(SS, UPPC) ||
8916 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC))
8917 return IER_Error;
8918
8919 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
8920}
8921
8922concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) {
8923 return BuildExprRequirement(E, /*IsSimple=*/true,
8924 /*NoexceptLoc=*/SourceLocation(),
8925 /*ReturnTypeRequirement=*/{});
8926}
8927
8928concepts::Requirement *
8929Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS,
8930 SourceLocation NameLoc, IdentifierInfo *TypeName,
8931 TemplateIdAnnotation *TemplateId) {
8932 assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) &&(static_cast <bool> (((!TypeName && TemplateId)
|| (TypeName && !TemplateId)) && "Exactly one of TypeName and TemplateId must be specified."
) ? void (0) : __assert_fail ("((!TypeName && TemplateId) || (TypeName && !TemplateId)) && \"Exactly one of TypeName and TemplateId must be specified.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 8933, __extension__ __PRETTY_FUNCTION__
))
8933 "Exactly one of TypeName and TemplateId must be specified.")(static_cast <bool> (((!TypeName && TemplateId)
|| (TypeName && !TemplateId)) && "Exactly one of TypeName and TemplateId must be specified."
) ? void (0) : __assert_fail ("((!TypeName && TemplateId) || (TypeName && !TemplateId)) && \"Exactly one of TypeName and TemplateId must be specified.\""
, "clang/lib/Sema/SemaExprCXX.cpp", 8933, __extension__ __PRETTY_FUNCTION__
))
;
8934 TypeSourceInfo *TSI = nullptr;
8935 if (TypeName) {
8936 QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc,
8937 SS.getWithLocInContext(Context), *TypeName,
8938 NameLoc, &TSI, /*DeducedTSTContext=*/false);
8939 if (T.isNull())
8940 return nullptr;
8941 } else {
8942 ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(),
8943 TemplateId->NumArgs);
8944 TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS,
8945 TemplateId->TemplateKWLoc,
8946 TemplateId->Template, TemplateId->Name,
8947 TemplateId->TemplateNameLoc,
8948 TemplateId->LAngleLoc, ArgsPtr,
8949 TemplateId->RAngleLoc);
8950 if (T.isInvalid())
8951 return nullptr;
8952 if (GetTypeFromParser(T.get(), &TSI).isNull())
8953 return nullptr;
8954 }
8955 return BuildTypeRequirement(TSI);
8956}
8957
8958concepts::Requirement *
8959Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) {
8960 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc,
8961 /*ReturnTypeRequirement=*/{});
8962}
8963
8964concepts::Requirement *
8965Sema::ActOnCompoundRequirement(
8966 Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS,
8967 TemplateIdAnnotation *TypeConstraint, unsigned Depth) {
8968 // C++2a [expr.prim.req.compound] p1.3.3
8969 // [..] the expression is deduced against an invented function template
8970 // F [...] F is a void function template with a single type template
8971 // parameter T declared with the constrained-parameter. Form a new
8972 // cv-qualifier-seq cv by taking the union of const and volatile specifiers
8973 // around the constrained-parameter. F has a single parameter whose
8974 // type-specifier is cv T followed by the abstract-declarator. [...]
8975 //
8976 // The cv part is done in the calling function - we get the concept with
8977 // arguments and the abstract declarator with the correct CV qualification and
8978 // have to synthesize T and the single parameter of F.
8979 auto &II = Context.Idents.get("expr-type");
8980 auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext,
8981 SourceLocation(),
8982 SourceLocation(), Depth,
8983 /*Index=*/0, &II,
8984 /*Typename=*/true,
8985 /*ParameterPack=*/false,
8986 /*HasTypeConstraint=*/true);
8987
8988 if (BuildTypeConstraint(SS, TypeConstraint, TParam,
8989 /*EllipsisLoc=*/SourceLocation(),
8990 /*AllowUnexpandedPack=*/true))
8991 // Just produce a requirement with no type requirements.
8992 return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {});
8993
8994 auto *TPL = TemplateParameterList::Create(Context, SourceLocation(),
8995 SourceLocation(),
8996 ArrayRef<NamedDecl *>(TParam),
8997 SourceLocation(),
8998 /*RequiresClause=*/nullptr);
8999 return BuildExprRequirement(
9000 E, /*IsSimple=*/false, NoexceptLoc,
9001 concepts::ExprRequirement::ReturnTypeRequirement(TPL));
9002}
9003
9004concepts::ExprRequirement *
9005Sema::BuildExprRequirement(
9006 Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
9007 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
9008 auto Status = concepts::ExprRequirement::SS_Satisfied;
9009 ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr;
9010 if (E->isInstantiationDependent() || ReturnTypeRequirement.isDependent())
9011 Status = concepts::ExprRequirement::SS_Dependent;
9012 else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can)
9013 Status = concepts::ExprRequirement::SS_NoexceptNotMet;
9014 else if (ReturnTypeRequirement.isSubstitutionFailure())
9015 Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure;
9016 else if (ReturnTypeRequirement.isTypeConstraint()) {
9017 // C++2a [expr.prim.req]p1.3.3
9018 // The immediately-declared constraint ([temp]) of decltype((E)) shall
9019 // be satisfied.
9020 TemplateParameterList *TPL =
9021 ReturnTypeRequirement.getTypeConstraintTemplateParameterList();
9022 QualType MatchedType =
9023 Context.getReferenceQualifiedType(E).getCanonicalType();
9024 llvm::SmallVector<TemplateArgument, 1> Args;
9025 Args.push_back(TemplateArgument(MatchedType));
9026
9027 auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0));
9028
9029 TemplateArgumentList TAL(TemplateArgumentList::OnStack, Args);
9030 MultiLevelTemplateArgumentList MLTAL(Param, TAL.asArray(),
9031 /*Final=*/false);
9032 MLTAL.addOuterRetainedLevels(TPL->getDepth());
9033 Expr *IDC = Param->getTypeConstraint()->getImmediatelyDeclaredConstraint();
9034 ExprResult Constraint = SubstExpr(IDC, MLTAL);
9035 if (Constraint.isInvalid()) {
9036 Status = concepts::ExprRequirement::SS_ExprSubstitutionFailure;
9037 } else {
9038 SubstitutedConstraintExpr =
9039 cast<ConceptSpecializationExpr>(Constraint.get());
9040 if (!SubstitutedConstraintExpr->isSatisfied())
9041 Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied;
9042 }
9043 }
9044 return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc,
9045 ReturnTypeRequirement, Status,
9046 SubstitutedConstraintExpr);
9047}
9048
9049concepts::ExprRequirement *
9050Sema::BuildExprRequirement(
9051 concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic,
9052 bool IsSimple, SourceLocation NoexceptLoc,
9053 concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) {
9054 return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic,
9055 IsSimple, NoexceptLoc,
9056 ReturnTypeRequirement);
9057}
9058
9059concepts::TypeRequirement *
9060Sema::BuildTypeRequirement(TypeSourceInfo *Type) {
9061 return new (Context) concepts::TypeRequirement(Type);
9062}
9063
9064concepts::TypeRequirement *
9065Sema::BuildTypeRequirement(
9066 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
9067 return new (Context) concepts::TypeRequirement(SubstDiag);
9068}
9069
9070concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) {
9071 return BuildNestedRequirement(Constraint);
9072}
9073
9074concepts::NestedRequirement *
9075Sema::BuildNestedRequirement(Expr *Constraint) {
9076 ConstraintSatisfaction Satisfaction;
9077 if (!Constraint->isInstantiationDependent() &&
9078 CheckConstraintSatisfaction(nullptr, {Constraint}, /*TemplateArgs=*/{},
9079 Constraint->getSourceRange(), Satisfaction))
9080 return nullptr;
9081 return new (Context) concepts::NestedRequirement(Context, Constraint,
9082 Satisfaction);
9083}
9084
9085concepts::NestedRequirement *
9086Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity,
9087 const ASTConstraintSatisfaction &Satisfaction) {
9088 return new (Context) concepts::NestedRequirement(
9089 InvalidConstraintEntity,
9090 ASTConstraintSatisfaction::Rebuild(Context, Satisfaction));
9091}
9092
9093RequiresExprBodyDecl *
9094Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc,
9095 ArrayRef<ParmVarDecl *> LocalParameters,
9096 Scope *BodyScope) {
9097 assert(BodyScope)(static_cast <bool> (BodyScope) ? void (0) : __assert_fail
("BodyScope", "clang/lib/Sema/SemaExprCXX.cpp", 9097, __extension__
__PRETTY_FUNCTION__))
;
9098
9099 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext,
9100 RequiresKWLoc);
9101
9102 PushDeclContext(BodyScope, Body);
9103
9104 for (ParmVarDecl *Param : LocalParameters) {
9105 if (Param->hasDefaultArg())
9106 // C++2a [expr.prim.req] p4
9107 // [...] A local parameter of a requires-expression shall not have a
9108 // default argument. [...]
9109 Diag(Param->getDefaultArgRange().getBegin(),
9110 diag::err_requires_expr_local_parameter_default_argument);
9111 // Ignore default argument and move on
9112
9113 Param->setDeclContext(Body);
9114 // If this has an identifier, add it to the scope stack.
9115 if (Param->getIdentifier()) {
9116 CheckShadow(BodyScope, Param);
9117 PushOnScopeChains(Param, BodyScope);
9118 }
9119 }
9120 return Body;
9121}
9122
9123void Sema::ActOnFinishRequiresExpr() {
9124 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "clang/lib/Sema/SemaExprCXX.cpp", 9124, __extension__ __PRETTY_FUNCTION__
))
;
9125 CurContext = CurContext->getLexicalParent();
9126 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "clang/lib/Sema/SemaExprCXX.cpp", 9126, __extension__ __PRETTY_FUNCTION__
))
;
9127}
9128
9129ExprResult
9130Sema::ActOnRequiresExpr(SourceLocation RequiresKWLoc,
9131 RequiresExprBodyDecl *Body,
9132 ArrayRef<ParmVarDecl *> LocalParameters,
9133 ArrayRef<concepts::Requirement *> Requirements,
9134 SourceLocation ClosingBraceLoc) {
9135 auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LocalParameters,
9136 Requirements, ClosingBraceLoc);
9137 if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE))
9138 return ExprError();
9139 return RE;
9140}