Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions include/analysis/PromotedValues.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@
#include <cstdint>
#include <functional>
#include <memory>
#include <optional>
#include <vector>

namespace llvm
{
class BasicBlock;
class Function;
class Instruction;
class Module;
class StoreInst;
class Value;
} // namespace llvm

Expand All @@ -35,6 +39,17 @@ namespace ctrace::stack::analysis
std::uint32_t reservedFlags : 30 = 0;
};

/// @brief The bytes a store writes over every iteration of the loop around it.
struct LoopWrites
{
std::int64_t begin = 0; ///< First byte written, as an offset from the base.
std::int64_t end = 0; ///< One past the last byte written.
/// The only block the loop leaves from, and its successors outside the loop: every edge
/// from the one to the others leaves the loop with these bytes written.
const llvm::BasicBlock* exiting = nullptr;
std::vector<const llvm::BasicBlock*> exits;
};

/// @brief Value queries about the original IR, answered on a copy of the module where
/// promotable locals live in registers, so ScalarEvolution sees loop counters.
///
Expand Down Expand Up @@ -73,6 +88,13 @@ namespace ctrace::stack::analysis
[[nodiscard]] bool provesWithin(const llvm::Instruction& access, const llvm::Value& index,
std::int64_t lower, std::int64_t upper);

/// Bytes @p store writes from @p base over the loop around it, when the loop leaves from
/// one block after a constant number of iterations, the store runs on each of them, and
/// its address moves by a constant step no larger than what it writes, so that the
/// bytes are contiguous. Both belong to the original IR.
[[nodiscard]] std::optional<LoopWrites> loopWrites(const llvm::StoreInst& store,
const llvm::Value& base);

private:
struct Impl;
std::unique_ptr<Impl> impl_;
Expand Down
81 changes: 81 additions & 0 deletions src/analysis/PromotedValues.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// SPDX-License-Identifier: Apache-2.0
#include "analysis/PromotedValues.hpp"

#include <algorithm>
#include <optional>
#include <string>
#include <vector>
Expand All @@ -19,6 +20,7 @@
#include <llvm/IR/InstIterator.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/CheckedArithmetic.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/TargetParser/Triple.h>
#include <llvm/Transforms/Utils/Cloning.h>
Expand Down Expand Up @@ -406,4 +408,83 @@ namespace ctrace::stack::analysis
scev.isKnownPredicateAt(ICmpInst::ICMP_SLT, indexValue,
scev.getConstant(type, upper, /*isSigned=*/true), at);
}

