Skip to content

Commit e21bea7

Browse files
committed
Update tryToSinkFreeOperands() to avoid sinking if an equivalent instruction exists in BB
1 parent d6d21c8 commit e21bea7

File tree

1 file changed

+31
-13
lines changed

1 file changed

+31
-13
lines changed

llvm/lib/CodeGen/CodeGenPrepare.cpp

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8001,23 +8001,41 @@ bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
80018001
DenseMap<Instruction *, Instruction *> NewInstructions;
80028002
for (Use *U : ToReplace) {
80038003
auto *UI = cast<Instruction>(U->get());
8004-
Instruction *NI = UI->clone();
8005-
8006-
if (IsHugeFunc) {
8007-
// Now we clone an instruction, its operands' defs may sink to this BB
8008-
// now. So we put the operands defs' BBs into FreshBBs to do optimization.
8009-
for (Value *Op : NI->operands())
8010-
if (auto *OpDef = dyn_cast<Instruction>(Op))
8011-
FreshBBs.insert(OpDef->getParent());
8004+
// Before we clone the instruction, check if we already created an
8005+
// equivalent instruction in the BB and use that instead.
8006+
bool foundEquiv = false;
8007+
Instruction *NI = nullptr;
8008+
for (auto &IToCheck : *TargetBB) {
8009+
if (&IToCheck == I)
8010+
break;
8011+
if (UI->isIdenticalTo(&IToCheck)) {
8012+
// We found an equivalent instruction in this BB that dominates I, let's
8013+
// use it instead!
8014+
NI = &IToCheck;
8015+
LLVM_DEBUG(dbgs() << "Found an equivalent instruction for " << *UI << " in BB: " << *NI << "\n");
8016+
foundEquiv = true;
8017+
break;
8018+
}
80128019
}
8020+
if (!foundEquiv) {
8021+
NI = UI->clone();
80138022

8023+
if (IsHugeFunc) {
8024+
// Now we clone an instruction, its operands' defs may sink to this BB
8025+
// now. So we put the operands defs' BBs into FreshBBs to do optimization.
8026+
for (Value *Op : NI->operands())
8027+
if (auto *OpDef = dyn_cast<Instruction>(Op))
8028+
FreshBBs.insert(OpDef->getParent());
8029+
}
8030+
8031+
LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
8032+
NI->insertBefore(InsertPoint->getIterator());
8033+
InsertPoint = NI;
8034+
InsertedInsts.insert(NI);
8035+
}
8036+
assert(NI && "Didn't find/create a valid sunk instruction!");
80148037
NewInstructions[UI] = NI;
80158038
MaybeDead.insert(UI);
8016-
LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
8017-
NI->insertBefore(InsertPoint->getIterator());
8018-
InsertPoint = NI;
8019-
InsertedInsts.insert(NI);
8020-
80218039
// Update the use for the new instruction, making sure that we update the
80228040
// sunk instruction uses, if it is part of a chain that has already been
80238041
// sunk.

0 commit comments

Comments
 (0)