1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
|
//===--- OSSALifetimeCompletion.cpp ---------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// OSSA lifetime completion adds lifetime ending instructions to make
/// linear lifetimes complete.
///
/// Interior liveness handles the following cases naturally:
///
/// When completing the lifetime of the initial value, %v1, transitively
/// include all uses of dominated reborrows as, such as %phi1 in this example:
///
/// %v1 = ...
/// cond_br bb1, bb2
/// bb1:
/// %b1 = begin_borrow %v1
/// br bb3(%b1)
/// bb2:
/// %b2 = begin_borrow %v1
/// br bb3(%b2)
/// bb3(%phi1):
/// %u1 = %phi1
/// end_borrow %phi1
/// %k1 = destroy_value %v1 // must be below end_borrow %phi1
///
/// When completing the lifetime for a phi (%phi2) transitively include all
/// uses of inner adjacent reborrows, such as %phi1 in this example:
///
/// bb1:
/// %v1 = ...
/// %b1 = begin_borrow %v1
/// br bb3(%b1, %v1)
/// bb2:
/// %v2 = ...
/// %b2 = begin_borrow %v2
/// br bb3(%b2, %v2)
/// bb3(%phi1, %phi2):
/// %u1 = %phi1
/// end_borrow %phi1
/// %k1 = destroy_value %phi1
///
//===----------------------------------------------------------------------===//
#include "swift/SIL/OSSALifetimeCompletion.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/Test.h"
#include "llvm/ADT/STLExtras.h"
using namespace swift;
static SILInstruction *endOSSALifetime(SILValue value, SILBuilder &builder) {
auto loc =
RegularLocation::getAutoGeneratedLocation(builder.getInsertionPointLoc());
if (value->getOwnershipKind() == OwnershipKind::Owned) {
return builder.createDestroyValue(loc, value);
}
return builder.createEndBorrow(loc, value);
}
static bool endLifetimeAtBoundary(SILValue value,
const SSAPrunedLiveness &liveness) {
PrunedLivenessBoundary boundary;
liveness.computeBoundary(boundary);
bool changed = false;
for (SILInstruction *lastUser : boundary.lastUsers) {
if (liveness.isInterestingUser(lastUser)
!= PrunedLiveness::LifetimeEndingUse) {
changed = true;
SILBuilderWithScope::insertAfter(lastUser, [value](SILBuilder &builder) {
endOSSALifetime(value, builder);
});
}
}
for (SILBasicBlock *edge : boundary.boundaryEdges) {
changed = true;
SILBuilderWithScope builder(edge->begin());
endOSSALifetime(value, builder);
}
for (SILNode *deadDef : boundary.deadDefs) {
SILInstruction *next = nullptr;
if (auto *deadInst = dyn_cast<SILInstruction>(deadDef)) {
next = deadInst->getNextInstruction();
} else {
next = cast<ValueBase>(deadDef)->getNextInstruction();
}
changed = true;
SILBuilderWithScope builder(next);
endOSSALifetime(value, builder);
}
return changed;
}
namespace {
/// Implements OSSALifetimeCompletion::visitUnreachableLifetimeEnds. Finds
/// positions as near as possible to unreachables at which `value`'s lifetime
/// is available.
///
/// Finding these positions is a three step process:
/// 1) computeRegion: Forward CFG walk from non-lifetime-ending boundary to find
/// the dead-end region in which the value might be available.
/// 2) propagateAvailability: Forward iterative dataflow within the region to
/// determine which blocks the value is available in.
/// 3) visitAvailabilityBoundary: Visits the final blocks in the region where
/// the value is available--these are the blocks
/// without successors or with at least one
/// unavailable successor.
class VisitUnreachableLifetimeEnds {
/// The value whose dead-end block lifetime ends are to be visited.
SILValue value;
/// The non-lifetime-ending boundary of `value`.
BasicBlockSet starts;
/// The region between (inclusive) the `starts` and the unreachable blocks.
BasicBlockSetVector region;
public:
VisitUnreachableLifetimeEnds(SILValue value)
: value(value), starts(value->getFunction()),
region(value->getFunction()) {}
/// Region discovery.
///
/// Forward CFG walk from non-lifetime-ending boundary to unreachable
/// instructions.
void computeRegion(const SSAPrunedLiveness &liveness);
struct Result;
/// Iterative dataflow to determine availability for each block in `region`.
void propagateAvailablity(Result &result);
/// Visit the terminators of blocks on the boundary of availability.
void
visitAvailabilityBoundary(Result const &result,
llvm::function_ref<void(SILInstruction *)> visit);
struct State {
enum class Value : uint8_t {
Unavailable = 0,
Available,
Unknown,
};
Value value;
State(Value value) : value(value){};
operator Value() const { return value; }
State meet(State const other) const {
return *this < other ? *this : other;
}
static State Unavailable() { return {Value::Unavailable}; }
static State Available() { return {Value::Available}; }
static State Unknown() { return {Value::Unknown}; }
};
struct Result {
BasicBlockBitfield states;
Result(SILFunction *function) : states(function, 2) {}
State getState(SILBasicBlock *block) const {
return {(State::Value)states.get(block)};
}
void setState(SILBasicBlock *block, State newState) {
states.set(block, (unsigned)newState.value);
}
/// Propagate predecessors' state into `block`.
///
/// states[block] ∧= state[predecessor_1] ∧ ... ∧ state[predecessor_n]
bool updateState(SILBasicBlock *block) {
auto oldState = getState(block);
auto state = oldState;
for (auto *predecessor : block->getPredecessorBlocks()) {
state = state.meet(getState(predecessor));
}
setState(block, state);
return state != oldState;
}
};
};
void VisitUnreachableLifetimeEnds::computeRegion(
const SSAPrunedLiveness &liveness) {
// Find the non-lifetime-ending boundary of `value`.
PrunedLivenessBoundary boundary;
liveness.computeBoundary(boundary);
for (SILInstruction *lastUser : boundary.lastUsers) {
if (liveness.isInterestingUser(lastUser)
!= PrunedLiveness::LifetimeEndingUse) {
region.insert(lastUser->getParent());
starts.insert(lastUser->getParent());
}
}
for (SILBasicBlock *edge : boundary.boundaryEdges) {
region.insert(edge);
starts.insert(edge);
}
for (SILNode *deadDef : boundary.deadDefs) {
region.insert(deadDef->getParentBlock());
starts.insert(deadDef->getParentBlock());
}
// Forward walk to find the region in which `value` might be available.
BasicBlockWorklist regionWorklist(value->getFunction());
// Start the forward walk from the non-lifetime-ending boundary.
for (auto *start : region) {
regionWorklist.push(start);
}
while (auto *block = regionWorklist.pop()) {
if (block->succ_empty()) {
// This assert will fail unless there are already lifetime-ending
// instruction on all paths to normal function exits.
assert(isa<UnreachableInst>(block->getTerminator()));
}
for (auto *successor : block->getSuccessorBlocks()) {
regionWorklist.pushIfNotVisited(successor);
region.insert(successor);
}
}
}
void VisitUnreachableLifetimeEnds::propagateAvailablity(Result &result) {
// Initialize per-block state.
// - all blocks outside of the region are ::Unavailable (automatically
// initialized)
// - non-initial in-region blocks are Unknown
// - start blocks are ::Available
for (auto *block : region) {
if (starts.contains(block))
result.setState(block, State::Available());
else
result.setState(block, State::Unknown());
}
BasicBlockWorklist worklist(value->getFunction());
// Initialize worklist with all participating blocks.
//
// Only perform dataflow in the non-initial region. Every initial block is
// by definition ::Available.
for (auto *block : region) {
if (starts.contains(block))
continue;
worklist.push(block);
}
// Iterate over blocks which are successors of blocks whose state changed.
while (auto *block = worklist.popAndForget()) {
// Only propagate availability in non-initial, in-region blocks.
if (!region.contains(block) || starts.contains(block))
continue;
auto changed = result.updateState(block);
if (!changed) {
continue;
}
// The state has changed. Propagate the new state into successors.
for (auto *successor : block->getSuccessorBlocks()) {
worklist.pushIfNotVisited(successor);
}
}
}
void VisitUnreachableLifetimeEnds::visitAvailabilityBoundary(
Result const &result, llvm::function_ref<void(SILInstruction *)> visit) {
for (auto *block : region) {
auto available = result.getState(block) == State::Available();
if (!available) {
continue;
}
auto hasUnreachableSuccessor = [&]() {
// Use a lambda to avoid checking if possible.
return llvm::any_of(block->getSuccessorBlocks(), [&result](auto *block) {
return result.getState(block) == State::Unavailable();
});
};
if (!block->succ_empty() && !hasUnreachableSuccessor()) {
continue;
}
assert(hasUnreachableSuccessor() ||
isa<UnreachableInst>(block->getTerminator()));
visit(block->getTerminator());
}
}
} // end anonymous namespace
void OSSALifetimeCompletion::visitUnreachableLifetimeEnds(
SILValue value, const SSAPrunedLiveness &liveness,
llvm::function_ref<void(SILInstruction *)> visit) {
VisitUnreachableLifetimeEnds visitor(value);
visitor.computeRegion(liveness);
VisitUnreachableLifetimeEnds::Result result(value->getFunction());
visitor.propagateAvailablity(result);
visitor.visitAvailabilityBoundary(result, visit);
}
static bool endLifetimeAtUnreachableBlocks(SILValue value,
const SSAPrunedLiveness &liveness) {
bool changed = false;
OSSALifetimeCompletion::visitUnreachableLifetimeEnds(
value, liveness, [&](auto *unreachable) {
SILBuilderWithScope builder(unreachable);
endOSSALifetime(value, builder);
changed = true;
});
return changed;
}
/// End the lifetime of \p value at unreachable instructions.
///
/// Returns true if any new instructions were created to complete the lifetime.
///
/// This is only meant to cleanup lifetimes that lead to dead-end blocks. After
/// recursively completing all nested scopes, it then simply ends the lifetime
/// at the Unreachable instruction.
bool OSSALifetimeCompletion::analyzeAndUpdateLifetime(
SILValue value, bool forceBoundaryCompletion) {
// Called for inner borrows, inner adjacent reborrows, inner reborrows, and
// scoped addresses.
auto handleInnerScope = [this](SILValue innerBorrowedValue) {
completeOSSALifetime(innerBorrowedValue);
};
InteriorLiveness liveness(value);
liveness.compute(domInfo, handleInnerScope);
bool changed = false;
if (value->isLexical() && !forceBoundaryCompletion) {
changed |= endLifetimeAtUnreachableBlocks(value, liveness.getLiveness());
} else {
changed |= endLifetimeAtBoundary(value, liveness.getLiveness());
}
// TODO: Rebuild outer adjacent phis on demand (SILGen does not currently
// produce guaranteed phis). See FindEnclosingDefs &
// findSuccessorDefsFromPredDefs. If no enclosing phi is found, we can create
// it here and use updateSSA to recursively populate phis.
assert(liveness.getUnenclosedPhis().empty());
return changed;
}
namespace swift::test {
// Arguments:
// - SILValue: value
// Dumps:
// - function
static FunctionTest OSSALifetimeCompletionTest(
"ossa-lifetime-completion",
[](auto &function, auto &arguments, auto &test) {
SILValue value = arguments.takeValue();
llvm::outs() << "OSSA lifetime completion: " << value;
OSSALifetimeCompletion completion(&function, /*domInfo*/ nullptr);
completion.completeOSSALifetime(value);
function.print(llvm::outs());
});
} // end namespace swift::test
// TODO: create a fast check for 'mayEndLifetime(SILInstruction *)'. Verify that
// it returns true for every instruction that has a lifetime-ending operand.
void UnreachableLifetimeCompletion::visitUnreachableInst(
SILInstruction *instruction) {
auto *block = instruction->getParent();
bool inReachableBlock = !unreachableBlocks.contains(block);
// If this instruction's block is already marked unreachable, and
// updatingLifetimes is not yet set, then this instruction will be visited
// again later when propagating unreachable blocks.
if (!inReachableBlock && !updatingLifetimes)
return;
for (Operand &operand : instruction->getAllOperands()) {
if (!operand.isLifetimeEnding())
continue;
SILValue value = operand.get();
SILBasicBlock *defBlock = value->getParentBlock();
if (unreachableBlocks.contains(defBlock))
continue;
auto *def = value->getDefiningInstruction();
if (def && unreachableInsts.contains(def))
continue;
// The operand's definition is still reachable and its lifetime ends on a
// newly unreachable path.
//
// Note: The arguments of a no-return try_apply may still appear reachable
// here because the try_apply itself is never visited as unreachable, hence
// its successor blocks are not marked . But it
// seems harmless to recompute their lifetimes.
// Insert this unreachable instruction in unreachableInsts if its parent
// block is not already marked unreachable.
if (inReachableBlock) {
unreachableInsts.insert(instruction);
}
incompleteValues.insert(value);
// Add unreachable successors to the forward traversal worklist.
if (auto *term = dyn_cast<TermInst>(instruction)) {
for (auto *succBlock : term->getSuccessorBlocks()) {
if (llvm::all_of(succBlock->getPredecessorBlocks(),
[&](SILBasicBlock *predBlock) {
if (predBlock == block)
return true;
return unreachableBlocks.contains(predBlock);
})) {
unreachableBlocks.insert(succBlock);
}
}
}
}
}
bool UnreachableLifetimeCompletion::completeLifetimes() {
assert(!updatingLifetimes && "don't call this more than once");
updatingLifetimes = true;
// Now that all unreachable terminator instructions have been visited,
// propagate unreachable blocks.
for (auto blockIt = unreachableBlocks.begin();
blockIt != unreachableBlocks.end(); ++blockIt) {
auto *block = *blockIt;
for (auto &instruction : *block) {
visitUnreachableInst(&instruction);
}
}
OSSALifetimeCompletion completion(function, domInfo);
bool changed = false;
for (auto value : incompleteValues) {
if (completion.completeOSSALifetime(value)
== LifetimeCompletion::WasCompleted) {
changed = true;
}
}
return changed;
}
|