std::optional<LoopWrites> PromotedValues::loopWrites(const llvm::StoreInst& store,
const llvm::Value& base)
{
PromotedFunction* promoted = impl_->promoted(*store.getFunction());
const auto* at = dyn_cast_or_null<StoreInst>(impl_->copyOf(&store));
const Value* copiedBase = impl_->copyOf(&base);
if (!promoted || !at || !copiedBase)
return std::nullopt;

// The store in the loop itself, not in one nested in it. The loop leaves from one block
// and goes back to its header from one latch, which the store runs before.
const BasicBlock* block = at->getParent();
const Loop* loop = promoted->loops.getLoopFor(block);
const BasicBlock* exiting = loop ? loop->getExitingBlock() : nullptr;
const BasicBlock* latch = loop ? loop->getLoopLatch() : nullptr;
if (!exiting || !latch || !promoted->dominators.dominates(block, latch))
return std::nullopt;

// A constant iteration count, and an address that moves by a constant step from a
// constant offset of the base.
ScalarEvolution& scev = promoted->scev;
const auto* count = dyn_cast<SCEVConstant>(scev.getBackedgeTakenCount(loop));
const auto* offset = dyn_cast<SCEVAddRecExpr>(
scev.getMinusSCEV(scev.getSCEV(const_cast<Value*>(at->getPointerOperand())),
scev.getSCEV(const_cast<Value*>(copiedBase))));
if (!count || count->getAPInt().getActiveBits() > 32 || !offset ||
offset->getLoop() != loop || !offset->isAffine())
return std::nullopt;
const auto* start = dyn_cast<SCEVConstant>(offset->getStart());
const auto* step = dyn_cast<SCEVConstant>(offset->getStepRecurrence(scev));
const TypeSize size =
promoted->function.getDataLayout().getTypeStoreSize(at->getValueOperand()->getType());
if (!start || !step || start->getAPInt().getBitWidth() > 64 || size.isScalable())
return std::nullopt;

// The store runs on each iteration that goes back to the header, and on the last one
// when it lies on every way to the exit. A step no larger than the bytes written leaves
// no gap between iterations.
const std::int64_t runs = static_cast<std::int64_t>(count->getAPInt().getZExtValue()) +
(promoted->dominators.dominates(block, exiting) ? 1 : 0);
const std::int64_t stride = step->getAPInt().getSExtValue();
const auto bytes = static_cast<std::int64_t>(size.getFixedValue());
if (runs == 0 || stride > bytes || stride < -bytes)
return std::nullopt;
const std::int64_t first = start->getAPInt().getSExtValue();
const std::optional<std::int64_t> span = checkedMul(runs - 1, stride);
const std::optional<std::int64_t> last = span ? checkedAdd(first, *span) : std::nullopt;
const std::optional<std::int64_t> end =
last ? checkedAdd(std::max(first, *last), bytes) : std::nullopt;
if (!end)
return std::nullopt;

// The copy keeps the blocks of the original and the order of their successors.
const BasicBlock* originalExiting = nullptr;
for (const BasicBlock& candidate : *store.getFunction())
{
if (impl_->copyOf(&candidate) == exiting)
{
originalExiting = &candidate;
break;
}
}
if (!originalExiting)
return std::nullopt;

LoopWrites out;
out.begin = std::min(first, *last);
out.end = *end;
out.exiting = originalExiting;
const Instruction* copiedTerminator = exiting->getTerminator();
const Instruction* terminator = originalExiting->getTerminator();
for (unsigned idx = 0; idx < copiedTerminator->getNumSuccessors(); ++idx)
{
if (!loop->contains(copiedTerminator->getSuccessor(idx)))
out.exits.push_back(terminator->getSuccessor(idx));
}
return out;
}
} // namespace ctrace::stack::analysis
120 changes: 106 additions & 14 deletions src/analysis/UninitializedVarAnalysis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "analysis/UninitializedVarAnalysis.hpp"
#include "analysis/ParameterDebugBinding.hpp"
#include "analysis/AnalyzerUtils.hpp"
#include "analysis/PromotedValues.hpp"

#include <algorithm>
#include <array>
Expand Down Expand Up @@ -1125,11 +1126,84 @@ namespace ctrace::stack::analysis
}
}

// The bytes counted loops write, by edge leaving the loop (#224). The dataflow sees each
// iteration store to an element it cannot name, so it adds nothing; the promoted copy,
// where the loop counter lives in a register, gives the bytes of every iteration.
using LoopExitWrites =
llvm::DenseMap<std::pair<const llvm::BasicBlock*, const llvm::BasicBlock*>,
llvm::SmallVector<MemoryAccess, 2>>;

