Skip to content

Commit 437b30a

Browse files
authored
Merge pull request #135 from CoreTrace/134-smt-path-conditions
feat(smt): path conditions over a MemorySSA memory model
2 parents 98ca081 + 47ff7e6 commit 437b30a

22 files changed

Lines changed: 1314 additions & 172 deletions

‎docs/architecture/smt-solver-integration.md‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -261,7 +261,7 @@ This is required to track precision/performance tradeoffs.
261261
- Integrate selected stack-buffer and size-arg ambiguous diagnostics.
262262
- Tune budgets per rule category.
263263

264-
## Current Implementation Status (March 2026)
264+
## Current Implementation Status (September 2026)
265265

266266
Implemented in codebase:
267267

@@ -271,12 +271,21 @@ Implemented in codebase:
271271
4. Recursion rule onboarding using a dedicated encoder (`LLVM range state -> ConstraintIR`).
272272
5. Conservative fallback policy for recursion (`Unknown`/`Timeout`/`Error` never suppresses baseline diagnostics).
273273
6. Optional Z3 backend integration with CMake auto-detection and safe fallback when unavailable.
274+
7. Path-sensitive queries for integer-overflow, size-minus-k, stack-buffer and oob-read: the
275+
reachability condition of the query point over the CFG without back edges, from the farthest
276+
dominator within the node budget; loads encoded through their MemorySSA clobber
277+
(`FunctionFacts::clobberingAccess`); wrapping semantics, no `nsw`/`nuw` assumption. A query
278+
suppresses a report only at a point proven reachable, so a defect in code that never runs
279+
stays reported, as the default pass reports it. Stack-buffer, size-minus-k and oob-read
280+
query the index or size the access really uses, casts included.
281+
8. Queries are built only when SMT is on for the rule, and asked even when no range is known.
282+
9. CI builds and exercises the Z3 backend.
274283

275284
Planned next:
276285

277-
1. Extend encoder coverage beyond interval-derived constraints for richer path conditions.
286+
1. Recursion still encodes interval-derived constraints only; path-sensitive base-case queries
287+
would make `unsat` add diagnostics, which is a separate decision.
278288
2. Add query cache and telemetry counters (query count/status/latency).
279-
3. Onboard SMT to additional high-FP rules (integer overflow, size-minus-k, ambiguous stack buffer cases).
280289

281290
## Risk Register
282291

‎include/analysis/FunctionFacts.hpp‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ namespace llvm
1313
class Function;
1414
class Instruction;
1515
class LazyValueInfo;
16+
class LoadInst;
17+
class MemoryAccess;
1618
class TargetLibraryInfo;
1719
class Value;
1820
} // namespace llvm
@@ -69,6 +71,14 @@ namespace ctrace::stack::analysis
6971
[[nodiscard]] std::optional<std::uint64_t>
7072
objectSizeBytes(const llvm::Value* pointer) const;
7173

74+
/// @brief Access that may last have written the memory read by @p load (MemorySSA
75+
/// clobber).
76+
///
77+
/// BasicAA and MemorySSA are built on the first call, so functions that never ask pay
78+
/// nothing. Loads of one pointer with one clobber read the same value; a clobber that
79+
/// stores to that pointer is the value they read.
80+
[[nodiscard]] const llvm::MemoryAccess* clobberingAccess(const llvm::LoadInst& load) const;
81+
7282
private:
7383
struct Impl;
7484
std::unique_ptr<Impl> impl_;

‎include/analysis/smt/SmtEncoding.hpp‎

Lines changed: 28 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,25 @@ namespace llvm
1515
class Value;
1616
} // namespace llvm
1717

18+
namespace ctrace::stack::analysis
19+
{
20+
class FunctionFacts;
21+
} // namespace ctrace::stack::analysis
22+
1823
namespace ctrace::stack::analysis::smt
1924
{
25+
/// @brief Where a query is asked, and what the encoder may use to encode it.
26+
struct QueryPoint
27+
{
28+
/// Instruction the query is about; nullptr encodes the bare query.
29+
const llvm::Instruction* inst = nullptr;
30+
/// Facts of the function holding @ref inst. When set, loads are related through
31+
/// MemorySSA and the query carries the reachability condition of @ref inst.
32+
const FunctionFacts* facts = nullptr;
33+
/// Largest query, in ConstraintIR nodes, the path condition may grow it to; 0 = none.
34+
std::uint64_t budgetNodes = 0;
35+
};
36+
2037
class LlvmConstraintEncoder
2138
{
2239
public:
@@ -31,14 +48,20 @@ namespace ctrace::stack::analysis::smt
3148
ConstraintIR
3249
encodeSignedOverflowFeasibility(const std::map<const llvm::Value*, IntRange>& ranges,
3350
const llvm::BinaryOperator& binaryOperation,
34-
const llvm::Instruction* contextInst = nullptr);
51+
const QueryPoint& point = {});
3552

3653
ConstraintIR
3754
encodeUnsignedOverflowFeasibility(const std::map<const llvm::Value*, IntRange>& ranges,
3855
const llvm::BinaryOperator& binaryOperation,
39-
const llvm::Instruction* contextInst = nullptr);
56+
const QueryPoint& point = {});
57+
58+
ConstraintIR
59+
encodeSignedComparisonFeasibility(const std::map<const llvm::Value*, IntRange>& ranges,
60+
const llvm::Value& lhs, std::int64_t rhsConstant,
61+
bool greaterThan, const QueryPoint& point = {});
4062

