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 | |
2 | |
3 | |
4 | |
5 | |
6 | |
7 | |
8 | |
9 | |
10 | |
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> |
49 | using namespace clang; |
50 | using namespace sema; |
51 | |
52 | |
53 | |
54 | |
55 | |
56 | ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, |
57 | SourceLocation NameLoc, |
58 | IdentifierInfo &Name) { |
59 | NestedNameSpecifier *NNS = SS.getScopeRep(); |
60 | |
61 | |
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 | |
71 | |
72 | assert(NNS->getAsIdentifier() == &Name && "not a constructor name"); |
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"); |
82 | } |
83 | |
84 | |
85 | |
86 | return CreateParsedType(Type, |
87 | Context.getTrivialTypeSourceInfo(Type, NameLoc)); |
88 | } |
89 | |
90 | ParsedType 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() && |
96 | "not a constructor name"); |
97 | |
98 | |
99 | |
100 | |
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 | |
110 | |
111 | |
112 | |
113 | |
114 | |
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 | |
126 | |
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, false); |
136 | |
137 | return ParsedType::make(T); |
138 | } |
139 | |
140 | ParsedType Sema::getDestructorName(SourceLocation TildeLoc, |
141 | IdentifierInfo &II, |
142 | SourceLocation NameLoc, |
143 | Scope *S, CXXScopeSpec &SS, |
144 | ParsedType ObjectTypePtr, |
145 | bool EnteringContext) { |
146 | |
147 | |
148 | |
149 | |
150 | |
151 | |
152 | |
153 | |
154 | |
155 | |
156 | |
157 | |
158 | |
159 | |
160 | |
161 | |
162 | |
163 | |
164 | |
165 | |
166 | |
167 | |
168 | |
169 | |
170 | |
171 | |
172 | |
173 | |
174 | |
175 | if (SS.isInvalid()) |
176 | return nullptr; |
177 | |
178 | |
179 | bool Failed = false; |
180 | |
181 | llvm::SmallVector<NamedDecl*, 8> FoundDecls; |
182 | llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet; |
183 | |
184 | |
185 | |
186 | |
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 | |
209 | |
210 | |
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 | |
220 | |
221 | |
222 | |
223 | |
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, 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 | |
300 | |
301 | |
302 | |
303 | |
304 | |
305 | |
306 | |
307 | |
308 | |
309 | |
310 | |
311 | |
312 | |
313 | |
314 | |
315 | |
316 | |
317 | |
318 | |
319 | |
320 | |
321 | |
322 | |
323 | |
324 | |
325 | |
326 | |
327 | |
328 | |
329 | |
330 | |
331 | |
332 | |
333 | |
334 | if (NestedNameSpecifier *Prefix = |
335 | SS.isSet() ? SS.getScopeRep()->getPrefix() : nullptr) { |
336 | |
337 | |
338 | |
339 | |
340 | |
341 | CXXScopeSpec PrefixSS; |
342 | PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data())); |
343 | if (ParsedType T = LookupInNestedNameSpec(PrefixSS)) |
344 | return T; |
345 | } else { |
346 | |
347 | |
348 | |
349 | |
350 | |
351 | |
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 | |
363 | |
364 | |
365 | QualType T = CheckTypenameType(ETK_None, SourceLocation(), |
366 | SS.getWithLocInContext(Context), |
367 | II, NameLoc); |
368 | return ParsedType::make(T); |
369 | } |
370 | |
371 | |
372 | |
373 | unsigned NumNonExtensionDecls = FoundDecls.size(); |
374 | |
375 | if (SS.isSet()) { |
376 | |
377 | |
378 | |
379 | |
380 | |
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 | |
390 | |
391 | |
392 | |
393 | |
394 | |
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 | |
407 | |
408 | |
409 | |
410 | FoundDecls.resize(NumNonExtensionDecls); |
411 | |
412 | |
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 | |
420 | auto MakeFixItHint = [&]{ |
421 | const CXXRecordDecl *Destroyed = nullptr; |
422 | |
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 | |
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() && |
440 | "should only reject a type result if we have a search type"); |
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 | |
466 | ParsedType 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 && |
477 | "unexpected type in getDestructorType"); |
478 | QualType T = BuildDecltypeType(DS.getRepAsExpr()); |
479 | |
480 | |
481 | |
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 | |
493 | bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, |
494 | const UnqualifiedId &Name, bool IsUDSuffix) { |
495 | assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId); |
496 | if (!IsUDSuffix) { |
497 | |
498 | |
499 | |
500 | |
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 | |
522 | |
523 | |
524 | |
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"); |
537 | } |
538 | |
539 | |
540 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, |
541 | SourceLocation TypeidLoc, |
542 | TypeSourceInfo *Operand, |
543 | SourceLocation RParenLoc) { |
544 | |
545 | |
546 | |
547 | |
548 | |
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 | |
568 | ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, |
569 | SourceLocation TypeidLoc, |
570 | Expr *E, |
571 | SourceLocation RParenLoc) { |
572 | bool WasEvaluated = false; |
573 | if (E && !E->isTypeDependent()) { |
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 | |
584 | |
585 | |
586 | if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) |
587 | return ExprError(); |
588 | |
589 | |
590 | |
591 | |
592 | |
593 | if (RecordD->isPolymorphic() && E->isGLValue()) { |
594 | if (isUnevaluatedContext()) { |
595 | |
596 | |
597 | ExprResult Result = TransformToPotentiallyEvaluated(E); |
598 | if (Result.isInvalid()) |
599 | return ExprError(); |
600 | E = Result.get(); |
601 | } |
602 | |
603 | |
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 | |
615 | |
616 | |
617 | |
618 | |
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()) |
628 | return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) |
629 | << E->getType()); |
630 | else if (!inTemplateInstantiation() && |
631 | E->HasSideEffects(Context, WasEvaluated)) { |
632 | |
633 | |
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 | |
644 | ExprResult |
645 | Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, |
646 | bool isType, void *TyOrExpr, SourceLocation RParenLoc) { |
647 | |
648 | if (getLangOpts().OpenCLCPlusPlus) { |
649 | return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) |
650 | << "typeid"); |
651 | } |
652 | |
653 | |
654 | if (!getStdNamespace()) |
655 | return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid)); |
656 | |
657 | if (!CXXTypeInfoDecl) { |
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 | |
663 | |
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) { |
673 | return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); |
674 | } |
675 | |
676 | QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl); |
677 | |
678 | if (isType) { |
679 | |
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 | |
693 | ExprResult Result = |
694 | BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc); |
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 | |
706 | |
707 | static void |
708 | getUuidAttrOfType(Sema &SemaRef, QualType QT, |
709 | llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { |
710 | |
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 | |
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 | |
743 | ExprResult 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 | |
763 | ExprResult 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 | |
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 | |
786 | ExprResult |
787 | Sema::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 | |
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 | |
807 | return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); |
808 | } |
809 | |
810 | |
811 | ExprResult |
812 | Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { |
813 | assert((Kind == tok::kw_true || Kind == tok::kw_false) && |
814 | "Unknown C++ Boolean value!"); |
815 | return new (Context) |
816 | CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); |
817 | } |
818 | |
819 | |
820 | ExprResult |
821 | Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { |
822 | return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); |
823 | } |
824 | |
825 | |
826 | ExprResult |
827 | Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { |
828 | bool IsThrownVarInScope = false; |
829 | if (Ex) { |
830 | |
831 | |
832 | |
833 | |
834 | |
835 | |
836 | |
837 | |
838 | |
839 | |
840 | |
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 | |
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 | |
863 | ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, |
864 | bool IsThrownVarInScope) { |
865 | |
866 | if (!getLangOpts().CXXExceptions && |
867 | !getSourceManager().isInSystemHeader(OpLoc) && !getLangOpts().CUDA) { |
868 | |
869 | targetDiag(OpLoc, diag::err_exceptions_disabled) << "throw"; |
870 | } |
871 | |
872 | |
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 | |
882 | |
883 | |
884 | |
885 | |
886 | |
887 | |
888 | |
889 | |
890 | |
891 | |
892 | |
893 | |
894 | |
895 | |
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 | |
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 | |
919 | static void |
920 | collectPublicBases(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 | |
929 | |
930 | if (BS.isVirtual()) |
931 | NewSubobject = VBases.insert(BaseDecl).second; |
932 | else |
933 | NewSubobject = true; |
934 | |
935 | if (NewSubobject) |
936 | ++SubobjectsSeen[BaseDecl]; |
937 | |
938 | |
939 | bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; |
940 | if (PublicPath) |
941 | PublicSubobjectsSeen.insert(BaseDecl); |
942 | |
943 | |
944 | collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, |
945 | PublicPath); |
946 | } |
947 | } |
948 | |
949 | static 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 | true); |
958 | |
959 | for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { |
960 | |
961 | if (SubobjectsSeen[PublicSubobject] > 1) |
962 | continue; |
963 | |
964 | Objects.push_back(PublicSubobject); |
965 | } |
966 | } |
967 | |
968 | |
969 | bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, |
970 | QualType ExceptionObjectTy, Expr *E) { |
971 | |
972 | |
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 | |
997 | CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); |
998 | if (!RD) |
999 | return false; |
1000 | |
1001 | |
1002 | |
1003 | MarkVTableUsed(ThrowLoc, RD); |
1004 | |
1005 | |
1006 | if (isPointer) |
1007 | return false; |
1008 | |
1009 | |
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 | |
1021 | |
1022 | |
1023 | if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
1024 | |
1025 | |
1026 | |
1027 | llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; |
1028 | getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); |
1029 | |
1030 | for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { |
1031 | |
1032 | |
1033 | |
1034 | |
1035 | CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); |
1036 | if (!CD || CD->isDeleted()) |
1037 | continue; |
1038 | |
1039 | |
1040 | MarkFunctionReferenced(E->getExprLoc(), CD); |
1041 | |
1042 | |
1043 | |
1044 | if (CD->isTrivial()) |
1045 | continue; |
1046 | |
1047 | |
1048 | |
1049 | |
1050 | |
1051 | |
1052 | |
1053 | Context.addCopyConstructorForExceptionObject(Subobject, CD); |
1054 | |
1055 | |
1056 | |
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 | |
1065 | |
1066 | |
1067 | |
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 | |
1082 | static 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 | |
1091 | |
1092 | |
1093 | |
1094 | |
1095 | |
1096 | |
1097 | |
1098 | |
1099 | |
1100 | |
1101 | |
1102 | |
1103 | |
1104 | |
1105 | |
1106 | |
1107 | |
1108 | |
1109 | |
1110 | |
1111 | |
1112 | |
1113 | |
1114 | |
1115 | |
1116 | |
1117 | |
1118 | |
1119 | |
1120 | |
1121 | |
1122 | |
1123 | |
1124 | |
1125 | |
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 | |
1146 | |
1147 | |
1148 | if (CurLSI && isLambdaCallOperator(CurDC)) { |
1149 | assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && |
1150 | "While computing 'this' capture-type for a generic lambda, when we " |
1151 | "run out of enclosing LSI's, yet the enclosing DC is a " |
1152 | "lambda-call-operator we must be (i.e. Current LSI) in a generic " |
1153 | "lambda call oeprator"); |
1154 | assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)); |
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 | |
1190 | QualType 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 | |
1203 | |
1204 | |
1205 | QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC)); |
1206 | |
1207 | |
1208 | ThisTy = Context.getPointerType(ClassTy); |
1209 | } |
1210 | |
1211 | |
1212 | |
1213 | |
1214 | if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) |
1215 | return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, |
1216 | CurContext, Context); |
1217 | return ThisTy; |
1218 | } |
1219 | |
1220 | Sema::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 | |
1244 | Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { |
1245 | if (Enabled) { |
1246 | S.CXXThisTypeOverride = OldCXXThisTypeOverride; |
1247 | } |
1248 | } |
1249 | |
1250 | static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) { |
1251 | SourceLocation DiagLoc = LSI->IntroducerRange.getEnd(); |
| 24 | | Called C++ object pointer is null |
|
1252 | assert(!LSI->isCXXThisCaptured()); |
1253 | |
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 | |
1262 | bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, |
1263 | bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, |
1264 | const bool ByCopy) { |
1265 | |
1266 | if (isUnevaluatedContext() && !Explicit) |
1267 | return true; |
1268 | |
1269 | assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value"); |
| |
1270 | |
1271 | const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt |
| |
1272 | ? *FunctionScopeIndexToStopAt |
1273 | : FunctionScopes.size() - 1; |
1274 | |
1275 | |
1276 | |
1277 | |
1278 | |
1279 | |
1280 | |
1281 | |
1282 | |
1283 | |
1284 | |
1285 | |
1286 | |
1287 | |
1288 | |
1289 | |
1290 | |
1291 | |
1292 | |
1293 | |
1294 | |
1295 | |
1296 | |
1297 | |
1298 | unsigned NumCapturingClosures = 0; |
1299 | for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { |
| |
| 9 | | Loop condition is true. Entering loop body | |
|
1300 | if (CapturingScopeInfo *CSI = |
| |
1301 | dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { |
| 10 | | Assuming the object is a 'CastReturnType' | |
|
1302 | if (CSI->CXXThisCaptureIndex != 0) { |
| 12 | | Assuming field 'CXXThisCaptureIndex' is equal to 0 | |
|
| |
1303 | |
1304 | CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); |
1305 | break; |
1306 | } |
1307 | LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); |
| 14 | | Assuming 'CSI' is not a 'CastReturnType' | |
|
| 15 | | 'LSI' initialized to a null pointer value | |
|
1308 | if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { |
1309 | |
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 || |
| 16 | | Assuming field 'ImpCaptureStyle' is not equal to ImpCap_LambdaByref | |
|
1319 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || |
| 17 | | Assuming field 'ImpCaptureStyle' is not equal to ImpCap_LambdaByval | |
|
1320 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || |
| 18 | | Assuming field 'ImpCaptureStyle' is not equal to ImpCap_Block | |
|
1321 | CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || |
| 19 | | Assuming field 'ImpCaptureStyle' is not equal to ImpCap_CapturedRegion | |
|
1322 | (Explicit && idx == MaxFunctionScopesIndex)) { |
1323 | |
1324 | |
1325 | |
1326 | |
1327 | |
1328 | NumCapturingClosures++; |
1329 | continue; |
1330 | } |
1331 | |
1332 | if (BuildAndDiagnose) |
| |
1333 | Diag(Loc, diag::err_this_capture) |
1334 | << (Explicit && idx == MaxFunctionScopesIndex); |
1335 | |
1336 | if (!Explicit) |
| |
1337 | buildLambdaThisCaptureFixit(*this, LSI); |
| 22 | | Passing null pointer value via 2nd parameter 'LSI' | |
|
| 23 | | Calling 'buildLambdaThisCaptureFixit' | |
|
1338 | return true; |
1339 | } |
1340 | break; |
1341 | } |
1342 | if (!BuildAndDiagnose) return false; |
1343 | |
1344 | |
1345 | |
1346 | |
1347 | |
1348 | |
1349 | |
1350 | |
1351 | |
1352 | |
1353 | assert((!ByCopy || |
1354 | isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && |
1355 | "Only a lambda can capture the enclosing object (referred to by " |
1356 | "*this) by copy"); |
1357 | QualType ThisTy = getCurrentThisType(); |
1358 | for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; |
1359 | --idx, --NumCapturingClosures) { |
1360 | CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); |
1361 | |
1362 | |
1363 | |
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 | |
1372 | ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { |
1373 | |
1374 | |
1375 | |
1376 | |
1377 | QualType ThisTy = getCurrentThisType(); |
1378 | if (ThisTy.isNull()) |
| |
1379 | return Diag(Loc, diag::err_invalid_this_use); |
1380 | return BuildCXXThisExpr(Loc, ThisTy, false); |
| 2 | | Calling 'Sema::BuildCXXThisExpr' | |
|
1381 | } |
1382 | |
1383 | Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, |
1384 | bool IsImplicit) { |
1385 | if (getLangOpts().HLSL && Type.getTypePtr()->isPointerType()) { |
| 3 | | Assuming field 'HLSL' is 0 | |
|
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); |
| 4 | | Calling 'Sema::MarkThisReferenced' | |
|
1394 | return This; |
1395 | } |
1396 | |
1397 | void Sema::MarkThisReferenced(CXXThisExpr *This) { |
1398 | CheckCXXThisCapture(This->getExprLoc()); |
| 5 | | Calling 'Sema::CheckCXXThisCapture' | |
|
1399 | } |
1400 | |
1401 | bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { |
1402 | |
1403 | |
1404 | if (CXXThisTypeOverride.isNull()) |
1405 | return false; |
1406 | |
1407 | |
1408 | |
1409 | CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); |
1410 | return Class && Class->isBeingDefined(); |
1411 | } |
1412 | |
1413 | |
1414 | |
1415 | |
1416 | |
1417 | ExprResult |
1418 | Sema::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 | |
1434 | |
1435 | |
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 | |
1445 | ExprResult |
1446 | Sema::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) && |
1455 | "List initialization must have exactly one expression."); |
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 | |
1471 | |
1472 | |
1473 | |
1474 | |
1475 | |
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); |
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 | |
1532 | |
1533 | |
1534 | |
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 | |
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 | |
1552 | |
1553 | |
1554 | |
1555 | if (Ty->isFunctionType()) |
1556 | return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) |
1557 | << Ty << FullRange); |
1558 | |
1559 | |
1560 | |
1561 | |
1562 | if (!Ty->isVoidType() && |
1563 | RequireCompleteType(TyBeginLoc, ElemTy, |
1564 | diag::err_invalid_incomplete_type_use, FullRange)) |
1565 | return ExprError(); |
1566 | |
1567 | |
1568 | |
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 | |
1584 | |
1585 | |
1586 | |
1587 | |
1588 | |
1589 | |
1590 | |
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(), nullptr, CurFPFeatureOverrides(), |
1598 | Locs.getBegin(), Locs.getEnd()); |
1599 | } |
1600 | |
1601 | return Result; |
1602 | } |
1603 | |
1604 | bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { |
1605 | |
1606 | const FunctionDecl *Caller = getCurFunctionDecl(true); |
1607 | if (getLangOpts().CUDA) { |
1608 | auto CallPreference = IdentifyCUDAPreference(Caller, Method); |
1609 | |
1610 | if (CallPreference < CFP_WrongSide) |
1611 | return false; |
1612 | if (CallPreference == CFP_WrongSide) { |
1613 | |
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 | |
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 | |
1633 | |
1634 | return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { |
1635 | assert(FD->getNumParams() == 1 && |
1636 | "Only single-operand functions should be in PreventedBy"); |
1637 | return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice; |
1638 | }); |
1639 | } |
1640 | |
1641 | |
1642 | |
1643 | static 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 | |
1668 | namespace { |
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 | |
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 | |
1699 | if (S.getLangOpts().CUDA) |
1700 | if (auto *Caller = S.getCurFunctionDecl(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 | |
1709 | |
1710 | |
1711 | if (Destroying != Other.Destroying) |
1712 | return Destroying; |
1713 | |
1714 | |
1715 | |
1716 | |
1717 | |
1718 | if (HasAlignValT != Other.HasAlignValT) |
1719 | return HasAlignValT == WantAlign; |
1720 | |
1721 | if (HasSizeT != Other.HasSizeT) |
1722 | return HasSizeT == WantSize; |
1723 | |
1724 | |
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 | |
1736 | |
1737 | |
1738 | |
1739 | static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { |
1740 | return S.getLangOpts().AlignedAllocation && |
1741 | S.getASTContext().getTypeAlignIfKnown(AllocType) > |
1742 | S.getASTContext().getTargetInfo().getNewAlign(); |
1743 | } |
1744 | |
1745 | |
1746 | |
1747 | static 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 | |
1769 | |
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 | |
1782 | |
1783 | |
1784 | |
1785 | static 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 | |
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 | |
1799 | ops.suppressDiagnostics(); |
1800 | |
1801 | |
1802 | if (ops.empty()) return false; |
1803 | |
1804 | |
1805 | |
1806 | if (ops.isAmbiguous()) return false; |
1807 | |
1808 | |
1809 | |
1810 | |
1811 | auto Best = resolveDeallocationOverload( |
1812 | S, ops, false, |
1813 | hasNewExtendedAlignment(S, allocType)); |
1814 | return Best && Best.HasSizeT; |
1815 | } |
1816 | |
1817 | |
1818 | |
1819 | |
1820 | |
1821 | |
1822 | |
1823 | |
1824 | |
1825 | |
1826 | |
1827 | |
1828 | |
1829 | |
1830 | |
1831 | |
1832 | |
1833 | ExprResult |
1834 | Sema::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 | |
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 | |
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 | |
1867 | |
1868 | if (getLangOpts().CPlusPlus14) { |
1869 | |
1870 | |
1871 | |
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, 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 | |
1905 | static 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) && |
1918 | "Shouldn't create list CXXConstructExprs for arrays."); |
1919 | return true; |
1920 | } |
1921 | return false; |
1922 | } |
1923 | |
1924 | bool |
1925 | Sema::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 | |
1938 | |
1939 | void 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 | |
1956 | ExprResult 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."); |
1970 | initStyle = CXXNewExpr::CallInit; |
1971 | } else if (Initializer && isa<InitListExpr>(Initializer)) |
1972 | initStyle = CXXNewExpr::ListInit; |
1973 | else { |
1974 | assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || |
1975 | isa<CXXConstructExpr>(Initializer)) && |
1976 | "Initializer expression that cannot have been implicitly created."); |
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"); |
1983 | Exprs = MultiExprArg(List->getExprs(), List->getNumExprs()); |
1984 | } |
1985 | |
1986 | |
1987 | |
1988 | |
1989 | InitializationKind Kind |
1990 | |
1991 | |
1992 | |
1993 | = initStyle == CXXNewExpr::NoInit |
1994 | ? InitializationKind::CreateDefault(TypeRange.getBegin()) |
1995 | |
1996 | |
1997 | |
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 | |
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 | << 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); |
2058 | return ExprError(); |
2059 | } |
2060 | AllocType = DeducedType; |
2061 | } |
2062 | |
2063 | |
2064 | |
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 | |
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 | |
2098 | |
2099 | |
2100 | |
2101 | |
2102 | |
2103 | |
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?"); |
2109 | |
2110 | ConvertedSize = PerformImplicitConversion(*ArraySize, Context.getSizeType(), |
2111 | AA_Converting); |
2112 | |
2113 | if (!ConvertedSize.isInvalid() && |
2114 | (*ArraySize)->getType()->getAs<RecordType>()) |
2115 | |
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(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 | |
2186 | |
2187 | |
2188 | |
2189 | |
2190 | |
2191 | |
2192 | |
2193 | |
2194 | |
2195 | |
2196 | |
2197 | |
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 | |
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 | |
2227 | |
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 | |
2248 | |
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 | |
2261 | |
2262 | |
2263 | |
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 | |
2274 | |
2275 | |
2276 | |
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 | |
2285 | std::optional<llvm::APInt> AllocationSize; |
2286 | if (!ArraySize && !AllocType->isDependentType()) { |
2287 | |
2288 | AllocationSize = SingleEltSize; |
2289 | } else if (KnownArraySize && !AllocType->isDependentType()) { |
2290 | |
2291 | bool Overflow; |
2292 | AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) |
2293 | .umul_ov(SingleEltSize, Overflow); |
2294 | (void)Overflow; |
2295 | assert( |
2296 | !Overflow && |
2297 | "Expected that all the overflows would have been handled already."); |
2298 | } |
2299 | |
2300 | IntegerLiteral AllocationSizeLiteral( |
2301 | Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)), |
2302 | SizeTy, SourceLocation()); |
2303 | |
2304 | |
2305 | OpaqueValueExpr OpaqueAllocationSize(SourceLocation(), SizeTy, VK_PRValue, |
2306 | OK_Ordinary, nullptr); |
2307 | |
2308 | |
2309 | |
2310 | |
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 | |
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, nullptr, CallArgs, |
2336 | false, StartLoc, Range, CallType); |
2337 | |
2338 | |
2339 | |
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 | |
2353 | |
2354 | |
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 | |
2363 | |
2364 | if (!AllocType->isDependentType() && |
2365 | !Expr::hasAnyTypeDependentArguments(Exprs)) { |
2366 | |
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 | |
2388 | |
2389 | |
2390 | if (CXXBindTemporaryExpr *Binder = |
2391 | dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) |
2392 | FullInit = Binder->getSubExpr(); |
2393 | |
2394 | Initializer = FullInit.get(); |
2395 | |
2396 | |
2397 | |
2398 | |
2399 | if (ArraySize && !*ArraySize) { |
2400 | auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); |
2401 | if (CAT) { |
2402 | |
2403 | |
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 | |
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 | |
2433 | |
2434 | bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, |
2435 | SourceRange R) { |
2436 | |
2437 | |
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 | |
2472 | static 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 | |
2481 | |
2482 | NamedDecl *D = (*Alloc)->getUnderlyingDecl(); |
2483 | |
2484 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { |
2485 | S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), |
2486 | nullptr, Args, |
2487 | Candidates, |
2488 | false); |
2489 | continue; |
2490 | } |
2491 | |
2492 | FunctionDecl *Fn = cast<FunctionDecl>(D); |
2493 | S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, |
2494 | false); |
2495 | } |
2496 | |
2497 | |
2498 | OverloadCandidateSet::iterator Best; |
2499 | switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { |
2500 | case OR_Success: { |
2501 | |
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 | |
2513 | |
2514 | |
2515 | |
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 | |
2526 | |
2527 | |
2528 | |
2529 | |
2530 | |
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 | |
2537 | return resolveAllocationOverload(S, R, Range, Args, PassAlignment, |
2538 | Operator, nullptr, |
2539 | nullptr, Diagnose); |
2540 | } |
2541 | |
2542 | if (Diagnose) { |
2543 | |
2544 | |
2545 | |
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 | |
2552 | return true; |
2553 | } |
2554 | |
2555 | |
2556 | |
2557 | |
2558 | |
2559 | |
2560 | |
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"); |
2616 | } |
2617 | |
2618 | bool 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 | |
2627 | |
2628 | |
2629 | |
2630 | |
2631 | |
2632 | |
2633 | |
2634 | |
2635 | |
2636 | SmallVector<Expr*, 8> AllocArgs; |
2637 | AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size()); |
2638 | |
2639 | |
2640 | |
2641 | |
2642 | |
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 | |
2662 | |
2663 | |
2664 | |
2665 | |
2666 | |
2667 | DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( |
2668 | IsArray ? OO_Array_New : OO_New); |
2669 | |
2670 | QualType AllocElemType = Context.getBaseElementType(AllocType); |
2671 | |
2672 | |
2673 | { |
2674 | LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); |
2675 | |
2676 | |
2677 | |
2678 | |
2679 | |
2680 | |
2681 | if (AllocElemType->isRecordType() && NewScope != AFS_Global) |
2682 | LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); |
2683 | |
2684 | |
2685 | |
2686 | if (R.isAmbiguous()) |
2687 | return true; |
2688 | |
2689 | |
2690 | |
2691 | |
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"); |
2709 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); |
2710 | |
2711 | |
2712 | R.suppressDiagnostics(); |
2713 | |
2714 | if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment, |
2715 | OperatorNew, nullptr, |
2716 | nullptr, Diagnose)) |
2717 | return true; |
2718 | } |
2719 | |
2720 | |
2721 | if (!getLangOpts().Exceptions) { |
2722 | OperatorDelete = nullptr; |
2723 | return false; |
2724 | } |
2725 | |
2726 | |
2727 | |
2728 | DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( |
2729 | OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New |
2730 | ? OO_Array_Delete |
2731 | : OO_Delete); |
2732 | |
2733 | |
2734 | |
2735 | |
2736 | |
2737 | |
2738 | |
2739 | |
2740 | |
2741 | |
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; |
2750 | |
2751 | |
2752 | |
2753 | |
2754 | |
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 | |
2781 | |
2782 | |
2783 | |
2784 | |
2785 | |
2786 | |
2787 | |
2788 | |
2789 | |
2790 | |
2791 | |
2792 | |
2793 | bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 || |
2794 | OperatorNew->isVariadic(); |
2795 | |
2796 | if (isPlacementNew) { |
2797 | |
2798 | |
2799 | |
2800 | |
2801 | |
2802 | |
2803 | |
2804 | |
2805 | |
2806 | |
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 | |
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 | |
2831 | |
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 | true), |
2842 | ExpectedFunctionType)) |
2843 | Matches.push_back(std::make_pair(D.getPair(), Fn)); |
2844 | } |
2845 | |
2846 | if (getLangOpts().CUDA) |
2847 | EraseUnwantedCUDAMatches(getCurFunctionDecl(true), |
2848 | Matches); |
2849 | } else { |
2850 | |
2851 | |
2852 | |
2853 | |
2854 | |
2855 | |
2856 | |
2857 | llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; |
2858 | UsualDeallocFnInfo Selected = resolveDeallocationOverload( |
2859 | *this, FoundDelete, FoundGlobalDelete, |
2860 | hasNewExtendedAlignment(*this, AllocElemType), |
2861 | &BestDeallocFns); |
2862 | if (Selected) |
2863 | Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); |
2864 | else { |
2865 | |
2866 | |
2867 | for (auto Fn : BestDeallocFns) |
2868 | Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); |
2869 | } |
2870 | } |
2871 | |
2872 | |
2873 | |
2874 | |
2875 | |
2876 | if (Matches.size() == 1) { |
2877 | OperatorDelete = Matches[0].second; |
2878 | |
2879 | |
2880 | |
2881 | |
2882 | |
2883 | |
2884 | |
2885 | if (getLangOpts().CPlusPlus11 && isPlacementNew && |
2886 | isNonPlacementDeallocationFunction(*this, OperatorDelete)) { |
2887 | UsualDeallocFnInfo Info(*this, |
2888 | DeclAccessPair::make(OperatorDelete, AS_public)); |
2889 | |
2890 | |
2891 | |
2892 | |
2893 | bool IsSizedDelete = Info.HasSizeT; |
2894 | if (IsSizedDelete && !FoundGlobalDelete) { |
2895 | auto NonSizedDelete = |
2896 | resolveDeallocationOverload(*this, FoundDelete, false, |
2897 | 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 | |
2919 | |
2920 | |
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 | |
2933 | |
2934 | |
2935 | |
2936 | |
2937 | |
2938 | |
2939 | |
2940 | |
2941 | |
2942 | |
2943 | |
2944 | |
2945 | |
2946 | |
2947 | |
2948 | |
2949 | |
2950 | |
2951 | |
2952 | |
2953 | |
2954 | |
2955 | void Sema::DeclareGlobalNewDelete() { |
2956 | if (GlobalNewDeleteDeclared) |
2957 | return; |
2958 | |
2959 | |
2960 | |
2961 | if (getLangOpts().OpenCLCPlusPlus) |
2962 | return; |
2963 | |
2964 | |
2965 | |
2966 | |
2967 | |
2968 | |
2969 | if (getLangOpts().CPlusPlusModules && getCurrentModule()) |
2970 | PushGlobalModuleFragment(SourceLocation()); |
2971 | |
2972 | |
2973 | |
2974 | |
2975 | |
2976 | |
2977 | |
2978 | |
2979 | |
2980 | |
2981 | |
2982 | |
2983 | |
2984 | |
2985 | |
2986 | |
2987 | |
2988 | |
2989 | |
2990 | |
2991 | |
2992 | |
2993 | |
2994 | |
2995 | |
2996 | |
2997 | |
2998 | |
2999 | |
3000 | |
3001 | |
3002 | if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { |
3003 | |
3004 | |
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 | |
3013 | |
3014 | if (TheGlobalModuleFragment) { |
3015 | getStdBadAlloc()->setModuleOwnershipKind( |
3016 | Decl::ModuleOwnershipKind::ReachableWhenImported); |
3017 | getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment); |
3018 | } |
3019 | } |
3020 | if (!StdAlignValT && getLangOpts().AlignedAllocation) { |
3021 | |
3022 | |
3023 | auto *AlignValT = EnumDecl::Create( |
3024 | Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), |
3025 | &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); |
3026 | |
3027 | |
3028 | |
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 | |
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 | |
3086 | |
3087 | void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, |
3088 | QualType Return, |
3089 | ArrayRef<QualType> Params) { |
3090 | DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); |
3091 | |
3092 | |
3093 | DeclContext::lookup_result R = GlobalCtx->lookup(Name); |
3094 | for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); |
3095 | Alloc != AllocEnd; ++Alloc) { |
3096 | |
3097 | |
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 | |
3106 | |
3107 | |
3108 | Func->setVisibleDespiteOwningModule(); |
3109 | return; |
3110 | } |
3111 | } |
3112 | } |
3113 | } |
3114 | |
3115 | FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( |
3116 | false, false, 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"); |
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 | nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false, |
3142 | true); |
3143 | Alloc->setImplicit(); |
3144 | |
3145 | Alloc->setVisibleDespiteOwningModule(); |
3146 | |
3147 | if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible) |
3148 | Alloc->addAttr( |
3149 | ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation())); |
3150 | |
3151 | |
3152 | |
3153 | |
3154 | |
3155 | |
3156 | |
3157 | |
3158 | |
3159 | |
3160 | |
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 | 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 | |
3191 | |
3192 | CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); |
3193 | CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); |
3194 | } |
3195 | } |
3196 | |
3197 | FunctionDecl *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 | |
3207 | |
3208 | |
3209 | |
3210 | auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize, |
3211 | Overaligned); |
3212 | assert(Result.FD && "operator delete missing from global scope?"); |
3213 | return Result.FD; |
3214 | } |
3215 | |
3216 | FunctionDecl *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 | |
3227 | |
3228 | return FindUsualDeallocationFunction( |
3229 | Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)), |
3230 | Name); |
3231 | } |
3232 | |
3233 | bool 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 | |
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 | |
3250 | |
3251 | |
3252 | llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; |
3253 | resolveDeallocationOverload(*this, Found, WantSize, |
3254 | Overaligned, &Matches); |
3255 | |
3256 | |
3257 | if (Matches.size() == 1) { |
3258 | Operator = cast<CXXMethodDecl>(Matches[0].FD); |
3259 | |
3260 | |
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 | |
3277 | |
3278 | |
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 | |
3290 | |
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 | |
3307 | namespace { |
3308 | |
3309 | |
3310 | class MismatchingNewDeleteDetector { |
3311 | public: |
3312 | enum MismatchResult { |
3313 | |
3314 | NoMismatch, |
3315 | |
3316 | VarInitMismatches, |
3317 | |
3318 | MemberInitMismatches, |
3319 | |
3320 | |
3321 | AnalyzeLater |
3322 | }; |
3323 | |
3324 | |
3325 | |
3326 | |
3327 | explicit MismatchingNewDeleteDetector(bool EndOfTU) |
3328 | : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), |
3329 | HasUndefinedConstructors(false) {} |
3330 | |
3331 | |
3332 | |
3333 | |
3334 | |
3335 | |
3336 | |
3337 | |
3338 | |
3339 | |
3340 | |
3341 | MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); |
3342 | |
3343 | |
3344 | |
3345 | |
3346 | MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); |
3347 | FieldDecl *Field; |
3348 | |
3349 | llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; |
3350 | |
3351 | bool IsArrayForm; |
3352 | |
3353 | private: |
3354 | const bool EndOfTU; |
3355 | |
3356 | bool HasUndefinedConstructors; |
3357 | |
3358 | |
3359 | |
3360 | const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); |
3361 | |
3362 | |
3363 | |
3364 | |
3365 | |
3366 | |
3367 | |
3368 | MismatchResult analyzeMemberExpr(const MemberExpr *ME); |
3369 | |
3370 | |
3371 | |
3372 | |
3373 | |
3374 | |
3375 | |
3376 | bool hasMatchingVarInit(const DeclRefExpr *D); |
3377 | |
3378 | |
3379 | |
3380 | |
3381 | |
3382 | |
3383 | |
3384 | |
3385 | bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); |
3386 | |
3387 | |
3388 | bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); |
3389 | |
3390 | |
3391 | MismatchResult analyzeInClassInitializer(); |
3392 | }; |
3393 | } |
3394 | |
3395 | MismatchingNewDeleteDetector::MismatchResult |
3396 | MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { |
3397 | NewExprs.clear(); |
3398 | assert(DE && "Expected delete-expression"); |
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 | |
3410 | const CXXNewExpr * |
3411 | MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { |
3412 | assert(E != nullptr && "Expected a valid initializer expression"); |
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 | |
3422 | bool 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 | |
3435 | bool 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 | |
3451 | MismatchingNewDeleteDetector::MismatchResult |
3452 | MismatchingNewDeleteDetector::analyzeInClassInitializer() { |
3453 | assert(Field != nullptr && "This should be called only for members"); |
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 | |
3466 | MismatchingNewDeleteDetector::MismatchResult |
3467 | MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, |
3468 | bool DeleteWasArrayForm) { |
3469 | assert(Field != nullptr && "Analysis requires a valid class member."); |
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 | |
3485 | MismatchingNewDeleteDetector::MismatchResult |
3486 | MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { |
3487 | assert(ME != nullptr && "Expected a member expression"); |
3488 | if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) |
3489 | return analyzeField(F, IsArrayForm); |
3490 | return NoMismatch; |
3491 | } |
3492 | |
3493 | bool 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 | |
3504 | static void |
3505 | DiagnoseMismatchedNewDelete(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 | |
3526 | void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { |
3527 | if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) |
3528 | return; |
3529 | MismatchingNewDeleteDetector Detector(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 | |
3546 | void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, |
3547 | bool DeleteWasArrayForm) { |
3548 | MismatchingNewDeleteDetector Detector(true); |
3549 | switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { |
3550 | case MismatchingNewDeleteDetector::VarInitMismatches: |
3551 | llvm_unreachable("This analysis should have been done for class members."); |
3552 | case MismatchingNewDeleteDetector::AnalyzeLater: |
3553 | llvm_unreachable("Analysis cannot be postponed any point beyond end of " |
3554 | "translation unit."); |
3555 | case MismatchingNewDeleteDetector::MemberInitMismatches: |
3556 | DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); |
3557 | break; |
3558 | case MismatchingNewDeleteDetector::NoMismatch: |
3559 | break; |
3560 | } |
3561 | } |
3562 | |
3563 | |
3564 | |
3565 | |
3566 | |
3567 | ExprResult |
3568 | Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, |
3569 | bool ArrayForm, Expr *ExE) { |
3570 | |
3571 | |
3572 | |
3573 | |
3574 | |
3575 | |
3576 | |
3577 | ExprResult Ex = ExE; |
3578 | FunctionDecl *OperatorDelete = nullptr; |
3579 | bool ArrayFormAsWritten = ArrayForm; |
3580 | bool UsualArrayDeleteWantsSize = false; |
3581 | |
3582 | if (!Ex.get()->isTypeDependent()) { |
3583 | |
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 | |
3596 | |
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"); |
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 | |
3649 | |
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 | |
3665 | |
3666 | |
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 | |
3675 | |
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 | |
3700 | |
3701 | if (ArrayForm) { |
3702 | |
3703 | |
3704 | if (UseGlobal) |
3705 | UsualArrayDeleteWantsSize = |
3706 | doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem); |
3707 | |
3708 | |
3709 | |
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 | true, true, |
3727 | !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 | |
3744 | OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize, |
3745 | Overaligned, DeleteName); |
3746 | } |
3747 | |
3748 | MarkFunctionReferenced(StartLoc, OperatorDelete); |
3749 | |
3750 | |
3751 | |
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 | |
3764 | |
3765 | |
3766 | |
3767 | QualType ParamType = OperatorDelete->getParamDecl(0)->getType(); |
3768 | if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { |
3769 | Qualifiers Qs = Pointee.getQualifiers(); |
3770 | if (Qs.hasCVRQualifiers()) { |
3771 | |
3772 | |
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 | |
3791 | static 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"); |
3801 | assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); |
3802 | |
3803 | |
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 | |
3812 | |
3813 | NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); |
3814 | |
3815 | if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { |
3816 | S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), |
3817 | nullptr, Args, |
3818 | Candidates, |
3819 | false); |
3820 | continue; |
3821 | } |
3822 | |
3823 | FunctionDecl *Fn = cast<FunctionDecl>(D); |
3824 | S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, |
3825 | false); |
3826 | } |
3827 | |
3828 | SourceRange Range = TheCall->getSourceRange(); |
3829 | |
3830 | |
3831 | OverloadCandidateSet::iterator Best; |
3832 | switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { |
3833 | case OR_Success: { |
3834 | |
3835 | FunctionDecl *FnDecl = Best->Function; |
3836 | assert(R.getNamingClass() == nullptr && |
3837 | "class members should not be considered"); |
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"); |
3876 | } |
3877 | |
3878 | ExprResult |
3879 | Sema::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 | |
3889 | |
3890 | DeclareGlobalNewDelete(); |
3891 | |
3892 | FunctionDecl *OperatorNewOrDelete = nullptr; |
3893 | if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, |
3894 | OperatorNewOrDelete)) |
3895 | return ExprError(); |
3896 | assert(OperatorNewOrDelete && "should be found"); |
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 && |
3914 | "Callee expected to be implicit cast to a builtin function pointer"); |
3915 | Callee->setType(OperatorNewOrDelete->getType()); |
3916 | |
3917 | return TheCallResult; |
3918 | } |
3919 | |
3920 | void 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 | |
3928 | |
3929 | |
3930 | |
3931 | |
3932 | |
3933 | |
3934 | const CXXRecordDecl *PointeeRD = dtor->getParent(); |
3935 | |
3936 | if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) |
3937 | return; |
3938 | |
3939 | |
3940 | |
3941 | |
3942 | if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) |
3943 | return; |
3944 | |
3945 | QualType ClassType = dtor->getThisType()->getPointeeType(); |
3946 | if (PointeeRD->isAbstract()) { |
3947 | |
3948 | |
3949 | Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) |
3950 | << ClassType; |
3951 | } else if (WarnOnNonAbstractTypes) { |
3952 | |
3953 | |
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 | |
3965 | Sema::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 | |
3977 | |
3978 | ExprResult 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 | |
3987 | |
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"); |
4013 | } |
4014 | |
4015 | |
4016 | ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { |
4017 | |
4018 | |
4019 | |
4020 | |
4021 | |
4022 | |
4023 | |
4024 | |
4025 | |
4026 | |
4027 | |
4028 | |
4029 | |
4030 | |
4031 | ExprResult E = PerformContextuallyConvertToBool(CondExpr); |
4032 | if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent()) |
4033 | return E; |
4034 | |
4035 | |
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 | |
4044 | |
4045 | |
4046 | |
4047 | bool |
4048 | Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { |
4049 | |
4050 | if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) |
4051 | From = Cast->getSubExpr(); |
4052 | |
4053 | |
4054 | |
4055 | |
4056 | |
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 | |
4062 | |
4063 | if (!ToPtrType->getPointeeType().hasQualifiers()) { |
4064 | switch (StrLit->getKind()) { |
4065 | case StringLiteral::UTF8: |
4066 | case StringLiteral::UTF16: |
4067 | case StringLiteral::UTF32: |
4068 | |
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 | |
4083 | static 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!"); |
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 | false, false, 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!"); |
4123 | |
4124 | S.CheckMemberOperatorAccess(CastLoc, From, nullptr, FoundDecl); |
4125 | if (S.DiagnoseUseOfDecl(Method, CastLoc)) |
4126 | return ExprError(); |
4127 | |
4128 | |
4129 | CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); |
4130 | ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, |
4131 | HadMultipleCandidates); |
4132 | if (Result.isInvalid()) |
4133 | return ExprError(); |
4134 | |
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 | |
4146 | |
4147 | |
4148 | |
4149 | |
4150 | ExprResult |
4151 | Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
4152 | const ImplicitConversionSequence &ICS, |
4153 | AssignmentAction Action, |
4154 | CheckedConversionKind CCK) { |
4155 | |
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"); |
4175 | if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { |
4176 | CastKind = CK_UserDefinedConversion; |
4177 | |
4178 | |
4179 | |
4180 | |
4181 | BeforeToType = Context.getTagDeclType(Conv->getParent()); |
4182 | } else { |
4183 | const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); |
4184 | CastKind = CK_ConstructorConversion; |
4185 | |
4186 | if (!ICS.UserDefined.EllipsisConversion) { |
4187 | |
4188 | |
4189 | |
4190 | BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); |
4191 | } |
4192 | } |
4193 | |
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 | |
4215 | |
4216 | |
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"); |
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"); (void)Diagnosed; |
4241 | return ExprError(); |
4242 | } |
4243 | |
4244 | |
4245 | return From; |
4246 | } |
4247 | |
4248 | |
4249 | |
4250 | |
4251 | |
4252 | |
4253 | ExprResult |
4254 | Sema::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 | |
4261 | |
4262 | |
4263 | |
4264 | QualType FromType = From->getType(); |
4265 | |
4266 | if (SCS.CopyConstructor) { |
4267 | |
4268 | assert(!ToType->isReferenceType()); |
4269 | if (SCS.Second == ICK_Derived_To_Base) { |
4270 | SmallVector<Expr*, 8> ConstructorArgs; |
4271 | if (CompleteConstructorCall( |
4272 | cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From, |
4273 | SourceLocation(), ConstructorArgs)) |
4274 | return ExprError(); |
4275 | return BuildCXXConstructExpr( |
4276 | SourceLocation(), ToType, |
4277 | SCS.FoundCopyConstructor, SCS.CopyConstructor, |
4278 | ConstructorArgs, false, |
4279 | false, false, false, |
4280 | CXXConstructExpr::CK_Complete, SourceRange()); |
4281 | } |
4282 | return BuildCXXConstructExpr( |
4283 | SourceLocation(), ToType, |
4284 | SCS.FoundCopyConstructor, SCS.CopyConstructor, |
4285 | From, false, |
4286 | false, false, false, |
4287 | CXXConstructExpr::CK_Complete, SourceRange()); |
4288 | } |
4289 | |
4290 | |
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 | |
4304 | |
4305 | ExprResult Checked = CheckPlaceholderExpr(From); |
4306 | if (Checked.isInvalid()) |
4307 | return ExprError(); |
4308 | |
4309 | From = Checked.get(); |
4310 | FromType = From->getType(); |
4311 | } |
4312 | |
4313 | |
4314 | |
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 | |
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, nullptr, VK_PRValue, |
4329 | FPOptionsOverride()); |
4330 | } |
4331 | break; |
4332 | |
4333 | case ICK_Lvalue_To_Rvalue: { |
4334 | assert(From->getObjectKind() != OK_ObjCProperty); |
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 | 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, nullptr, CCK) |
4355 | .get(); |
4356 | break; |
4357 | |
4358 | default: |
4359 | llvm_unreachable("Improper first standard conversion"); |
4360 | } |
4361 | |
4362 | |
4363 | switch (SCS.Second) { |
4364 | case ICK_Identity: |
4365 | |
4366 | |
4367 | |
4368 | |
4369 | |
4370 | switch (Action) { |
4371 | case AA_Assigning: |
4372 | case AA_Initializing: |
4373 | |
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 | |
4385 | |
4386 | break; |
4387 | } |
4388 | |
4389 | break; |
4390 | |
4391 | case ICK_Integral_Promotion: |
4392 | case ICK_Integral_Conversion: |
4393 | if (ToType->isBooleanType()) { |
4394 | assert(FromType->castAs<EnumType>()->getDecl()->isFixed() && |
4395 | SCS.Second == ICK_Integral_Promotion && |
4396 | "only enums with fixed underlying type can promote to bool"); |
4397 | From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean, VK_PRValue, |
4398 | nullptr, CCK) |
4399 | .get(); |
4400 | } else { |
4401 | From = ImpCastExprToType(From, ToType, CK_IntegralCast, VK_PRValue, |
4402 | 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 | 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, 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 | nullptr, CCK) |
4439 | .get(); |
4440 | else |
4441 | From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral, VK_PRValue, |
4442 | nullptr, CCK) |
4443 | .get(); |
4444 | break; |
4445 | |
4446 | case ICK_Compatible_Conversion: |
4447 | From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), |
4448 | nullptr, CCK).get(); |
4449 | break; |
4450 | |
4451 | case ICK_Writeback_Conversion: |
4452 | case ICK_Pointer_Conversion: { |
4453 | if (SCS.IncompatibleObjC && Action != AA_Casting) { |
4454 | |
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 | |
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 | |
4503 | |
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 | |
4525 | |
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 | |
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 | 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 | 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 | nullptr, CCK) |
4572 | .get(); |
4573 | break; |
4574 | |
4575 | case ICK_Vector_Splat: { |
4576 | |
4577 | Expr *Elem = prepareVectorSplat(ToType, From).get(); |
4578 | From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue, |
4579 | nullptr, CCK) |
4580 | .get(); |
4581 | break; |
4582 | } |
4583 | |
4584 | case ICK_Complex_Real: |
4585 | |
4586 | if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { |
4587 | QualType ElType = ToComplex->getElementType(); |
4588 | bool isFloatingComplex = ElType->isRealFloatingType(); |
4589 | |
4590 | |
4591 | if (Context.hasSameUnqualifiedType(ElType, From->getType())) { |
4592 | |
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()); |
4598 | From = ImpCastExprToType(From, ElType, |
4599 | isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); |
4600 | } |
4601 | |
4602 | From = ImpCastExprToType(From, ToType, |
4603 | isFloatingComplex ? CK_FloatingRealToComplex |
4604 | : CK_IntegralRealToComplex).get(); |
4605 | |
4606 | |
4607 | } else { |
4608 | auto *FromComplex = From->getType()->castAs<ComplexType>(); |
4609 | QualType ElType = FromComplex->getElementType(); |
4610 | bool isFloatingComplex = ElType->isRealFloatingType(); |
4611 | |
4612 | |
4613 | From = ImpCastExprToType(From, ElType, |
4614 | isFloatingComplex ? CK_FloatingComplexToReal |
4615 | : CK_IntegralComplexToReal, |
4616 | VK_PRValue, nullptr, CCK) |
4617 | .get(); |
4618 | |
4619 | |
4620 | if (Context.hasSameUnqualifiedType(ElType, ToType)) { |
4621 | |
4622 | } else if (ToType->isRealFloatingType()) { |
4623 | From = ImpCastExprToType(From, ToType, |
4624 | isFloatingComplex ? CK_FloatingCast |
4625 | : CK_IntegralToFloating, |
4626 | VK_PRValue, nullptr, CCK) |
4627 | .get(); |
4628 | } else { |
4629 | assert(ToType->isIntegerType()); |
4630 | From = ImpCastExprToType(From, ToType, |
4631 | isFloatingComplex ? CK_FloatingToIntegral |
4632 | : CK_IntegralCast, |
4633 | VK_PRValue, 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) && |
4645 | "Invalid cast"); |
4646 | CastKind Kind = |
4647 | AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
4648 | From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, |
4649 | VK_PRValue, 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) && |
4662 | "Improper transparent union conversion"); |
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"); |
4683 | } |
4684 | |
4685 | switch (SCS.Third) { |
4686 | case ICK_Identity: |
4687 | |
4688 | break; |
4689 | |
4690 | case ICK_Function_Conversion: |
4691 | |
4692 | |
4693 | if (CheckExceptionSpecCompatibility(From, ToType)) |
4694 | return ExprError(); |
4695 | |
4696 | From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue, |
4697 | 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 | 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"); |
4740 | } |
4741 | |
4742 | |
4743 | |
4744 | if (!ToAtomicType.isNull()) { |
4745 | assert(Context.hasSameType( |
4746 | ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); |
4747 | From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, |
4748 | VK_PRValue, nullptr, CCK) |
4749 | .get(); |
4750 | } |
4751 | |
4752 | |
4753 | |
4754 | |
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 | |
4763 | |
4764 | if (!isCast(CCK)) |
4765 | diagnoseNullableToNonnullConversion(ToType, InitialFromType, |
4766 | From->getBeginLoc()); |
4767 | |
4768 | return From; |
4769 | } |
4770 | |
4771 | |
4772 | |
4773 | |
4774 | |
4775 | |
4776 | |
4777 | static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT, |
4778 | SourceLocation Loc, |
4779 | QualType ArgTy) { |
4780 | |
4781 | |
4782 | |
4783 | |
4784 | |
4785 | |
4786 | |
4787 | |
4788 | |
4789 | switch (UTT) { |
4790 | default: llvm_unreachable("not a UTT"); |
4791 | |
4792 | case UTT_IsCompleteType: |
4793 | |
4794 | |
4795 | |
4796 | |
4797 | |
4798 | |
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 | |
4824 | |
4825 | |
4826 | |
4827 | |
4828 | |
4829 | |
4830 | case UTT_IsConst: |
4831 | case UTT_IsVolatile: |
4832 | case UTT_IsSigned: |
4833 | case UTT_IsUnboundedArray: |
4834 | case UTT_IsUnsigned: |
4835 | |
4836 | |
4837 | case UTT_IsInterfaceClass: |
4838 | return true; |
4839 | |
4840 | |
4841 | |
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 | |
4852 | |
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 | |
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 | |
4869 | |
4870 | case UTT_IsTrivial: |
4871 | case UTT_IsTriviallyCopyable: |
4872 | case UTT_IsStandardLayout: |
4873 | case UTT_IsPOD: |
4874 | case UTT_IsLiteral: |
4875 | |
4876 | |
4877 | case UTT_IsTriviallyRelocatable: |
4878 | case UTT_IsTriviallyEqualityComparable: |
4879 | case UTT_CanPassInRegs: |
4880 | |
4881 | |
4882 | |
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 | |
4898 | |
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 | |
4911 | static 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 | |
4946 | static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT, |
4947 | SourceLocation KeyLoc, QualType T) { |
4948 | assert(!T->isDependentType() && "Cannot evaluate traits of dependent type"); |
4949 | |
4950 | ASTContext &C = Self.Context; |
4951 | switch(UTT) { |
4952 | default: llvm_unreachable("not a UTT"); |
4953 | |
4954 | |
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 | |
5003 | |
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 | |
5014 | |
5015 | |
5016 | |
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 | |
5037 | |
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 | |
5066 | |
5067 | |
5068 | return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() || |
5069 | T->isAnyComplexType(); |
5070 | |
5071 | |
5072 | |
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 | |
5082 | |
5083 | return T->isFloatingType() || |
5084 | (T->isSignedIntegerType() && !T->isEnumeralType()); |
5085 | case UTT_IsUnsigned: |
5086 | |
5087 | return T->isUnsignedIntegerType() && !T->isEnumeralType(); |
5088 | |
5089 | |
5090 | |
5091 | |
5092 | |
5093 | |
5094 | |
5095 | |
5096 | |
5097 | |
5098 | |
5099 | |
5100 | |
5101 | |
5102 | |
5103 | |
5104 | case UTT_HasTrivialDefaultConstructor: |
5105 | |
5106 | |
5107 | |
5108 | |
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 | |
5117 | |
5118 | |
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 | |
5126 | |
5127 | |
5128 | |
5129 | |
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 | |
5138 | |
5139 | |
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 | |
5147 | |
5148 | |
5149 | |
5150 | |
5151 | |
5152 | |
5153 | |
5154 | |
5155 | |
5156 | |
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 | |
5170 | |
5171 | if (T->isReferenceType()) |
5172 | return true; |
5173 | |
5174 | |
5175 | if (T->isObjCLifetimeType() && |
5176 | T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) |
5177 | return true; |
5178 | |
5179 | |
5180 | |
5181 | |
5182 | if (T->isIncompleteType() || T->isFunctionType()) |
5183 | return false; |
5184 | |
5185 | |
5186 | |
5187 | if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType()) |
5188 | return false; |
5189 | |
5190 | |
5191 | |
5192 | |
5193 | |
5194 | if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) { |
5195 | CXXDestructorDecl *Destructor = Self.LookupDestructor(RD); |
5196 | if (!Destructor) |
5197 | return false; |
5198 | |
5199 | |
5200 | |
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 | |
5216 | |
5217 | |
5218 | |
5219 | |
5220 | |
5221 | if (T.isPODType(C) || T->isReferenceType()) |
5222 | return true; |
5223 | |
5224 | |
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 | |
5233 | case UTT_HasNothrowAssign: |
5234 | |
5235 | |
5236 | |
5237 | |
5238 | |
5239 | |
5240 | |
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 | |
5256 | |
5257 | |
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 | |
5269 | |
5270 | |
5271 | |
5272 | |
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 | |
5284 | |
5285 | |
5286 | if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) |
5287 | continue; |
5288 | |
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 | |
5299 | |
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 | |
5310 | |
5311 | |
5312 | |
5313 | |
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 | |
5324 | if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl())) |
5325 | continue; |
5326 | |
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 | |
5337 | |
5338 | if (!CPT->isNothrow() || CPT->getNumParams() > 0) |
5339 | return false; |
5340 | } |
5341 | } |
5342 | return FoundConstructor; |
5343 | } |
5344 | return false; |
5345 | case UTT_HasVirtualDestructor: |
5346 | |
5347 | |
5348 | |
5349 | if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) |
5350 | if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD)) |
5351 | return Destructor->isVirtual(); |
5352 | return false; |
5353 | |
5354 | |
5355 | |
5356 | |
5357 | case UTT_IsCompleteType: |
5358 | |
5359 | |
5360 | |
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 | |
5378 | static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, |
5379 | QualType RhsT, SourceLocation KeyLoc); |
5380 | |
5381 | static 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 | |
5388 | |
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 | |
5399 | |
5400 | |
5401 | |
5402 | |
5403 | |
5404 | |
5405 | |
5406 | |
5407 | |
5408 | |
5409 | |
5410 | |
5411 | assert(!Args.empty()); |
5412 | |
5413 | |
5414 | |
5415 | |
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 | |
5427 | QualType T = Args[0]->getType(); |
5428 | if (T->isIncompleteType() || T->isFunctionType()) |
5429 | return false; |
5430 | |
5431 | |
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 | |
5451 | |
5452 | EnterExpressionEvaluationContext Unevaluated( |
5453 | S, Sema::ExpressionEvaluationContext::Unevaluated); |
5454 | Sema::SFINAETrap SFINAE(S, 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 | |
5483 | |
5484 | if (T.getNonReferenceType().hasNonTrivialObjCLifetime()) |
5485 | return false; |
5486 | |
5487 | |
5488 | |
5489 | return !Result.get()->hasNonTrivialCall(S.Context); |
5490 | } |
5491 | |
5492 | llvm_unreachable("unhandled type trait"); |
5493 | return false; |
5494 | } |
5495 | default: llvm_unreachable("not a TT"); |
5496 | } |
5497 | |
5498 | return false; |
5499 | } |
5500 | |
5501 | namespace { |
5502 | void 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 | |
5536 | bool 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 | |
5551 | ExprResult 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 | |
5580 | ExprResult 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 | |
5598 | static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT, |
5599 | QualType RhsT, SourceLocation KeyLoc) { |
5600 | assert(!LhsT->isDependentType() && !RhsT->isDependentType() && |
5601 | "Cannot evaluate traits of dependent types"); |
5602 | |
5603 | switch(BTT) { |
5604 | case BTT_IsBaseOf: { |
5605 | |
5606 | |
5607 | |
5608 | |
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) |
5631 | == (lhsRecord == rhsRecord)); |
5632 | |
5633 | |
5634 | |
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 | |
5644 | |
5645 | |
5646 | |
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 | |
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 | |
5666 | |
5667 | |
5668 | |
5669 | |
5670 | |
5671 | |
5672 | |
5673 | |
5674 | |
5675 | |
5676 | |
5677 | |
5678 | |
5679 | |
5680 | |
5681 | |
5682 | |
5683 | |
5684 | |
5685 | |
5686 | |
5687 | |
5688 | |
5689 | |
5690 | |
5691 | if (RhsT->isFunctionType() || RhsT->isArrayType()) |
5692 | return false; |
5693 | |
5694 | |
5695 | if (RhsT->isVoidType()) |
5696 | return LhsT->isVoidType(); |
5697 | |
5698 | |
5699 | if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT)) |
5700 | return false; |
5701 | |
5702 | |
5703 | if (LhsT->isObjectType() || LhsT->isFunctionType()) |
5704 | LhsT = Self.Context.getRValueReferenceType(LhsT); |
5705 | |
5706 | |
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 | |
5715 | |
5716 | EnterExpressionEvaluationContext Unevaluated( |
5717 | Self, Sema::ExpressionEvaluationContext::Unevaluated); |
5718 | Sema::SFINAETrap SFINAE(Self, 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 | |
5732 | |
5733 | |
5734 | |
5735 | |
5736 | |
5737 | |
5738 | |
5739 | |
5740 | |
5741 | |
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 | |
5752 | if (LhsT->isVoidType() || RhsT->isVoidType()) |
5753 | return false; |
5754 | |
5755 | |
5756 | |
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 | |
5767 | |
5768 | EnterExpressionEvaluationContext Unevaluated( |
5769 | Self, Sema::ExpressionEvaluationContext::Unevaluated); |
5770 | Sema::SFINAETrap SFINAE(Self, true); |
5771 | Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl()); |
5772 | ExprResult Result = Self.BuildBinOp(nullptr, KeyLoc, BO_Assign, &Lhs, |
5773 | &Rhs); |
5774 | if (Result.isInvalid()) |
5775 | return false; |
5776 | |
5777 | |
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 | |
5791 | |
5792 | if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime()) |
5793 | return false; |
5794 | |
5795 | return !Result.get()->hasNonTrivialCall(Self.Context); |
5796 | } |
5797 | |
5798 | llvm_unreachable("unhandled type trait"); |
5799 | return false; |
5800 | } |
5801 | default: llvm_unreachable("not a BTT"); |
5802 | } |
5803 | llvm_unreachable("Unknown type trait or not implemented"); |
5804 | } |
5805 | |
5806 | ExprResult 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 | |
5819 | static 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"); |
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"); |
5871 | } |
5872 | |
5873 | ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT, |
5874 | SourceLocation KWLoc, |
5875 | TypeSourceInfo *TSInfo, |
5876 | Expr* DimExpr, |
5877 | SourceLocation RParen) { |
5878 | QualType T = TSInfo->getType(); |
5879 | |
5880 | |
5881 | |
5882 | uint64_t Value = 0; |
5883 | if (!T->isDependentType()) |
5884 | Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc); |
5885 | |
5886 | |
5887 | |
5888 | |
5889 | |
5890 | |
5891 | return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr, |
5892 | RParen, Context.getSizeType()); |
5893 | } |
5894 | |
5895 | ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET, |
5896 | SourceLocation KWLoc, |
5897 | Expr *Queried, |
5898 | SourceLocation RParen) { |
5899 | |
5900 | if (!Queried) |
5901 | return ExprError(); |
5902 | |
5903 | ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen); |
5904 | |
5905 | return Result; |
5906 | } |
5907 | |
5908 | static 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"); |
5915 | } |
5916 | |
5917 | ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET, |
5918 | SourceLocation KWLoc, |
5919 | Expr *Queried, |
5920 | SourceLocation RParen) { |
5921 | if (Queried->isTypeDependent()) { |
5922 | |
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 | |
5935 | QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, |
5936 | ExprValueKind &VK, |
5937 | SourceLocation Loc, |
5938 | bool isIndirect) { |
5939 | assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() && |
5940 | "placeholders should have been weeded out by now"); |
5941 | |
5942 | |
5943 | |
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 | |
5952 | RHS = DefaultLvalueConversion(RHS.get()); |
5953 | if (RHS.isInvalid()) return QualType(); |
5954 | |
5955 | const char *OpSpelling = isIndirect ? "->*" : ".*"; |
5956 | |
5957 | |
5958 | |
5959 | |
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 | |
5971 | |
5972 | |
5973 | |
5974 | |
5975 | |
5976 | |
5977 | |
5978 | |
5979 | |
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 | |
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 | |
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 | |
6023 | |
6024 | Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; |
6025 | return QualType(); |
6026 | } |
6027 | |
6028 | |
6029 | |
6030 | |
6031 | |
6032 | |
6033 | QualType Result = MemPtr->getPointeeType(); |
6034 | Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); |
6035 | |
6036 | |
6037 | |
6038 | |
6039 | |
6040 | |
6041 | |
6042 | if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { |
6043 | switch (Proto->getRefQualifier()) { |
6044 | case RQ_None: |
6045 | |
6046 | break; |
6047 | |
6048 | case RQ_LValue: |
6049 | if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { |
6050 | |
6051 | |
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 | |
6071 | |
6072 | |
6073 | |
6074 | |
6075 | |
6076 | |
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 | |
6090 | |
6091 | |
6092 | |
6093 | |
6094 | |
6095 | |
6096 | static 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 | |
6106 | |
6107 | |
6108 | |
6109 | |
6110 | |
6111 | |
6112 | |
6113 | |
6114 | |
6115 | |
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 | |
6132 | |
6133 | |
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 | |
6143 | |
6144 | |
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 | |
6163 | |
6164 | |
6165 | |
6166 | |
6167 | |
6168 | |
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 | |
6182 | |
6183 | |
6184 | |
6185 | |
6186 | static 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 | |
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 | |
6219 | |
6220 | |
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 | |
6234 | |
6235 | break; |
6236 | |
6237 | case OR_Deleted: |
6238 | llvm_unreachable("Conditional operator has only built-in overloads"); |
6239 | } |
6240 | return true; |
6241 | } |
6242 | |
6243 | |
6244 | |
6245 | static 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 | |
6260 | |
6261 | static 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"); |
6268 | return EltTy->isIntegralType(Ctx); |
6269 | } |
6270 | |
6271 | static 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"); |
6278 | return EltTy->isIntegralType(Ctx); |
6279 | } |
6280 | |
6281 | QualType 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 | << isa<ExtVectorType>(CondVT); |
6303 | return {}; |
6304 | } |
6305 | |
6306 | |
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, false, true, |
6316 | false, |
6317 | true, |
6318 | true); |
6319 | if (ResultType.isNull()) |
6320 | return {}; |
6321 | } else { |
6322 | |
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() && |
6348 | (!CondType->isExtVectorType() || ResultType->isExtVectorType()) && |
6349 | "Result should have been a vector type"); |
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 | |
6370 | QualType 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 | |
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, false, ACK_Conditional); |
6403 | if (ResultType.isNull()) |
6404 | return QualType(); |
6405 | } else { |
6406 | |
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() && |
6431 | "Result should have been a vector type"); |
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 | |
6454 | |
6455 | |
6456 | |
6457 | |
6458 | |
6459 | |
6460 | |
6461 | |
6462 | |
6463 | |
6464 | |
6465 | |
6466 | |
6467 | |
6468 | |
6469 | |
6470 | |
6471 | |
6472 | |
6473 | QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, |
6474 | ExprResult &RHS, ExprValueKind &VK, |
6475 | ExprObjectKind &OK, |
6476 | SourceLocation QuestionLoc) { |
6477 | |
6478 | |
6479 | |
6480 | |
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 | |
6491 | |
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 | |
6501 | |
6502 | |
6503 | |
6504 | |
6505 | return Context.DependentTy; |
6506 | } |
6507 | |
6508 | |
6509 | |
6510 | if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) |
6511 | return Context.DependentTy; |
6512 | |
6513 | |
6514 | |
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 | |
6521 | |
6522 | |
6523 | |
6524 | bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); |
6525 | bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); |
6526 | |
6527 | |
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 | |
6541 | |
6542 | OK = NonThrow->getObjectKind(); |
6543 | return NonThrow->getType(); |
6544 | } |
6545 | |
6546 | |
6547 | |
6548 | if (LVoid && RVoid) |
6549 | return Context.getCommonSugaredType(LTy, RTy); |
6550 | |
6551 | |
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 | |
6559 | if (IsVectorConditional) |
6560 | return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); |
6561 | |
6562 | if (IsSizelessVectorConditional) |
6563 | return CheckSizelessVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); |
6564 | |
6565 | |
6566 | |
6567 | |
6568 | |
6569 | if (!Context.hasSameType(LTy, RTy) && |
6570 | (LTy->isRecordType() || RTy->isRecordType())) { |
6571 | |
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 | |
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 | |
6587 | |
6588 | |
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 | |
6601 | |
6602 | |
6603 | |
6604 | |
6605 | |
6606 | |
6607 | |
6608 | |
6609 | |
6610 | |
6611 | ExprValueKind LVK = LHS.get()->getValueKind(); |
6612 | ExprValueKind RVK = RHS.get()->getValueKind(); |
6613 | if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) { |
6614 | |
6615 | |
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 | |
6626 | |
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 | |
6641 | |
6642 | |
6643 | |
6644 | |
6645 | |
6646 | |
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 | |
6659 | |
6660 | |
6661 | if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { |
6662 | |
6663 | |
6664 | |
6665 | if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) |
6666 | return QualType(); |
6667 | } |
6668 | |
6669 | |
6670 | |
6671 | |
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 | |
6680 | |
6681 | |
6682 | |
6683 | |
6684 | |
6685 | if (Context.hasSameType(LTy, RTy)) { |
6686 | if (LTy->isRecordType()) { |
6687 | |
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 | |
6705 | if (LTy->isVectorType() || RTy->isVectorType()) |
6706 | return CheckVectorOperands(LHS, RHS, QuestionLoc, false, |
6707 | true, |
6708 | false, |
6709 | false, |
6710 | true); |
6711 | |
6712 | |
6713 | |
6714 | |
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 | |
6734 | |
6735 | |
6736 | |
6737 | |
6738 | |
6739 | |
6740 | |
6741 | |
6742 | |
6743 | |
6744 | |
6745 | QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); |
6746 | if (!Composite.isNull()) |
6747 | return Composite; |
6748 | |
6749 | |
6750 | Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); |
6751 | if (LHS.isInvalid() || RHS.isInvalid()) |
6752 | return QualType(); |
6753 | if (!Composite.isNull()) |
6754 | return Composite; |
6755 | |
6756 | |
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 | |
6767 | |
6768 | |
6769 | |
6770 | |
6771 | |
6772 | |
6773 | |
6774 | |
6775 | |
6776 | |
6777 | QualType Sema::FindCompositePointerType(SourceLocation Loc, |
6778 | Expr *&E1, Expr *&E2, |
6779 | bool ConvertArgs) { |
6780 | assert(getLangOpts().CPlusPlus && "This function assumes C++"); |
6781 | |
6782 | |
6783 | |
6784 | |
6785 | QualType T1 = E1->getType(), T2 = E2->getType(); |
6786 | |
6787 | |
6788 | |
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 | |
6797 | |
6798 | |
6799 | |
6800 | |
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 | |
6819 | if (!T1IsPointerLike || !T2IsPointerLike) |
6820 | return QualType(); |
6821 | assert(!T1->isNullPtrType() && !T2->isNullPtrType() && |
6822 | "nullptr_t should be a null pointer constant"); |
6823 | |
6824 | struct Step { |
6825 | enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; |
6826 | |
6827 | Qualifiers Quals; |
6828 | |
6829 | |
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"); |
6851 | } |
6852 | }; |
6853 | |
6854 | SmallVector<Step, 8> Steps; |
6855 | |
6856 | |
6857 | |
6858 | |
6859 | |
6860 | |
6861 | |
6862 | |
6863 | |
6864 | |
6865 | |
6866 | |
6867 | |
6868 | |
6869 | |
6870 | QualType Composite1 = T1; |
6871 | QualType Composite2 = T2; |
6872 | unsigned NeedConstBefore = 0; |
6873 | while (true) { |
6874 | assert(!Composite1.isNull() && !Composite2.isNull()); |
6875 | |
6876 | Qualifiers Q1, Q2; |
6877 | Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1); |
6878 | Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2); |
6879 | |
6880 | |
6881 | if (!Steps.empty()) { |
6882 | |
6883 | |
6884 | Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() | |
6885 | Q2.getCVRUQualifiers()); |
6886 | |
6887 | |
6888 | |
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 | |
6896 | |
6897 | if (isPtrSizeAddressSpace(Q1.getAddressSpace()) || |
6898 | isPtrSizeAddressSpace(Q2.getAddressSpace())) |
6899 | MaybeQ1 = true; |
6900 | else |
6901 | return QualType(); |
6902 | } |
6903 | Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() |
6904 | : Q2.getAddressSpace()); |
6905 | } else { |
6906 | return QualType(); |
6907 | } |
6908 | |
6909 | |
6910 | if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) |
6911 | Quals.setObjCGCAttr(Q1.getObjCGCAttr()); |
6912 | else if (T1->isVoidPointerType() || T2->isVoidPointerType()) |
6913 | assert(Steps.size() == 1); |
6914 | else |
6915 | return QualType(); |
6916 | |
6917 | |
6918 | if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) |
6919 | Quals.setObjCLifetime(Q1.getObjCLifetime()); |
6920 | else if (T1->isVoidPointerType() || T2->isVoidPointerType()) |
6921 | assert(Steps.size() == 1); |
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 | |
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 | |
6950 | |
6951 | |
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 | |
6986 | |
6987 | |
6988 | |
6989 | |
6990 | |
6991 | |
6992 | |
6993 | |
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 | |
7010 | |
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 | |
7022 | |
7023 | |
7024 | break; |
7025 | } |
7026 | |
7027 | |
7028 | |
7029 | |
7030 | |
7031 | |
7032 | |
7033 | |
7034 | |
7035 | |
7036 | |
7037 | |
7038 | |
7039 | |
7040 | |
7041 | |
7042 | |
7043 | |
7044 | |
7045 | |
7046 | |
7047 | |
7048 | |
7049 | |
7050 | |
7051 | |
7052 | |
7053 | |
7054 | |
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 | |
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 | |
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 | |
7082 | if (Steps.size() == 1 && Steps.front().K == Step::Pointer && |
7083 | !Context.hasSameType(Composite1, Composite2)) { |
7084 | |
7085 | |
7086 | |
7087 | if (Composite1->isVoidType() && Composite2->isObjectType()) |
7088 | Composite2 = Composite1; |
7089 | else if (Composite2->isVoidType() && Composite1->isObjectType()) |
7090 | Composite1 = Composite2; |
7091 | |
7092 | |
7093 | |
7094 | |
7095 | |
7096 | |
7097 | |
7098 | else if (IsDerivedFrom(Loc, Composite1, Composite2)) |
7099 | Composite1 = Composite2; |
7100 | else if (IsDerivedFrom(Loc, Composite2, Composite1)) |
7101 | Composite2 = Composite1; |
7102 | } |
7103 | |
7104 | |
7105 | |
7106 | if (!Context.hasSameType(Composite1, Composite2)) |
7107 | return QualType(); |
7108 | |
7109 | |
7110 | |
7111 | for (unsigned I = 0; I != NeedConstBefore; ++I) |
7112 | Steps[I].Quals.addConst(); |
7113 | |
7114 | |
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 | |
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 | |
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 | |
7149 | ExprResult Sema::MaybeBindToTemporary(Expr *E) { |
7150 | if (!E) |
7151 | return ExprError(); |
7152 | |
7153 | assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); |
7154 | |
7155 | |
7156 | if (E->isGLValue()) |
7157 | return E; |
7158 | |
7159 | |
7160 | |
7161 | if (getLangOpts().ObjCAutoRefCount && |
7162 | E->getType()->isObjCRetainableType()) { |
7163 | |
7164 | bool ReturnsRetained; |
7165 | |
7166 | |
7167 | |
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 | |
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 | |
7191 | |
7192 | } else if (isa<StmtExpr>(E)) { |
7193 | ReturnsRetained = true; |
7194 | |
7195 | |
7196 | |
7197 | } else if (isa<CastExpr>(E) && |
7198 | isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { |
7199 | return E; |
7200 | |
7201 | |
7202 | |
7203 | |
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 | |
7212 | |
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 | |
7221 | |
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 | |
7232 | |
7233 | |
7234 | if (!ReturnsRetained && |
7235 | D && D->getMethodFamily() == OMF_performSelector) |
7236 | return E; |
7237 | } |
7238 | |
7239 | |
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 | |
7258 | |
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 | |
7278 | |
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 | |
7296 | if (Destructor->isTrivial()) |
7297 | return E; |
7298 | |
7299 | |
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 | |
7312 | ExprResult |
7313 | Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { |
7314 | if (SubExpr.isInvalid()) |
7315 | return ExprError(); |
7316 | |
7317 | return MaybeCreateExprWithCleanups(SubExpr.get()); |
7318 | } |
7319 | |
7320 | Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { |
7321 | assert(SubExpr && "subexpression can't be null!"); |
7322 | |
7323 | CleanupVarDeclMarking(); |
7324 | |
7325 | unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; |
7326 | assert(ExprCleanupObjects.size() >= FirstCleanup); |
7327 | assert(Cleanup.exprNeedsCleanups() || |
7328 | ExprCleanupObjects.size() == FirstCleanup); |
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 | |
7342 | Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { |
7343 | assert(SubStmt && "sub-statement can't be null!"); |
7344 | |
7345 | CleanupVarDeclMarking(); |
7346 | |
7347 | if (!Cleanup.exprNeedsCleanups()) |
7348 | return SubStmt; |
7349 | |
7350 | |
7351 | |
7352 | |
7353 | |
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 | 0); |
7360 | return MaybeCreateExprWithCleanups(E); |
7361 | } |
7362 | |
7363 | |
7364 | |
7365 | |
7366 | |
7367 | ExprResult Sema::ActOnDecltypeExpression(Expr *E) { |
7368 | assert(ExprEvalContexts.back().ExprContext == |
7369 | ExpressionEvaluationContextRecord::EK_Decltype && |
7370 | "not in a decltype expression"); |
7371 | |
7372 | ExprResult Result = CheckPlaceholderExpr(E); |
7373 | if (Result.isInvalid()) |
7374 | return ExprError(); |
7375 | E = Result.get(); |
7376 | |
7377 | |
7378 | |
7379 | |
7380 | |
7381 | |
7382 | |
7383 | |
7384 | |
7385 | |
7386 | |
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 | |
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 | |
7427 | |
7428 | if (getLangOpts().MSVCCompat) |
7429 | return E; |
7430 | |
7431 | |
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 | |
7444 | |
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 | |
7467 | Cleanup.setExprNeedsCleanups(true); |
7468 | } |
7469 | |
7470 | |
7471 | return E; |
7472 | } |
7473 | |
7474 | |
7475 | static void noteOperatorArrows(Sema &S, |
7476 | ArrayRef<FunctionDecl *> OperatorArrows) { |
7477 | unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; |
7478 | |
7479 | unsigned Limit = 9; |
7480 | if (OperatorArrows.size() > Limit) { |
7481 | |
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 | |
7500 | ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, |
7501 | SourceLocation OpLoc, |
7502 | tok::TokenKind OpKind, |
7503 | ParsedType &ObjectType, |
7504 | bool &MayBePseudoDestructor) { |
7505 | |
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 | |
7518 | |
7519 | |
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 | |
7530 | |
7531 | |
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 | |
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 | |
7555 | |
7556 | |
7557 | |
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 | |
7602 | |
7603 | if (BaseType->isObjCObjectPointerType()) |
7604 | BaseType = BaseType->getPointeeType(); |
7605 | |
7606 | |
7607 | |
7608 | |
7609 | |
7610 | |
7611 | |
7612 | |
7613 | |
7614 | |
7615 | |
7616 | |
7617 | if (!BaseType->isRecordType()) { |
7618 | ObjectType = ParsedType::make(BaseType); |
7619 | MayBePseudoDestructor = true; |
7620 | return Base; |
7621 | } |
7622 | |
7623 | |
7624 | |
7625 | |
7626 | |
7627 | |
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 | |
7636 | |
7637 | |
7638 | |
7639 | |
7640 | ObjectType = ParsedType::make(BaseType); |
7641 | return Base; |
7642 | } |
7643 | |
7644 | static 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 | |
7654 | |
7655 | |
7656 | |
7657 | |
7658 | |
7659 | if (OpKind == tok::arrow) { |
7660 | |
7661 | |
7662 | |
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 | |
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 | |
7690 | |
7691 | static bool |
7692 | canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, |
7693 | QualType DestructedType) { |
7694 | |
7695 | if (auto *RD = DestructedType->getAsCXXRecordDecl()) { |
7696 | if (RD->hasDefinition()) |
7697 | if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) |
7698 | return SemaRef.CanUseDecl(D, false); |
7699 | return false; |
7700 | } |
7701 | |
7702 | |
7703 | return DestructedType->isDependentType() || DestructedType->isScalarType() || |
7704 | DestructedType->isVectorType(); |
7705 | } |
7706 | |
7707 | ExprResult 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 | |
7733 | |
7734 | |
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 | |
7742 | |
7743 | |
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 << 0 << Base->getSourceRange(); |
7750 | |
7751 | |
7752 | if (canRecoverDotPseudoDestructorCallsOnPointerObjects( |
7753 | *this, DestructedType)) |
7754 | Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); |
7755 | |
7756 | |
7757 | |
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 | |
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 | |
7776 | |
7777 | } else { |
7778 | Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) |
7779 | << ObjectType << DestructedType << Base->getSourceRange() |
7780 | << DestructedTypeInfo->getTypeLoc().getSourceRange(); |
7781 | } |
7782 | |
7783 | |
7784 | DestructedType = ObjectType; |
7785 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, |
7786 | DestructedTypeStart); |
7787 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
7788 | } |
7789 | } |
7790 | } |
7791 | |
7792 | |
7793 | |
7794 | |
7795 | |
7796 | |
7797 | |
7798 | |
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 | |
7826 | ExprResult 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 || |
7835 | FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && |
7836 | "Invalid first type name in pseudo-destructor"); |
7837 | assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || |
7838 | SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && |
7839 | "Invalid second type name in pseudo-destructor"); |
7840 | |
7841 | QualType ObjectType; |
7842 | if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) |
7843 | return ExprError(); |
7844 | |
7845 | |
7846 | |
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 | |
7856 | |
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 | true); |
7865 | if (!T && |
7866 | ((SS.isSet() && !computeDeclContext(SS, false)) || |
7867 | (!SS.isSet() && ObjectType->isDependentType()))) { |
7868 | |
7869 | |
7870 | |
7871 | |
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 | |
7882 | DestructedType = ObjectType; |
7883 | } else |
7884 | DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); |
7885 | } else { |
7886 | |
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 | true); |
7900 | if (T.isInvalid() || !T.get()) { |
7901 | |
7902 | DestructedType = ObjectType; |
7903 | } else |
7904 | DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); |
7905 | } |
7906 | |
7907 | |
7908 | |
7909 | if (!DestructedType.isNull()) { |
7910 | if (!DestructedTypeInfo) |
7911 | DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, |
7912 | SecondTypeName.StartLocation); |
7913 | Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
7914 | } |
7915 | |
7916 | |
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 | 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 | |
7935 | ScopeType = QualType(); |
7936 | } else |
7937 | ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); |
7938 | } else { |
7939 | |
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 | true); |
7953 | if (T.isInvalid() || !T.get()) { |
7954 | |
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 | |
7971 | ExprResult 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(), 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 | |
7999 | ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl, |
8000 | CXXConversionDecl *Method, |
8001 | bool HadMultipleCandidates) { |
8002 | |
8003 | |
8004 | ExprResult Exp = PerformObjectArgumentInitialization(E, nullptr, |
8005 | FoundDecl, Method); |
8006 | if (Exp.isInvalid()) |
8007 | return true; |
8008 | |
8009 | if (Method->getParent()->isLambda() && |
8010 | Method->getConversionType()->isBlockPointerType()) { |
8011 | |
8012 | |
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 | |
8022 | |
8023 | |
8024 | |
8025 | |
8026 | PushExpressionEvaluationContext( |
8027 | ExpressionEvaluationContext::PotentiallyEvaluated); |
8028 | ExprResult BlockExp = BuildBlockForLambdaConversion( |
8029 | Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get()); |
8030 | PopExpressionEvaluationContext(); |
8031 | |
8032 | |
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(), 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, {}, 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 | |
8061 | ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, |
8062 | SourceLocation RParen) { |
8063 | |
8064 | |
8065 | |
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 | |
8079 | |
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 | |
8088 | ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, |
8089 | Expr *Operand, SourceLocation RParen) { |
8090 | return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); |
8091 | } |
8092 | |
8093 | static 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 | |
8124 | |
8125 | |
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 | |
8136 | |
8137 | ExprResult 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 | |
8147 | |
8148 | |
8149 | |
8150 | if (E->isPRValue()) { |
8151 | |
8152 | |
8153 | |
8154 | |
8155 | if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) |
8156 | return DefaultFunctionArrayConversion(E); |
8157 | |
8158 | return E; |
8159 | } |
8160 | |
8161 | if (getLangOpts().CPlusPlus) { |
8162 | |
8163 | |
8164 | |
8165 | |
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 | |
8173 | |
8174 | CheckUnusedVolatileAssignment(E); |
8175 | } |
8176 | |
8177 | |
8178 | |
8179 | |
8180 | |
8181 | |
8182 | |
8183 | |
8184 | |
8185 | |
8186 | return E; |
8187 | } |
8188 | |
8189 | |
8190 | if (const EnumType *T = E->getType()->getAs<EnumType>()) { |
8191 | if (!T->getDecl()->isComplete()) { |
8192 | |
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 | |
8209 | ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { |
8210 | |
8211 | |
8212 | CheckUnusedVolatileAssignment(E); |
8213 | |
8214 | return E; |
8215 | } |
8216 | |
8217 | |
8218 | |
8219 | |
8220 | |
8221 | |
8222 | |
8223 | |
8224 | |
8225 | |
8226 | |
8227 | |
8228 | |
8229 | static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, |
8230 | ASTContext &Context) { |
8231 | if (isa<ParmVarDecl>(Var)) return true; |
8232 | const VarDecl *DefVD = nullptr; |
8233 | |
8234 | |
8235 | const Expr *Init = Var->getAnyInitializer(DefVD); |
8236 | if (!Init) |
8237 | return true; |
8238 | assert(DefVD); |
8239 | if (DefVD->isWeak()) |
8240 | return false; |
8241 | |
8242 | if (Var->getType()->isDependentType() || Init->isValueDependent()) { |
8243 | |
8244 | |
8245 | |
8246 | return false; |
8247 | } |
8248 | |
8249 | return !Var->isUsableInConstantExpressions(Context); |
8250 | } |
8251 | |
8252 | |
8253 | |
8254 | |
8255 | |
8256 | |
8257 | |
8258 | |
8259 | static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( |
8260 | Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { |
8261 | |
8262 | assert(!S.isUnevaluatedContext()); |
8263 | assert(S.CurContext->isDependentContext()); |
8264 | #ifndef NDEBUG |
8265 | DeclContext *DC = S.CurContext; |
8266 | while (DC && isa<CapturedDecl>(DC)) |
8267 | DC = DC->getParent(); |
8268 | assert( |
8269 | CurrentLSI->CallOperator == DC && |
8270 | "The current call operator must be synchronized with Sema's CurContext"); |
8271 | #endif // NDEBUG |
8272 | |
8273 | const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); |
8274 | |
8275 | |
8276 | |
8277 | |
8278 | CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) { |
8279 | |
8280 | |
8281 | |
8282 | |
8283 | |
8284 | |
8285 | |
8286 | |
8287 | |
8288 | |
8289 | |
8290 | if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && |
8291 | !IsFullExprInstantiationDependent) |
8292 | return; |
8293 | |
8294 | VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl(); |
8295 | if (!UnderlyingVar) |
8296 | return; |
8297 | |
8298 | |
8299 | |
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 | |
8308 | |
8309 | |
8310 | |
8311 | |
8312 | |
8313 | QualType CaptureType, DeclRefType; |
8314 | SourceLocation ExprLoc = VarExpr->getExprLoc(); |
8315 | if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, |
8316 | SourceLocation(), |
8317 | false, CaptureType, |
8318 | DeclRefType, nullptr)) { |
8319 | |
8320 | |
8321 | S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit, |
8322 | SourceLocation(), |
8323 | true, CaptureType, |
8324 | DeclRefType, nullptr); |
8325 | } |
8326 | } |
8327 | }); |
8328 | |
8329 | |
8330 | if (CurrentLSI->hasPotentialThisCapture()) { |
8331 | |
8332 | |
8333 | if (const std::optional<unsigned> Index = |
8334 | getStackIndexOfNearestEnclosingCaptureCapableLambda( |
8335 | S.FunctionScopes, nullptr, S)) { |
8336 | const unsigned FunctionScopeIndexOfCapturableLambda = *Index; |
8337 | S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, |
8338 | false, true, |
8339 | &FunctionScopeIndexOfCapturableLambda); |
8340 | } |
8341 | } |
8342 | |
8343 | |
8344 | CurrentLSI->clearPotentialCaptures(); |
8345 | } |
8346 | |
8347 | static 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 | |
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 | |
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 | |
8376 | |
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, SourceLocation(), R, |
8394 | nullptr, 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, false, |
8402 | true); |
8403 | } |
8404 | |
8405 | namespace { |
8406 | class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> { |
8407 | llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs; |
8408 | |
8409 | public: |
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 | |
8418 | class TransformTypos : public TreeTransform<TransformTypos> { |
8419 | typedef TreeTransform<TransformTypos> BaseTransform; |
8420 | |
8421 | VarDecl *InitDecl; |
8422 | |
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 | |
8429 | |
8430 | |
8431 | |
8432 | |
8433 | |
8434 | |
8435 | |
8436 | |
8437 | |
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 | |
8447 | |
8448 | |
8449 | |
8450 | |
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 | |
8462 | |
8463 | |
8464 | |
8465 | |
8466 | |
8467 | |
8468 | |
8469 | |
8470 | |
8471 | |
8472 | |
8473 | |
8474 | |
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 | |
8499 | |
8500 | |
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 | |
8514 | |
8515 | |
8516 | ExprResult CheckForRecursiveTypos(ExprResult Res, bool &IsAmbiguous) { |
8517 | if (Res.isInvalid()) { |
8518 | return Res; |
8519 | } |
8520 | |
8521 | |
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 | |
8532 | |
8533 | ExprResult RecurResult = |
8534 | RecursiveTransformLoop(FixedExpr, IsAmbiguous); |
8535 | if (RecurResult.isInvalid()) { |
8536 | Res = ExprError(); |
8537 | |
8538 | |
8539 | |
8540 | |
8541 | |
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 | |
8554 | |
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 | |
8567 | |
8568 | |
8569 | |
8570 | |
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 | |
8580 | |
8581 | if (IsAmbiguous) |
8582 | break; |
8583 | |
8584 | |
8585 | |
8586 | if (!Res.isInvalid()) |
8587 | break; |
8588 | |
8589 | |
8590 | |
8591 | if (!CheckAndAdvanceTypoExprCorrectionStreams()) |
8592 | break; |
8593 | } |
8594 | |
8595 | |
8596 | if (!IsAmbiguous && !Res.isInvalid() && !AmbiguousTypoExprs.empty()) { |
8597 | auto SavedTransformCache = |
8598 | llvm::SmallDenseMap<TypoExpr *, ExprResult, 2>(TransformCache); |
8599 | |
8600 | |
8601 | |
8602 | while (!AmbiguousTypoExprs.empty()) { |
8603 | auto TE = AmbiguousTypoExprs.back(); |
8604 | |
8605 | |
8606 | |
8607 | SemaRef.getTypoExprState(TE).Consumer->saveCurrentPosition(); |
8608 | |
8609 | TypoCorrection TC = SemaRef.getTypoExprState(TE).Consumer->peekNextCorrection(); |
8610 | TypoCorrection Next; |
8611 | do { |
8612 | |
8613 | |
8614 | |
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 | |
8639 | |
8640 | |
8641 | |
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 | |
8658 | public: |
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 | |
8698 | |
8699 | |
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"); |
8707 | |
8708 | |
8709 | |
8710 | while (TypoCorrection TC = State.Consumer->getNextCorrection()) { |
8711 | if (InitDecl && TC.getFoundDecl() == InitDecl) |
8712 | continue; |
8713 | |
8714 | |
8715 | ExprResult NE = State.RecoveryHandler ? |
8716 | State.RecoveryHandler(SemaRef, E, TC) : |
8717 | attemptRecovery(SemaRef, *State.Consumer, TC); |
8718 | if (!NE.isInvalid()) { |
8719 | |
8720 | |
8721 | |
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() && |
8730 | "Typo was transformed into a valid-but-null ExprResult"); |
8731 | return CacheEntry = NE; |
8732 | } |
8733 | } |
8734 | return CacheEntry = ExprError(); |
8735 | } |
8736 | }; |
8737 | } |
8738 | |
8739 | ExprResult |
8740 | Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl, |
8741 | bool RecoverUncorrectedTypos, |
8742 | llvm::function_ref<ExprResult(Expr *)> Filter) { |
8743 | |
8744 | |
8745 | |
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?"); |
8767 | } |
8768 | return E; |
8769 | } |
8770 | |
8771 | ExprResult 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 | |
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(), nullptr, |
8803 | true); |
8804 | if (FullExpr.isInvalid()) |
8805 | return ExprError(); |
8806 | |
8807 | CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); |
8808 | |
8809 | |
8810 | |
8811 | |
8812 | |
8813 | |
8814 | |
8815 | |
8816 | |
8817 | |
8818 | |
8819 | |
8820 | |
8821 | |
8822 | |
8823 | |
8824 | |
8825 | |
8826 | |
8827 | |
8828 | |
8829 | |
8830 | |
8831 | |
8832 | |
8833 | |
8834 | |
8835 | |
8836 | |
8837 | |
8838 | |
8839 | LambdaScopeInfo *const CurrentLSI = |
8840 | getCurLambda(true); |
8841 | |
8842 | |
8843 | |
8844 | |
8845 | |
8846 | |
8847 | |
8848 | |
8849 | |
8850 | |
8851 | |
8852 | |
8853 | |
8854 | |
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 | |
8866 | StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { |
8867 | if (!FullStmt) return StmtError(); |
8868 | |
8869 | return MaybeCreateStmtWithCleanups(FullStmt); |
8870 | } |
8871 | |
8872 | Sema::IfExistsResult |
8873 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, |
8874 | CXXScopeSpec &SS, |
8875 | const DeclarationNameInfo &TargetNameInfo) { |
8876 | DeclarationName TargetName = TargetNameInfo.getName(); |
8877 | if (!TargetName) |
8878 | return IER_DoesNotExist; |
8879 | |
8880 | |
8881 | if (TargetName.isDependentName()) |
8882 | return IER_Dependent; |
8883 | |
8884 | |
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!"); |
8905 | } |
8906 | |
8907 | Sema::IfExistsResult |
8908 | Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, |
8909 | bool IsIfExists, CXXScopeSpec &SS, |
8910 | UnqualifiedId &Name) { |
8911 | DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); |
8912 | |
8913 | |
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 | |
8922 | concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { |
8923 | return BuildExprRequirement(E, true, |
8924 | SourceLocation(), |
8925 | {}); |
8926 | } |
8927 | |
8928 | concepts::Requirement * |
8929 | Sema::ActOnTypeRequirement(SourceLocation TypenameKWLoc, CXXScopeSpec &SS, |
8930 | SourceLocation NameLoc, IdentifierInfo *TypeName, |
8931 | TemplateIdAnnotation *TemplateId) { |
8932 | assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) && |
8933 | "Exactly one of TypeName and TemplateId must be specified."); |
8934 | TypeSourceInfo *TSI = nullptr; |
8935 | if (TypeName) { |
8936 | QualType T = CheckTypenameType(ETK_Typename, TypenameKWLoc, |
8937 | SS.getWithLocInContext(Context), *TypeName, |
8938 | NameLoc, &TSI, 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 | |
8958 | concepts::Requirement * |
8959 | Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { |
8960 | return BuildExprRequirement(E, false, NoexceptLoc, |
8961 | {}); |
8962 | } |
8963 | |
8964 | concepts::Requirement * |
8965 | Sema::ActOnCompoundRequirement( |
8966 | Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, |
8967 | TemplateIdAnnotation *TypeConstraint, unsigned Depth) { |
8968 | |
8969 | |
8970 | |
8971 | |
8972 | |
8973 | |
8974 | |
8975 | |
8976 | |
8977 | |
8978 | |
8979 | auto &II = Context.Idents.get("expr-type"); |
8980 | auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext, |
8981 | SourceLocation(), |
8982 | SourceLocation(), Depth, |
8983 | 0, &II, |
8984 | true, |
8985 | false, |
8986 | true); |
8987 | |
8988 | if (BuildTypeConstraint(SS, TypeConstraint, TParam, |
8989 | SourceLocation(), |
8990 | true)) |
8991 | |
8992 | return BuildExprRequirement(E, false, NoexceptLoc, {}); |
8993 | |
8994 | auto *TPL = TemplateParameterList::Create(Context, SourceLocation(), |
8995 | SourceLocation(), |
8996 | ArrayRef<NamedDecl *>(TParam), |
8997 | SourceLocation(), |
8998 | nullptr); |
8999 | return BuildExprRequirement( |
9000 | E, false, NoexceptLoc, |
9001 | concepts::ExprRequirement::ReturnTypeRequirement(TPL)); |
9002 | } |
9003 | |
9004 | concepts::ExprRequirement * |
9005 | Sema::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 | |
9018 | |
9019 | |
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 | 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 | |
9049 | concepts::ExprRequirement * |
9050 | Sema::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 | |
9059 | concepts::TypeRequirement * |
9060 | Sema::BuildTypeRequirement(TypeSourceInfo *Type) { |
9061 | return new (Context) concepts::TypeRequirement(Type); |
9062 | } |
9063 | |
9064 | concepts::TypeRequirement * |
9065 | Sema::BuildTypeRequirement( |
9066 | concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { |
9067 | return new (Context) concepts::TypeRequirement(SubstDiag); |
9068 | } |
9069 | |
9070 | concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { |
9071 | return BuildNestedRequirement(Constraint); |
9072 | } |
9073 | |
9074 | concepts::NestedRequirement * |
9075 | Sema::BuildNestedRequirement(Expr *Constraint) { |
9076 | ConstraintSatisfaction Satisfaction; |
9077 | if (!Constraint->isInstantiationDependent() && |
9078 | CheckConstraintSatisfaction(nullptr, {Constraint}, {}, |
9079 | Constraint->getSourceRange(), Satisfaction)) |
9080 | return nullptr; |
9081 | return new (Context) concepts::NestedRequirement(Context, Constraint, |
9082 | Satisfaction); |
9083 | } |
9084 | |
9085 | concepts::NestedRequirement * |
9086 | Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity, |
9087 | const ASTConstraintSatisfaction &Satisfaction) { |
9088 | return new (Context) concepts::NestedRequirement( |
9089 | InvalidConstraintEntity, |
9090 | ASTConstraintSatisfaction::Rebuild(Context, Satisfaction)); |
9091 | } |
9092 | |
9093 | RequiresExprBodyDecl * |
9094 | Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, |
9095 | ArrayRef<ParmVarDecl *> LocalParameters, |
9096 | Scope *BodyScope) { |
9097 | assert(BodyScope); |
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 | |
9107 | |
9108 | |
9109 | Diag(Param->getDefaultArgRange().getBegin(), |
9110 | diag::err_requires_expr_local_parameter_default_argument); |
9111 | |
9112 | |
9113 | Param->setDeclContext(Body); |
9114 | |
9115 | if (Param->getIdentifier()) { |
9116 | CheckShadow(BodyScope, Param); |
9117 | PushOnScopeChains(Param, BodyScope); |
9118 | } |
9119 | } |
9120 | return Body; |
9121 | } |
9122 | |
9123 | void Sema::ActOnFinishRequiresExpr() { |
9124 | assert(CurContext && "DeclContext imbalance!"); |
9125 | CurContext = CurContext->getLexicalParent(); |
9126 | assert(CurContext && "Popped translation unit!"); |
9127 | } |
9128 | |
9129 | ExprResult |
9130 | Sema::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 | } |