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