[clang] [analyzer] Add alpha.cplusplus.PlacementSelfCopy checker (PR #233525)

Donát Nagy via cfe-commits cfe-commits at lists.llvm.org
Thu Nov 26 02:05:47 PST 2026


================
@@ -0,0 +1,541 @@
+//===- PlacementSelfCopyChecker.cpp -----------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Defines a checker that finds placement new expressions that access the
+// target storage through the old object while the new object is being
+// constructed, e.g. `::new (p) T(*p)`. A call that is not inlined is assumed
+// to access the old object passed to it; when it is the copy or move
+// constructor called by placement new itself, it is reported as a self-copy.
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/AST/ExprCXX.h"
+#include "clang/AST/ParentMap.h"
+#include "clang/Basic/Builtins.h"
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+
+using namespace clang;
+using namespace ento;
+
+using PlacementKey = std::pair<const CXXNewExpr *, const StackFrame *>;
+REGISTER_MAP_WITH_PROGRAMSTATE(PlacementTargets, PlacementKey,
+                               const MemRegion *)
+// Variables that refer to the old storage, mapped to the placement target.
+REGISTER_MAP_WITH_PROGRAMSTATE(SourceVars, const MemRegion *, const MemRegion *)
+// Frames of methods called on the old storage, mapped to the placement target.
+REGISTER_MAP_WITH_PROGRAMSTATE(SourceFrames, const StackFrame *,
+                               const MemRegion *)
+REGISTER_TRAIT_WITH_PROGRAMSTATE(PendingSelfCopy, const MemRegion *)
+
+namespace {
+class PlacementSelfCopyChecker
+    : public Checker<check::PostCall, check::PreCall, check::Bind,
+                     check::Location, check::PostStmt<LambdaExpr>,
+                     check::PostStmt<CXXNewExpr>> {
+  const BugType BT{this, "Placement new initialized from its own storage",
+                   categories::MemoryError};
+  const BugType AccessBT{this, "Placement new accesses its own storage",
+                         categories::MemoryError};
+
+  void reportAccess(const Expr *E, CheckerContext &C) const;
+  void reportSelfCopy(const Expr *Arg, CheckerContext &C) const;
+  void reportPendingSelfCopy(const CallEvent &Call, CheckerContext &C) const;
+
+public:
+  void checkPostCall(const CallEvent &Call, CheckerContext &C) const;
+  void checkPreCall(const CallEvent &Call, CheckerContext &C) const;
+  void checkBind(SVal Loc, SVal Val, const Stmt *S, bool AtDeclInit,
+                 CheckerContext &C) const;
+  void checkLocation(SVal Loc, bool IsLoad, const Stmt *S,
+                     CheckerContext &C) const;
+  void checkPostStmt(const LambdaExpr *LE, CheckerContext &C) const;
+  void checkPostStmt(const CXXNewExpr *NE, CheckerContext &C) const;
+};
+} // namespace
+
+namespace {
+struct Extent {
+  const MemRegion *Base;
+  int64_t Begin;
+  std::optional<int64_t> End;
+};
+} // namespace
+
+// Base class subobjects keep their own extent.
+static const MemRegion *stripCasts(const MemRegion *R) {
+  return R->StripCasts(/*StripBaseAndDerivedCasts=*/false);
+}
+
+static std::optional<Extent> getExtent(const MemRegion *R, ASTContext &Ctx) {
+  RegionOffset Offset = R->getAsOffset();
+  if (!Offset.isValid() || Offset.hasSymbolicOffset())
+    return std::nullopt;
+  Extent E{Offset.getRegion(), Offset.getOffset(), std::nullopt};
+  QualType Ty;
+  if (const auto *TR = dyn_cast<TypedValueRegion>(R))
+    Ty = TR->getValueType();
+  else if (const auto *SR = dyn_cast<SymbolicRegion>(R))
+    Ty = SR->getPointeeStaticType();
+  if (!Ty.isNull() && !Ty->isIncompleteType())
+    E.End = E.Begin + Ctx.getTypeSize(Ty);
+  return E;
+}
+
+// Returns the extents of A and B if both are known within the same base.
+static std::optional<std::pair<Extent, Extent>>
+getKnownExtents(const MemRegion *A, const MemRegion *B, ASTContext &Ctx) {
+  std::optional<Extent> EA = getExtent(A, Ctx), EB = getExtent(B, Ctx);
+  if (!EA || !EB || !EA->End || !EB->End || EA->Base != EB->Base)
+    return std::nullopt;
+  return std::make_pair(*EA, *EB);
+}
+
+static bool overlaps(const MemRegion *A, const MemRegion *B, ASTContext &Ctx) {
+  if (auto E = getKnownExtents(A, B, Ctx))
+    return E->first.Begin < *E->second.End && E->second.Begin < *E->first.End;
+  A = stripCasts(A);
+  return A == stripCasts(B) || A->isSubRegionOf(B) || B->isSubRegionOf(A);
+}
+
+static bool isWithin(const MemRegion *R, const MemRegion *Container,
+                     ASTContext &Ctx) {
+  if (auto E = getKnownExtents(R, Container, Ctx))
+    return E->second.Begin <= E->first.Begin && *E->first.End <= *E->second.End;
+  R = stripCasts(R);
+  return R == stripCasts(Container) || R->isSubRegionOf(Container);
+}
+
+// Limits R to the placed object instead of the whole buffer it lives in.
+static const MemRegion *getPlacedRegion(const CXXNewExpr *NE,
+                                        const MemRegion *R, CheckerContext &C) {
+  ASTContext &Ctx = C.getASTContext();
+  QualType Ty = NE->getAllocatedType();
+  if (NE->isArray()) {
+    std::optional<const Expr *> Size = NE->getArraySize();
+    std::optional<llvm::APSInt> N =
+        Size && *Size ? (*Size)->getIntegerConstantExpr(Ctx) : std::nullopt;
+    if (!N)
+      return R;
+    Ty =
+        Ctx.getConstantArrayType(Ty, *N, nullptr, ArraySizeModifier::Normal, 0);
+  }
+  const auto *SR = dyn_cast<SubRegion>(R);
+  const auto *TR = dyn_cast<TypedValueRegion>(R);
+  if (!SR || (TR && Ctx.hasSameUnqualifiedType(TR->getValueType(), Ty)))
+    return R;
+  return C.getStoreManager().getRegionManager().getElementRegion(
+      Ty, C.getSValBuilder().makeArrayIndex(0), SR, Ctx);
+}
+
+// Calls that return their argument or its address without accessing it, e.g.
+// `std::move(X)`, `std::addressof(X)` or `&X` with an overloaded `operator&`.
+static bool isPassThroughCall(const CallExpr *CE) {
+  if (!CE || CE->getNumArgs() != 1)
+    return false;
+  if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE))
+    return OCE->getOperator() == OO_Amp;
+  const FunctionDecl *FD = CE->getDirectCallee();
+  switch (FD ? FD->getBuiltinID() : 0) {
+  case Builtin::BIaddressof:
+  case Builtin::BI__addressof:
+  case Builtin::BI__builtin_addressof:
+  case Builtin::BIas_const:
+  case Builtin::BIforward:
+  case Builtin::BIforward_like:
+  case Builtin::BImove:
+  case Builtin::BImove_if_noexcept:
+    return true;
+  default:
+    return false;
+  }
+}
+
+// Collects the variables that E accesses memory through, e.g. `O` for
+// `O->X[1]`, `O.A + 1` or `O.data()`, and both `A` and `B` for
+// `(C ? A : B).X`.
+static void collectBaseVars(const Expr *E,
+                            SmallVectorImpl<const VarDecl *> &Vars,
+                            bool &ViaThis) {
----------------
NagyDonat wrote:

> collectBaseVars is for what happens later, inside the functions that receive the old object. For example, inside constructor the parameter and this , both refer to the same storage, so the values can't tell them apart, while [class.cdtor]/2 depends on whether the glvalue was obtained from this

I see... :slightly_frowning_face: You are right that the "values can't tell them apart" i.e. the standard modeling procedure done by the analyzer is not sufficient to detect these issues.

However, your code still tries to reimplement very complex logic, which necessarily means that it will take shortcuts. (E.g. `collectBaseVars` says that in `(C ? A : B).X` both `A` and `B` are accessed, while the standard modeling procedure splits the path and separately handles the cases where `A` is accessed and where `B` is accessed – I strongly suspect that there are others in the code that I didn't review yet.) I fear that the discrepancies and "friction" between your shortcuts and the standard modeling procedure would make this checker fragile, inaccurate and difficult to maintain.

I feel that understanding the details and risks of this implementation would be a significant effort for me, and I don't know when (/whether) will I have time for it.

https://github.com/llvm/llvm-project/pull/233525


More information about the cfe-commits mailing list