41-
ConstraintIR encodeSignedComparisonFeasibility(
42-
const std::map<const llvm::Value*, IntRange>& ranges, const llvm::Value& lhs,
43-
std::int64_t rhsConstant, bool greaterThan, const llvm::Instruction* contextInst = nullptr);
63+
/// @brief The query of @p point without any violation: the rule's ranges, the assumptions
64+
/// before @p point and its reachability condition. Satisfiable when @p point can run.
65+
ConstraintIR encodeReachability(const std::map<const llvm::Value*, IntRange>& ranges,
66+
const QueryPoint& point);
4467
} // namespace ctrace::stack::analysis::smt

‎include/analysis/smt/SmtRefinement.hpp‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33

44
#include "StackUsageAnalyzer.hpp"
55
#include "analysis/smt/ConstraintIR.hpp"
6+
#include "analysis/smt/SmtEncoding.hpp"
67
#include "analysis/smt/SolverOrchestrator.hpp"
78
#include "analysis/smt/TextUtil.hpp"
89

910
#include <cstdint>
11+
#include <map>
1012
#include <optional>
1113
#include <string>
1214
#include <string_view>
@@ -68,6 +70,31 @@ namespace ctrace::stack::analysis::smt
6870
return solve(encode());
6971
}
7072

73+
/// @brief Solves the query built by @p encode at @p point, a point that can run.
74+
///
75+
/// A query is also infeasible when the path condition of @p point is unsatisfiable,
76+
/// that is when @p point never runs. A defect there stays reported, as the default pass
77+
/// reports it (flagged unreachable): Infeasible holds only once the reachability of
78+
/// @p point is proven, and is Inconclusive otherwise.
79+
template <typename Encode>
80+
SmtFeasibility evaluateQueryAt(const std::map<const llvm::Value*, IntRange>& ranges,
81+
const QueryPoint& point, Encode encode) const
82+
{
83+
const SmtFeasibility result = evaluateQuery(std::move(encode));
84+
if (result != SmtFeasibility::Infeasible || !point.facts)
85+
return result;
86+
return solve(encodeReachability(ranges, point)) == SmtFeasibility::Feasible
87+
? result
88+
: SmtFeasibility::Inconclusive;
89+
}
90+
91+
/// @brief Query point for @p inst, with this rule's node budget.
92+
[[nodiscard]] QueryPoint queryPoint(const llvm::Instruction* inst,
93+
const FunctionFacts* facts) const
94+
{
95+
return QueryPoint{.inst = inst, .facts = facts, .budgetNodes = budgetNodes_};
96+
}
97+
7198
private:
7299
SmtFeasibility solve(ConstraintIR ir) const
73100
{

‎src/analysis/FunctionFacts.cpp‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
// SPDX-License-Identifier: Apache-2.0
22
#include "analysis/FunctionFacts.hpp"
33

4+
#include <llvm/Analysis/AliasAnalysis.h>
45
#include <llvm/Analysis/AssumptionCache.h>
6+
#include <llvm/Analysis/BasicAliasAnalysis.h>
57
#include <llvm/Analysis/LazyValueInfo.h>
68
#include <llvm/Analysis/MemoryBuiltins.h>
9+
#include <llvm/Analysis/MemorySSA.h>
710
#include <llvm/Analysis/TargetLibraryInfo.h>
811
#include <llvm/Analysis/ValueTracking.h>
912
#include <llvm/IR/ConstantRange.h>
@@ -32,6 +35,26 @@ namespace ctrace::stack::analysis
3235
out.upper = range.getSignedMax().getSExtValue();
3336
return out;
3437
}
38+
39+
/// BasicAA and the MemorySSA built on it. MemorySSA keeps a pointer to the AA, so both
40+
/// live together.
41+
struct MemoryModel final
42+
{
43+
MemoryModel(llvm::Function& function, const llvm::DataLayout& dataLayout,
44+
const llvm::TargetLibraryInfo& libraryInfo,
45+
llvm::AssumptionCache& assumptions, llvm::DominatorTree& dominators)
46+
: basicAA(dataLayout, function, libraryInfo, assumptions, &dominators),
47+
aliasAnalysis(libraryInfo)
48+
{
49+
aliasAnalysis.addAAResult(basicAA);
50+
memorySSA =
51+
std::make_unique<llvm::MemorySSA>(function, &aliasAnalysis, &dominators);
52+
}
53+
54+
llvm::BasicAAResult basicAA;
55+
llvm::AAResults aliasAnalysis;
56+
std::unique_ptr<llvm::MemorySSA> memorySSA;
57+
};
3558
} // namespace
3659

