clang 23.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"
17#include <optional>
18
19namespace clang {
20
24
26 const Expr *E, bool StopAtFirstRefCountedObj,
28 std::function<bool(const clang::QualType)> isSafePtrType,
29 std::function<bool(const clang::Decl *)> isSafeGlobalDecl,
30 std::function<bool(const clang::Expr *, bool)> callback) {
31 while (E) {
32 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
33 if (auto *VD = dyn_cast_or_null<VarDecl>(DRE->getDecl())) {
34 auto QT = VD->getType();
35 auto IsImmortal = safeGetName(VD) == "NSApp";
36 if (VD->hasGlobalStorage() && (IsImmortal || QT.isConstQualified()))
37 return callback(E, true);
38 if (VD->hasGlobalStorage() && isSafeGlobalDecl(VD))
39 return callback(E, true);
40 }
41 }
42 if (auto *tempExpr = dyn_cast<MaterializeTemporaryExpr>(E)) {
43 E = tempExpr->getSubExpr();
44 continue;
45 }
46 if (auto *tempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) {
47 E = tempExpr->getSubExpr();
48 continue;
49 }
50 if (auto *tempExpr = dyn_cast<CXXConstructExpr>(E)) {
51 if (auto *C = tempExpr->getConstructor()) {
52 if (auto *Class = C->getParent(); Class && isSafePtr(Class))
53 return callback(E, true);
54 break;
55 }
56 }
57 if (auto *TempExpr = dyn_cast<CXXUnresolvedConstructExpr>(E)) {
58 if (isSafePtrType(TempExpr->getTypeAsWritten()))
59 return callback(TempExpr, true);
60 }
61 if (auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
62 if (auto *RF = POE->getResultExpr()) {
63 E = RF;
64 continue;
65 }
66 }
67 if (auto *tempExpr = dyn_cast<ParenExpr>(E)) {
68 E = tempExpr->getSubExpr();
69 continue;
70 }
71 if (auto *OpaqueValue = dyn_cast<OpaqueValueExpr>(E)) {
72 E = OpaqueValue->getSourceExpr();
73 continue;
74 }
75 if (auto *Expr = dyn_cast<ConditionalOperator>(E)) {
76 return tryToFindPtrOrigin(Expr->getTrueExpr(), StopAtFirstRefCountedObj,
77 isSafePtr, isSafePtrType, isSafeGlobalDecl,
78 callback) &&
79 tryToFindPtrOrigin(Expr->getFalseExpr(), StopAtFirstRefCountedObj,
80 isSafePtr, isSafePtrType, isSafeGlobalDecl,
81 callback);
82 }
83 if (auto *cast = dyn_cast<CastExpr>(E)) {
84 if (StopAtFirstRefCountedObj) {
85 if (auto *ConversionFunc =
86 dyn_cast_or_null<FunctionDecl>(cast->getConversionFunction())) {
87 if (isCtorOfSafePtr(ConversionFunc))
88 return callback(E, true);
89 }
90 if (isa<CXXFunctionalCastExpr>(E) && isSafePtrType(cast->getType()))
91 return callback(E, true);
92 }
93 // FIXME: This can give false "origin" that would lead to false negatives
94 // in checkers. See https://reviews.llvm.org/D37023 for reference.
95 E = cast->getSubExpr();
96 continue;
97 }
98 if (auto *call = dyn_cast<CallExpr>(E)) {
99 if (auto *Callee = call->getCalleeDecl()) {
100 if (Callee->hasAttr<CFReturnsRetainedAttr>() ||
101 Callee->hasAttr<NSReturnsRetainedAttr>() ||
102 Callee->hasAttr<NSReturnsAutoreleasedAttr>()) {
103 return callback(E, true);
104 }
105 }
106
107 if (auto *memberCall = dyn_cast<CXXMemberCallExpr>(call)) {
108 if (auto *decl = memberCall->getMethodDecl()) {
109 std::optional<bool> IsGetterOfRefCt = isGetterOfSafePtr(decl);
110 if (IsGetterOfRefCt && *IsGetterOfRefCt) {
111 E = memberCall->getImplicitObjectArgument()->IgnoreParenCasts();
112 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
113 if (auto *Decl = dyn_cast_or_null<VarDecl>(DRE->getDecl())) {
114 if (Decl->isLocalVarDeclOrParm()) {
115 if (StopAtFirstRefCountedObj)
116 return callback(E, true);
117 }
118 }
119 }
120 continue;
121 }
122 }
123 }
124
125 if (auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(E)) {
126 if (auto *Callee = operatorCall->getDirectCallee()) {
127 auto ClsName = safeGetName(Callee->getParent());
128 if (isRefType(ClsName) || isCheckedPtr(ClsName) ||
129 isRetainPtrOrOSPtr(ClsName) || ClsName == "unique_ptr" ||
130 ClsName == "UniqueRef" || ClsName == "WeakPtr" ||
131 ClsName == "WeakRef") {
132 if (operatorCall->getNumArgs() == 1) {
133 E = operatorCall->getArg(0);
134 continue;
135 }
136 }
137 }
138 }
139
140 if (auto *callee = call->getDirectCallee()) {
141 if (isCtorOfSafePtr(callee)) {
142 if (StopAtFirstRefCountedObj)
143 return callback(E, true);
144
145 E = call->getArg(0);
146 continue;
147 }
148
149 if (isStdOrWTFMove(callee) && call->getNumArgs() == 1) {
150 E = call->getArg(0)->IgnoreParenCasts();
151 continue;
152 }
153
154 if (isSafePtrType(callee->getReturnType()))
155 return callback(E, true);
156
157 if (isSingleton(callee))
158 return callback(E, true);
159
160 if (callee->isInStdNamespace() && safeGetName(callee) == "forward") {
161 E = call->getArg(0);
162 continue;
163 }
164
165 if (isPtrConversion(callee)) {
166 E = call->getArg(0);
167 continue;
168 }
169
170 auto Name = safeGetName(callee);
171 if (Name == "__builtin___CFStringMakeConstantString" ||
172 Name == "NSStringFromSelector" || Name == "NSSelectorFromString" ||
173 Name == "NSStringFromClass" || Name == "NSClassFromString" ||
174 Name == "NSStringFromProtocol" || Name == "NSProtocolFromString")
175 return callback(E, true);
176 } else if (auto *CalleeE = call->getCallee()) {
177 if (auto *E = dyn_cast<DeclRefExpr>(CalleeE->IgnoreParenCasts())) {
178 if (isSingleton(E->getFoundDecl()))
179 return callback(E, true);
180 }
181
182 if (auto *MemberExpr = dyn_cast<CXXDependentScopeMemberExpr>(CalleeE)) {
183 auto *Base = MemberExpr->getBase();
184 auto MemberName = MemberExpr->getMember().getAsString();
185 bool IsGetter = MemberName == "get" || MemberName == "ptr";
186 if (Base && isSafePtrType(Base->getType()) && IsGetter)
187 return callback(E, true);
188 }
189 }
190
191 // Sometimes, canonical type erroneously turns Ref<T> into T.
192 // Workaround this problem by checking again if the original type was
193 // a SubstTemplateTypeParmType of a safe smart pointer type (e.g. Ref).
194 if (auto *CalleeDecl = call->getCalleeDecl()) {
195 if (auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) {
196 auto RetType = FD->getReturnType();
197 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(RetType)) {
198 if (auto *SubstType = Subst->desugar().getTypePtr()) {
199 if (auto *RD = dyn_cast<RecordType>(SubstType)) {
200 if (auto *CXX = dyn_cast<CXXRecordDecl>(RD->getDecl()))
201 if (isSafePtr(CXX))
202 return callback(E, true);
203 }
204 }
205 }
206 }
207 }
208 }
209 if (auto *ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(E)) {
210 if (auto *Method = ObjCMsgExpr->getMethodDecl()) {
211 if (isSafePtrType(Method->getReturnType()))
212 return callback(E, true);
213 }
214 if (ObjCMsgExpr->isClassMessage())
215 return callback(E, true);
216 auto Selector = ObjCMsgExpr->getSelector();
217 auto NameForFirstSlot = Selector.getNameForSlot(0);
218 if ((NameForFirstSlot == "class" || NameForFirstSlot == "superclass") &&
220 return callback(E, true);
221 }
222 if (auto *ObjCProtocol = dyn_cast<ObjCProtocolExpr>(E))
223 return callback(ObjCProtocol, true);
224 if (auto *ObjCDict = dyn_cast<ObjCDictionaryLiteral>(E))
225 return callback(ObjCDict, true);
226 if (auto *ObjCArray = dyn_cast<ObjCArrayLiteral>(E))
227 return callback(ObjCArray, true);
228 if (auto *ObjCStr = dyn_cast<ObjCStringLiteral>(E))
229 return callback(ObjCStr, true);
230 if (auto *unaryOp = dyn_cast<UnaryOperator>(E)) {
231 // FIXME: Currently accepts ANY unary operator. Is it OK?
232 E = unaryOp->getSubExpr();
233 continue;
234 }
235 if (auto *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
236 if (StopAtFirstRefCountedObj)
237 return callback(BoxedExpr, true);
238 E = BoxedExpr->getSubExpr();
239 continue;
240 }
241 break;
242 }
243 // Some other expression.
244 return callback(E, false);
245}
246
247bool isASafeCallArg(const Expr *E) {
248 assert(E);
249 auto IsCheckedLocalVarOrParam = [](const VarDecl *Decl) {
250 auto Ty = Decl->getType();
251 const CXXRecordDecl *CXXRD = Ty->getAsCXXRecordDecl();
252 if (!CXXRD)
253 CXXRD = Ty->getPointeeCXXRecordDecl();
254 if (CXXRD && isWeakPtr(CXXRD))
255 return false;
256 return Decl->isLocalVarDeclOrParm();
257 };
258 if (auto *Ref = dyn_cast<DeclRefExpr>(E)) {
259 auto *FoundDecl = Ref->getFoundDecl();
260 if (auto *D = dyn_cast_or_null<VarDecl>(FoundDecl)) {
261 if (IsCheckedLocalVarOrParam(D))
262 return true;
263 if (auto *ImplicitP = dyn_cast<ImplicitParamDecl>(D)) {
264 auto Kind = ImplicitP->getParameterKind();
265 if (Kind == ImplicitParamKind::ObjCSelf ||
269 return true;
270 }
271 } else if (auto *BD = dyn_cast_or_null<BindingDecl>(FoundDecl)) {
272 if (VarDecl *VD = BD->getHoldingVar()) {
273 if (IsCheckedLocalVarOrParam(VD))
274 return true;
275 }
276 }
277 }
279 return true; // A temporary lives until the end of this statement.
281 return true;
282
283 // TODO: checker for method calls on non-refcounted objects
284 return isa<CXXThisExpr>(E);
285}
286
287bool isNullPtr(const clang::Expr *E) {
289 return true;
290 if (auto *Int = dyn_cast_or_null<IntegerLiteral>(E)) {
291 if (Int->getValue().isZero())
292 return true;
293 }
294 return false;
295}
296
298 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(E)) {
299 if (auto *Callee = MCE->getDirectCallee()) {
300 auto Name = safeGetName(Callee);
301 if (Name == "get" || Name == "ptr")
302 E = MCE->getImplicitObjectArgument();
303 if (isa<CXXConversionDecl>(Callee))
304 E = MCE->getImplicitObjectArgument();
305 }
306 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
307 if (OCE->getOperator() == OO_Star && OCE->getNumArgs() == 1)
308 E = OCE->getArg(0);
309 }
310 const ValueDecl *D = nullptr;
311 if (auto *ME = dyn_cast<MemberExpr>(E))
312 D = ME->getMemberDecl();
313 else if (auto *IVR = dyn_cast<ObjCIvarRefExpr>(E))
314 D = IVR->getDecl();
315 if (!D)
316 return false;
317 auto T = D->getType();
318 return isOwnerPtrType(T) && T.isConstQualified();
319}
320
322 auto *ME = dyn_cast<MemberExpr>(E);
323 if (!ME)
324 return false;
325 auto *Base = ME->getBase();
326 if (!Base)
327 return false;
328 if (!isa<CXXThisExpr>(Base->IgnoreParenCasts()))
329 return false;
330 auto *D = ME->getMemberDecl();
331 if (!D)
332 return false;
333 auto T = D->getType();
334 auto *CXXRD = T->getAsCXXRecordDecl();
335 if (!CXXRD)
336 return false;
337 auto result = isCheckedPtrCapable(CXXRD);
338 return result && *result;
339}
340
341bool isAllocInit(const Expr *E, const Expr **InnerExpr) {
342 auto *ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(E);
343 if (auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
344 if (unsigned ExprCount = POE->getNumSemanticExprs()) {
345 auto *Expr = POE->getSemanticExpr(ExprCount - 1)->IgnoreParenCasts();
346 ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(Expr);
347 if (InnerExpr)
348 *InnerExpr = ObjCMsgExpr;
349 }
350 }
351 if (!ObjCMsgExpr)
352 return false;
353 auto Selector = ObjCMsgExpr->getSelector();
354 auto NameForFirstSlot = Selector.getNameForSlot(0);
355 if (NameForFirstSlot.starts_with("alloc") ||
356 NameForFirstSlot.starts_with("copy") ||
357 NameForFirstSlot.starts_with("mutableCopy")) {
358 if (auto *MD = ObjCMsgExpr->getMethodDecl()) {
359 if (MD->getReturnType()->isVoidType())
360 return false;
361 }
362 return true;
363 }
364 if (!NameForFirstSlot.starts_with("init") &&
365 !NameForFirstSlot.starts_with("_init"))
366 return false;
367 if (!ObjCMsgExpr->isInstanceMessage())
368 return false;
369 auto *Receiver = ObjCMsgExpr->getInstanceReceiver();
370 if (!Receiver)
371 return false;
372 Receiver = Receiver->IgnoreParenCasts();
373 if (auto *Inner = dyn_cast<ObjCMessageExpr>(Receiver)) {
374 if (InnerExpr)
375 *InnerExpr = Inner;
376 auto InnerSelector = Inner->getSelector();
377 return InnerSelector.getNameForSlot(0).starts_with("alloc");
378 } else if (auto *CE = dyn_cast<CallExpr>(Receiver)) {
379 if (InnerExpr)
380 *InnerExpr = CE;
381 if (auto *Callee = CE->getDirectCallee()) {
382 if (Callee->getDeclName().isIdentifier()) {
383 auto CalleeName = Callee->getName();
384 return CalleeName.starts_with("alloc");
385 }
386 }
387 }
388 return false;
389}
390
392 : public ConstStmtVisitor<EnsureFunctionVisitor, bool> {
393public:
394 bool VisitStmt(const Stmt *S) {
395 for (const Stmt *Child : S->children()) {
396 if (Child && !Visit(Child))
397 return false;
398 }
399 return true;
400 }
401
402 bool VisitReturnStmt(const ReturnStmt *RS) {
403 if (auto *RV = RS->getRetValue()) {
404 RV = RV->IgnoreParenCasts();
405 if (isNullPtr(RV))
406 return true;
407 return isConstOwnerPtrMemberExpr(RV);
408 }
409 return false;
410 }
411};
412
414 auto *MCE = dyn_cast<CXXMemberCallExpr>(E);
415 if (!MCE)
416 return false;
417 auto *Callee = MCE->getDirectCallee();
418 if (!Callee)
419 return false;
420 auto *Body = Callee->getBody();
421 if (!Body || Callee->isVirtualAsWritten())
422 return false;
423 auto [CacheIt, IsNew] = Cache.insert(std::make_pair(Callee, false));
424 if (IsNew)
425 CacheIt->second = EnsureFunctionVisitor().Visit(Body);
426 return CacheIt->second;
427}
428
429} // 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 C++ struct/union/class.
Definition DeclCXX.h:258
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:413
bool VisitReturnStmt(const ReturnStmt *RS)
Definition ASTUtils.cpp:402
bool VisitStmt(const Stmt *S)
Definition ASTUtils.cpp:394
This represents one expression.
Definition Expr.h:112
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3103
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3367
Expr * getBase() const
Definition Expr.h:3444
A (possibly-)qualified type.
Definition TypeBase.h:937
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3170
Expr * getRetValue()
Definition Stmt.h:3197
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:86
child_range children()
Definition Stmt.cpp:304
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
Represents a variable declaration or definition.
Definition Decl.h:924
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
The JSON file list parser is used to communicate input to InstallAPI.
bool isCtorOfSafePtr(const clang::FunctionDecl *F)
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isExprToGetCheckedPtrCapableMember(const clang::Expr *E)
Definition ASTUtils.cpp:321
bool isPtrConversion(const FunctionDecl *F)
std::optional< bool > isCheckedPtrCapable(const clang::CXXRecordDecl *R)
bool tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj, 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)> callback)
This function de-facto defines a set of transformations that we consider safe (in heuristical sense).
Definition ASTUtils.cpp:25
bool isASafeCallArg(const Expr *E)
For E referring to a ref-countable/-counted pointer/reference we return whether it's a safe call argu...
Definition ASTUtils.cpp:247
bool isRefCounted(const CXXRecordDecl *R)
bool isOwnerPtrType(const clang::QualType T)
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:21
std::string safeGetName(const T *ASTNode)
Definition ASTUtils.h:95
bool isSingleton(const NamedDecl *F)
bool isNullPtr(const clang::Expr *E)
Definition ASTUtils.cpp:287
bool isCheckedPtr(const std::string &Name)
bool isStdOrWTFMove(const clang::FunctionDecl *F)
U cast(CodeGen::Address addr)
Definition Address.h:327
bool isAllocInit(const Expr *E, const Expr **InnerExpr)
Definition ASTUtils.cpp:341
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5979
@ CXXThis
Parameter for C++ 'this' argument.
Definition Decl.h:1751
@ CXXVTT
Parameter for C++ virtual table pointers.
Definition Decl.h:1754
@ ObjCSelf
Parameter for Objective-C 'self' argument.
Definition Decl.h:1745
@ ObjCCmd
Parameter for Objective-C '_cmd' argument.
Definition Decl.h:1748
bool isConstOwnerPtrMemberExpr(const clang::Expr *E)
Definition ASTUtils.cpp:297
bool isWeakPtr(const CXXRecordDecl *R)
int const char * function
Definition c++config.h:31