[clang] 80fd8f8 - [CIR] Add a points-to analysis skeleton (#244356)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Dec 4 20:46:24 PST 2026
Author: Bruno Cardoso Lopes
Date: 2026-12-04T20:46:18-08:00
New Revision: 80fd8f850a7d9701b736460dda43e2ecb24cd54b
URL: https://github.com/llvm/llvm-project/commit/80fd8f850a7d9701b736460dda43e2ecb24cd54b
DIFF: https://github.com/llvm/llvm-project/commit/80fd8f850a7d9701b736460dda43e2ecb24cd54b.diff
LOG: [CIR] Add a points-to analysis skeleton (#244356)
The CIR alias analysis stops at loads, so it cannot tell anything about
pointers loaded from memory. Since Clang emits a cir.alloca for every
local, including local pointers, most pointer uses in CIR go through a
load.
This adds a minimal points-to analysis that follows pointers through
memory. It is inclusion based and flow insensitive, tracks cir.alloca
objects through cir.store and cir.load, and treats any other use of an
address as an escape. Its work is bounded by PointsToLimits, using the
limits of a similar analysis tuned on large C++ code bases downstream.
Results are reported as optimization remarks in the points-to category,
which the tests check on CIR and on C++ sources.
This is the base for the lifetime checker in the ClangIR incubator and
for other downstream optimizations we'd like to upstream later. More
operations, track unknown states, an alias analysis built on the
points-to sets, and more optimizations to the solver will come in follow
up PRs, see `clang/docs/CIR/PointsToAnalysis.md` for the roadmap.
## Why it doesn't use MLIR dataflow framework
MLIR's sparse data-flow framework skips operations without results, so
it never sees cir.store and can't follow pointers through memory. Doing
that needs either the dense, flow-sensitive framework or a custom
analysis on DataFlowSolver, and both also depend on DeadCodeAnalysis and
SparseConstantPropagation.
I wrote the same analysis on DataFlowSolver, and it gives identical
points-to sets on all 7.2M functions of LLVM, Clang and MLIR at -O3. It
is 9.7x slower alone, 22x slower with the analyses it depends on (0.74%
of compile time, up to 4.5% for one TU), and 78x slower as a dense
flow-sensitive version (2.3 s on one PassBuilder.cpp function, against
under 1 ms).
This PR approach costs 0.033% of compile time. The gap is the
framework's bookkeeping: a state per value and per object, dependency
tracking between states, and a worklist of program points. Its worklist
only helps on long reverse copy chains, which a cheaper worklist solver,
already planned, will handle.
Added:
clang/docs/CIR/PointsToAnalysis.md
clang/include/clang/CIR/Dialect/Analysis/CIRPointsToAnalysis.h
clang/lib/CIR/Dialect/Analysis/CIRPointsToAnalysis.cpp
clang/test/CIR/Analysis/points-to-limits.cir
clang/test/CIR/Analysis/points-to.cir
clang/test/CIR/Analysis/points-to.cpp
clang/test/CIR/lib/Analysis/TestCIRPointsToAnalysis.cpp
Modified:
clang/docs/CIR/index.md
clang/lib/CIR/Dialect/Analysis/CMakeLists.txt
clang/test/CIR/lib/Analysis/CMakeLists.txt
clang/tools/cir-opt/cir-opt.cpp
Removed:
################################################################################
diff --git a/clang/docs/CIR/PointsToAnalysis.md b/clang/docs/CIR/PointsToAnalysis.md
new file mode 100644
index 00000000000000..be646d68683bfe
--- /dev/null
+++ b/clang/docs/CIR/PointsToAnalysis.md
@@ -0,0 +1,241 @@
+# ClangIR Points-to Analysis
+
+
+## Introduction
+
+This document describes the points-to analysis for CIR. For each pointer value
+in a function, the analysis computes the set of objects the pointer may point
+to. Transformations can use these sets to tell which objects a memory access
+may touch, and which objects may be reached by code the analysis does not see.
+
+The analysis is in an early stage. It tracks only a small set of operations,
+and it is meant to grow in small steps. The last part of this document
+describes what it handles today and what is expected to come next.
+
+The analysis is implemented in
+`clang/lib/CIR/Dialect/Analysis/CIRPointsToAnalysis.cpp`.
+
+## Relation to Alias Analysis
+
+CIR also has alias analysis, built on MLIR's `mlir::AliasAnalysis`. Its basic
+implementation, `CIRBasicAliasAnalysis`, walks a pointer back through address
+computations such as `cir.get_member` and `cir.ptr_stride` to the object it
+comes from. It stops at loads, so two pointers loaded from memory may always
+alias as far as it can tell. This is common in CIR, because Clang emits a
+`cir.alloca` for every local variable, including local pointer variables, and
+every use of such a variable loads the pointer from its slot.
+
+The points-to analysis follows pointers through memory instead, which is the
+part the basic alias analysis cannot see. The two are meant to complement each
+other. A later change can register an alias analysis implementation based on
+the points-to sets after the basic one, so that it is only asked about the
+pairs the basic analysis cannot answer.
+
+## Objects and Points-to Sets
+
+An object is identified by the operation that allocates it. Currently only
+`cir.alloca` objects are tracked, and an object is represented by the
+`cir.alloca` result. A points-to set holds tracked objects and may also contain
+"unknown", which stands for any object the analysis does not track: memory
+reached through a function argument or a global, memory written by code the
+analysis does not see, and tracked objects whose address escaped.
+
+The analysis keeps two kinds of sets:
+
+- for each value, the objects the value may point to,
+- for each tracked object, the objects its memory may point to, that is, what
+ a load from the object may return.
+
+For example:
+
+```c
+int a;
+int *p = &a;
+int **pp = &p;
+```
+
+Each variable is a `cir.alloca` object: `a`, `p` and `pp`. The address of each
+variable points to the variable itself, so the `cir.alloca` result for `p`
+points to `{p}`. The memory sets are `p -> {a}` and `pp -> {p}`. Loading from
+`pp` gives a value that points to `{p}`, and loading again through that value
+gives a value that points to `{a}`.
+
+## Computing the Sets
+
+The analysis is inclusion based and flow insensitive. Every operation adds
+members to some sets, and sets never lose members. The order of operations and
+the control flow between them are not taken into account: a pointer stored
+into an object anywhere in the function may be loaded back from it anywhere in
+the function.
+
+The rules are:
+
+- A `cir.alloca` result points to the object it allocates.
+- A null pointer constant points to no object.
+- `cir.store %v, %p`: for every object `%p` points to, the memory of that object
+ may point to everything `%v` points to.
+- `%v = cir.load %p`: `%v` points to everything the memory of the objects `%p`
+ points to may point to.
+- Any other value, such as a function argument or the result of an operation
+ the analysis does not model, points to unknown. So does a value defined
+ outside the operation the analysis was computed for.
+- If `%p` points to unknown, a load through `%p` returns unknown and a store
+ through `%p` makes the stored objects escape.
+- Comparing two pointers with `cir.cmp`, or testing a pointer for null with
+ `cir.cast ptr_to_bool`, doesn't make the objects they point to escape: the
+ result is a boolean, from which code can't get back to an object. Such code
+ does learn something about the address, so a user that needs to know whether
+ an address may be compared, for example to fold `&a == p`, can't rely on
+ escapes for it.
+- Any other use of a value makes the objects it points to escape.
+
+When an object escapes, code the analysis does not see may access it, so its
+memory is assumed to point to unknown in addition to what was stored in it, and
+every object stored in it escapes as well.
+
+The rules are applied to every operation, repeatedly, until no set changes.
+Because sets only grow, this terminates.
+
+## Limits
+
+The analysis has limits on its size and on the number of times it visits
+operations, so that large functions don't make compilation slow. The limits
+are given by `PointsToLimits`:
+
+- The number of operations. As soon as it finds more than `maxOperations`
+ (5000) operations nested in the operation it is computed for, the analysis
+ gives up.
+- The work to compute the sets, counted as the number of times an operation is
+ visited. Every operation is visited again each time a set changed during the
+ previous visit of the function. The limit is `workPerOperation` (32) visits
+ for each operation, and at least `minWork` (100000) visits in total. When it
+ is reached, the analysis gives up.
+- The size of a set. A set that grows past `maxSetSize` (100) objects is
+ replaced by unknown. The analysis no longer knows which objects the set held,
+ so they escape. Because a visit merges sets, this also bounds the work of a
+ single visit.
+
+When the analysis hits the operation or the work limit, it drops every set, and
+every value points to unknown.
+
+## Using the Results
+
+`PointsToAnalysis` is built for an operation, usually a function, and computes
+all the sets in its constructor. `getPointsTo(value)` returns the set of a
+value. Values the analysis did not compute a set for point to unknown.
+
+```c++
+cir::PointsToAnalysis pointsTo(funcOp);
+const cir::PointsToSet &set = pointsTo.getPointsTo(ptr);
+if (!set.containsUnknown())
+ for (mlir::Value object : set.getObjects())
+ ...
+```
+
+Unknown may stand for a tracked object whose address escaped. The analysis
+doesn't tell yet which objects escaped, so a set that contains unknown has to
+be treated as possibly pointing to any object, including the tracked ones.
+
+A set with no object and no unknown belongs to a null pointer, or to a value
+loaded from memory that only null pointers, or nothing, were stored to.
+
+A set can be printed with `<<`, which prints the names of its objects, sorted,
+followed by unknown if the set contains it, for example `[a, b, unknown]`.
+
+The sets describe the IR at the time the analysis is built and are not updated
+afterwards. A pass that changes the IR in a way that affects how pointers flow
+must build a new analysis before using it again.
+
+For example:
+
+```c
+void f(void) {
+ int a, b;
+ int *p = &a, *q = &b;
+ *p = 1;
+ *q = 2;
+}
+```
+
+```mlir
+%1 = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+%2 = cir.alloca "b" align(4) : !cir.ptr<!s32i>
+%3 = cir.alloca "p" align(8) init : !cir.ptr<!cir.ptr<!s32i>>
+%4 = cir.alloca "q" align(8) init : !cir.ptr<!cir.ptr<!s32i>>
+cir.store align(8) %1, %3 : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+cir.store align(8) %2, %4 : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+%6 = cir.load deref align(8) %3 : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+cir.store align(4) %5, %6 : !s32i, !cir.ptr<!s32i>
+%8 = cir.load deref align(8) %4 : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+cir.store align(4) %7, %8 : !s32i, !cir.ptr<!s32i>
+```
+
+The two stores go through `%6` and `%8`, which are load results, so the basic
+alias analysis cannot tell them apart. The memory of `p` only ever holds `a`
+and the memory of `q` only ever holds `b`, so `%6` points to `{a}` and `%8`
+points to `{b}`: the two stores write to
diff erent objects.
+
+## Remarks
+
+The analysis doesn't emit remarks by itself. A client that wants to report the
+results it got calls `emitRemarks()` after building the analysis, optionally
+with a subcategory naming the client. The results are then reported through
+MLIR's optimization remarks, in the `points-to` category. They are only emitted
+when remarks are enabled for that category, for example with
+`--remarks-filter=points-to` in `cir-opt`, and cost nothing otherwise. There
+are two kinds:
+
+- Analysis remarks give the set of every pointer loaded in the function, on the
+ `cir.load` that loads it.
+- Missed remarks tell where the analysis lost precision: each object whose
+ address escapes, on the operation that first made it escape, each set that
+ grew past the size limit and was replaced by unknown, and the operation or
+ work limit when the analysis gave up on it, on the operation it is computed
+ for.
+
+For the example above, in a file `f.c`, the `test-cir-points-to` pass, which
+calls `emitRemarks()`, reports with `--remarks-filter=points-to`:
+
+```
+f.c:4:4: remark: [Analysis] PointsTo | Category:points-to | Function=f | Remark="points to [a]", RemarkId=1
+f.c:5:4: remark: [Analysis] PointsTo | Category:points-to | Function=f | Remark="points to [b]", RemarkId=2
+```
+
+`--remarks-filter-analyse` and `--remarks-filter-missed` select only one of the
+two kinds.
+
+## Current Limitations and Next Steps
+
+The analysis is deliberately small, and conservative wherever it does not model
+something. The following are expected to be added, roughly in this order, each
+as its own change:
+
+- Following address computations (`cir.get_member`, `cir.ptr_stride`,
+ `cir.get_element`, casts), so that the address of a member or an element
+ that is only loaded from and stored to does not make the object escape.
+ Objects stay whole: when such an address escapes, the whole object escapes,
+ since code can get back to the rest of the object from it, for example with
+ `offsetof`.
+- Telling users of the analysis which objects escaped, so that an object whose
+ address never escapes can be told apart from what unknown stands for. Today
+ this is only reported through remarks.
+- Calls, using the side effect attributes of `cir.call` and the copy and move
+ semantics of special member functions.
+- Values passed through region results and block arguments.
+- Heap allocations and globals as tracked objects.
+- An alias analysis implementation based on the points-to sets, registered
+ after `CIRBasicAliasAnalysis`, as described above.
+- A solver that only revisits the operations affected by a change, instead of
+ every operation.
+
+## Testing
+
+The analysis is tested with the `test-cir-points-to` pass of `cir-opt`, which
+computes the analysis for each function and calls `emitRemarks()`. The remarks
+are checked with `-verify-diagnostics`. CIR generated from C++ sources is tested the same
+way, with the expected remarks written next to the source lines. The
+`max-operations`, `min-work`, `work-per-operation` and `max-set-size` options
+of the pass override the limits.
+
+The tests are in `clang/test/CIR/Analysis/`, and the test pass is in
+`clang/test/CIR/lib/Analysis/`.
diff --git a/clang/docs/CIR/index.md b/clang/docs/CIR/index.md
index d11235c704a0b7..aeb99fdaafb765 100644
--- a/clang/docs/CIR/index.md
+++ b/clang/docs/CIR/index.md
@@ -40,6 +40,7 @@ ABILowering
CleanupAndEHDesign
CodeDuplication
EmitPoints
+PointsToAnalysis
```
## RFCs
diff --git a/clang/include/clang/CIR/Dialect/Analysis/CIRPointsToAnalysis.h b/clang/include/clang/CIR/Dialect/Analysis/CIRPointsToAnalysis.h
new file mode 100644
index 00000000000000..1878875aceed1f
--- /dev/null
+++ b/clang/include/clang/CIR/Dialect/Analysis/CIRPointsToAnalysis.h
@@ -0,0 +1,193 @@
+//===- CIRPointsToAnalysis.h - Points-to analysis for CIR -------*- 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
+//
+//===----------------------------------------------------------------------===//
+//
+// This file defines PointsToAnalysis, which computes the set of objects each
+// value in an operation may point to.
+//
+// The analysis is inclusion based and flow insensitive: a pointer stored into
+// a memory location at any point may be loaded back from it at any point.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef CLANG_CIR_DIALECT_ANALYSIS_CIRPOINTSTOANALYSIS_H
+#define CLANG_CIR_DIALECT_ANALYSIS_CIRPOINTSTOANALYSIS_H
+
+#include "mlir/IR/Operation.h"
+#include "mlir/IR/Value.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/SetVector.h"
+#include "llvm/Support/Compiler.h"
+#include "llvm/Support/raw_ostream.h"
+
+#include <utility>
+
+namespace cir {
+
+/// The objects a value may point to.
+///
+/// An object is identified by the value that allocates it, which for now is
+/// always the result of a cir.alloca. A set may also contain "unknown", which
+/// stands for any object the analysis does not track: memory reached through a
+/// function argument or a global, memory written by code the analysis cannot
+/// see, and any tracked object whose address has escaped.
+class PointsToSet {
+public:
+ /// The tracked objects in the set.
+ llvm::ArrayRef<mlir::Value> getObjects() const {
+ return objects.getArrayRef();
+ }
+
+ /// Whether the set contains "unknown". "unknown" may stand for any object
+ /// whose address escaped, including tracked ones, so a set that contains it
+ /// may point to any object.
+ bool containsUnknown() const { return unknown; }
+
+ /// Print the set as the sorted names of the cir.alloca operations of its
+ /// objects, followed by "unknown" if the set contains it, e.g. "[a, b]".
+ void print(llvm::raw_ostream &os) const;
+ LLVM_DUMP_METHOD void dump() const;
+
+private:
+ friend class PointsToAnalysis;
+
+ /// Whether the set grew past the size limit of the analysis and was replaced
+ /// by "unknown". Such a set no longer names the objects it held.
+ bool hitSizeLimit() const { return sizeLimitHit; }
+
+ /// Add `object` to the set. Return true if the set changed.
+ bool insert(mlir::Value object) { return objects.insert(object); }
+
+ /// Add "unknown" to the set. Return true if the set changed.
+ bool insertUnknown() { return !std::exchange(unknown, true); }
+
+ /// Add every member of `other` to the set. Return true if the set changed.
+ bool merge(const PointsToSet &other);
+
+ /// Remove the tracked objects and keep only "unknown". The set stays this way
+ /// from then on.
+ void replaceWithUnknown();
+
+ llvm::SmallSetVector<mlir::Value, 4> objects;
+ bool unknown = false;
+ bool sizeLimitHit = false;
+};
+
+inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os,
+ const PointsToSet &set) {
+ set.print(os);
+ return os;
+}
+
+/// Limits on the work done by PointsToAnalysis. When the operation is too
+/// large, or the sets take too long to compute, the analysis gives up, and
+/// every value points to "unknown".
+struct PointsToLimits {
+ /// The largest number of operations the analysis is computed for.
+ unsigned maxOperations = 5000;
+
+ /// The work allowed to compute the sets, counted as the number of times an
+ /// operation is visited. It is `workPerOperation` for each operation, and at
+ /// least `minWork`.
+ unsigned workPerOperation = 32;
+ unsigned minWork = 100000;
+
+ /// The largest number of objects a set holds. A set that grows past it is
+ /// replaced by "unknown", and its objects escape.
+ unsigned maxSetSize = 100;
+};
+
+/// Computes the points-to set of every value in an operation.
+///
+/// The analysis looks at the operations nested in the operation it is built
+/// for and tracks the addresses of cir.alloca objects through cir.store and
+/// cir.load. Comparing a tracked address or testing it for null doesn't let
+/// code reach the object, but any other use of a tracked address is treated
+/// as an escape: the object may then be read or written by code the analysis
+/// does not model, so its memory is assumed to hold "unknown", and everything
+/// stored in it escapes too. Values the analysis does not compute a set for,
+/// such as function arguments or the results of operations it does not model,
+/// point to "unknown". A null pointer constant points to no object.
+///
+/// The sets describe the IR at the time the analysis is built and are not
+/// updated when it changes.
+class PointsToAnalysis {
+public:
+ explicit PointsToAnalysis(mlir::Operation *op,
+ const PointsToLimits &limits = PointsToLimits());
+ PointsToAnalysis(const PointsToAnalysis &) = delete;
+ PointsToAnalysis &operator=(const PointsToAnalysis &) = delete;
+
+ /// Return the objects `value` may point to. Values that were not analyzed
+ /// point to "unknown".
+ const PointsToSet &getPointsTo(mlir::Value value) const;
+
+ /// Report the results as optimization remarks in the "points-to" category,
+ /// when remarks are enabled for it: the set of every loaded pointer as an
+ /// analysis remark, and what made the analysis lose precision as missed
+ /// remarks: the objects that escaped, the sets that were replaced by
+ /// "unknown", and the operation or work limit, if the analysis gave up on
+ /// one. `subCategory` names the client, if any.
+ /// The analysis doesn't emit remarks by itself.
+ void emitRemarks(llvm::StringRef subCategory = {}) const;
+
+private:
+ /// Compute the sets of the values in `op`.
+ void compute(mlir::Operation *op);
+
+ /// Apply the effect of `op` on the points-to sets. Return true if any set
+ /// changed.
+ bool visit(mlir::Operation *op);
+
+ /// Add the members of `from` to `to`, replacing `to` by "unknown" if it grows
+ /// past the size limit. `op` is the operation being visited. Return true if
+ /// anything changed.
+ bool addTo(PointsToSet &to, const PointsToSet &from, mlir::Operation *op);
+
+ /// Record that `objects` may be accessed by code the analysis cannot see,
+ /// because of `op`. Return true if anything changed.
+ bool markEscaped(llvm::ArrayRef<mlir::Value> objects, mlir::Operation *op);
+
+ /// Drop every set, so that every value points to "unknown".
+ void dropAllSets();
+
+ /// The operation the analysis is built for.
+ mlir::Operation *root;
+
+ PointsToLimits limits;
+
+ /// The objects each value may point to.
+ llvm::DenseMap<mlir::Value, PointsToSet> valuePointsTo;
+
+ /// The objects the memory of each tracked object may point to.
+ llvm::DenseMap<mlir::Value, PointsToSet> memoryPointsTo;
+
+ /// Tracked objects whose address escaped, and the operation that first made
+ /// each of them escape.
+ llvm::MapVector<mlir::Value, mlir::Operation *> escaped;
+
+ /// The operations that made a set grow past the size limit, and the number of
+ /// objects the set held.
+ llvm::SmallVector<std::pair<mlir::Operation *, size_t>> sizeLimitHits;
+
+ /// Whether the analysis gave up because the operation has more than
+ /// `maxOperations` operations.
+ bool operationLimitHit = false;
+
+ /// The work limit, in operation visits, if the analysis gave up on it, and 0
+ /// otherwise.
+ uint64_t workLimitHit = 0;
+
+ /// The set returned for values that were not analyzed.
+ PointsToSet unknownSet;
+};
+
+} // namespace cir
+
+#endif // CLANG_CIR_DIALECT_ANALYSIS_CIRPOINTSTOANALYSIS_H
diff --git a/clang/lib/CIR/Dialect/Analysis/CIRPointsToAnalysis.cpp b/clang/lib/CIR/Dialect/Analysis/CIRPointsToAnalysis.cpp
new file mode 100644
index 00000000000000..e58f05cfd6fac4
--- /dev/null
+++ b/clang/lib/CIR/Dialect/Analysis/CIRPointsToAnalysis.cpp
@@ -0,0 +1,297 @@
+//===- CIRPointsToAnalysis.cpp - Points-to analysis for CIR ---------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "clang/CIR/Dialect/Analysis/CIRPointsToAnalysis.h"
+#include "mlir/IR/Remarks.h"
+#include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/TypeSwitch.h"
+#include "llvm/Support/DebugLog.h"
+
+#include <algorithm>
+
+#define DEBUG_TYPE "cir-points-to-analysis"
+
+using namespace cir;
+
+/// The name used to print `object`: the name of the cir.alloca allocating it.
+static llvm::StringRef getObjectName(mlir::Value object) {
+ llvm::StringRef name = object.getDefiningOp<cir::AllocaOp>().getName();
+ return name.empty() ? "<unnamed>" : name;
+}
+
+/// The options of every remark emitted for the analysis of `root`.
+static mlir::remark::RemarkOpts getRemarkOpts(llvm::StringRef name,
+ mlir::Operation *root,
+ llvm::StringRef subCategory) {
+ mlir::remark::RemarkOpts opts = mlir::remark::RemarkOpts::name(name)
+ .category("points-to")
+ .subCategory(subCategory);
+ if (auto func = mlir::dyn_cast<cir::FuncOp>(root))
+ opts = opts.function(func.getSymName());
+ return opts;
+}
+
+/// Walk the operations nested in `op`, without `op` itself.
+static mlir::WalkResult
+walkNested(mlir::Operation *op,
+ llvm::function_ref<mlir::WalkResult(mlir::Operation *)> callback) {
+ for (mlir::Region ®ion : op->getRegions())
+ if (region.walk(callback).wasInterrupted())
+ return mlir::WalkResult::interrupt();
+ return mlir::WalkResult::advance();
+}
+
+//===----------------------------------------------------------------------===//
+// PointsToSet
+//===----------------------------------------------------------------------===//
+
+bool PointsToSet::merge(const PointsToSet &other) {
+ assert(!sizeLimitHit && "merging into a set that hit the size limit");
+ bool changed = objects.set_union(other.objects);
+ if (other.unknown)
+ changed |= insertUnknown();
+ return changed;
+}
+
+void PointsToSet::replaceWithUnknown() {
+ objects.clear();
+ unknown = true;
+ sizeLimitHit = true;
+}
+
+void PointsToSet::print(llvm::raw_ostream &os) const {
+ llvm::SmallVector<llvm::StringRef> names =
+ llvm::map_to_vector(objects, getObjectName);
+ llvm::sort(names);
+ if (unknown)
+ names.push_back("unknown");
+ os << '[';
+ llvm::interleaveComma(names, os);
+ os << ']';
+}
+
+#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
+void PointsToSet::dump() const {
+ print(llvm::errs());
+ llvm::errs() << '\n';
+}
+#endif
+
+//===----------------------------------------------------------------------===//
+// PointsToAnalysis
+//===----------------------------------------------------------------------===//
+
+PointsToAnalysis::PointsToAnalysis(mlir::Operation *op,
+ const PointsToLimits &limits)
+ : root(op), limits(limits) {
+ unknownSet.insertUnknown();
+ compute(op);
+}
+
+void PointsToAnalysis::compute(mlir::Operation *op) {
+ // Create the sets of the values the analysis computes before solving, so a
+ // value never changes from "not analyzed", which reads as "unknown", to a set
+ // with fewer members. Each cir.alloca result points to the object it
+ // allocates, each cir.load result starts out pointing to nothing, and a null
+ // pointer constant points to nothing.
+ uint64_t numOperations = 0;
+ mlir::WalkResult tooLarge = walkNested(op, [&](mlir::Operation *nested) {
+ if (++numOperations > limits.maxOperations)
+ return mlir::WalkResult::interrupt();
+ llvm::TypeSwitch<mlir::Operation *>(nested)
+ .Case([&](cir::AllocaOp alloca) {
+ valuePointsTo[alloca.getResult()].insert(alloca.getResult());
+ })
+ .Case([&](cir::LoadOp load) {
+ valuePointsTo.try_emplace(load.getResult());
+ })
+ .Case([&](cir::ConstantOp constant) {
+ if (constant.isNullPtr())
+ valuePointsTo.try_emplace(constant.getResult());
+ });
+ return mlir::WalkResult::advance();
+ });
+ if (tooLarge.wasInterrupted()) {
+ dropAllSets();
+ operationLimitHit = true;
+ return;
+ }
+
+ // Sets only grow, so revisiting every operation until nothing changes
+ // terminates. The work limit bounds how long that may take.
+ uint64_t budget = std::max<uint64_t>(
+ limits.minWork, uint64_t(limits.workPerOperation) * numOperations);
+ uint64_t work = 0;
+ unsigned iterations = 0;
+ bool changed;
+ do {
+ changed = false;
+ mlir::WalkResult result = walkNested(op, [&](mlir::Operation *nested) {
+ if (++work > budget)
+ return mlir::WalkResult::interrupt();
+ changed |= visit(nested);
+ return mlir::WalkResult::advance();
+ });
+ if (result.wasInterrupted()) {
+ dropAllSets();
+ workLimitHit = budget;
+ return;
+ }
+ ++iterations;
+ } while (changed);
+ LDBG() << "Solved in " << iterations << " iterations";
+}
+
+void PointsToAnalysis::emitRemarks(llvm::StringRef subCategory) const {
+ if (!root->getContext()->getRemarkEngine())
+ return;
+
+ if (operationLimitHit)
+ mlir::remark::missed(root->getLoc(),
+ getRemarkOpts("OperationLimit", root, subCategory))
+ << mlir::remark::add("gave up: more than {0} operations",
+ limits.maxOperations);
+ if (workLimitHit)
+ mlir::remark::missed(root->getLoc(),
+ getRemarkOpts("WorkLimit", root, subCategory))
+ << mlir::remark::add("gave up: more than {0} operation visits",
+ workLimitHit);
+ for (auto [object, op] : escaped)
+ mlir::remark::missed(op->getLoc(),
+ getRemarkOpts("Escaped", root, subCategory))
+ << mlir::remark::add("the address of {0} escapes",
+ getObjectName(object));
+ for (auto [op, size] : sizeLimitHits)
+ mlir::remark::missed(op->getLoc(),
+ getRemarkOpts("SizeLimit", root, subCategory))
+ << mlir::remark::add(
+ "a set of {0} objects is replaced by unknown, the limit is {1}",
+ size, limits.maxSetSize);
+
+ root->walk([&](cir::LoadOp load) {
+ if (!mlir::isa<cir::PointerType>(load.getType()))
+ return;
+ mlir::remark::analysis(load.getLoc(),
+ getRemarkOpts("PointsTo", root, subCategory))
+ << mlir::remark::add("points to {0}", getPointsTo(load.getResult()));
+ });
+}
+
+const PointsToSet &PointsToAnalysis::getPointsTo(mlir::Value value) const {
+ auto it = valuePointsTo.find(value);
+ if (it == valuePointsTo.end())
+ return unknownSet;
+ return it->second;
+}
+
+void PointsToAnalysis::dropAllSets() {
+ // Values without a set point to "unknown", so dropping every set is enough
+ // to make every answer conservative.
+ valuePointsTo.clear();
+ memoryPointsTo.clear();
+ escaped.clear();
+ sizeLimitHits.clear();
+}
+
+bool PointsToAnalysis::addTo(PointsToSet &to, const PointsToSet &from,
+ mlir::Operation *op) {
+ // A set that hit the size limit no longer names its objects, so the objects
+ // added to it are lost. Make them escape, so that dropping them is
+ // conservative.
+ if (to.hitSizeLimit())
+ return markEscaped(from.getObjects(), op);
+
+ bool changed = to.merge(from);
+ if (to.getObjects().size() <= limits.maxSetSize)
+ return changed;
+
+ // The objects the set held are lost too. They would escape when the
+ // operations that added them are visited again, but making them escape here
+ // doesn't depend on the order operations are visited in.
+ llvm::SmallVector<mlir::Value> objects(to.getObjects());
+ sizeLimitHits.emplace_back(op, objects.size());
+ to.replaceWithUnknown();
+ // `to` may be an element of memoryPointsTo, which markEscaped() can grow, so
+ // it must not be used after this point.
+ markEscaped(objects, op);
+ return true;
+}
+
+bool PointsToAnalysis::markEscaped(llvm::ArrayRef<mlir::Value> objects,
+ mlir::Operation *op) {
+ bool changed = false;
+ llvm::SmallVector<mlir::Value> worklist;
+ for (mlir::Value object : objects)
+ if (escaped.insert({object, op}).second)
+ worklist.push_back(object);
+
+ while (!worklist.empty()) {
+ mlir::Value object = worklist.pop_back_val();
+ changed = true;
+
+ // Code the analysis cannot see may store any address it can reach into an
+ // escaped object, and may follow the addresses already stored there.
+ PointsToSet &memory = memoryPointsTo[object];
+ memory.insertUnknown();
+ for (mlir::Value inner : memory.getObjects())
+ if (escaped.insert({inner, op}).second)
+ worklist.push_back(inner);
+ }
+ return changed;
+}
+
+bool PointsToAnalysis::visit(mlir::Operation *op) {
+ // The analysis does not know what any other operation does with an address
+ // it receives, so the objects it points to escape. The results of such an
+ // operation have no set, and so point to "unknown".
+ auto escapeOperands = [&] {
+ bool changed = false;
+ for (mlir::Value operand : op->getOperands())
+ changed |= markEscaped(getPointsTo(operand).getObjects(), op);
+ return changed;
+ };
+
+ return llvm::TypeSwitch<mlir::Operation *, bool>(op)
+ .Case([&](cir::StoreOp store) {
+ const PointsToSet &addr = getPointsTo(store.getAddr());
+ const PointsToSet &value = getPointsTo(store.getValue());
+ bool changed = false;
+ for (mlir::Value object : addr.getObjects()) {
+ changed |= addTo(memoryPointsTo[object], value, op);
+ if (escaped.contains(object))
+ changed |= markEscaped(value.getObjects(), op);
+ }
+ // A store through an address the analysis does not know may write to
+ // an escaped object or to memory it does not track at all.
+ if (addr.containsUnknown())
+ changed |= markEscaped(value.getObjects(), op);
+ return changed;
+ })
+ .Case([&](cir::LoadOp load) {
+ const PointsToSet &addr = getPointsTo(load.getAddr());
+ PointsToSet loaded;
+ for (mlir::Value object : addr.getObjects()) {
+ auto it = memoryPointsTo.find(object);
+ if (it != memoryPointsTo.end())
+ loaded.merge(it->second);
+ }
+ if (addr.containsUnknown())
+ loaded.insertUnknown();
+ return addTo(valuePointsTo[load.getResult()], loaded, op);
+ })
+ // Comparing addresses or testing one for null gives a boolean, from
+ // which no code can get back to an object, so nothing escapes.
+ .Case([&](cir::CmpOp) { return false; })
+ .Case([&](cir::CastOp cast) {
+ if (cast.getKind() == cir::CastKind::ptr_to_bool)
+ return false;
+ return escapeOperands();
+ })
+ .Default([&](mlir::Operation *) { return escapeOperands(); });
+}
diff --git a/clang/lib/CIR/Dialect/Analysis/CMakeLists.txt b/clang/lib/CIR/Dialect/Analysis/CMakeLists.txt
index 45ecc00c7d20e0..077abfffa7b7bc 100644
--- a/clang/lib/CIR/Dialect/Analysis/CMakeLists.txt
+++ b/clang/lib/CIR/Dialect/Analysis/CMakeLists.txt
@@ -1,6 +1,7 @@
add_clang_library(MLIRCIRAnalysis
CIRAliasAnalysis.cpp
CIRBasicAliasAnalysis.cpp
+ CIRPointsToAnalysis.cpp
DEPENDS
mlir-headers
diff --git a/clang/test/CIR/Analysis/points-to-limits.cir b/clang/test/CIR/Analysis/points-to-limits.cir
new file mode 100644
index 00000000000000..dbed34b9230f03
--- /dev/null
+++ b/clang/test/CIR/Analysis/points-to-limits.cir
@@ -0,0 +1,144 @@
+// RUN: split-file %s %t
+// RUN: cir-opt %t/operations.cir --remarks-filter=points-to -verify-diagnostics \
+// RUN: -pass-pipeline='builtin.module(cir.func(test-cir-points-to{max-operations=5}))'
+// RUN: cir-opt %t/work.cir --remarks-filter=points-to -verify-diagnostics \
+// RUN: -pass-pipeline='builtin.module(cir.func(test-cir-points-to{min-work=14 work-per-operation=1}))'
+// RUN: cir-opt %t/work-per-operation.cir --remarks-filter=points-to -verify-diagnostics \
+// RUN: -pass-pipeline='builtin.module(cir.func(test-cir-points-to{min-work=1 work-per-operation=3}))'
+// RUN: cir-opt %t/set-size.cir --remarks-filter=points-to -verify-diagnostics \
+// RUN: -pass-pipeline='builtin.module(cir.func(test-cir-points-to{max-set-size=2}))'
+
+//--- operations.cir
+
+// The limit is 5 operations, not counting the function itself. The first
+// function is at the limit and is analyzed. The second one has one more
+// operation, so the analysis gives up, and every value points to unknown
+// objects.
+
+!s32i = !cir.int<s, 32>
+cir.func @at_limit() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [a]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// expected-remark @below {{gave up: more than 5 operations}}
+cir.func @over_limit() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %b = cir.alloca "b" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [unknown]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+//--- work.cir
+
+// The load comes before the store, so the sets only settle after visiting the
+// 5 operations of the function three times, 15 visits. The work limit is the
+// larger of 14 and one visit for each operation, so the analysis gives up.
+
+!s32i = !cir.int<s, 32>
+// expected-remark @below {{gave up: more than 14 operation visits}}
+cir.func @work() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [unknown]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.return
+}
+
+//--- work-per-operation.cir
+
+// The same function, with a work limit of three visits for each operation,
+// 15 visits, which is enough.
+
+!s32i = !cir.int<s, 32>
+cir.func @work_per_operation() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [a]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.return
+}
+
+//--- set-size.cir
+
+// The addresses of three slots are stored into `p`, more than the limit of two
+// objects, so the memory of `p` is replaced by unknown objects and a load from
+// `p` gives unknown. The three slots escape, and so does `x`, which `s1` holds.
+//
+// The address of `s4` is only known to reach `p` after the set was replaced,
+// because it is loaded from `q` before being stored there. It escapes when the
+// store into `p` is visited again, and so does `y`.
+
+!s32i = !cir.int<s, 32>
+!pi = !cir.ptr<!s32i>
+!ppi = !cir.ptr<!pi>
+!pppi = !cir.ptr<!ppi>
+cir.func @set_size() {
+ %x = cir.alloca "x" align(4) : !pi
+ %y = cir.alloca "y" align(4) : !pi
+ %s1 = cir.alloca "s1" align(8) : !ppi
+ %s2 = cir.alloca "s2" align(8) : !ppi
+ %s3 = cir.alloca "s3" align(8) : !ppi
+ %s4 = cir.alloca "s4" align(8) : !ppi
+ %p = cir.alloca "p" align(8) : !pppi
+ %q = cir.alloca "q" align(8) : !pppi
+ cir.store %x, %s1 : !pi, !ppi
+ cir.store %y, %s4 : !pi, !ppi
+ cir.store %s1, %p : !ppi, !pppi
+ cir.store %s2, %p : !ppi, !pppi
+ // expected-remark @below {{a set of 3 objects is replaced by unknown, the limit is 2}}
+ // expected-remark @below {{the address of s1 escapes}}
+ // expected-remark @below {{the address of s2 escapes}}
+ // expected-remark @below {{the address of s3 escapes}}
+ // expected-remark @below {{the address of x escapes}}
+ cir.store %s3, %p : !ppi, !pppi
+ // expected-remark @below {{points to [s4]}}
+ %l = cir.load %q : !pppi, !ppi
+ // expected-remark @below {{the address of s4 escapes}}
+ // expected-remark @below {{the address of y escapes}}
+ cir.store %l, %p : !ppi, !pppi
+ cir.store %s4, %q : !ppi, !pppi
+ // expected-remark @below {{points to [unknown]}}
+ %v = cir.load %p : !pppi, !ppi
+ // expected-remark @below {{points to [x, unknown]}}
+ %w = cir.load %s1 : !ppi, !pi
+ // expected-remark @below {{points to [y, unknown]}}
+ %z = cir.load %s4 : !ppi, !pi
+ cir.return
+}
+
+// `p1` holds the address of one object and `p2` of two, so a pointer that may
+// point to both slots loads three objects. Its set is replaced by unknown
+// objects, and the three objects escape.
+
+cir.func @value_set_size() {
+ %x = cir.alloca "x" align(4) : !pi
+ %y = cir.alloca "y" align(4) : !pi
+ %z = cir.alloca "z" align(4) : !pi
+ %p1 = cir.alloca "p1" align(8) : !ppi
+ %p2 = cir.alloca "p2" align(8) : !ppi
+ %pp = cir.alloca "pp" align(8) : !pppi
+ cir.store %x, %p1 : !pi, !ppi
+ cir.store %y, %p2 : !pi, !ppi
+ cir.store %z, %p2 : !pi, !ppi
+ cir.store %p1, %pp : !ppi, !pppi
+ cir.store %p2, %pp : !ppi, !pppi
+ // expected-remark @below {{points to [p1, p2]}}
+ %l = cir.load %pp : !pppi, !ppi
+ // expected-remark @below {{points to [unknown]}}
+ // expected-remark @below {{a set of 3 objects is replaced by unknown, the limit is 2}}
+ // expected-remark @below {{the address of x escapes}}
+ // expected-remark @below {{the address of y escapes}}
+ // expected-remark @below {{the address of z escapes}}
+ %v = cir.load %l : !ppi, !pi
+ cir.return
+}
diff --git a/clang/test/CIR/Analysis/points-to.cir b/clang/test/CIR/Analysis/points-to.cir
new file mode 100644
index 00000000000000..24b250b50cd76e
--- /dev/null
+++ b/clang/test/CIR/Analysis/points-to.cir
@@ -0,0 +1,365 @@
+// RUN: cir-opt %s -pass-pipeline='builtin.module(cir.func(test-cir-points-to))' \
+// RUN: --remarks-filter=points-to -split-input-file -verify-diagnostics
+
+// The analysis emits a remark with the points-to set of every loaded pointer,
+// and a remark for every object whose address escapes, on the operation that
+// makes it escape.
+
+// A pointer stored into a slot is loaded back from it.
+
+!s32i = !cir.int<s, 32>
+cir.func @store_load() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %b = cir.alloca "b" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %q = cir.alloca "q" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %b, %q : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [a]}}
+ %pa = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ // expected-remark @below {{points to [b]}}
+ %pb = cir.load %q : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// The analysis is flow insensitive: a load sees every pointer stored into the
+// slot, including stores that come after it.
+
+!s32i = !cir.int<s, 32>
+cir.func @flow_insensitive() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %b = cir.alloca "b" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [a, b]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.store %b, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.return
+}
+
+// -----
+
+// Two levels of indirection: the slot `pp` holds the address of `p`, which
+// holds the address of `a`.
+
+!s32i = !cir.int<s, 32>
+cir.func @double_indirection() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %pp = cir.alloca "pp" align(8) : !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %p, %pp : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ // expected-remark @below {{points to [p]}}
+ %lp = cir.load %pp : !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [a]}}
+ %la = cir.load %lp : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// A store or a load through a pointer that may point to two slots may write or
+// read either of them.
+
+!s32i = !cir.int<s, 32>
+!pi = !cir.ptr<!s32i>
+!ppi = !cir.ptr<!pi>
+cir.func @two_slots() {
+ %a = cir.alloca "a" align(4) : !pi
+ %b = cir.alloca "b" align(4) : !pi
+ %p = cir.alloca "p" align(8) : !ppi
+ %q = cir.alloca "q" align(8) : !ppi
+ %pp = cir.alloca "pp" align(8) : !cir.ptr<!ppi>
+ cir.store %p, %pp : !ppi, !cir.ptr<!ppi>
+ cir.store %q, %pp : !ppi, !cir.ptr<!ppi>
+ // expected-remark @below {{points to [p, q]}}
+ %l = cir.load %pp : !cir.ptr<!ppi>, !ppi
+ cir.store %a, %l : !pi, !ppi
+ cir.store %b, %q : !pi, !ppi
+ // expected-remark @below {{points to [a]}}
+ %vp = cir.load %p : !ppi, !pi
+ // expected-remark @below {{points to [a, b]}}
+ %vq = cir.load %q : !ppi, !pi
+ // expected-remark @below {{points to [a, b]}}
+ %vl = cir.load %l : !ppi, !pi
+ cir.return
+}
+
+// -----
+
+// A null pointer points to no object, so storing it doesn't add unknown
+// objects to the slot.
+
+!s32i = !cir.int<s, 32>
+cir.func @null_pointer() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %null = cir.const #cir.ptr<null> : !cir.ptr<!s32i>
+ cir.store %null, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [a]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// A store through a loaded pointer is seen by loads through the slot it
+// points to, even when the store is visited after the load.
+
+!s32i = !cir.int<s, 32>
+cir.func @store_through_loaded_pointer() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %b = cir.alloca "b" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %pp = cir.alloca "pp" align(8) : !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %p, %pp : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ // expected-remark @below {{points to [a, b]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ // expected-remark @below {{points to [p]}}
+ %lp = cir.load %pp : !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %b, %lp : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.return
+}
+
+// -----
+
+// Function arguments point to unknown objects, and so does anything loaded
+// through them.
+
+!s32i = !cir.int<s, 32>
+cir.func @argument(%arg: !cir.ptr<!cir.ptr<!s32i>>) {
+ // expected-remark @below {{points to [unknown]}}
+ %v = cir.load %arg : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// Storing the address of `p` through an argument lets code outside the
+// function reach `p`, so its memory may hold any address, not only `a`, and
+// `a` escapes with it. The same holds when `p` is reached through `pp`. The
+// slot `q` did not escape and still holds only `c`.
+
+!s32i = !cir.int<s, 32>
+cir.func @escape_through_store(%arg: !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>) {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %c = cir.alloca "c" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %q = cir.alloca "q" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %pp = cir.alloca "pp" align(8) : !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %p, %pp : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ cir.store %c, %q : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{the address of p escapes}}
+ // expected-remark @below {{the address of a escapes}}
+ cir.store %p, %arg : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ // expected-remark @below {{points to [a, unknown]}}
+ %own = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ // expected-remark @below {{points to [p]}}
+ %lp = cir.load %pp : !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [a, unknown]}}
+ %inner = cir.load %lp : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ // expected-remark @below {{points to [c]}}
+ %other = cir.load %q : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// The analysis does not model calls yet, so passing an address to a call makes
+// the object escape. The callee can reach `a` through `p`, so `a` escapes with
+// it.
+
+!s32i = !cir.int<s, 32>
+cir.func private @take(!cir.ptr<!cir.ptr<!s32i>>)
+cir.func @escape_through_call() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{the address of p escapes}}
+ // expected-remark @below {{the address of a escapes}}
+ cir.call @take(%p) : (!cir.ptr<!cir.ptr<!s32i>>) -> ()
+ // expected-remark @below {{points to [a, unknown]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// The object an operation the analysis does not model operates on escapes.
+
+!s32i = !cir.int<s, 32>
+!u8i = !cir.int<u, 8>
+cir.func @unmodeled_op() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{the address of p escapes}}
+ // expected-remark @below {{the address of a escapes}}
+ %cast = cir.cast bitcast %p : !cir.ptr<!cir.ptr<!s32i>> -> !cir.ptr<!u8i>
+ // expected-remark @below {{points to [a, unknown]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// A global is not tracked: its address points to unknown objects, and storing
+// an address into it makes the object escape. `a` is stored into `p` after `p`
+// escaped, so it escapes too.
+
+!s32i = !cir.int<s, 32>
+cir.global external @gp = #cir.ptr<null> : !cir.ptr<!cir.ptr<!s32i>>
+cir.func @global() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %g = cir.get_global @gp : !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ // expected-remark @below {{the address of p escapes}}
+ cir.store %p, %g : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ // expected-remark @below {{the address of a escapes}}
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [a, unknown]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ // expected-remark @below {{points to [unknown]}}
+ %lg = cir.load %g : !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>, !cir.ptr<!cir.ptr<!s32i>>
+ cir.return
+}
+
+// -----
+
+// Values passed through region results are not followed yet: the result of the
+// cir.ternary points to unknown objects, and the yielded objects escape.
+
+!s32i = !cir.int<s, 32>
+cir.func @region_result(%c: !cir.bool) {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %b = cir.alloca "b" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ %r = cir.ternary(%c, true {
+ // expected-remark @below {{the address of p escapes}}
+ // expected-remark @below {{the address of a escapes}}
+ cir.yield %p : !cir.ptr<!cir.ptr<!s32i>>
+ }, false {
+ cir.yield %p : !cir.ptr<!cir.ptr<!s32i>>
+ }) : (!cir.bool) -> !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [unknown]}}
+ %lr = cir.load %r : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ // expected-remark @below {{points to [a, unknown]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// Converting an address to an integer makes the object escape, and converting
+// an integer back to a pointer gives a pointer to unknown objects.
+
+!s32i = !cir.int<s, 32>
+!s64i = !cir.int<s, 64>
+cir.func @ptr_to_int() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %i = cir.alloca "i" align(8) : !cir.ptr<!s64i>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{the address of p escapes}}
+ // expected-remark @below {{the address of a escapes}}
+ %int = cir.cast ptr_to_int %p : !cir.ptr<!cir.ptr<!s32i>> -> !s64i
+ cir.store %int, %i : !s64i, !cir.ptr<!s64i>
+ // expected-remark @below {{points to [a, unknown]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ %li = cir.load %i : !cir.ptr<!s64i>, !s64i
+ %back = cir.cast int_to_ptr %li : !s64i -> !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to [unknown]}}
+ %lb = cir.load %back : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// A slot that is never stored to points to nothing.
+
+!s32i = !cir.int<s, 32>
+cir.func @never_stored() {
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{points to []}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// Storing into an object that already escaped makes the stored object escape:
+// the callee may have kept the address of `p`, so it can reach `a` and anything
+// stored in it, here `x`.
+
+!s32i = !cir.int<s, 32>
+cir.func private @take(!cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>)
+cir.func @store_into_escaped() {
+ %a = cir.alloca "a" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ %x = cir.alloca "x" align(4) : !cir.ptr<!s32i>
+ cir.store %x, %a : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ // expected-remark @below {{the address of p escapes}}
+ cir.call @take(%p) : (!cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>) -> ()
+ // expected-remark @below {{the address of a escapes}}
+ // expected-remark @below {{the address of x escapes}}
+ cir.store %a, %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!cir.ptr<!cir.ptr<!s32i>>>
+ // expected-remark @below {{points to [x, unknown]}}
+ %v = cir.load %a : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+// -----
+
+// When the address of a member escapes, the whole object escapes, not only the
+// member: code given the address of `s.b` can get back to `s.a` with offsetof.
+// The analysis does not follow cir.get_member yet, so `s` escapes on the first
+// one.
+
+!s32i = !cir.int<s, 32>
+!rec_S = !cir.struct<"S" {data !s32i, data !s32i}>
+cir.func private @naughty(!cir.ptr<!s32i>)
+cir.func @member_escapes() -> !s32i {
+ %s = cir.alloca "s" align(4) : !cir.ptr<!rec_S>
+ %zero = cir.const #cir.int<0> : !s32i
+ // expected-remark @below {{the address of s escapes}}
+ %a = cir.get_member %s[0] {name = "a"} : !cir.ptr<!rec_S> -> !cir.ptr<!s32i>
+ cir.store %zero, %a : !s32i, !cir.ptr<!s32i>
+ %b = cir.get_member %s[1] {name = "b"} : !cir.ptr<!rec_S> -> !cir.ptr<!s32i>
+ cir.call @naughty(%b) : (!cir.ptr<!s32i>) -> ()
+ %a2 = cir.get_member %s[0] {name = "a"} : !cir.ptr<!rec_S> -> !cir.ptr<!s32i>
+ %v = cir.load %a2 : !cir.ptr<!s32i>, !s32i
+ cir.return %v : !s32i
+}
+
+// -----
+
+// Comparing pointers or testing one for null gives a boolean, from which code
+// cannot get back to an object, so `a` and `p` don't escape. Other casts make
+// the object escape, see @unmodeled_op.
+
+!s32i = !cir.int<s, 32>
+cir.func @compare(%q: !cir.ptr<!s32i>) {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ %eq = cir.cmp eq %a, %q : !cir.ptr<!s32i>
+ // expected-remark @below {{points to [a]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
+
+cir.func @null_check() {
+ %a = cir.alloca "a" align(4) : !cir.ptr<!s32i>
+ %p = cir.alloca "p" align(8) : !cir.ptr<!cir.ptr<!s32i>>
+ cir.store %a, %p : !cir.ptr<!s32i>, !cir.ptr<!cir.ptr<!s32i>>
+ %nonnull = cir.cast ptr_to_bool %p : !cir.ptr<!cir.ptr<!s32i>> -> !cir.bool
+ // expected-remark @below {{points to [a]}}
+ %v = cir.load %p : !cir.ptr<!cir.ptr<!s32i>>, !cir.ptr<!s32i>
+ cir.return
+}
diff --git a/clang/test/CIR/Analysis/points-to.cpp b/clang/test/CIR/Analysis/points-to.cpp
new file mode 100644
index 00000000000000..c93a84ccf40030
--- /dev/null
+++ b/clang/test/CIR/Analysis/points-to.cpp
@@ -0,0 +1,105 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir %s -o - \
+// RUN: | cir-opt --remarks-filter=points-to -verify-diagnostics -o /dev/null \
+// RUN: -pass-pipeline='builtin.module(cir.func(test-cir-points-to))'
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir %s -o - \
+// RUN: | cir-opt --remarks-filter-analyse=points-to -o /dev/null 2>&1 \
+// RUN: -pass-pipeline='builtin.module(cir.func(test-cir-points-to))' \
+// RUN: | FileCheck %s --check-prefix=ANALYSIS --implicit-check-not='[Missed]'
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir -emit-cir %s -o - \
+// RUN: | cir-opt --remarks-filter-missed=points-to -o /dev/null 2>&1 \
+// RUN: -pass-pipeline='builtin.module(cir.func(test-cir-points-to))' \
+// RUN: | FileCheck %s --check-prefix=MISSED --implicit-check-not='[Analysis]'
+
+// The analysis emits an analysis remark for each load of a pointer from a local
+// variable, with the objects the loaded pointer may point to, and a missed
+// remark for each object whose address escapes. --remarks-filter=points-to
+// enables both kinds, and --remarks-filter-analyse and --remarks-filter-missed
+// only one of them.
+
+// ANALYSIS: remark: [Analysis] PointsTo
+// MISSED: remark: [Missed] Escaped {{.*}} Remark="the address of p escapes"
+// MISSED: remark: [Missed] Escaped {{.*}} Remark="the address of a escapes"
+
+void take(int **);
+
+void two_pointers() {
+ int a, b;
+ int *p = &a, *q = &b;
+ *p = 1; // expected-remark {{points to [a]}}
+ *q = 2; // expected-remark {{points to [b]}}
+}
+
+void pointer_to_pointer() {
+ int a;
+ int *p = &a;
+ int **pp = &p;
+ // expected-remark @below {{points to [p]}}
+ // expected-remark @below {{points to [a]}}
+ **pp = 1;
+}
+
+// A null pointer points to no object.
+void null_then_address() {
+ int a;
+ int *p = nullptr;
+ p = &a;
+ *p = 1; // expected-remark {{points to [a]}}
+}
+
+// The address of `p` is passed to a call, which may store any address into it,
+// and can reach `a` through it.
+void escape_to_call() {
+ int a;
+ int *p = &a;
+ // expected-remark at +2 {{the address of p escapes}}
+ // expected-remark at +1 {{the address of a escapes}}
+ take(&p);
+ *p = 1; // expected-remark {{points to [a, unknown]}}
+}
+
+// `p` is assigned on two paths, so it may point to `a` or `b`.
+void two_paths(bool c) {
+ int a, b;
+ int *p = &a;
+ if (c)
+ p = &b;
+ *p = 1; // expected-remark {{points to [a, b]}}
+}
+
+// When the address of a member escapes, the whole object escapes, not only the
+// member: code given `&s.b` can get back to `s.a` with offsetof. The escape is
+// reported on the first cir.get_member on `s`, which CIRGen gives the location
+// of the member.
+struct S {
+ int a; // expected-remark {{the address of s escapes}}
+ int b;
+};
+
+int *escaped;
+
+void naughty(int *p) {
+ // expected-remark @below {{points to [unknown]}}
+ S *parent = (S *)((char *)p - __builtin_offsetof(S, b));
+ escaped = &parent->a; // expected-remark {{points to [unknown]}}
+}
+
+int trusting() {
+ S s;
+ s.a = 0;
+ naughty(&s.b);
+ *escaped = 1; // expected-remark {{points to [unknown]}}
+ return s.a;
+}
+
+// Testing `pp` for null and comparing `p` with `q` give booleans, from which
+// code can't get back to an object, so `p` and `a` don't escape.
+bool null_check_and_compare(int *q) {
+ int a;
+ int *p = &a;
+ int **pp = &p;
+ if (pp) // expected-remark {{points to [p]}}
+ // expected-remark @+1 {{points to [p]}}
+ **pp = 1; // expected-remark {{points to [a]}}
+ // expected-remark @+1 {{points to [a]}}
+ return p == q; // expected-remark {{points to [unknown]}}
+}
diff --git a/clang/test/CIR/lib/Analysis/CMakeLists.txt b/clang/test/CIR/lib/Analysis/CMakeLists.txt
index 39292698db348e..4ddab7e666717c 100644
--- a/clang/test/CIR/lib/Analysis/CMakeLists.txt
+++ b/clang/test/CIR/lib/Analysis/CMakeLists.txt
@@ -1,5 +1,6 @@
add_clang_library(CIRTestAnalysis
TestCIRAliasAnalysis.cpp
+ TestCIRPointsToAnalysis.cpp
LINK_LIBS PUBLIC
MLIRCIRAnalysis
diff --git a/clang/test/CIR/lib/Analysis/TestCIRPointsToAnalysis.cpp b/clang/test/CIR/lib/Analysis/TestCIRPointsToAnalysis.cpp
new file mode 100644
index 00000000000000..a672d0d426f5e1
--- /dev/null
+++ b/clang/test/CIR/lib/Analysis/TestCIRPointsToAnalysis.cpp
@@ -0,0 +1,70 @@
+//===- TestCIRPointsToAnalysis.cpp - Test CIR points-to analysis ----------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#include "mlir/Pass/Pass.h"
+#include "clang/CIR/Dialect/Analysis/CIRPointsToAnalysis.h"
+#include "clang/CIR/Dialect/IR/CIRDialect.h"
+
+using namespace mlir;
+
+namespace {
+
+/// Compute the points-to analysis of the function, with limits that can be
+/// overridden, and report its results as remarks, which the tests check.
+struct TestCIRPointsToAnalysisPass
+ : PassWrapper<TestCIRPointsToAnalysisPass, OperationPass<cir::FuncOp>> {
+ MLIR_DEFINE_EXPLICIT_INTERNAL_INLINE_TYPE_ID(TestCIRPointsToAnalysisPass)
+
+ TestCIRPointsToAnalysisPass() = default;
+ TestCIRPointsToAnalysisPass(const TestCIRPointsToAnalysisPass &other)
+ : PassWrapper(other) {}
+
+ StringRef getArgument() const final { return "test-cir-points-to"; }
+ StringRef getDescription() const final {
+ return "Test CIR points-to analysis results.";
+ }
+
+ Option<unsigned> maxOperations{
+ *this, "max-operations",
+ llvm::cl::desc("Override the operation limit of the analysis"),
+ llvm::cl::init(cir::PointsToLimits().maxOperations)};
+ Option<unsigned> minWork{
+ *this, "min-work",
+ llvm::cl::desc("Override the minimum work limit of the analysis"),
+ llvm::cl::init(cir::PointsToLimits().minWork)};
+ Option<unsigned> workPerOperation{
+ *this, "work-per-operation",
+ llvm::cl::desc("Override the work limit for each operation"),
+ llvm::cl::init(cir::PointsToLimits().workPerOperation)};
+ Option<unsigned> maxSetSize{
+ *this, "max-set-size",
+ llvm::cl::desc("Override the set size limit of the analysis"),
+ llvm::cl::init(cir::PointsToLimits().maxSetSize)};
+
+ void runOnOperation() override {
+ cir::PointsToLimits limits;
+ limits.maxOperations = maxOperations;
+ limits.minWork = minWork;
+ limits.workPerOperation = workPerOperation;
+ limits.maxSetSize = maxSetSize;
+
+ cir::PointsToAnalysis pointsTo(getOperation(), limits);
+ pointsTo.emitRemarks();
+ markAllAnalysesPreserved();
+ }
+};
+
+} // namespace
+
+namespace cir {
+namespace test {
+void registerTestCIRPointsToAnalysisPass() {
+ PassRegistration<TestCIRPointsToAnalysisPass>();
+}
+} // namespace test
+} // namespace cir
diff --git a/clang/tools/cir-opt/cir-opt.cpp b/clang/tools/cir-opt/cir-opt.cpp
index 63c52a046c4414..d238cd800451f9 100644
--- a/clang/tools/cir-opt/cir-opt.cpp
+++ b/clang/tools/cir-opt/cir-opt.cpp
@@ -30,6 +30,7 @@
#ifdef CLANG_INCLUDE_TESTS
namespace cir::test {
void registerTestCIRAliasAnalysisPass();
+void registerTestCIRPointsToAnalysisPass();
} // namespace cir::test
#endif
@@ -48,6 +49,7 @@ int main(int argc, char **argv) {
#ifdef CLANG_INCLUDE_TESTS
cir::test::registerTestCIRAliasAnalysisPass();
+ cir::test::registerTestCIRPointsToAnalysisPass();
#endif
registry.insert<mlir::gpu::GPUDialect, mlir::memref::MemRefDialect,
mlir::LLVM::LLVMDialect>();
More information about the cfe-commits
mailing list