3760
struct FunctionFacts::Impl final
@@ -50,6 +73,8 @@ namespace ctrace::stack::analysis
5073
llvm::TargetLibraryInfoImpl libraryInfoImpl;
5174
llvm::TargetLibraryInfo targetLibraryInfo;
5275
llvm::LazyValueInfo lazyValueInfo;
76+
// Last, so it is destroyed before the analyses it references.
77+
std::unique_ptr<MemoryModel> memoryModel;
5378
};
5479

5580
FunctionFacts::FunctionFacts(llvm::Function& function) : impl_(std::make_unique<Impl>(function))
@@ -142,4 +167,16 @@ namespace ctrace::stack::analysis
142167

143168
return result.Size.getZExtValue();
144169
}
170+
171+
const llvm::MemoryAccess* FunctionFacts::clobberingAccess(const llvm::LoadInst& load) const
172+
{
173+
Impl& impl = *impl_;
174+
if (!impl.memoryModel)
175+
{
176+
impl.memoryModel = std::make_unique<MemoryModel>(
177+
impl.function, impl.dataLayout, impl.targetLibraryInfo, impl.assumptionCache,
178+
impl.dominatorTree);
179+
}
180+
return impl.memoryModel->memorySSA->getWalker()->getClobberingMemoryAccess(&load);
181+
}
145182
} // namespace ctrace::stack::analysis

‎src/analysis/IntegerOverflowAnalysis.cpp‎

Lines changed: 39 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -57,49 +57,55 @@ namespace ctrace::stack::analysis
5757
SmtFeasibility
5858
isSignedOverflowFeasible(const std::map<const llvm::Value*, IntRange>& ranges,
5959
const llvm::BinaryOperator& binary,
60-
const llvm::Instruction* contextInst) const
60+
const llvm::Instruction* contextInst,
61+
const FunctionFacts* facts) const
6162
{
62-
return smt::SmtConstraintEvaluator::evaluateQuery(
63-
[&]
64-
{ return smt::encodeSignedOverflowFeasibility(ranges, binary, contextInst); });
63+
const smt::QueryPoint point = queryPoint(contextInst, facts);
64+
return evaluateQueryAt(
65+
ranges, point,
66+
[&] { return smt::encodeSignedOverflowFeasibility(ranges, binary, point); });
6567
}
6668

6769
SmtFeasibility
6870
isUnsignedOverflowFeasible(const std::map<const llvm::Value*, IntRange>& ranges,
6971
const llvm::BinaryOperator& binary,
70-
const llvm::Instruction* contextInst) const
72+
const llvm::Instruction* contextInst,
73+
const FunctionFacts* facts) const
7174
{
72-
return smt::SmtConstraintEvaluator::evaluateQuery(
73-
[&]
74-
{
75-
return smt::encodeUnsignedOverflowFeasibility(ranges, binary, contextInst);
76-
});
75+
const smt::QueryPoint point = queryPoint(contextInst, facts);
76+
return evaluateQueryAt(
77+
ranges, point,
78+
[&] { return smt::encodeUnsignedOverflowFeasibility(ranges, binary, point); });
7779
}
7880

7981
SmtFeasibility
8082
isSignedGreaterThanFeasible(const std::map<const llvm::Value*, IntRange>& ranges,
8183
const llvm::Value& lhs, std::int64_t rhsConstant,
82-
const llvm::Instruction* contextInst) const
84+
const llvm::Instruction* contextInst,
85+
const FunctionFacts* facts) const
8386
{
84-
return smt::SmtConstraintEvaluator::evaluateQuery(
85-
[&]
86-
{
87-
return smt::encodeSignedComparisonFeasibility(ranges, lhs, rhsConstant,
88-
true, contextInst);
89-
});
87+
const smt::QueryPoint point = queryPoint(contextInst, facts);
88+
return evaluateQueryAt(ranges, point,
89+
[&]
90+
{
91+
return smt::encodeSignedComparisonFeasibility(
92+
ranges, lhs, rhsConstant, true, point);
93+
});
9094
}
9195

