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