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/CXXInheritance.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/ExprCXX.h"
15#include <optional>
16
17namespace clang {
18
19std::pair<const Expr *, bool>
20tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj) {
21  while (E) {
22    if (auto *cast = dyn_cast<CastExpr>(E)) {
23      if (StopAtFirstRefCountedObj) {
24        if (auto *ConversionFunc =
25                dyn_cast_or_null<FunctionDecl>(cast->getConversionFunction())) {
26          if (isCtorOfRefCounted(ConversionFunc))
27            return {E, true};
28        }
29      }
30      // FIXME: This can give false "origin" that would lead to false negatives
31      // in checkers. See https://reviews.llvm.org/D37023 for reference.
32      E = cast->getSubExpr();
33      continue;
34    }
35    if (auto *call = dyn_cast<CallExpr>(E)) {
36      if (auto *memberCall = dyn_cast<CXXMemberCallExpr>(call)) {
37        std::optional<bool> IsGetterOfRefCt = isGetterOfRefCounted(memberCall->getMethodDecl());
38        if (IsGetterOfRefCt && *IsGetterOfRefCt) {
39          E = memberCall->getImplicitObjectArgument();
40          if (StopAtFirstRefCountedObj) {
41            return {E, true};
42          }
43          continue;
44        }
45      }
46
47      if (auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(E)) {
48        if (operatorCall->getNumArgs() == 1) {
49          E = operatorCall->getArg(0);
50          continue;
51        }
52      }
53
54      if (auto *callee = call->getDirectCallee()) {
55        if (isCtorOfRefCounted(callee)) {
56          if (StopAtFirstRefCountedObj)
57            return {E, true};
58
59          E = call->getArg(0);
60          continue;
61        }
62
63        if (isPtrConversion(callee)) {
64          E = call->getArg(0);
65          continue;
66        }
67      }
68    }
69    if (auto *unaryOp = dyn_cast<UnaryOperator>(E)) {
70      // FIXME: Currently accepts ANY unary operator. Is it OK?
71      E = unaryOp->getSubExpr();
72      continue;
73    }
74
75    break;
76  }
77  // Some other expression.
78  return {E, false};
79}
80
81bool isASafeCallArg(const Expr *E) {
82  assert(E);
83  if (auto *Ref = dyn_cast<DeclRefExpr>(E)) {
84    if (auto *D = dyn_cast_or_null<VarDecl>(Ref->getFoundDecl())) {
85      if (isa<ParmVarDecl>(D) || D->isLocalVarDecl())
86        return true;
87    }
88  }
89
90  // TODO: checker for method calls on non-refcounted objects
91  return isa<CXXThisExpr>(E);
92}
93
94} // namespace clang
95