9296
SmtFeasibility
9397
isSignedLessEqualFeasible(const std::map<const llvm::Value*, IntRange>& ranges,
9498
const llvm::Value& lhs, std::int64_t rhsConstant,
95-
const llvm::Instruction* contextInst) const
99+
const llvm::Instruction* contextInst,
100+
const FunctionFacts* facts) const
96101
{
97-
return smt::SmtConstraintEvaluator::evaluateQuery(
98-
[&]
99-
{
100-
return smt::encodeSignedComparisonFeasibility(ranges, lhs, rhsConstant,
101-
false, contextInst);
102-
});
102+
const smt::QueryPoint point = queryPoint(contextInst, facts);
103+
return evaluateQueryAt(ranges, point,
104+
[&]
105+
{
106+
return smt::encodeSignedComparisonFeasibility(
107+
ranges, lhs, rhsConstant, false, point);
108+
});
103109
}
104110
};
105111

@@ -715,7 +721,8 @@ namespace ctrace::stack::analysis
715721
static bool shouldSuppressRiskWithSmt(const IntegerOverflowConstraintEvaluator& evaluator,
716722
const std::map<const llvm::Value*, IntRange>& ranges,
717723
const RiskSummary& risk,
718-
const llvm::Instruction& contextInst)
724+
const llvm::Instruction& contextInst,
725+
const FunctionFacts& facts)
719726
{
720727
switch (risk.kind)
721728
{
@@ -725,7 +732,7 @@ namespace ctrace::stack::analysis
725732
const std::map<const llvm::Value*, IntRange> queryRanges =
726733
buildArithmeticQueryRanges(*risk.arithmeticOp, ranges);
727734
return evaluator.isUnsignedOverflowFeasible(queryRanges, *risk.arithmeticOp,
728-
&contextInst) ==
735+
&contextInst, &facts) ==
729736
SmtFeasibility::Infeasible;
730737
}
731738
return false;
@@ -735,7 +742,7 @@ namespace ctrace::stack::analysis
735742
const std::map<const llvm::Value*, IntRange> queryRanges =
736743
buildValueQueryRanges(*risk.relatedValue, ranges);
737744
return evaluator.isSignedLessEqualFeasible(queryRanges, *risk.relatedValue, -1,
738-
&contextInst) ==
745+
&contextInst, &facts) ==
739746
SmtFeasibility::Infeasible;
740747
}
741748
return false;
@@ -750,9 +757,9 @@ namespace ctrace::stack::analysis
750757
buildValueQueryRanges(*risk.relatedValue, ranges);
751758
const std::int64_t truncMax = (std::int64_t{1} << risk.truncTargetBitWidth) - 1;
752759
const SmtFeasibility negativeFeasible = evaluator.isSignedLessEqualFeasible(
753-
queryRanges, *risk.relatedValue, -1, &contextInst);
760+
queryRanges, *risk.relatedValue, -1, &contextInst, &facts);
754761
const SmtFeasibility aboveMaxFeasible = evaluator.isSignedGreaterThanFeasible(
755-
queryRanges, *risk.relatedValue, truncMax, &contextInst);
762+
queryRanges, *risk.relatedValue, truncMax, &contextInst, &facts);
756763
return negativeFeasible == SmtFeasibility::Infeasible &&
757764
aboveMaxFeasible == SmtFeasibility::Infeasible;
758765
}
@@ -801,7 +808,8 @@ namespace ctrace::stack::analysis
801808
{
802809
const std::map<const llvm::Value*, IntRange> queryRanges =
803810
buildArithmeticQueryRanges(*binary, ranges);
804-
if (evaluator.isSignedOverflowFeasible(queryRanges, *binary, &inst) ==
811+
if (evaluator.isSignedOverflowFeasible(queryRanges, *binary, &inst,
812+
&facts) ==
805813
SmtFeasibility::Infeasible)
806814
{
807815
continue;
@@ -863,7 +871,7 @@ namespace ctrace::stack::analysis
863871
classifySizeOperand(sizeOperand, ranges);
864872
if (!risk)
865873
continue;
866-
if (shouldSuppressRiskWithSmt(evaluator, ranges, *risk, inst))
874+
if (shouldSuppressRiskWithSmt(evaluator, ranges, *risk, inst, facts))
867875
continue;
868876

869877
IntegerOverflowIssue issue;

0 commit comments

Comments
 (0)