class CountedLoopWrites
{
public:
explicit CountedLoopWrites(const llvm::Module& module) : module_(module) {}

// Found on the first query of @p F: the summary fixpoint analyzes a function several
// times, its loops once.
const LoopExitWrites& of(const llvm::Function& F, const TrackedObjectContext& tracked,
const llvm::DataLayout& DL)
{
auto [it, inserted] = byFunction_.try_emplace(&F);
if (inserted)
collect(F, tracked, DL, it->second);
return it->second;
}

private:
void collect(const llvm::Function& F, const TrackedObjectContext& tracked,
const llvm::DataLayout& DL, LoopExitWrites& out)
{
for (const llvm::BasicBlock& BB : F)
{
for (const llvm::Instruction& I : BB)
{
// A store at a constant offset is already a write of the dataflow.
const auto* SI = llvm::dyn_cast<llvm::StoreInst>(&I);
unsigned objectIdx = 0;
std::uint64_t offset = 0;
bool hasConstOffset = false;
if (!SI || llvm::isa<llvm::UndefValue>(SI->getValueOperand()) ||
!resolveTrackedObjectBase(SI->getPointerOperand(), tracked, DL,
objectIdx, offset, hasConstOffset) ||
hasConstOffset)
{
continue;
}

const TrackedMemoryObject& obj = tracked.objects[objectIdx];
const llvm::Value* base = obj.alloca;
if (!base)
base = obj.param;
if (!base)
continue;
if (!promoted_)
promoted_.emplace(module_, [](const llvm::Function&) { return true; });
const std::optional<LoopWrites> writes = promoted_->loopWrites(*SI, *base);
MemoryAccess access;
access.objectIdx = objectIdx;
if (!writes || writes->begin < 0 ||
!clipRangeToObject(obj, static_cast<std::uint64_t>(writes->begin),
static_cast<std::uint64_t>(writes->end),
access.begin, access.end))
{
continue;
}
for (const llvm::BasicBlock* exit : writes->exits)
out[{writes->exiting, exit}].push_back(access);
}
}
}

const llvm::Module& module_;
std::optional<PromotedValues> promoted_;
llvm::DenseMap<const llvm::Function*, LoopExitWrites> byFunction_;
};

static InitRangeState
computeInState(const llvm::BasicBlock& BB, const llvm::BasicBlock* entryBlock,
const llvm::DenseMap<const llvm::BasicBlock*, bool>& reachable,
const llvm::DenseMap<const llvm::BasicBlock*, InitRangeState>& outState,
const TrackedObjectContext& tracked)
const TrackedObjectContext& tracked, const LoopExitWrites& loopExitWrites)
{
InitRangeState in = makeBottomState(tracked.objects.size());
if (&BB == entryBlock)
Expand All @@ -1150,7 +1224,17 @@ namespace ctrace::stack::analysis
merged = makeBottomState(tracked.objects.size());
break;
}
meetMustState(merged, itOut->second);
auto itLoop = loopExitWrites.find({pred, &BB});
if (itLoop == loopExitWrites.end())
{
meetMustState(merged, itOut->second);
continue;
}
// The edge leaves a counted loop: what the loop wrote holds on it.
InitRangeState leaving = itOut->second;
for (const MemoryAccess& access : itLoop->second)
addRange(leaving[access.objectIdx], access.begin, access.end);
meetMustState(merged, leaving);
}

if (!havePred)
Expand Down Expand Up @@ -3214,13 +3298,15 @@ namespace ctrace::stack::analysis
const FunctionSummaryMap& summaries,
const ExternalSummaryMapByName* externalSummariesByName,
const CalleeSymbolNameMap* calleeSymbolNames,
unsigned fixpointIterationLimit, FunctionSummary* outSummary,
CountedLoopWrites& loopWrites, unsigned fixpointIterationLimit,
FunctionSummary* outSummary,
std::vector<UninitializedLocalReadIssue>* outIssues)
{
TrackedObjectContext tracked;
collectTrackedObjects(F, DL, tracked);
if (tracked.objects.empty())
return;
const LoopExitWrites& loopExitWrites = loopWrites.of(F, tracked, DL);

const unsigned trackedCount = static_cast<unsigned>(tracked.objects.size());

Expand Down Expand Up @@ -3321,8 +3407,8 @@ namespace ctrace::stack::analysis
if (!reachable.lookup(&BB))
continue;

InitRangeState newIn =
computeInState(BB, &F.getEntryBlock(), reachable, outState, tracked);
InitRangeState newIn = computeInState(BB, &F.getEntryBlock(), reachable,
outState, tracked, loopExitWrites);

InitRangeState state = newIn;
if (fuseIssueCollection)
Expand Down Expand Up @@ -3467,10 +3553,12 @@ namespace ctrace::stack::analysis
}
}

