clang 24.0.0git
ASTUtils.cpp
Go to the documentation of this file.
1//=======- ASTUtils.cpp ------------------------------------------*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ASTUtils.h"
10#include "PtrTypesSemantics.h"
11#include "clang/AST/Attr.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/ExprCXX.h"
15#include "clang/AST/ExprObjC.h"
18#include <optional>
19#include <utility>
20
21namespace clang {
22
26
27static bool tryToFindPtrOriginImpl(
28 const Expr *E, bool StopAtFirstRefCountedObj, bool FollowLifetimeBound,
30 std::function<bool(const clang::QualType)> isSafePtrType,
31 std::function<bool(const clang::Decl *)> isSafeGlobalDecl,
32 std::function<bool(const clang::Expr *, bool /*IsSafe*/,
33 bool /*OriginDependsOnFullExpressionTemporary*/,
34 bool /*PtrIsLifetimeBoundToOrigin*/)>
35 callback,
36 bool OriginDependsOnFullExpressionTemporary,
37 bool PtrIsLifetimeBoundToOrigin);
38
39namespace {
40
41bool isStdViewType(QualType T) {
42 return !T.isNull() &&
43 isStdView(T.getNonReferenceType()->getAsCXXRecordDecl());
44}
45
46void appendPresumedBorrowSources(
47 const FunctionDecl *Callee, ArrayRef<const Expr *> Args,
48 SmallVectorImpl<const Expr *> &LifetimeBoundArgs) {
49 for (unsigned I = 0; I < Args.size(); ++I) {
50 QualType ParamType;
51 if (Callee && I < Callee->getNumParams())
52 ParamType = Callee->getParamDecl(I)->getType();
53 QualType ArgType = Args[I]->getType();
54 if ((!ParamType.isNull() && ParamType->isReferenceType()) ||
55 (!ArgType.isNull() && isView(ArgType)))
56 LifetimeBoundArgs.push_back(Args[I]);
57 }
58}
59
60/// Collects the entries of \p Args that \p Callee declares
61/// [[clang::lifetimebound]].
62void findLifetimeBoundArgs(const FunctionDecl *Callee,
64 SmallVectorImpl<const Expr *> &LifetimeBoundArgs) {
65 if (!Callee)
66 return;
67 const FunctionDecl *Canon =
69 unsigned Count = std::min<unsigned>(Canon->getNumParams(), Args.size());
70 for (unsigned I = 0; I < Count; ++I) {
71 if (Canon->getParamDecl(I)->hasAttr<LifetimeBoundAttr>())
72 LifetimeBoundArgs.push_back(Args[I]);
73 }
74}
75
76/// Collects the arguments that \p Construct declares [[clang::lifetimebound]].
77/// Absent annotations, a std view constructor is treated as if libc++ had
78/// annotated it.
79void findLifetimeBoundArgs(const CXXConstructExpr *Construct,
80 SmallVectorImpl<const Expr *> &LifetimeBoundArgs) {
81 const auto *Ctor = Construct->getConstructor();
82 ArrayRef<const Expr *> Args(Construct->getArgs(), Construct->getNumArgs());
83 findLifetimeBoundArgs(Ctor, Args, LifetimeBoundArgs);
84 if (!LifetimeBoundArgs.empty() || !Ctor || !isStdView(Ctor->getParent()))
85 return;
86 appendPresumedBorrowSources(Ctor, Args, LifetimeBoundArgs);
87}
88
89/// Collects the arguments that \p Call declares [[clang::lifetimebound]],
90/// including the implicit 'this' argument. Absent annotations, a call that
91/// returns or operates on a std view, or to std::data or std::get, is treated
92/// as if libc++ had annotated it.
93void findLifetimeBoundArgs(const CallExpr *Call,
94 SmallVectorImpl<const Expr *> &LifetimeBoundArgs) {
95 const FunctionDecl *Callee = Call->getDirectCallee();
96
97 const Expr *ObjectArg = nullptr;
98 unsigned ArgOffset = 0;
99 if (isa<CXXOperatorCallExpr>(Call) && Callee &&
100 Callee->isCXXInstanceMember() && Call->getNumArgs()) {
101 ObjectArg = Call->getArg(0);
102 ArgOffset = 1;
103 } else if (auto *MemberCall = dyn_cast<CXXMemberCallExpr>(Call))
104 ObjectArg = MemberCall->getImplicitObjectArgument();
105 ArrayRef<const Expr *> Args(Call->getArgs() + ArgOffset,
106 Call->getNumArgs() - ArgOffset);
107
108 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(Callee)) {
110 LifetimeBoundArgs.push_back(ObjectArg);
111 }
112 findLifetimeBoundArgs(Callee, Args, LifetimeBoundArgs);
113 if (!LifetimeBoundArgs.empty() || !Callee)
114 return;
115
116 bool IsStdAccessor =
117 Callee->isInStdNamespace() &&
118 (safeGetName(Callee) == "data" || safeGetName(Callee) == "get");
119 if (!isStdViewType(Callee->getReturnType()) &&
120 !(ObjectArg && isStdViewType(ObjectArg->getType())) && !IsStdAccessor)
121 return;
122
123 if (ObjectArg)
124 LifetimeBoundArgs.push_back(ObjectArg);
125 appendPresumedBorrowSources(Callee, Args, LifetimeBoundArgs);
126}
127
128/// Traces each of \p Args independently and requires every one to be safe.
129bool tryToFindPtrOriginOfEach(
130 ArrayRef<const Expr *> Args, bool StopAtFirstRefCountedObj,
131 const std::function<bool(const clang::CXXRecordDecl *)> &isSafePtr,
132 const std::function<bool(const clang::QualType)> &isSafePtrType,
133 const std::function<bool(const clang::Decl *)> &isSafeGlobalDecl,
134 const std::function<bool(const clang::Expr *, bool, bool, bool)> &callback,
135 bool OriginDependsOnFullExpressionTemporary,
136 bool PtrIsLifetimeBoundToOrigin) {
137 for (const Expr *Arg : Args) {
139 Arg, StopAtFirstRefCountedObj, /*FollowLifetimeBound=*/true,
140 isSafePtr, isSafePtrType, isSafeGlobalDecl, callback,
141 OriginDependsOnFullExpressionTemporary, PtrIsLifetimeBoundToOrigin))
142 return false;
143 }
144 return true;
145}
146
147} // namespace
148
150 const Expr *E, bool StopAtFirstRefCountedObj, bool FollowLifetimeBound,
152 std::function<bool(const clang::QualType)> isSafePtrType,
153 std::function<bool(const clang::Decl *)> isSafeGlobalDecl,
154 std::function<bool(const clang::Expr *, bool /*IsSafe*/,
155 bool /*OriginDependsOnFullExpressionTemporary*/,
156 bool /*PtrIsLifetimeBoundToOrigin*/)>
157 callback,
158 bool OriginDependsOnFullExpressionTemporary,
159 bool PtrIsLifetimeBoundToOrigin) {
160 while (E) {
161 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
162 if (auto *VD = dyn_cast_or_null<VarDecl>(DRE->getDecl())) {
163 auto QT = VD->getType();
164 auto IsImmortal = safeGetName(VD) == "NSApp";
165 if (VD->hasGlobalStorage() && (IsImmortal || QT.isConstQualified()))
166 return callback(E, /*IsSafe=*/true,
167 OriginDependsOnFullExpressionTemporary,
168 PtrIsLifetimeBoundToOrigin);
169 if (VD->hasGlobalStorage() && isSafeGlobalDecl(VD))
170 return callback(E, /*IsSafe=*/true,
171 OriginDependsOnFullExpressionTemporary,
172 PtrIsLifetimeBoundToOrigin);
173 if (isImmortalVar(VD))
174 return callback(E, /*IsSafe=*/true,
175 OriginDependsOnFullExpressionTemporary,
176 PtrIsLifetimeBoundToOrigin);
177
178 if (FollowLifetimeBound && VD->isImplicit() && VD->isLocalVarDecl()) {
179 if (auto *Init = VD->getInit()) {
180 E = Init;
181 continue;
182 }
183 }
184 }
185 }
186 if (auto *Cleanups = dyn_cast<ExprWithCleanups>(E)) {
187 E = Cleanups->getSubExpr();
188 continue;
189 }
190 if (auto *tempExpr = dyn_cast<MaterializeTemporaryExpr>(E)) {
191 if (tempExpr->getStorageDuration() == SD_FullExpression)
192 OriginDependsOnFullExpressionTemporary = true;
193 E = tempExpr->getSubExpr();
194 continue;
195 }
196 if (auto *tempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) {
197 E = tempExpr->getSubExpr();
198 continue;
199 }
200 if (auto *tempExpr = dyn_cast<CXXConstructExpr>(E)) {
201 if (auto *C = tempExpr->getConstructor()) {
202 if (auto *Class = C->getParent(); Class && isSafePtr(Class))
203 return callback(E, /*IsSafe=*/true,
204 OriginDependsOnFullExpressionTemporary,
205 PtrIsLifetimeBoundToOrigin);
206
207 if (FollowLifetimeBound) {
208 SmallVector<const Expr *, 2> LifetimeBoundArgs;
209 findLifetimeBoundArgs(tempExpr, LifetimeBoundArgs);
210 if (!LifetimeBoundArgs.empty())
211 return tryToFindPtrOriginOfEach(
212 LifetimeBoundArgs, StopAtFirstRefCountedObj, isSafePtr,
213 isSafePtrType, isSafeGlobalDecl, callback,
214 /*OriginDependsOnFullExpressionTemporary=*/false,
215 /*PtrIsLifetimeBoundToOrigin=*/true);
216 }
217 break;
218 }
219 }
220 if (auto *TempExpr = dyn_cast<CXXUnresolvedConstructExpr>(E)) {
221 if (isSafePtrType(TempExpr->getTypeAsWritten()))
222 return callback(TempExpr, /*IsSafe=*/true,
223 OriginDependsOnFullExpressionTemporary,
224 PtrIsLifetimeBoundToOrigin);
225 }
226 if (auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
227 if (auto *RF = POE->getResultExpr()) {
228 E = RF;
229 continue;
230 }
231 }
232 if (auto *tempExpr = dyn_cast<ParenExpr>(E)) {
233 E = tempExpr->getSubExpr();
234 continue;
235 }
236 if (auto *OpaqueValue = dyn_cast<OpaqueValueExpr>(E)) {
237 E = OpaqueValue->getSourceExpr();
238 continue;
239 }
240 if (auto *Expr = dyn_cast<ConditionalOperator>(E)) {
241 return tryToFindPtrOriginImpl(Expr->getTrueExpr(),
242 StopAtFirstRefCountedObj,
243 FollowLifetimeBound, isSafePtr,
244 isSafePtrType, isSafeGlobalDecl, callback,
245 OriginDependsOnFullExpressionTemporary,
246 PtrIsLifetimeBoundToOrigin) &&
247 tryToFindPtrOriginImpl(Expr->getFalseExpr(),
248 StopAtFirstRefCountedObj,
249 FollowLifetimeBound, isSafePtr,
250 isSafePtrType, isSafeGlobalDecl, callback,
251 OriginDependsOnFullExpressionTemporary,
252 PtrIsLifetimeBoundToOrigin);
253 }
254 if (auto *cast = dyn_cast<CastExpr>(E)) {
255 if (StopAtFirstRefCountedObj) {
256 if (auto *ConversionFunc =
257 dyn_cast_or_null<FunctionDecl>(cast->getConversionFunction())) {
258 if (isCtorOfSafePtr(ConversionFunc))
259 return callback(E, /*IsSafe=*/true,
260 OriginDependsOnFullExpressionTemporary,
261 PtrIsLifetimeBoundToOrigin);
262 }
263 if (isa<CXXFunctionalCastExpr>(E) && isSafePtrType(cast->getType()))
264 return callback(E, /*IsSafe=*/true,
265 OriginDependsOnFullExpressionTemporary,
266 PtrIsLifetimeBoundToOrigin);
267 }
268 // FIXME: This can give false "origin" that would lead to false negatives
269 // in checkers. See https://reviews.llvm.org/D37023 for reference.
270 E = cast->getSubExpr();
271 continue;
272 }
273 if (auto *call = dyn_cast<CallExpr>(E)) {
274 if (auto *Callee = call->getCalleeDecl()) {
275 if (Callee->hasAttr<CFReturnsRetainedAttr>() ||
276 Callee->hasAttr<NSReturnsRetainedAttr>() ||
277 Callee->hasAttr<NSReturnsAutoreleasedAttr>()) {
278 return callback(E, /*IsSafe=*/true,
279 OriginDependsOnFullExpressionTemporary,
280 PtrIsLifetimeBoundToOrigin);
281 }
282 }
283
284 if (call->isPRValue() && isSafePtrType(call->getType()))
285 return callback(E, /*IsSafe=*/true,
286 OriginDependsOnFullExpressionTemporary,
287 PtrIsLifetimeBoundToOrigin);
288
289 if (auto *memberCall = dyn_cast<CXXMemberCallExpr>(call)) {
290 if (auto *decl = memberCall->getMethodDecl()) {
291 std::optional<bool> IsGetterOfRefCt = isGetterOfSafePtr(decl);
292 if (IsGetterOfRefCt && *IsGetterOfRefCt) {
293 E = memberCall->getImplicitObjectArgument();
294 if (StopAtFirstRefCountedObj) {
295 return callback(E, /*IsSafe=*/true,
296 OriginDependsOnFullExpressionTemporary,
297 PtrIsLifetimeBoundToOrigin);
298 }
299 continue;
300 }
302 E = memberCall->getImplicitObjectArgument();
303 continue;
304 }
306 E = memberCall->getImplicitObjectArgument();
307 continue;
308 }
309 }
310 }
311
312 if (auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(E)) {
313 if (auto *Callee = operatorCall->getDirectCallee()) {
314 auto ClsName = safeGetName(Callee->getParent());
315 if (isRefType(ClsName) || isCheckedPtr(ClsName) ||
316 isRetainPtrOrOSPtr(ClsName) || ClsName == "unique_ptr" ||
317 ClsName == "UniqueRef" || ClsName == "WeakPtr" ||
318 ClsName == "WeakRef") {
319 if (operatorCall->getNumArgs() == 1) {
320 E = operatorCall->getArg(0);
321 continue;
322 }
323 }
324 auto *Method = dyn_cast<CXXMethodDecl>(Callee);
326 operatorCall->getNumArgs() == 1) {
327 E = operatorCall->getArg(0);
328 continue;
329 }
330 }
331 }
332
333 if (auto *callee = call->getDirectCallee()) {
334 if (isCtorOfSafePtr(callee)) {
335 if (StopAtFirstRefCountedObj)
336 return callback(E, /*IsSafe=*/true,
337 OriginDependsOnFullExpressionTemporary,
338 PtrIsLifetimeBoundToOrigin);
339
340 E = call->getArg(0);
341 continue;
342 }
343
344 if (isStdOrWTFMove(callee) && call->getNumArgs() == 1) {
345 E = call->getArg(0)->IgnoreParenCasts();
346 continue;
347 }
348
349 if (isSafePtrType(callee->getReturnType()))
350 return callback(E, /*IsSafe=*/true,
351 OriginDependsOnFullExpressionTemporary,
352 PtrIsLifetimeBoundToOrigin);
353
354 if (isSingleton(callee))
355 return callback(E, /*IsSafe=*/true,
356 OriginDependsOnFullExpressionTemporary,
357 PtrIsLifetimeBoundToOrigin);
358
359 if (callee->isInStdNamespace() && safeGetName(callee) == "forward") {
360 E = call->getArg(0);
361 continue;
362 }
363
364 if (isPtrConversion(callee)) {
365 E = call->getArg(0);
366 continue;
367 }
368
369 auto Name = safeGetName(callee);
370 if (Name == "__builtin___CFStringMakeConstantString" ||
371 Name == "NSStringFromSelector" || Name == "NSSelectorFromString" ||
372 Name == "NSStringFromClass" || Name == "NSClassFromString" ||
373 Name == "NSStringFromProtocol" || Name == "NSProtocolFromString")
374 return callback(E, /*IsSafe=*/true,
375 OriginDependsOnFullExpressionTemporary,
376 PtrIsLifetimeBoundToOrigin);
377 } else if (auto *CalleeE = call->getCallee()) {
378 if (auto *E = dyn_cast<DeclRefExpr>(CalleeE->IgnoreParenCasts())) {
379 if (isSingleton(E->getFoundDecl()))
380 return callback(E, /*IsSafe=*/true,
381 OriginDependsOnFullExpressionTemporary,
382 PtrIsLifetimeBoundToOrigin);
383 }
384
385 if (auto *MemberExpr = dyn_cast<CXXDependentScopeMemberExpr>(CalleeE)) {
386 auto *Base = MemberExpr->getBase();
387 auto MemberName = MemberExpr->getMember().getAsString();
388 bool IsGetter = MemberName == "get" || MemberName == "ptr";
389 if (Base && isSafePtrType(Base->getType()) && IsGetter)
390 return callback(E, /*IsSafe=*/true,
391 OriginDependsOnFullExpressionTemporary,
392 PtrIsLifetimeBoundToOrigin);
393 }
394 }
395
396 // Sometimes, canonical type erroneously turns Ref<T> into T.
397 // Workaround this problem by checking again if the original type was
398 // a SubstTemplateTypeParmType of a safe smart pointer type (e.g. Ref).
399 if (auto *CalleeDecl = call->getCalleeDecl()) {
400 if (auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) {
401 auto RetType = FD->getReturnType();
402 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(RetType)) {
403 if (auto *SubstType = Subst->desugar().getTypePtr()) {
404 if (auto *RD = dyn_cast<RecordType>(SubstType)) {
405 if (auto *CXX = dyn_cast<CXXRecordDecl>(RD->getDecl()))
406 if (isSafePtr(CXX))
407 return callback(E, /*IsSafe=*/true,
408 OriginDependsOnFullExpressionTemporary,
409 PtrIsLifetimeBoundToOrigin);
410 }
411 }
412 }
413 }
414 }
415
416 if (FollowLifetimeBound) {
417 SmallVector<const Expr *, 2> LifetimeBoundArgs;
418 findLifetimeBoundArgs(call, LifetimeBoundArgs);
419 if (!LifetimeBoundArgs.empty())
420 return tryToFindPtrOriginOfEach(
421 LifetimeBoundArgs, StopAtFirstRefCountedObj, isSafePtr,
422 isSafePtrType, isSafeGlobalDecl, callback,
423 /*OriginDependsOnFullExpressionTemporary=*/false,
424 /*PtrIsLifetimeBoundToOrigin=*/true);
425 }
426 }
427 if (auto *ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(E)) {
428 if (auto *Method = ObjCMsgExpr->getMethodDecl()) {
429 if (isSafePtrType(Method->getReturnType()))
430 return callback(E, /*IsSafe=*/true,
431 OriginDependsOnFullExpressionTemporary,
432 PtrIsLifetimeBoundToOrigin);
433 }
434 auto Selector = ObjCMsgExpr->getSelector();
435 auto NameForFirstSlot = Selector.getNameForSlot(0);
436 if ((NameForFirstSlot == "class" || NameForFirstSlot == "superclass") &&
438 return callback(E, /*IsSafe=*/true,
439 OriginDependsOnFullExpressionTemporary,
440 PtrIsLifetimeBoundToOrigin);
441 }
442 if (auto *ObjCProtocol = dyn_cast<ObjCProtocolExpr>(E))
443 return callback(ObjCProtocol, /*IsSafe=*/true,
444 OriginDependsOnFullExpressionTemporary,
445 PtrIsLifetimeBoundToOrigin);
446 if (auto *ObjCDict = dyn_cast<ObjCDictionaryLiteral>(E))
447 return callback(ObjCDict, /*IsSafe=*/true,
448 OriginDependsOnFullExpressionTemporary,
449 PtrIsLifetimeBoundToOrigin);
450 if (auto *ObjCArray = dyn_cast<ObjCArrayLiteral>(E))
451 return callback(ObjCArray, /*IsSafe=*/true,
452 OriginDependsOnFullExpressionTemporary,
453 PtrIsLifetimeBoundToOrigin);
454 if (auto *ObjCStr = dyn_cast<ObjCStringLiteral>(E))
455 return callback(ObjCStr, /*IsSafe=*/true,
456 OriginDependsOnFullExpressionTemporary,
457 PtrIsLifetimeBoundToOrigin);
458 if (auto *unaryOp = dyn_cast<UnaryOperator>(E)) {
459 // FIXME: Currently accepts ANY unary operator. Is it OK?
460 E = unaryOp->getSubExpr();
461 continue;
462 }
463 if (auto *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
464 if (StopAtFirstRefCountedObj)
465 return callback(BoxedExpr, /*IsSafe=*/true,
466 OriginDependsOnFullExpressionTemporary,
467 PtrIsLifetimeBoundToOrigin);
468 E = BoxedExpr->getSubExpr();
469 continue;
470 }
471 break;
472 }
473 // Some other expression.
474 return callback(E, /*IsSafe=*/false, OriginDependsOnFullExpressionTemporary,
475 PtrIsLifetimeBoundToOrigin);
476}
477
479 const Expr *E, bool StopAtFirstRefCountedObj, bool FollowLifetimeBound,
481 std::function<bool(const clang::QualType)> isSafePtrType,
482 std::function<bool(const clang::Decl *)> isSafeGlobalDecl,
483 std::function<bool(const clang::Expr *, bool /*IsSafe*/,
484 bool /*OriginDependsOnFullExpressionTemporary*/,
485 bool /*PtrIsLifetimeBoundToOrigin*/)>
486 callback) {
488 E, StopAtFirstRefCountedObj, FollowLifetimeBound, std::move(isSafePtr),
489 std::move(isSafePtrType), std::move(isSafeGlobalDecl),
490 std::move(callback),
491 /*OriginDependsOnFullExpressionTemporary=*/false,
492 /*PtrIsLifetimeBoundToOrigin=*/false);
493}
494
495bool originOutlivesCall(const Expr *E) {
496 assert(E);
497 auto IsCheckedLocalVarOrParam = [](const VarDecl *Decl) {
498 auto Ty = Decl->getType();
499 const CXXRecordDecl *CXXRD = Ty->getAsCXXRecordDecl();
500 if (!CXXRD)
501 CXXRD = Ty->getPointeeCXXRecordDecl();
502 if (CXXRD && isWeakPtr(CXXRD))
503 return false;
504 return Decl->isLocalVarDeclOrParm();
505 };
506 if (auto *Ref = dyn_cast<DeclRefExpr>(E)) {
507 auto *FoundDecl = Ref->getFoundDecl();
508 if (auto *D = dyn_cast_or_null<VarDecl>(FoundDecl)) {
509 if (IsCheckedLocalVarOrParam(D))
510 return true;
511 if (auto *ImplicitP = dyn_cast<ImplicitParamDecl>(D)) {
512 auto Kind = ImplicitP->getParameterKind();
513 if (Kind == ImplicitParamKind::ObjCSelf ||
517 return true;
518 }
519 } else if (auto *BD = dyn_cast_or_null<BindingDecl>(FoundDecl)) {
520 if (VarDecl *VD = BD->getHoldingVar()) {
521 if (IsCheckedLocalVarOrParam(VD))
522 return true;
523 }
524 }
525 }
527 return true; // A temporary lives until the end of this statement.
529 return true;
530
531 // TODO: checker for method calls on non-refcounted objects
532 return isa<CXXThisExpr>(E);
533}
534
535bool isNullPtr(const clang::Expr *E) {
537 return true;
538 if (auto *Int = dyn_cast_or_null<IntegerLiteral>(E)) {
539 if (Int->getValue().isZero())
540 return true;
541 }
542 return false;
543}
544
546 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(E)) {
547 if (auto *Callee = MCE->getDirectCallee()) {
548 auto Name = safeGetName(Callee);
549 if (Name == "get" || Name == "ptr")
550 E = MCE->getImplicitObjectArgument();
551 if (isa<CXXConversionDecl>(Callee))
552 E = MCE->getImplicitObjectArgument();
553 }
554 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
555 if (OCE->getOperator() == OO_Star && OCE->getNumArgs() == 1)
556 E = OCE->getArg(0);
557 }
558 const ValueDecl *D = nullptr;
559 if (auto *ME = dyn_cast<MemberExpr>(E))
560 D = ME->getMemberDecl();
561 else if (auto *IVR = dyn_cast<ObjCIvarRefExpr>(E))
562 D = IVR->getDecl();
563 if (!D)
564 return false;
565 auto T = D->getType();
566 return isOwnerPtrType(T) && T.isConstQualified();
567}
568
570 auto *ME = dyn_cast<MemberExpr>(E);
571 if (!ME)
572 return false;
573 auto *Base = ME->getBase();
574 if (!Base)
575 return false;
576 if (!isa<CXXThisExpr>(Base->IgnoreParenCasts()))
577 return false;
578 auto *D = ME->getMemberDecl();
579 if (!D)
580 return false;
581 auto T = D->getType();
582 auto *CXXRD = T->getAsCXXRecordDecl();
583 if (!CXXRD)
584 return false;
585 auto result = isCheckedPtrCapable(CXXRD);
586 return result && *result;
587}
588
589bool isAllocInit(const Expr *E, const Expr **InnerExpr) {
590 auto *ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(E);
591 if (auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
592 if (unsigned ExprCount = POE->getNumSemanticExprs()) {
593 auto *Expr = POE->getSemanticExpr(ExprCount - 1)->IgnoreParenCasts();
594 ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(Expr);
595 if (InnerExpr)
596 *InnerExpr = ObjCMsgExpr;
597 }
598 }
599 if (!ObjCMsgExpr)
600 return false;
601 auto Selector = ObjCMsgExpr->getSelector();
602 auto NameForFirstSlot = Selector.getNameForSlot(0);
603 if (NameForFirstSlot.starts_with("alloc") ||
604 NameForFirstSlot.starts_with("copy") ||
605 NameForFirstSlot.starts_with("mutableCopy")) {
606 if (auto *MD = ObjCMsgExpr->getMethodDecl()) {
607 if (MD->getReturnType()->isVoidType())
608 return false;
609 }
610 return true;
611 }
612 if (!NameForFirstSlot.starts_with("init") &&
613 !NameForFirstSlot.starts_with("_init"))
614 return false;
615 if (!ObjCMsgExpr->isInstanceMessage())
616 return false;
617 auto *Receiver = ObjCMsgExpr->getInstanceReceiver();
618 if (!Receiver)
619 return false;
620 Receiver = Receiver->IgnoreParenCasts();
621 if (auto *Inner = dyn_cast<ObjCMessageExpr>(Receiver)) {
622 if (InnerExpr)
623 *InnerExpr = Inner;
624 auto InnerSelector = Inner->getSelector();
625 return InnerSelector.getNameForSlot(0).starts_with("alloc");
626 } else if (auto *CE = dyn_cast<CallExpr>(Receiver)) {
627 if (InnerExpr)
628 *InnerExpr = CE;
629 if (auto *Callee = CE->getDirectCallee()) {
630 if (Callee->getDeclName().isIdentifier()) {
631 auto CalleeName = Callee->getName();
632 return CalleeName.starts_with("alloc");
633 }
634 }
635 }
636 return false;
637}
638
640 auto *PointeeType = TypePtr->getPointeeType().getTypePtrOrNull();
641 if (!PointeeType)
642 return nullptr;
643 auto *Desugared = PointeeType->getUnqualifiedDesugaredType();
644 if (!Desugared)
645 return nullptr;
646 if (auto *ObjCType = dyn_cast<ObjCInterfaceType>(Desugared))
647 return ObjCType->getDecl();
648 if (auto *ObjCType = dyn_cast<ObjCObjectType>(Desugared))
649 return ObjCType->getInterface();
650 return nullptr;
651}
652
654 : public ConstStmtVisitor<EnsureFunctionVisitor, bool> {
655public:
656 bool VisitStmt(const Stmt *S) {
657 for (const Stmt *Child : S->children()) {
658 if (Child && !Visit(Child))
659 return false;
660 }
661 return true;
662 }
663
664 bool VisitReturnStmt(const ReturnStmt *RS) {
665 if (auto *RV = RS->getRetValue()) {
666 RV = RV->IgnoreParenCasts();
667 if (isNullPtr(RV))
668 return true;
669 return isConstOwnerPtrMemberExpr(RV);
670 }
671 return false;
672 }
673};
674
676 auto *MCE = dyn_cast<CXXMemberCallExpr>(E);
677 if (!MCE)
678 return false;
679 auto *Callee = MCE->getDirectCallee();
680 if (!Callee)
681 return false;
682 auto *Body = Callee->getBody();
683 if (!Body || Callee->isVirtualAsWritten())
684 return false;
685 auto [CacheIt, IsNew] = Cache.insert(std::make_pair(Callee, false));
686 if (IsNew)
687 CacheIt->second = EnsureFunctionVisitor().Visit(Body);
688 return CacheIt->second;
689}
690
691} // namespace clang
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isACallToEnsureFn(const Expr *E) const
Definition ASTUtils.cpp:675
bool VisitReturnStmt(const ReturnStmt *RS)
Definition ASTUtils.cpp:664
bool VisitStmt(const Stmt *S)
Definition ASTUtils.cpp:656
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3134
Represents a function declaration or definition.
Definition Decl.h:2071
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
Expr * getBase() const
Definition Expr.h:3510
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
A (possibly-)qualified type.
Definition TypeBase.h:938
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8450
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3172
Expr * getRetValue()
Definition Stmt.h:3199
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
unsigned getNumArgs() const
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
The base class of the type hierarchy.
Definition TypeBase.h:1879
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:786
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD)
const FunctionDecl * getDeclWithMergedLifetimeBoundAttrs(const FunctionDecl *FD)
Top level wrappers for InstallAPI frontend operations.
bool isCtorOfSafePtr(const clang::FunctionDecl *F)
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isExprToGetCheckedPtrCapableMember(const clang::Expr *E)
Definition ASTUtils.cpp:569
bool isPtrConversion(const FunctionDecl *F)
std::optional< bool > isCheckedPtrCapable(const clang::CXXRecordDecl *R)
bool isAccessorOfNeverDestroyed(const CXXMethodDecl *M)
bool isView(const clang::QualType T)
bool isGetterOfUniquePtr(const CXXMethodDecl *M)
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:342
bool isStdView(const clang::CXXRecordDecl *R)
const FunctionProtoType * T
bool originOutlivesCall(const Expr *E)
For E referring to a ref-countable/-counted pointer/reference we return whether the pointee outlives ...
Definition ASTUtils.cpp:495
bool isImmortalVar(const VarDecl *V)
bool isRefCounted(const CXXRecordDecl *R)
bool isOwnerPtrType(const clang::QualType T)
static bool tryToFindPtrOriginImpl(const Expr *E, bool StopAtFirstRefCountedObj, bool FollowLifetimeBound, std::function< bool(const clang::CXXRecordDecl *)> isSafePtr, std::function< bool(const clang::QualType)> isSafePtrType, std::function< bool(const clang::Decl *)> isSafeGlobalDecl, std::function< bool(const clang::Expr *, bool, bool, bool)> callback, bool OriginDependsOnFullExpressionTemporary, bool PtrIsLifetimeBoundToOrigin)
Definition ASTUtils.cpp:149
std::optional< bool > isGetterOfSafePtr(const CXXMethodDecl *M)
bool isRetainPtrOrOSPtr(const std::string &Name)
bool isRefType(const std::string &Name)
bool isSafePtr(clang::CXXRecordDecl *Decl)
Definition ASTUtils.cpp:23
std::string safeGetName(const T *ASTNode)
Definition ASTUtils.h:109
ObjCInterfaceDecl * getObjCDeclFromObjCPtr(const Type *TypePtr)
Definition ASTUtils.cpp:639
bool isSingleton(const NamedDecl *F)
bool isNullPtr(const clang::Expr *E)
Definition ASTUtils.cpp:535
bool isCheckedPtr(const std::string &Name)
bool isStdOrWTFMove(const clang::FunctionDecl *F)
U cast(CodeGen::Address addr)
Definition Address.h:327
bool tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj, bool FollowLifetimeBound, std::function< bool(const clang::CXXRecordDecl *)> isSafePtr, std::function< bool(const clang::QualType)> isSafePtrType, std::function< bool(const clang::Decl *)> isSafeGlobalDecl, std::function< bool(const clang::Expr *, bool, bool, bool)> callback)
This function de-facto defines a set of transformations that we consider safe (in heuristical sense).
Definition ASTUtils.cpp:478
bool isAllocInit(const Expr *E, const Expr **InnerExpr)
Definition ASTUtils.cpp:589
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6025
@ CXXThis
Parameter for C++ 'this' argument.
Definition Decl.h:1775
@ CXXVTT
Parameter for C++ virtual table pointers.
Definition Decl.h:1778
@ ObjCSelf
Parameter for Objective-C 'self' argument.
Definition Decl.h:1769
@ ObjCCmd
Parameter for Objective-C '_cmd' argument.
Definition Decl.h:1772
bool isConstOwnerPtrMemberExpr(const clang::Expr *E)
Definition ASTUtils.cpp:545
bool isWeakPtr(const CXXRecordDecl *R)
int const char * function
Definition c++config.h:31