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
|
//===--- ConditionForwarding.cpp - Forwards conditions --------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "condbranch-forwarding"
#include "swift/SIL/BasicBlockBits.h"
#include "swift/SIL/DebugUtils.h"
#include "swift/SIL/OwnershipUtils.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/SILOptimizer/PassManager/Transforms.h"
using namespace swift;
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
namespace {
/// Moves a condition down to a switch_enum and performs jump threading.
/// Example:
///
/// cond_br %c, bb1, bb2
/// bb1:
/// ... // instructions without relevant side-effects
/// %e1 = enum E.caseA
/// br bb3(%e1)
/// bb2:
/// ... // instructions without relevant side-effects
/// %e2 = enum E.caseB
/// br bb3(%e2)
/// bb3(%e : $Enum):
/// ...
/// ... // Any code, including control flow
/// ...
/// switch_enum %e, case E.caseA : bb4, case E.caseB : bb5
/// bb4:
/// ... // bb4 code
/// bb5:
/// ... // bb5 code
///
/// is optimized to
///
/// br bb3
/// bb3(%e : $Enum):
/// ...
/// ... // Any code, including control flow
/// ...
/// cond_br %c, bb1, bb2
/// bb1:
/// ... // instructions without relevant side-effects
/// %e1 = enum E.caseA
/// br bb4(%e1)
/// bb2:
/// ... // instructions without relevant side-effects
/// %e2 = enum E.caseB
/// br bb5(%e2)
/// bb4(%e3 : $Enum):
/// ... // bb4 code
/// bb5(%e4 : $Enum):
/// ... // bb5 code
///
/// A subsequence run of SimplifyCFG can then optimize it to:
///
/// ...
/// ... // Any code, including control flow
/// ...
/// cond_br %c, bb1, bb2
/// bb1:
/// ... // instructions without relevant side-effects
/// %e1 = enum E.caseA
/// ... // bb4 code
/// bb2:
/// ... // instructions without relevant side-effects
/// %e2 = enum E.caseB
/// ... // bb5 code
///
/// This eliminates the switch_enum. Such a pattern occurs when using
/// closed-range iteration, e.g.
/// for i in 0...n { }
///
class ConditionForwarding : public SILFunctionTransform {
public:
ConditionForwarding() {}
private:
bool tryOptimize(SwitchEnumInst *SEI);
/// The entry point to the transformation.
void run() override {
bool Changed = false;
SILFunction *F = getFunction();
LLVM_DEBUG(llvm::dbgs()
<< "** ConditionForwarding on " << F->getName() << " **\n");
for (SILBasicBlock &BB : *F) {
if (auto *SEI = dyn_cast<SwitchEnumInst>(BB.getTerminator())) {
Changed |= tryOptimize(SEI);
}
}
if (Changed) {
invalidateAnalysis(SILAnalysis::InvalidationKind::BranchesAndInstructions);
}
}
};
/// Returns true if all instructions of block \p BB are safe to be moved
/// across other code.
static bool hasNoRelevantSideEffects(SILBasicBlock *BB) {
for (SILInstruction &I : *BB) {
if (I.getMemoryBehavior() == MemoryBehavior::None)
continue;
if (auto *CF = dyn_cast<CondFailInst>(&I)) {
// Allow cond_fail if the condition is "produced" by a builtin in the
// same basic block.
// Even if we move the whole block across other code, it's still
// guaranteed that the cond_fail is executed before the result of the
// builtin is used.
auto *TEI = dyn_cast<TupleExtractInst>(CF->getOperand());
if (!TEI)
return false;
auto *BI = dyn_cast<BuiltinInst>(TEI->getOperand());
if (!BI || BI->getParent() != BB)
return false;
continue;
}
if (isa<BeginBorrowInst>(&I) || isa<EndBorrowInst>(&I)) {
continue;
}
LLVM_DEBUG(llvm::dbgs() << "Bailing out, found inst with side-effects ");
LLVM_DEBUG(I.dump());
return false;
}
return true;
}
/// Try to move a condition, e.g. a whole if-then-else structure down to the
/// switch_enum instruction \p SEI. If successful, jump thread and replace
/// \p SEI with the condition.
/// Returns true if the a change was made.
bool ConditionForwarding::tryOptimize(SwitchEnumInst *SEI) {
// The switch_enum argument (an Enum) must be a block argument at the merging
// point of the condition's destinations.
auto *Arg = dyn_cast<SILArgument>(SEI->getOperand());
if (!Arg)
return false;
// The switch_enum must be the only use of the Enum, except it may be used in
// SEI's successors.
for (Operand *ArgUse : Arg->getUses()) {
SILInstruction *ArgUser = ArgUse->getUser();
if (ArgUser == SEI)
continue;
if (ArgUser->isDebugInstruction())
continue;
if (ArgUser->getParent()->getSinglePredecessorBlock() == SEI->getParent()) {
continue;
}
return false;
}
// No other values, beside the Enum, should be passed from the condition's
// destinations to the merging block.
SILBasicBlock *BB = Arg->getParent();
if (BB->getNumArguments() != 1)
return false;
llvm::SmallVector<SILBasicBlock *, 4> PredBlocks;
// Check if all predecessors of the merging block pass an Enum to its argument
// and have a single predecessor - the block of the condition.
SILBasicBlock *CommonBranchBlock = nullptr;
for (SILBasicBlock *Pred : BB->getPredecessorBlocks()) {
SILBasicBlock *PredPred = Pred->getSinglePredecessorBlock();
if (!PredPred)
return false;
auto *BI = dyn_cast<BranchInst>(Pred->getTerminator());
if (!BI)
return false;
auto *EI = dyn_cast<EnumInst>(BI->getArg(0));
if (!EI)
return false;
if (CommonBranchBlock && PredPred != CommonBranchBlock)
return false;
CommonBranchBlock = PredPred;
// We cannot move the block across other code if it has side-effects.
if (!hasNoRelevantSideEffects(Pred))
return false;
PredBlocks.push_back(Pred);
}
// It's important to check this, because only if the merging block has at
// least 2 predecessors, the predecessors don't have dominator children. This
// means that all values in the predecessor blocks cannot be used in other
// blocks.
if (PredBlocks.size() < 2)
return false;
// This optimization works with all kind of terminators, except those which
// have side-effects, like try_apply.
TermInst *Condition = CommonBranchBlock->getTerminator();
if (Condition->getMemoryBehavior() != MemoryBehavior::None)
return false;
// Are there any other branch block successors beside the predecessors which
// we collected?
if (CommonBranchBlock->getSuccessors().size() != PredBlocks.size())
return false;
if (getFunction()->hasOwnership()) {
// TODO: Currently disabled because this case may need lifetime extension
// Disabling this conservatively for now.
assert(Condition->getNumOperands() == 1);
BorrowedValue conditionOp(Condition->getOperand(0));
if (conditionOp && conditionOp.isLocalScope()) {
return false;
}
}
// Now do the transformation!
// First thing to do is to replace all uses of the Enum (= the merging block
// argument), as this argument gets deleted.
BasicBlockSet NeedEnumArg(BB->getParent());
while (!Arg->use_empty()) {
Operand *ArgUse = *Arg->use_begin();
SILInstruction *ArgUser = ArgUse->getUser();
if (ArgUser->isDebugInstruction()) {
// Don't care about debug instructions. Just remove them.
ArgUser->eraseFromParent();
continue;
}
SILBasicBlock *UseBlock = ArgUser->getParent();
if (UseBlock->getSinglePredecessorBlock() == SEI->getParent()) {
// The Arg is used in a successor block of the switch_enum. To keep things
// simple, we just create a new block argument and later (see below) we
// pass the corresponding enum to the block. This argument will be deleted
// by a subsequent SimplifyCFG.
SILArgument *NewArg = nullptr;
if (NeedEnumArg.insert(UseBlock)) {
// The first Enum use in this UseBlock.
NewArg = UseBlock->createPhiArgument(Arg->getType(),
Arg->getOwnershipKind());
} else {
// We already inserted the Enum argument for this UseBlock.
assert(UseBlock->getNumArguments() >= 1);
NewArg = UseBlock->getArgument(UseBlock->getNumArguments() - 1);
}
ArgUse->set(NewArg);
continue;
}
assert(ArgUser == SEI);
// We delete the SEI later anyway. Just get rid of the Arg use.
ArgUse->set(SILUndef::get(SEI->getOperand()));
}
// Redirect the predecessors of the condition's merging block to the
// successors of the switch_enum.
for (SILBasicBlock *Pred : PredBlocks) {
auto *BI = cast<BranchInst>(Pred->getTerminator());
auto *EI = cast<EnumInst>(BI->getArg(0));
SILBasicBlock *SEDest = SEI->getCaseDestination(EI->getElement());
SILBuilder B(BI);
llvm::SmallVector<SILValue, 2> BranchArgs;
unsigned HasEnumArg = NeedEnumArg.contains(SEDest);
if (SEDest->getNumArguments() == 1 + HasEnumArg) {
// The successor block has an original argument, which is the Enum's
// payload.
BranchArgs.push_back(EI->getOperand());
}
if (HasEnumArg) {
// The successor block has a new argument (which we created above) where
// we have to pass the Enum.
assert(!getFunction()->hasOwnership() ||
EI->getType().isTrivial(*getFunction()));
BranchArgs.push_back(EI);
}
B.createBranch(BI->getLoc(), SEDest, BranchArgs);
BI->eraseFromParent();
if (EI->use_empty()) {
assert(!HasEnumArg);
EI->eraseFromParent();
} else {
// If an @owned EI has uses remaining, ownership fixup is needed.
// 1. Create a copy_value of EI's operand and
// use it in the branch to avoid a double-consume.
// 2. Create a destroy_value of EI, to avoid a leak.
if (getFunction()->hasOwnership() && EI->hasOperand() &&
EI->getOwnershipKind() == OwnershipKind::Owned) {
auto *term = EI->getParent()->getTerminator();
assert(!HasEnumArg);
auto *copy = SILBuilderWithScope(EI).createCopyValue(EI->getLoc(),
EI->getOperand());
term->getOperandRef(0).set(copy);
SILBuilderWithScope(term).createDestroyValue(EI->getLoc(), EI);
}
}
}
// Final step: replace the switch_enum by the condition.
SILBuilder B(Condition);
B.createBranch(Condition->getLoc(), BB);
Condition->moveBefore(SEI);
SEI->eraseFromParent();
BB->eraseArgument(0);
return true;
}
} // end anonymous namespace
SILTransform *swift::createConditionForwarding() {
return new ConditionForwarding();
}
|