static FunctionSummaryMap computeFunctionSummaries(
llvm::Module& mod, const std::function<bool(const llvm::Function&)>& shouldAnalyze,
const ExternalSummaryMapByName* externalSummariesByName,
const CalleeSymbolNameMap* calleeSymbolNames, unsigned fixpointIterationLimit)
static FunctionSummaryMap
computeFunctionSummaries(llvm::Module& mod,
const std::function<bool(const llvm::Function&)>& shouldAnalyze,
const ExternalSummaryMapByName* externalSummariesByName,
const CalleeSymbolNameMap* calleeSymbolNames,
CountedLoopWrites& loopWrites, unsigned fixpointIterationLimit)
{
FunctionSummaryMap summaries;
llvm::SmallVector<const llvm::Function*, 64> analysisFunctions;
Expand Down Expand Up @@ -3523,7 +3611,8 @@ namespace ctrace::stack::analysis

FunctionSummary next = makeEmptySummary(*func);
analyzeFunction(*func, mod.getDataLayout(), summaries, externalSummariesByName,
calleeSymbolNames, fixpointIterationLimit, &next, nullptr);
calleeSymbolNames, loopWrites, fixpointIterationLimit, &next,
nullptr);
FunctionSummary& cur = summaries[func];
if (!(cur == next))
{
Expand Down Expand Up @@ -3978,8 +4067,10 @@ namespace ctrace::stack::analysis
{
externalMap = &preparedExternal->opaque->summariesByName;
}
FunctionSummaryMap summaries = computeFunctionSummaries(
mod, shouldSummarize, externalMap, calleeSymbolNames, fixpointIterationLimit);
CountedLoopWrites loopWrites(mod);
FunctionSummaryMap summaries =
computeFunctionSummaries(mod, shouldSummarize, externalMap, calleeSymbolNames,
loopWrites, fixpointIterationLimit);
return exportSummaryIndexForModule(mod, summaries);
}

Expand Down Expand Up @@ -4084,9 +4175,10 @@ namespace ctrace::stack::analysis
{ return summaryScope.find(&F) != summaryScope.end(); };
const CalleeSymbolNameMap calleeSymbolNames = buildCalleeSymbolNameMap(mod, summaryScope);
const ExternalSummaryMapByName externalMap = importExternalSummaryMap(externalSummaries);
CountedLoopWrites loopWrites(mod);
FunctionSummaryMap summaries = computeFunctionSummaries(
mod, shouldSummarize, externalMap.empty() ? nullptr : &externalMap, &calleeSymbolNames,
fixpointIterationLimit);
loopWrites, fixpointIterationLimit);

for (const llvm::Function& F : mod)
{
Expand All @@ -4097,7 +4189,7 @@ namespace ctrace::stack::analysis

analyzeFunction(F, mod.getDataLayout(), summaries,
externalMap.empty() ? nullptr : &externalMap, &calleeSymbolNames,
fixpointIterationLimit, nullptr, &issues);
loopWrites, fixpointIterationLimit, nullptr, &issues);
}

return issues;
Expand Down
10 changes: 2 additions & 8 deletions test/false-positive-repro/stb-like-next-code-uninitialized.c
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,5 @@ int fp_stb_like_next_code_uninitialized(Huff* z, const u8* sizelist, int num)
// at line 43, column 13
// [ !!Warn ] potential read of uninitialized local variable 'next_code'

// at line 22, column 9
// [ !!Warn ] potential read of uninitialized local variable 'sizes'

// at line 30, column 24
// [ !!Warn ] potential read of uninitialized local variable 'sizes'

// at line 33, column 14
// [ !!Warn ] potential read of uninitialized local variable 'sizes'
// The loop at line 20 writes every element of 'sizes' before any read of it (#224).
// not contains: potential read of uninitialized local variable 'sizes'
Loading
Loading