[RISCV] Fix mgather -> riscv.masked.strided.load combine not extending indices (...
[llvm-project.git] / llvm / lib / Transforms / Scalar / JumpThreading.cpp
blob87c01ead634ff86eb421482bdc29fa543e8b4753
1 //===- JumpThreading.cpp - Thread control through conditional blocks ------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Jump Threading pass.
11 //===----------------------------------------------------------------------===//
13 #include "llvm/Transforms/Scalar/JumpThreading.h"
14 #include "llvm/ADT/DenseMap.h"
15 #include "llvm/ADT/DenseSet.h"
16 #include "llvm/ADT/MapVector.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallPtrSet.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/BlockFrequencyInfo.h"
23 #include "llvm/Analysis/BranchProbabilityInfo.h"
24 #include "llvm/Analysis/CFG.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/GlobalsModRef.h"
27 #include "llvm/Analysis/GuardUtils.h"
28 #include "llvm/Analysis/InstructionSimplify.h"
29 #include "llvm/Analysis/LazyValueInfo.h"
30 #include "llvm/Analysis/Loads.h"
31 #include "llvm/Analysis/LoopInfo.h"
32 #include "llvm/Analysis/MemoryLocation.h"
33 #include "llvm/Analysis/PostDominators.h"
34 #include "llvm/Analysis/TargetLibraryInfo.h"
35 #include "llvm/Analysis/TargetTransformInfo.h"
36 #include "llvm/Analysis/ValueTracking.h"
37 #include "llvm/IR/BasicBlock.h"
38 #include "llvm/IR/CFG.h"
39 #include "llvm/IR/Constant.h"
40 #include "llvm/IR/ConstantRange.h"
41 #include "llvm/IR/Constants.h"
42 #include "llvm/IR/DataLayout.h"
43 #include "llvm/IR/DebugInfo.h"
44 #include "llvm/IR/Dominators.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/InstrTypes.h"
47 #include "llvm/IR/Instruction.h"
48 #include "llvm/IR/Instructions.h"
49 #include "llvm/IR/IntrinsicInst.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/MDBuilder.h"
53 #include "llvm/IR/Metadata.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/IR/PassManager.h"
56 #include "llvm/IR/PatternMatch.h"
57 #include "llvm/IR/ProfDataUtils.h"
58 #include "llvm/IR/Type.h"
59 #include "llvm/IR/Use.h"
60 #include "llvm/IR/Value.h"
61 #include "llvm/Support/BlockFrequency.h"
62 #include "llvm/Support/BranchProbability.h"
63 #include "llvm/Support/Casting.h"
64 #include "llvm/Support/CommandLine.h"
65 #include "llvm/Support/Debug.h"
66 #include "llvm/Support/raw_ostream.h"
67 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
68 #include "llvm/Transforms/Utils/Cloning.h"
69 #include "llvm/Transforms/Utils/Local.h"
70 #include "llvm/Transforms/Utils/SSAUpdater.h"
71 #include "llvm/Transforms/Utils/ValueMapper.h"
72 #include <algorithm>
73 #include <cassert>
74 #include <cstdint>
75 #include <iterator>
76 #include <memory>
77 #include <utility>
79 using namespace llvm;
80 using namespace jumpthreading;
82 #define DEBUG_TYPE "jump-threading"
84 STATISTIC(NumThreads, "Number of jumps threaded");
85 STATISTIC(NumFolds, "Number of terminators folded");
86 STATISTIC(NumDupes, "Number of branch blocks duplicated to eliminate phi");
88 static cl::opt<unsigned>
89 BBDuplicateThreshold("jump-threading-threshold",
90 cl::desc("Max block size to duplicate for jump threading"),
91 cl::init(6), cl::Hidden);
93 static cl::opt<unsigned>
94 ImplicationSearchThreshold(
95 "jump-threading-implication-search-threshold",
96 cl::desc("The number of predecessors to search for a stronger "
97 "condition to use to thread over a weaker condition"),
98 cl::init(3), cl::Hidden);
100 static cl::opt<unsigned> PhiDuplicateThreshold(
101 "jump-threading-phi-threshold",
102 cl::desc("Max PHIs in BB to duplicate for jump threading"), cl::init(76),
103 cl::Hidden);
105 static cl::opt<bool> ThreadAcrossLoopHeaders(
106 "jump-threading-across-loop-headers",
107 cl::desc("Allow JumpThreading to thread across loop headers, for testing"),
108 cl::init(false), cl::Hidden);
110 JumpThreadingPass::JumpThreadingPass(int T) {
111 DefaultBBDupThreshold = (T == -1) ? BBDuplicateThreshold : unsigned(T);
114 // Update branch probability information according to conditional
115 // branch probability. This is usually made possible for cloned branches
116 // in inline instances by the context specific profile in the caller.
117 // For instance,
119 // [Block PredBB]
120 // [Branch PredBr]
121 // if (t) {
122 // Block A;
123 // } else {
124 // Block B;
125 // }
127 // [Block BB]
128 // cond = PN([true, %A], [..., %B]); // PHI node
129 // [Branch CondBr]
130 // if (cond) {
131 // ... // P(cond == true) = 1%
132 // }
134 // Here we know that when block A is taken, cond must be true, which means
135 // P(cond == true | A) = 1
137 // Given that P(cond == true) = P(cond == true | A) * P(A) +
138 // P(cond == true | B) * P(B)
139 // we get:
140 // P(cond == true ) = P(A) + P(cond == true | B) * P(B)
142 // which gives us:
143 // P(A) is less than P(cond == true), i.e.
144 // P(t == true) <= P(cond == true)
146 // In other words, if we know P(cond == true) is unlikely, we know
147 // that P(t == true) is also unlikely.
149 static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB) {
150 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
151 if (!CondBr)
152 return;
154 uint64_t TrueWeight, FalseWeight;
155 if (!extractBranchWeights(*CondBr, TrueWeight, FalseWeight))
156 return;
158 if (TrueWeight + FalseWeight == 0)
159 // Zero branch_weights do not give a hint for getting branch probabilities.
160 // Technically it would result in division by zero denominator, which is
161 // TrueWeight + FalseWeight.
162 return;
164 // Returns the outgoing edge of the dominating predecessor block
165 // that leads to the PhiNode's incoming block:
166 auto GetPredOutEdge =
167 [](BasicBlock *IncomingBB,
168 BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
169 auto *PredBB = IncomingBB;
170 auto *SuccBB = PhiBB;
171 SmallPtrSet<BasicBlock *, 16> Visited;
172 while (true) {
173 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
174 if (PredBr && PredBr->isConditional())
175 return {PredBB, SuccBB};
176 Visited.insert(PredBB);
177 auto *SinglePredBB = PredBB->getSinglePredecessor();
178 if (!SinglePredBB)
179 return {nullptr, nullptr};
181 // Stop searching when SinglePredBB has been visited. It means we see
182 // an unreachable loop.
183 if (Visited.count(SinglePredBB))
184 return {nullptr, nullptr};
186 SuccBB = PredBB;
187 PredBB = SinglePredBB;
191 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
192 Value *PhiOpnd = PN->getIncomingValue(i);
193 ConstantInt *CI = dyn_cast<ConstantInt>(PhiOpnd);
195 if (!CI || !CI->getType()->isIntegerTy(1))
196 continue;
198 BranchProbability BP =
199 (CI->isOne() ? BranchProbability::getBranchProbability(
200 TrueWeight, TrueWeight + FalseWeight)
201 : BranchProbability::getBranchProbability(
202 FalseWeight, TrueWeight + FalseWeight));
204 auto PredOutEdge = GetPredOutEdge(PN->getIncomingBlock(i), BB);
205 if (!PredOutEdge.first)
206 return;
208 BasicBlock *PredBB = PredOutEdge.first;
209 BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator());
210 if (!PredBr)
211 return;
213 uint64_t PredTrueWeight, PredFalseWeight;
214 // FIXME: We currently only set the profile data when it is missing.
215 // With PGO, this can be used to refine even existing profile data with
216 // context information. This needs to be done after more performance
217 // testing.
218 if (extractBranchWeights(*PredBr, PredTrueWeight, PredFalseWeight))
219 continue;
221 // We can not infer anything useful when BP >= 50%, because BP is the
222 // upper bound probability value.
223 if (BP >= BranchProbability(50, 100))
224 continue;
226 uint32_t Weights[2];
227 if (PredBr->getSuccessor(0) == PredOutEdge.second) {
228 Weights[0] = BP.getNumerator();
229 Weights[1] = BP.getCompl().getNumerator();
230 } else {
231 Weights[0] = BP.getCompl().getNumerator();
232 Weights[1] = BP.getNumerator();
234 setBranchWeights(*PredBr, Weights);
238 PreservedAnalyses JumpThreadingPass::run(Function &F,
239 FunctionAnalysisManager &AM) {
240 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
241 // Jump Threading has no sense for the targets with divergent CF
242 if (TTI.hasBranchDivergence(&F))
243 return PreservedAnalyses::all();
244 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
245 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
246 auto &AA = AM.getResult<AAManager>(F);
247 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
249 bool Changed =
250 runImpl(F, &AM, &TLI, &TTI, &LVI, &AA,
251 std::make_unique<DomTreeUpdater>(
252 &DT, nullptr, DomTreeUpdater::UpdateStrategy::Lazy),
253 std::nullopt, std::nullopt);
255 if (!Changed)
256 return PreservedAnalyses::all();
259 getDomTreeUpdater()->flush();
261 #if defined(EXPENSIVE_CHECKS)
262 assert(getDomTreeUpdater()->getDomTree().verify(
263 DominatorTree::VerificationLevel::Full) &&
264 "DT broken after JumpThreading");
265 assert((!getDomTreeUpdater()->hasPostDomTree() ||
266 getDomTreeUpdater()->getPostDomTree().verify(
267 PostDominatorTree::VerificationLevel::Full)) &&
268 "PDT broken after JumpThreading");
269 #else
270 assert(getDomTreeUpdater()->getDomTree().verify(
271 DominatorTree::VerificationLevel::Fast) &&
272 "DT broken after JumpThreading");
273 assert((!getDomTreeUpdater()->hasPostDomTree() ||
274 getDomTreeUpdater()->getPostDomTree().verify(
275 PostDominatorTree::VerificationLevel::Fast)) &&
276 "PDT broken after JumpThreading");
277 #endif
279 return getPreservedAnalysis();
282 bool JumpThreadingPass::runImpl(Function &F_, FunctionAnalysisManager *FAM_,
283 TargetLibraryInfo *TLI_,
284 TargetTransformInfo *TTI_, LazyValueInfo *LVI_,
285 AliasAnalysis *AA_,
286 std::unique_ptr<DomTreeUpdater> DTU_,
287 std::optional<BlockFrequencyInfo *> BFI_,
288 std::optional<BranchProbabilityInfo *> BPI_) {
289 LLVM_DEBUG(dbgs() << "Jump threading on function '" << F_.getName() << "'\n");
290 F = &F_;
291 FAM = FAM_;
292 TLI = TLI_;
293 TTI = TTI_;
294 LVI = LVI_;
295 AA = AA_;
296 DTU = std::move(DTU_);
297 BFI = BFI_;
298 BPI = BPI_;
299 auto *GuardDecl = F->getParent()->getFunction(
300 Intrinsic::getName(Intrinsic::experimental_guard));
301 HasGuards = GuardDecl && !GuardDecl->use_empty();
303 // Reduce the number of instructions duplicated when optimizing strictly for
304 // size.
305 if (BBDuplicateThreshold.getNumOccurrences())
306 BBDupThreshold = BBDuplicateThreshold;
307 else if (F->hasFnAttribute(Attribute::MinSize))
308 BBDupThreshold = 3;
309 else
310 BBDupThreshold = DefaultBBDupThreshold;
312 // JumpThreading must not processes blocks unreachable from entry. It's a
313 // waste of compute time and can potentially lead to hangs.
314 SmallPtrSet<BasicBlock *, 16> Unreachable;
315 assert(DTU && "DTU isn't passed into JumpThreading before using it.");
316 assert(DTU->hasDomTree() && "JumpThreading relies on DomTree to proceed.");
317 DominatorTree &DT = DTU->getDomTree();
318 for (auto &BB : *F)
319 if (!DT.isReachableFromEntry(&BB))
320 Unreachable.insert(&BB);
322 if (!ThreadAcrossLoopHeaders)
323 findLoopHeaders(*F);
325 bool EverChanged = false;
326 bool Changed;
327 do {
328 Changed = false;
329 for (auto &BB : *F) {
330 if (Unreachable.count(&BB))
331 continue;
332 while (processBlock(&BB)) // Thread all of the branches we can over BB.
333 Changed = ChangedSinceLastAnalysisUpdate = true;
335 // Jump threading may have introduced redundant debug values into BB
336 // which should be removed.
337 if (Changed)
338 RemoveRedundantDbgInstrs(&BB);
340 // Stop processing BB if it's the entry or is now deleted. The following
341 // routines attempt to eliminate BB and locating a suitable replacement
342 // for the entry is non-trivial.
343 if (&BB == &F->getEntryBlock() || DTU->isBBPendingDeletion(&BB))
344 continue;
346 if (pred_empty(&BB)) {
347 // When processBlock makes BB unreachable it doesn't bother to fix up
348 // the instructions in it. We must remove BB to prevent invalid IR.
349 LLVM_DEBUG(dbgs() << " JT: Deleting dead block '" << BB.getName()
350 << "' with terminator: " << *BB.getTerminator()
351 << '\n');
352 LoopHeaders.erase(&BB);
353 LVI->eraseBlock(&BB);
354 DeleteDeadBlock(&BB, DTU.get());
355 Changed = ChangedSinceLastAnalysisUpdate = true;
356 continue;
359 // processBlock doesn't thread BBs with unconditional TIs. However, if BB
360 // is "almost empty", we attempt to merge BB with its sole successor.
361 auto *BI = dyn_cast<BranchInst>(BB.getTerminator());
362 if (BI && BI->isUnconditional()) {
363 BasicBlock *Succ = BI->getSuccessor(0);
364 if (
365 // The terminator must be the only non-phi instruction in BB.
366 BB.getFirstNonPHIOrDbg(true)->isTerminator() &&
367 // Don't alter Loop headers and latches to ensure another pass can
368 // detect and transform nested loops later.
369 !LoopHeaders.count(&BB) && !LoopHeaders.count(Succ) &&
370 TryToSimplifyUncondBranchFromEmptyBlock(&BB, DTU.get())) {
371 RemoveRedundantDbgInstrs(Succ);
372 // BB is valid for cleanup here because we passed in DTU. F remains
373 // BB's parent until a DTU->getDomTree() event.
374 LVI->eraseBlock(&BB);
375 Changed = ChangedSinceLastAnalysisUpdate = true;
379 EverChanged |= Changed;
380 } while (Changed);
382 LoopHeaders.clear();
383 return EverChanged;
386 // Replace uses of Cond with ToVal when safe to do so. If all uses are
387 // replaced, we can remove Cond. We cannot blindly replace all uses of Cond
388 // because we may incorrectly replace uses when guards/assumes are uses of
389 // of `Cond` and we used the guards/assume to reason about the `Cond` value
390 // at the end of block. RAUW unconditionally replaces all uses
391 // including the guards/assumes themselves and the uses before the
392 // guard/assume.
393 static bool replaceFoldableUses(Instruction *Cond, Value *ToVal,
394 BasicBlock *KnownAtEndOfBB) {
395 bool Changed = false;
396 assert(Cond->getType() == ToVal->getType());
397 // We can unconditionally replace all uses in non-local blocks (i.e. uses
398 // strictly dominated by BB), since LVI information is true from the
399 // terminator of BB.
400 if (Cond->getParent() == KnownAtEndOfBB)
401 Changed |= replaceNonLocalUsesWith(Cond, ToVal);
402 for (Instruction &I : reverse(*KnownAtEndOfBB)) {
403 // Replace any debug-info record users of Cond with ToVal.
404 for (DPValue &DPV : I.getDbgValueRange())
405 DPV.replaceVariableLocationOp(Cond, ToVal, true);
407 // Reached the Cond whose uses we are trying to replace, so there are no
408 // more uses.
409 if (&I == Cond)
410 break;
411 // We only replace uses in instructions that are guaranteed to reach the end
412 // of BB, where we know Cond is ToVal.
413 if (!isGuaranteedToTransferExecutionToSuccessor(&I))
414 break;
415 Changed |= I.replaceUsesOfWith(Cond, ToVal);
417 if (Cond->use_empty() && !Cond->mayHaveSideEffects()) {
418 Cond->eraseFromParent();
419 Changed = true;
421 return Changed;
424 /// Return the cost of duplicating a piece of this block from first non-phi
425 /// and before StopAt instruction to thread across it. Stop scanning the block
426 /// when exceeding the threshold. If duplication is impossible, returns ~0U.
427 static unsigned getJumpThreadDuplicationCost(const TargetTransformInfo *TTI,
428 BasicBlock *BB,
429 Instruction *StopAt,
430 unsigned Threshold) {
431 assert(StopAt->getParent() == BB && "Not an instruction from proper BB?");
433 // Do not duplicate the BB if it has a lot of PHI nodes.
434 // If a threadable chain is too long then the number of PHI nodes can add up,
435 // leading to a substantial increase in compile time when rewriting the SSA.
436 unsigned PhiCount = 0;
437 Instruction *FirstNonPHI = nullptr;
438 for (Instruction &I : *BB) {
439 if (!isa<PHINode>(&I)) {
440 FirstNonPHI = &I;
441 break;
443 if (++PhiCount > PhiDuplicateThreshold)
444 return ~0U;
447 /// Ignore PHI nodes, these will be flattened when duplication happens.
448 BasicBlock::const_iterator I(FirstNonPHI);
450 // FIXME: THREADING will delete values that are just used to compute the
451 // branch, so they shouldn't count against the duplication cost.
453 unsigned Bonus = 0;
454 if (BB->getTerminator() == StopAt) {
455 // Threading through a switch statement is particularly profitable. If this
456 // block ends in a switch, decrease its cost to make it more likely to
457 // happen.
458 if (isa<SwitchInst>(StopAt))
459 Bonus = 6;
461 // The same holds for indirect branches, but slightly more so.
462 if (isa<IndirectBrInst>(StopAt))
463 Bonus = 8;
466 // Bump the threshold up so the early exit from the loop doesn't skip the
467 // terminator-based Size adjustment at the end.
468 Threshold += Bonus;
470 // Sum up the cost of each instruction until we get to the terminator. Don't
471 // include the terminator because the copy won't include it.
472 unsigned Size = 0;
473 for (; &*I != StopAt; ++I) {
475 // Stop scanning the block if we've reached the threshold.
476 if (Size > Threshold)
477 return Size;
479 // Bail out if this instruction gives back a token type, it is not possible
480 // to duplicate it if it is used outside this BB.
481 if (I->getType()->isTokenTy() && I->isUsedOutsideOfBlock(BB))
482 return ~0U;
484 // Blocks with NoDuplicate are modelled as having infinite cost, so they
485 // are never duplicated.
486 if (const CallInst *CI = dyn_cast<CallInst>(I))
487 if (CI->cannotDuplicate() || CI->isConvergent())
488 return ~0U;
490 if (TTI->getInstructionCost(&*I, TargetTransformInfo::TCK_SizeAndLatency) ==
491 TargetTransformInfo::TCC_Free)
492 continue;
494 // All other instructions count for at least one unit.
495 ++Size;
497 // Calls are more expensive. If they are non-intrinsic calls, we model them
498 // as having cost of 4. If they are a non-vector intrinsic, we model them
499 // as having cost of 2 total, and if they are a vector intrinsic, we model
500 // them as having cost 1.
501 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
502 if (!isa<IntrinsicInst>(CI))
503 Size += 3;
504 else if (!CI->getType()->isVectorTy())
505 Size += 1;
509 return Size > Bonus ? Size - Bonus : 0;
512 /// findLoopHeaders - We do not want jump threading to turn proper loop
513 /// structures into irreducible loops. Doing this breaks up the loop nesting
514 /// hierarchy and pessimizes later transformations. To prevent this from
515 /// happening, we first have to find the loop headers. Here we approximate this
516 /// by finding targets of backedges in the CFG.
518 /// Note that there definitely are cases when we want to allow threading of
519 /// edges across a loop header. For example, threading a jump from outside the
520 /// loop (the preheader) to an exit block of the loop is definitely profitable.
521 /// It is also almost always profitable to thread backedges from within the loop
522 /// to exit blocks, and is often profitable to thread backedges to other blocks
523 /// within the loop (forming a nested loop). This simple analysis is not rich
524 /// enough to track all of these properties and keep it up-to-date as the CFG
525 /// mutates, so we don't allow any of these transformations.
526 void JumpThreadingPass::findLoopHeaders(Function &F) {
527 SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
528 FindFunctionBackedges(F, Edges);
530 for (const auto &Edge : Edges)
531 LoopHeaders.insert(Edge.second);
534 /// getKnownConstant - Helper method to determine if we can thread over a
535 /// terminator with the given value as its condition, and if so what value to
536 /// use for that. What kind of value this is depends on whether we want an
537 /// integer or a block address, but an undef is always accepted.
538 /// Returns null if Val is null or not an appropriate constant.
539 static Constant *getKnownConstant(Value *Val, ConstantPreference Preference) {
540 if (!Val)
541 return nullptr;
543 // Undef is "known" enough.
544 if (UndefValue *U = dyn_cast<UndefValue>(Val))
545 return U;
547 if (Preference == WantBlockAddress)
548 return dyn_cast<BlockAddress>(Val->stripPointerCasts());
550 return dyn_cast<ConstantInt>(Val);
553 /// computeValueKnownInPredecessors - Given a basic block BB and a value V, see
554 /// if we can infer that the value is a known ConstantInt/BlockAddress or undef
555 /// in any of our predecessors. If so, return the known list of value and pred
556 /// BB in the result vector.
558 /// This returns true if there were any known values.
559 bool JumpThreadingPass::computeValueKnownInPredecessorsImpl(
560 Value *V, BasicBlock *BB, PredValueInfo &Result,
561 ConstantPreference Preference, DenseSet<Value *> &RecursionSet,
562 Instruction *CxtI) {
563 const DataLayout &DL = BB->getModule()->getDataLayout();
565 // This method walks up use-def chains recursively. Because of this, we could
566 // get into an infinite loop going around loops in the use-def chain. To
567 // prevent this, keep track of what (value, block) pairs we've already visited
568 // and terminate the search if we loop back to them
569 if (!RecursionSet.insert(V).second)
570 return false;
572 // If V is a constant, then it is known in all predecessors.
573 if (Constant *KC = getKnownConstant(V, Preference)) {
574 for (BasicBlock *Pred : predecessors(BB))
575 Result.emplace_back(KC, Pred);
577 return !Result.empty();
580 // If V is a non-instruction value, or an instruction in a different block,
581 // then it can't be derived from a PHI.
582 Instruction *I = dyn_cast<Instruction>(V);
583 if (!I || I->getParent() != BB) {
585 // Okay, if this is a live-in value, see if it has a known value at the any
586 // edge from our predecessors.
587 for (BasicBlock *P : predecessors(BB)) {
588 using namespace PatternMatch;
589 // If the value is known by LazyValueInfo to be a constant in a
590 // predecessor, use that information to try to thread this block.
591 Constant *PredCst = LVI->getConstantOnEdge(V, P, BB, CxtI);
592 // If I is a non-local compare-with-constant instruction, use more-rich
593 // 'getPredicateOnEdge' method. This would be able to handle value
594 // inequalities better, for example if the compare is "X < 4" and "X < 3"
595 // is known true but "X < 4" itself is not available.
596 CmpInst::Predicate Pred;
597 Value *Val;
598 Constant *Cst;
599 if (!PredCst && match(V, m_Cmp(Pred, m_Value(Val), m_Constant(Cst)))) {
600 auto Res = LVI->getPredicateOnEdge(Pred, Val, Cst, P, BB, CxtI);
601 if (Res != LazyValueInfo::Unknown)
602 PredCst = ConstantInt::getBool(V->getContext(), Res);
604 if (Constant *KC = getKnownConstant(PredCst, Preference))
605 Result.emplace_back(KC, P);
608 return !Result.empty();
611 /// If I is a PHI node, then we know the incoming values for any constants.
612 if (PHINode *PN = dyn_cast<PHINode>(I)) {
613 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
614 Value *InVal = PN->getIncomingValue(i);
615 if (Constant *KC = getKnownConstant(InVal, Preference)) {
616 Result.emplace_back(KC, PN->getIncomingBlock(i));
617 } else {
618 Constant *CI = LVI->getConstantOnEdge(InVal,
619 PN->getIncomingBlock(i),
620 BB, CxtI);
621 if (Constant *KC = getKnownConstant(CI, Preference))
622 Result.emplace_back(KC, PN->getIncomingBlock(i));
626 return !Result.empty();
629 // Handle Cast instructions.
630 if (CastInst *CI = dyn_cast<CastInst>(I)) {
631 Value *Source = CI->getOperand(0);
632 PredValueInfoTy Vals;
633 computeValueKnownInPredecessorsImpl(Source, BB, Vals, Preference,
634 RecursionSet, CxtI);
635 if (Vals.empty())
636 return false;
638 // Convert the known values.
639 for (auto &Val : Vals)
640 if (Constant *Folded = ConstantFoldCastOperand(CI->getOpcode(), Val.first,
641 CI->getType(), DL))
642 Result.emplace_back(Folded, Val.second);
644 return !Result.empty();
647 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
648 Value *Source = FI->getOperand(0);
649 computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
650 RecursionSet, CxtI);
652 erase_if(Result, [](auto &Pair) {
653 return !isGuaranteedNotToBeUndefOrPoison(Pair.first);
656 return !Result.empty();
659 // Handle some boolean conditions.
660 if (I->getType()->getPrimitiveSizeInBits() == 1) {
661 using namespace PatternMatch;
662 if (Preference != WantInteger)
663 return false;
664 // X | true -> true
665 // X & false -> false
666 Value *Op0, *Op1;
667 if (match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
668 match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
669 PredValueInfoTy LHSVals, RHSVals;
671 computeValueKnownInPredecessorsImpl(Op0, BB, LHSVals, WantInteger,
672 RecursionSet, CxtI);
673 computeValueKnownInPredecessorsImpl(Op1, BB, RHSVals, WantInteger,
674 RecursionSet, CxtI);
676 if (LHSVals.empty() && RHSVals.empty())
677 return false;
679 ConstantInt *InterestingVal;
680 if (match(I, m_LogicalOr()))
681 InterestingVal = ConstantInt::getTrue(I->getContext());
682 else
683 InterestingVal = ConstantInt::getFalse(I->getContext());
685 SmallPtrSet<BasicBlock*, 4> LHSKnownBBs;
687 // Scan for the sentinel. If we find an undef, force it to the
688 // interesting value: x|undef -> true and x&undef -> false.
689 for (const auto &LHSVal : LHSVals)
690 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
691 Result.emplace_back(InterestingVal, LHSVal.second);
692 LHSKnownBBs.insert(LHSVal.second);
694 for (const auto &RHSVal : RHSVals)
695 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
696 // If we already inferred a value for this block on the LHS, don't
697 // re-add it.
698 if (!LHSKnownBBs.count(RHSVal.second))
699 Result.emplace_back(InterestingVal, RHSVal.second);
702 return !Result.empty();
705 // Handle the NOT form of XOR.
706 if (I->getOpcode() == Instruction::Xor &&
707 isa<ConstantInt>(I->getOperand(1)) &&
708 cast<ConstantInt>(I->getOperand(1))->isOne()) {
709 computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result,
710 WantInteger, RecursionSet, CxtI);
711 if (Result.empty())
712 return false;
714 // Invert the known values.
715 for (auto &R : Result)
716 R.first = ConstantExpr::getNot(R.first);
718 return true;
721 // Try to simplify some other binary operator values.
722 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
723 if (Preference != WantInteger)
724 return false;
725 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
726 PredValueInfoTy LHSVals;
727 computeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
728 WantInteger, RecursionSet, CxtI);
730 // Try to use constant folding to simplify the binary operator.
731 for (const auto &LHSVal : LHSVals) {
732 Constant *V = LHSVal.first;
733 Constant *Folded =
734 ConstantFoldBinaryOpOperands(BO->getOpcode(), V, CI, DL);
736 if (Constant *KC = getKnownConstant(Folded, WantInteger))
737 Result.emplace_back(KC, LHSVal.second);
741 return !Result.empty();
744 // Handle compare with phi operand, where the PHI is defined in this block.
745 if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
746 if (Preference != WantInteger)
747 return false;
748 Type *CmpType = Cmp->getType();
749 Value *CmpLHS = Cmp->getOperand(0);
750 Value *CmpRHS = Cmp->getOperand(1);
751 CmpInst::Predicate Pred = Cmp->getPredicate();
753 PHINode *PN = dyn_cast<PHINode>(CmpLHS);
754 if (!PN)
755 PN = dyn_cast<PHINode>(CmpRHS);
756 // Do not perform phi translation across a loop header phi, because this
757 // may result in comparison of values from two different loop iterations.
758 // FIXME: This check is broken if LoopHeaders is not populated.
759 if (PN && PN->getParent() == BB && !LoopHeaders.contains(BB)) {
760 const DataLayout &DL = PN->getModule()->getDataLayout();
761 // We can do this simplification if any comparisons fold to true or false.
762 // See if any do.
763 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
764 BasicBlock *PredBB = PN->getIncomingBlock(i);
765 Value *LHS, *RHS;
766 if (PN == CmpLHS) {
767 LHS = PN->getIncomingValue(i);
768 RHS = CmpRHS->DoPHITranslation(BB, PredBB);
769 } else {
770 LHS = CmpLHS->DoPHITranslation(BB, PredBB);
771 RHS = PN->getIncomingValue(i);
773 Value *Res = simplifyCmpInst(Pred, LHS, RHS, {DL});
774 if (!Res) {
775 if (!isa<Constant>(RHS))
776 continue;
778 // getPredicateOnEdge call will make no sense if LHS is defined in BB.
779 auto LHSInst = dyn_cast<Instruction>(LHS);
780 if (LHSInst && LHSInst->getParent() == BB)
781 continue;
783 LazyValueInfo::Tristate
784 ResT = LVI->getPredicateOnEdge(Pred, LHS,
785 cast<Constant>(RHS), PredBB, BB,
786 CxtI ? CxtI : Cmp);
787 if (ResT == LazyValueInfo::Unknown)
788 continue;
789 Res = ConstantInt::get(Type::getInt1Ty(LHS->getContext()), ResT);
792 if (Constant *KC = getKnownConstant(Res, WantInteger))
793 Result.emplace_back(KC, PredBB);
796 return !Result.empty();
799 // If comparing a live-in value against a constant, see if we know the
800 // live-in value on any predecessors.
801 if (isa<Constant>(CmpRHS) && !CmpType->isVectorTy()) {
802 Constant *CmpConst = cast<Constant>(CmpRHS);
804 if (!isa<Instruction>(CmpLHS) ||
805 cast<Instruction>(CmpLHS)->getParent() != BB) {
806 for (BasicBlock *P : predecessors(BB)) {
807 // If the value is known by LazyValueInfo to be a constant in a
808 // predecessor, use that information to try to thread this block.
809 LazyValueInfo::Tristate Res =
810 LVI->getPredicateOnEdge(Pred, CmpLHS,
811 CmpConst, P, BB, CxtI ? CxtI : Cmp);
812 if (Res == LazyValueInfo::Unknown)
813 continue;
815 Constant *ResC = ConstantInt::get(CmpType, Res);
816 Result.emplace_back(ResC, P);
819 return !Result.empty();
822 // InstCombine can fold some forms of constant range checks into
823 // (icmp (add (x, C1)), C2). See if we have we have such a thing with
824 // x as a live-in.
826 using namespace PatternMatch;
828 Value *AddLHS;
829 ConstantInt *AddConst;
830 if (isa<ConstantInt>(CmpConst) &&
831 match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) {
832 if (!isa<Instruction>(AddLHS) ||
833 cast<Instruction>(AddLHS)->getParent() != BB) {
834 for (BasicBlock *P : predecessors(BB)) {
835 // If the value is known by LazyValueInfo to be a ConstantRange in
836 // a predecessor, use that information to try to thread this
837 // block.
838 ConstantRange CR = LVI->getConstantRangeOnEdge(
839 AddLHS, P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
840 // Propagate the range through the addition.
841 CR = CR.add(AddConst->getValue());
843 // Get the range where the compare returns true.
844 ConstantRange CmpRange = ConstantRange::makeExactICmpRegion(
845 Pred, cast<ConstantInt>(CmpConst)->getValue());
847 Constant *ResC;
848 if (CmpRange.contains(CR))
849 ResC = ConstantInt::getTrue(CmpType);
850 else if (CmpRange.inverse().contains(CR))
851 ResC = ConstantInt::getFalse(CmpType);
852 else
853 continue;
855 Result.emplace_back(ResC, P);
858 return !Result.empty();
863 // Try to find a constant value for the LHS of a comparison,
864 // and evaluate it statically if we can.
865 PredValueInfoTy LHSVals;
866 computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, LHSVals,
867 WantInteger, RecursionSet, CxtI);
869 for (const auto &LHSVal : LHSVals) {
870 Constant *V = LHSVal.first;
871 Constant *Folded = ConstantExpr::getCompare(Pred, V, CmpConst);
872 if (Constant *KC = getKnownConstant(Folded, WantInteger))
873 Result.emplace_back(KC, LHSVal.second);
876 return !Result.empty();
880 if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
881 // Handle select instructions where at least one operand is a known constant
882 // and we can figure out the condition value for any predecessor block.
883 Constant *TrueVal = getKnownConstant(SI->getTrueValue(), Preference);
884 Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
885 PredValueInfoTy Conds;
886 if ((TrueVal || FalseVal) &&
887 computeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds,
888 WantInteger, RecursionSet, CxtI)) {
889 for (auto &C : Conds) {
890 Constant *Cond = C.first;
892 // Figure out what value to use for the condition.
893 bool KnownCond;
894 if (ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
895 // A known boolean.
896 KnownCond = CI->isOne();
897 } else {
898 assert(isa<UndefValue>(Cond) && "Unexpected condition value");
899 // Either operand will do, so be sure to pick the one that's a known
900 // constant.
901 // FIXME: Do this more cleverly if both values are known constants?
902 KnownCond = (TrueVal != nullptr);
905 // See if the select has a known constant value for this predecessor.
906 if (Constant *Val = KnownCond ? TrueVal : FalseVal)
907 Result.emplace_back(Val, C.second);
910 return !Result.empty();
914 // If all else fails, see if LVI can figure out a constant value for us.
915 assert(CxtI->getParent() == BB && "CxtI should be in BB");
916 Constant *CI = LVI->getConstant(V, CxtI);
917 if (Constant *KC = getKnownConstant(CI, Preference)) {
918 for (BasicBlock *Pred : predecessors(BB))
919 Result.emplace_back(KC, Pred);
922 return !Result.empty();
925 /// GetBestDestForBranchOnUndef - If we determine that the specified block ends
926 /// in an undefined jump, decide which block is best to revector to.
928 /// Since we can pick an arbitrary destination, we pick the successor with the
929 /// fewest predecessors. This should reduce the in-degree of the others.
930 static unsigned getBestDestForJumpOnUndef(BasicBlock *BB) {
931 Instruction *BBTerm = BB->getTerminator();
932 unsigned MinSucc = 0;
933 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
934 // Compute the successor with the minimum number of predecessors.
935 unsigned MinNumPreds = pred_size(TestBB);
936 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
937 TestBB = BBTerm->getSuccessor(i);
938 unsigned NumPreds = pred_size(TestBB);
939 if (NumPreds < MinNumPreds) {
940 MinSucc = i;
941 MinNumPreds = NumPreds;
945 return MinSucc;
948 static bool hasAddressTakenAndUsed(BasicBlock *BB) {
949 if (!BB->hasAddressTaken()) return false;
951 // If the block has its address taken, it may be a tree of dead constants
952 // hanging off of it. These shouldn't keep the block alive.
953 BlockAddress *BA = BlockAddress::get(BB);
954 BA->removeDeadConstantUsers();
955 return !BA->use_empty();
958 /// processBlock - If there are any predecessors whose control can be threaded
959 /// through to a successor, transform them now.
960 bool JumpThreadingPass::processBlock(BasicBlock *BB) {
961 // If the block is trivially dead, just return and let the caller nuke it.
962 // This simplifies other transformations.
963 if (DTU->isBBPendingDeletion(BB) ||
964 (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()))
965 return false;
967 // If this block has a single predecessor, and if that pred has a single
968 // successor, merge the blocks. This encourages recursive jump threading
969 // because now the condition in this block can be threaded through
970 // predecessors of our predecessor block.
971 if (maybeMergeBasicBlockIntoOnlyPred(BB))
972 return true;
974 if (tryToUnfoldSelectInCurrBB(BB))
975 return true;
977 // Look if we can propagate guards to predecessors.
978 if (HasGuards && processGuards(BB))
979 return true;
981 // What kind of constant we're looking for.
982 ConstantPreference Preference = WantInteger;
984 // Look to see if the terminator is a conditional branch, switch or indirect
985 // branch, if not we can't thread it.
986 Value *Condition;
987 Instruction *Terminator = BB->getTerminator();
988 if (BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
989 // Can't thread an unconditional jump.
990 if (BI->isUnconditional()) return false;
991 Condition = BI->getCondition();
992 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
993 Condition = SI->getCondition();
994 } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
995 // Can't thread indirect branch with no successors.
996 if (IB->getNumSuccessors() == 0) return false;
997 Condition = IB->getAddress()->stripPointerCasts();
998 Preference = WantBlockAddress;
999 } else {
1000 return false; // Must be an invoke or callbr.
1003 // Keep track if we constant folded the condition in this invocation.
1004 bool ConstantFolded = false;
1006 // Run constant folding to see if we can reduce the condition to a simple
1007 // constant.
1008 if (Instruction *I = dyn_cast<Instruction>(Condition)) {
1009 Value *SimpleVal =
1010 ConstantFoldInstruction(I, BB->getModule()->getDataLayout(), TLI);
1011 if (SimpleVal) {
1012 I->replaceAllUsesWith(SimpleVal);
1013 if (isInstructionTriviallyDead(I, TLI))
1014 I->eraseFromParent();
1015 Condition = SimpleVal;
1016 ConstantFolded = true;
1020 // If the terminator is branching on an undef or freeze undef, we can pick any
1021 // of the successors to branch to. Let getBestDestForJumpOnUndef decide.
1022 auto *FI = dyn_cast<FreezeInst>(Condition);
1023 if (isa<UndefValue>(Condition) ||
1024 (FI && isa<UndefValue>(FI->getOperand(0)) && FI->hasOneUse())) {
1025 unsigned BestSucc = getBestDestForJumpOnUndef(BB);
1026 std::vector<DominatorTree::UpdateType> Updates;
1028 // Fold the branch/switch.
1029 Instruction *BBTerm = BB->getTerminator();
1030 Updates.reserve(BBTerm->getNumSuccessors());
1031 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
1032 if (i == BestSucc) continue;
1033 BasicBlock *Succ = BBTerm->getSuccessor(i);
1034 Succ->removePredecessor(BB, true);
1035 Updates.push_back({DominatorTree::Delete, BB, Succ});
1038 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
1039 << "' folding undef terminator: " << *BBTerm << '\n');
1040 BranchInst::Create(BBTerm->getSuccessor(BestSucc), BBTerm);
1041 ++NumFolds;
1042 BBTerm->eraseFromParent();
1043 DTU->applyUpdatesPermissive(Updates);
1044 if (FI)
1045 FI->eraseFromParent();
1046 return true;
1049 // If the terminator of this block is branching on a constant, simplify the
1050 // terminator to an unconditional branch. This can occur due to threading in
1051 // other blocks.
1052 if (getKnownConstant(Condition, Preference)) {
1053 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
1054 << "' folding terminator: " << *BB->getTerminator()
1055 << '\n');
1056 ++NumFolds;
1057 ConstantFoldTerminator(BB, true, nullptr, DTU.get());
1058 if (auto *BPI = getBPI())
1059 BPI->eraseBlock(BB);
1060 return true;
1063 Instruction *CondInst = dyn_cast<Instruction>(Condition);
1065 // All the rest of our checks depend on the condition being an instruction.
1066 if (!CondInst) {
1067 // FIXME: Unify this with code below.
1068 if (processThreadableEdges(Condition, BB, Preference, Terminator))
1069 return true;
1070 return ConstantFolded;
1073 // Some of the following optimization can safely work on the unfrozen cond.
1074 Value *CondWithoutFreeze = CondInst;
1075 if (auto *FI = dyn_cast<FreezeInst>(CondInst))
1076 CondWithoutFreeze = FI->getOperand(0);
1078 if (CmpInst *CondCmp = dyn_cast<CmpInst>(CondWithoutFreeze)) {
1079 // If we're branching on a conditional, LVI might be able to determine
1080 // it's value at the branch instruction. We only handle comparisons
1081 // against a constant at this time.
1082 if (Constant *CondConst = dyn_cast<Constant>(CondCmp->getOperand(1))) {
1083 LazyValueInfo::Tristate Ret =
1084 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
1085 CondConst, BB->getTerminator(),
1086 /*UseBlockValue=*/false);
1087 if (Ret != LazyValueInfo::Unknown) {
1088 // We can safely replace *some* uses of the CondInst if it has
1089 // exactly one value as returned by LVI. RAUW is incorrect in the
1090 // presence of guards and assumes, that have the `Cond` as the use. This
1091 // is because we use the guards/assume to reason about the `Cond` value
1092 // at the end of block, but RAUW unconditionally replaces all uses
1093 // including the guards/assumes themselves and the uses before the
1094 // guard/assume.
1095 auto *CI = Ret == LazyValueInfo::True ?
1096 ConstantInt::getTrue(CondCmp->getType()) :
1097 ConstantInt::getFalse(CondCmp->getType());
1098 if (replaceFoldableUses(CondCmp, CI, BB))
1099 return true;
1102 // We did not manage to simplify this branch, try to see whether
1103 // CondCmp depends on a known phi-select pattern.
1104 if (tryToUnfoldSelect(CondCmp, BB))
1105 return true;
1109 if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator()))
1110 if (tryToUnfoldSelect(SI, BB))
1111 return true;
1113 // Check for some cases that are worth simplifying. Right now we want to look
1114 // for loads that are used by a switch or by the condition for the branch. If
1115 // we see one, check to see if it's partially redundant. If so, insert a PHI
1116 // which can then be used to thread the values.
1117 Value *SimplifyValue = CondWithoutFreeze;
1119 if (CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
1120 if (isa<Constant>(CondCmp->getOperand(1)))
1121 SimplifyValue = CondCmp->getOperand(0);
1123 // TODO: There are other places where load PRE would be profitable, such as
1124 // more complex comparisons.
1125 if (LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue))
1126 if (simplifyPartiallyRedundantLoad(LoadI))
1127 return true;
1129 // Before threading, try to propagate profile data backwards:
1130 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
1131 if (PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1132 updatePredecessorProfileMetadata(PN, BB);
1134 // Handle a variety of cases where we are branching on something derived from
1135 // a PHI node in the current block. If we can prove that any predecessors
1136 // compute a predictable value based on a PHI node, thread those predecessors.
1137 if (processThreadableEdges(CondInst, BB, Preference, Terminator))
1138 return true;
1140 // If this is an otherwise-unfoldable branch on a phi node or freeze(phi) in
1141 // the current block, see if we can simplify.
1142 PHINode *PN = dyn_cast<PHINode>(CondWithoutFreeze);
1143 if (PN && PN->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1144 return processBranchOnPHI(PN);
1146 // If this is an otherwise-unfoldable branch on a XOR, see if we can simplify.
1147 if (CondInst->getOpcode() == Instruction::Xor &&
1148 CondInst->getParent() == BB && isa<BranchInst>(BB->getTerminator()))
1149 return processBranchOnXOR(cast<BinaryOperator>(CondInst));
1151 // Search for a stronger dominating condition that can be used to simplify a
1152 // conditional branch leaving BB.
1153 if (processImpliedCondition(BB))
1154 return true;
1156 return false;
1159 bool JumpThreadingPass::processImpliedCondition(BasicBlock *BB) {
1160 auto *BI = dyn_cast<BranchInst>(BB->getTerminator());
1161 if (!BI || !BI->isConditional())
1162 return false;
1164 Value *Cond = BI->getCondition();
1165 // Assuming that predecessor's branch was taken, if pred's branch condition
1166 // (V) implies Cond, Cond can be either true, undef, or poison. In this case,
1167 // freeze(Cond) is either true or a nondeterministic value.
1168 // If freeze(Cond) has only one use, we can freely fold freeze(Cond) to true
1169 // without affecting other instructions.
1170 auto *FICond = dyn_cast<FreezeInst>(Cond);
1171 if (FICond && FICond->hasOneUse())
1172 Cond = FICond->getOperand(0);
1173 else
1174 FICond = nullptr;
1176 BasicBlock *CurrentBB = BB;
1177 BasicBlock *CurrentPred = BB->getSinglePredecessor();
1178 unsigned Iter = 0;
1180 auto &DL = BB->getModule()->getDataLayout();
1182 while (CurrentPred && Iter++ < ImplicationSearchThreshold) {
1183 auto *PBI = dyn_cast<BranchInst>(CurrentPred->getTerminator());
1184 if (!PBI || !PBI->isConditional())
1185 return false;
1186 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1187 return false;
1189 bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB;
1190 std::optional<bool> Implication =
1191 isImpliedCondition(PBI->getCondition(), Cond, DL, CondIsTrue);
1193 // If the branch condition of BB (which is Cond) and CurrentPred are
1194 // exactly the same freeze instruction, Cond can be folded into CondIsTrue.
1195 if (!Implication && FICond && isa<FreezeInst>(PBI->getCondition())) {
1196 if (cast<FreezeInst>(PBI->getCondition())->getOperand(0) ==
1197 FICond->getOperand(0))
1198 Implication = CondIsTrue;
1201 if (Implication) {
1202 BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
1203 BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
1204 RemoveSucc->removePredecessor(BB);
1205 BranchInst *UncondBI = BranchInst::Create(KeepSucc, BI);
1206 UncondBI->setDebugLoc(BI->getDebugLoc());
1207 ++NumFolds;
1208 BI->eraseFromParent();
1209 if (FICond)
1210 FICond->eraseFromParent();
1212 DTU->applyUpdatesPermissive({{DominatorTree::Delete, BB, RemoveSucc}});
1213 if (auto *BPI = getBPI())
1214 BPI->eraseBlock(BB);
1215 return true;
1217 CurrentBB = CurrentPred;
1218 CurrentPred = CurrentBB->getSinglePredecessor();
1221 return false;
1224 /// Return true if Op is an instruction defined in the given block.
1225 static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB) {
1226 if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1227 if (OpInst->getParent() == BB)
1228 return true;
1229 return false;
1232 /// simplifyPartiallyRedundantLoad - If LoadI is an obviously partially
1233 /// redundant load instruction, eliminate it by replacing it with a PHI node.
1234 /// This is an important optimization that encourages jump threading, and needs
1235 /// to be run interlaced with other jump threading tasks.
1236 bool JumpThreadingPass::simplifyPartiallyRedundantLoad(LoadInst *LoadI) {
1237 // Don't hack volatile and ordered loads.
1238 if (!LoadI->isUnordered()) return false;
1240 // If the load is defined in a block with exactly one predecessor, it can't be
1241 // partially redundant.
1242 BasicBlock *LoadBB = LoadI->getParent();
1243 if (LoadBB->getSinglePredecessor())
1244 return false;
1246 // If the load is defined in an EH pad, it can't be partially redundant,
1247 // because the edges between the invoke and the EH pad cannot have other
1248 // instructions between them.
1249 if (LoadBB->isEHPad())
1250 return false;
1252 Value *LoadedPtr = LoadI->getOperand(0);
1254 // If the loaded operand is defined in the LoadBB and its not a phi,
1255 // it can't be available in predecessors.
1256 if (isOpDefinedInBlock(LoadedPtr, LoadBB) && !isa<PHINode>(LoadedPtr))
1257 return false;
1259 // Scan a few instructions up from the load, to see if it is obviously live at
1260 // the entry to its block.
1261 BasicBlock::iterator BBIt(LoadI);
1262 bool IsLoadCSE;
1263 BatchAAResults BatchAA(*AA);
1264 // The dominator tree is updated lazily and may not be valid at this point.
1265 BatchAA.disableDominatorTree();
1266 if (Value *AvailableVal = FindAvailableLoadedValue(
1267 LoadI, LoadBB, BBIt, DefMaxInstsToScan, &BatchAA, &IsLoadCSE)) {
1268 // If the value of the load is locally available within the block, just use
1269 // it. This frequently occurs for reg2mem'd allocas.
1271 if (IsLoadCSE) {
1272 LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
1273 combineMetadataForCSE(NLoadI, LoadI, false);
1274 LVI->forgetValue(NLoadI);
1277 // If the returned value is the load itself, replace with poison. This can
1278 // only happen in dead loops.
1279 if (AvailableVal == LoadI)
1280 AvailableVal = PoisonValue::get(LoadI->getType());
1281 if (AvailableVal->getType() != LoadI->getType())
1282 AvailableVal = CastInst::CreateBitOrPointerCast(
1283 AvailableVal, LoadI->getType(), "", LoadI);
1284 LoadI->replaceAllUsesWith(AvailableVal);
1285 LoadI->eraseFromParent();
1286 return true;
1289 // Otherwise, if we scanned the whole block and got to the top of the block,
1290 // we know the block is locally transparent to the load. If not, something
1291 // might clobber its value.
1292 if (BBIt != LoadBB->begin())
1293 return false;
1295 // If all of the loads and stores that feed the value have the same AA tags,
1296 // then we can propagate them onto any newly inserted loads.
1297 AAMDNodes AATags = LoadI->getAAMetadata();
1299 SmallPtrSet<BasicBlock*, 8> PredsScanned;
1301 using AvailablePredsTy = SmallVector<std::pair<BasicBlock *, Value *>, 8>;
1303 AvailablePredsTy AvailablePreds;
1304 BasicBlock *OneUnavailablePred = nullptr;
1305 SmallVector<LoadInst*, 8> CSELoads;
1307 // If we got here, the loaded value is transparent through to the start of the
1308 // block. Check to see if it is available in any of the predecessor blocks.
1309 for (BasicBlock *PredBB : predecessors(LoadBB)) {
1310 // If we already scanned this predecessor, skip it.
1311 if (!PredsScanned.insert(PredBB).second)
1312 continue;
1314 BBIt = PredBB->end();
1315 unsigned NumScanedInst = 0;
1316 Value *PredAvailable = nullptr;
1317 // NOTE: We don't CSE load that is volatile or anything stronger than
1318 // unordered, that should have been checked when we entered the function.
1319 assert(LoadI->isUnordered() &&
1320 "Attempting to CSE volatile or atomic loads");
1321 // If this is a load on a phi pointer, phi-translate it and search
1322 // for available load/store to the pointer in predecessors.
1323 Type *AccessTy = LoadI->getType();
1324 const auto &DL = LoadI->getModule()->getDataLayout();
1325 MemoryLocation Loc(LoadedPtr->DoPHITranslation(LoadBB, PredBB),
1326 LocationSize::precise(DL.getTypeStoreSize(AccessTy)),
1327 AATags);
1328 PredAvailable = findAvailablePtrLoadStore(
1329 Loc, AccessTy, LoadI->isAtomic(), PredBB, BBIt, DefMaxInstsToScan,
1330 &BatchAA, &IsLoadCSE, &NumScanedInst);
1332 // If PredBB has a single predecessor, continue scanning through the
1333 // single predecessor.
1334 BasicBlock *SinglePredBB = PredBB;
1335 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
1336 NumScanedInst < DefMaxInstsToScan) {
1337 SinglePredBB = SinglePredBB->getSinglePredecessor();
1338 if (SinglePredBB) {
1339 BBIt = SinglePredBB->end();
1340 PredAvailable = findAvailablePtrLoadStore(
1341 Loc, AccessTy, LoadI->isAtomic(), SinglePredBB, BBIt,
1342 (DefMaxInstsToScan - NumScanedInst), &BatchAA, &IsLoadCSE,
1343 &NumScanedInst);
1347 if (!PredAvailable) {
1348 OneUnavailablePred = PredBB;
1349 continue;
1352 if (IsLoadCSE)
1353 CSELoads.push_back(cast<LoadInst>(PredAvailable));
1355 // If so, this load is partially redundant. Remember this info so that we
1356 // can create a PHI node.
1357 AvailablePreds.emplace_back(PredBB, PredAvailable);
1360 // If the loaded value isn't available in any predecessor, it isn't partially
1361 // redundant.
1362 if (AvailablePreds.empty()) return false;
1364 // Okay, the loaded value is available in at least one (and maybe all!)
1365 // predecessors. If the value is unavailable in more than one unique
1366 // predecessor, we want to insert a merge block for those common predecessors.
1367 // This ensures that we only have to insert one reload, thus not increasing
1368 // code size.
1369 BasicBlock *UnavailablePred = nullptr;
1371 // If the value is unavailable in one of predecessors, we will end up
1372 // inserting a new instruction into them. It is only valid if all the
1373 // instructions before LoadI are guaranteed to pass execution to its
1374 // successor, or if LoadI is safe to speculate.
1375 // TODO: If this logic becomes more complex, and we will perform PRE insertion
1376 // farther than to a predecessor, we need to reuse the code from GVN's PRE.
1377 // It requires domination tree analysis, so for this simple case it is an
1378 // overkill.
1379 if (PredsScanned.size() != AvailablePreds.size() &&
1380 !isSafeToSpeculativelyExecute(LoadI))
1381 for (auto I = LoadBB->begin(); &*I != LoadI; ++I)
1382 if (!isGuaranteedToTransferExecutionToSuccessor(&*I))
1383 return false;
1385 // If there is exactly one predecessor where the value is unavailable, the
1386 // already computed 'OneUnavailablePred' block is it. If it ends in an
1387 // unconditional branch, we know that it isn't a critical edge.
1388 if (PredsScanned.size() == AvailablePreds.size()+1 &&
1389 OneUnavailablePred->getTerminator()->getNumSuccessors() == 1) {
1390 UnavailablePred = OneUnavailablePred;
1391 } else if (PredsScanned.size() != AvailablePreds.size()) {
1392 // Otherwise, we had multiple unavailable predecessors or we had a critical
1393 // edge from the one.
1394 SmallVector<BasicBlock*, 8> PredsToSplit;
1395 SmallPtrSet<BasicBlock*, 8> AvailablePredSet;
1397 for (const auto &AvailablePred : AvailablePreds)
1398 AvailablePredSet.insert(AvailablePred.first);
1400 // Add all the unavailable predecessors to the PredsToSplit list.
1401 for (BasicBlock *P : predecessors(LoadBB)) {
1402 // If the predecessor is an indirect goto, we can't split the edge.
1403 if (isa<IndirectBrInst>(P->getTerminator()))
1404 return false;
1406 if (!AvailablePredSet.count(P))
1407 PredsToSplit.push_back(P);
1410 // Split them out to their own block.
1411 UnavailablePred = splitBlockPreds(LoadBB, PredsToSplit, "thread-pre-split");
1414 // If the value isn't available in all predecessors, then there will be
1415 // exactly one where it isn't available. Insert a load on that edge and add
1416 // it to the AvailablePreds list.
1417 if (UnavailablePred) {
1418 assert(UnavailablePred->getTerminator()->getNumSuccessors() == 1 &&
1419 "Can't handle critical edge here!");
1420 LoadInst *NewVal = new LoadInst(
1421 LoadI->getType(), LoadedPtr->DoPHITranslation(LoadBB, UnavailablePred),
1422 LoadI->getName() + ".pr", false, LoadI->getAlign(),
1423 LoadI->getOrdering(), LoadI->getSyncScopeID(),
1424 UnavailablePred->getTerminator());
1425 NewVal->setDebugLoc(LoadI->getDebugLoc());
1426 if (AATags)
1427 NewVal->setAAMetadata(AATags);
1429 AvailablePreds.emplace_back(UnavailablePred, NewVal);
1432 // Now we know that each predecessor of this block has a value in
1433 // AvailablePreds, sort them for efficient access as we're walking the preds.
1434 array_pod_sort(AvailablePreds.begin(), AvailablePreds.end());
1436 // Create a PHI node at the start of the block for the PRE'd load value.
1437 pred_iterator PB = pred_begin(LoadBB), PE = pred_end(LoadBB);
1438 PHINode *PN = PHINode::Create(LoadI->getType(), std::distance(PB, PE), "");
1439 PN->insertBefore(LoadBB->begin());
1440 PN->takeName(LoadI);
1441 PN->setDebugLoc(LoadI->getDebugLoc());
1443 // Insert new entries into the PHI for each predecessor. A single block may
1444 // have multiple entries here.
1445 for (pred_iterator PI = PB; PI != PE; ++PI) {
1446 BasicBlock *P = *PI;
1447 AvailablePredsTy::iterator I =
1448 llvm::lower_bound(AvailablePreds, std::make_pair(P, (Value *)nullptr));
1450 assert(I != AvailablePreds.end() && I->first == P &&
1451 "Didn't find entry for predecessor!");
1453 // If we have an available predecessor but it requires casting, insert the
1454 // cast in the predecessor and use the cast. Note that we have to update the
1455 // AvailablePreds vector as we go so that all of the PHI entries for this
1456 // predecessor use the same bitcast.
1457 Value *&PredV = I->second;
1458 if (PredV->getType() != LoadI->getType())
1459 PredV = CastInst::CreateBitOrPointerCast(PredV, LoadI->getType(), "",
1460 P->getTerminator());
1462 PN->addIncoming(PredV, I->first);
1465 for (LoadInst *PredLoadI : CSELoads) {
1466 combineMetadataForCSE(PredLoadI, LoadI, true);
1467 LVI->forgetValue(PredLoadI);
1470 LoadI->replaceAllUsesWith(PN);
1471 LoadI->eraseFromParent();
1473 return true;
1476 /// findMostPopularDest - The specified list contains multiple possible
1477 /// threadable destinations. Pick the one that occurs the most frequently in
1478 /// the list.
1479 static BasicBlock *
1480 findMostPopularDest(BasicBlock *BB,
1481 const SmallVectorImpl<std::pair<BasicBlock *,
1482 BasicBlock *>> &PredToDestList) {
1483 assert(!PredToDestList.empty());
1485 // Determine popularity. If there are multiple possible destinations, we
1486 // explicitly choose to ignore 'undef' destinations. We prefer to thread
1487 // blocks with known and real destinations to threading undef. We'll handle
1488 // them later if interesting.
1489 MapVector<BasicBlock *, unsigned> DestPopularity;
1491 // Populate DestPopularity with the successors in the order they appear in the
1492 // successor list. This way, we ensure determinism by iterating it in the
1493 // same order in std::max_element below. We map nullptr to 0 so that we can
1494 // return nullptr when PredToDestList contains nullptr only.
1495 DestPopularity[nullptr] = 0;
1496 for (auto *SuccBB : successors(BB))
1497 DestPopularity[SuccBB] = 0;
1499 for (const auto &PredToDest : PredToDestList)
1500 if (PredToDest.second)
1501 DestPopularity[PredToDest.second]++;
1503 // Find the most popular dest.
1504 auto MostPopular = std::max_element(
1505 DestPopularity.begin(), DestPopularity.end(), llvm::less_second());
1507 // Okay, we have finally picked the most popular destination.
1508 return MostPopular->first;
1511 // Try to evaluate the value of V when the control flows from PredPredBB to
1512 // BB->getSinglePredecessor() and then on to BB.
1513 Constant *JumpThreadingPass::evaluateOnPredecessorEdge(BasicBlock *BB,
1514 BasicBlock *PredPredBB,
1515 Value *V) {
1516 BasicBlock *PredBB = BB->getSinglePredecessor();
1517 assert(PredBB && "Expected a single predecessor");
1519 if (Constant *Cst = dyn_cast<Constant>(V)) {
1520 return Cst;
1523 // Consult LVI if V is not an instruction in BB or PredBB.
1524 Instruction *I = dyn_cast<Instruction>(V);
1525 if (!I || (I->getParent() != BB && I->getParent() != PredBB)) {
1526 return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr);
1529 // Look into a PHI argument.
1530 if (PHINode *PHI = dyn_cast<PHINode>(V)) {
1531 if (PHI->getParent() == PredBB)
1532 return dyn_cast<Constant>(PHI->getIncomingValueForBlock(PredPredBB));
1533 return nullptr;
1536 // If we have a CmpInst, try to fold it for each incoming edge into PredBB.
1537 if (CmpInst *CondCmp = dyn_cast<CmpInst>(V)) {
1538 if (CondCmp->getParent() == BB) {
1539 Constant *Op0 =
1540 evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(0));
1541 Constant *Op1 =
1542 evaluateOnPredecessorEdge(BB, PredPredBB, CondCmp->getOperand(1));
1543 if (Op0 && Op1) {
1544 return ConstantExpr::getCompare(CondCmp->getPredicate(), Op0, Op1);
1547 return nullptr;
1550 return nullptr;
1553 bool JumpThreadingPass::processThreadableEdges(Value *Cond, BasicBlock *BB,
1554 ConstantPreference Preference,
1555 Instruction *CxtI) {
1556 // If threading this would thread across a loop header, don't even try to
1557 // thread the edge.
1558 if (LoopHeaders.count(BB))
1559 return false;
1561 PredValueInfoTy PredValues;
1562 if (!computeValueKnownInPredecessors(Cond, BB, PredValues, Preference,
1563 CxtI)) {
1564 // We don't have known values in predecessors. See if we can thread through
1565 // BB and its sole predecessor.
1566 return maybethreadThroughTwoBasicBlocks(BB, Cond);
1569 assert(!PredValues.empty() &&
1570 "computeValueKnownInPredecessors returned true with no values");
1572 LLVM_DEBUG(dbgs() << "IN BB: " << *BB;
1573 for (const auto &PredValue : PredValues) {
1574 dbgs() << " BB '" << BB->getName()
1575 << "': FOUND condition = " << *PredValue.first
1576 << " for pred '" << PredValue.second->getName() << "'.\n";
1579 // Decide what we want to thread through. Convert our list of known values to
1580 // a list of known destinations for each pred. This also discards duplicate
1581 // predecessors and keeps track of the undefined inputs (which are represented
1582 // as a null dest in the PredToDestList).
1583 SmallPtrSet<BasicBlock*, 16> SeenPreds;
1584 SmallVector<std::pair<BasicBlock*, BasicBlock*>, 16> PredToDestList;
1586 BasicBlock *OnlyDest = nullptr;
1587 BasicBlock *MultipleDestSentinel = (BasicBlock*)(intptr_t)~0ULL;
1588 Constant *OnlyVal = nullptr;
1589 Constant *MultipleVal = (Constant *)(intptr_t)~0ULL;
1591 for (const auto &PredValue : PredValues) {
1592 BasicBlock *Pred = PredValue.second;
1593 if (!SeenPreds.insert(Pred).second)
1594 continue; // Duplicate predecessor entry.
1596 Constant *Val = PredValue.first;
1598 BasicBlock *DestBB;
1599 if (isa<UndefValue>(Val))
1600 DestBB = nullptr;
1601 else if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
1602 assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1603 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
1604 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1605 assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1606 DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
1607 } else {
1608 assert(isa<IndirectBrInst>(BB->getTerminator())
1609 && "Unexpected terminator");
1610 assert(isa<BlockAddress>(Val) && "Expecting a constant blockaddress");
1611 DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1614 // If we have exactly one destination, remember it for efficiency below.
1615 if (PredToDestList.empty()) {
1616 OnlyDest = DestBB;
1617 OnlyVal = Val;
1618 } else {
1619 if (OnlyDest != DestBB)
1620 OnlyDest = MultipleDestSentinel;
1621 // It possible we have same destination, but different value, e.g. default
1622 // case in switchinst.
1623 if (Val != OnlyVal)
1624 OnlyVal = MultipleVal;
1627 // If the predecessor ends with an indirect goto, we can't change its
1628 // destination.
1629 if (isa<IndirectBrInst>(Pred->getTerminator()))
1630 continue;
1632 PredToDestList.emplace_back(Pred, DestBB);
1635 // If all edges were unthreadable, we fail.
1636 if (PredToDestList.empty())
1637 return false;
1639 // If all the predecessors go to a single known successor, we want to fold,
1640 // not thread. By doing so, we do not need to duplicate the current block and
1641 // also miss potential opportunities in case we dont/cant duplicate.
1642 if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1643 if (BB->hasNPredecessors(PredToDestList.size())) {
1644 bool SeenFirstBranchToOnlyDest = false;
1645 std::vector <DominatorTree::UpdateType> Updates;
1646 Updates.reserve(BB->getTerminator()->getNumSuccessors() - 1);
1647 for (BasicBlock *SuccBB : successors(BB)) {
1648 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
1649 SeenFirstBranchToOnlyDest = true; // Don't modify the first branch.
1650 } else {
1651 SuccBB->removePredecessor(BB, true); // This is unreachable successor.
1652 Updates.push_back({DominatorTree::Delete, BB, SuccBB});
1656 // Finally update the terminator.
1657 Instruction *Term = BB->getTerminator();
1658 BranchInst::Create(OnlyDest, Term);
1659 ++NumFolds;
1660 Term->eraseFromParent();
1661 DTU->applyUpdatesPermissive(Updates);
1662 if (auto *BPI = getBPI())
1663 BPI->eraseBlock(BB);
1665 // If the condition is now dead due to the removal of the old terminator,
1666 // erase it.
1667 if (auto *CondInst = dyn_cast<Instruction>(Cond)) {
1668 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
1669 CondInst->eraseFromParent();
1670 // We can safely replace *some* uses of the CondInst if it has
1671 // exactly one value as returned by LVI. RAUW is incorrect in the
1672 // presence of guards and assumes, that have the `Cond` as the use. This
1673 // is because we use the guards/assume to reason about the `Cond` value
1674 // at the end of block, but RAUW unconditionally replaces all uses
1675 // including the guards/assumes themselves and the uses before the
1676 // guard/assume.
1677 else if (OnlyVal && OnlyVal != MultipleVal)
1678 replaceFoldableUses(CondInst, OnlyVal, BB);
1680 return true;
1684 // Determine which is the most common successor. If we have many inputs and
1685 // this block is a switch, we want to start by threading the batch that goes
1686 // to the most popular destination first. If we only know about one
1687 // threadable destination (the common case) we can avoid this.
1688 BasicBlock *MostPopularDest = OnlyDest;
1690 if (MostPopularDest == MultipleDestSentinel) {
1691 // Remove any loop headers from the Dest list, threadEdge conservatively
1692 // won't process them, but we might have other destination that are eligible
1693 // and we still want to process.
1694 erase_if(PredToDestList,
1695 [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1696 return LoopHeaders.contains(PredToDest.second);
1699 if (PredToDestList.empty())
1700 return false;
1702 MostPopularDest = findMostPopularDest(BB, PredToDestList);
1705 // Now that we know what the most popular destination is, factor all
1706 // predecessors that will jump to it into a single predecessor.
1707 SmallVector<BasicBlock*, 16> PredsToFactor;
1708 for (const auto &PredToDest : PredToDestList)
1709 if (PredToDest.second == MostPopularDest) {
1710 BasicBlock *Pred = PredToDest.first;
1712 // This predecessor may be a switch or something else that has multiple
1713 // edges to the block. Factor each of these edges by listing them
1714 // according to # occurrences in PredsToFactor.
1715 for (BasicBlock *Succ : successors(Pred))
1716 if (Succ == BB)
1717 PredsToFactor.push_back(Pred);
1720 // If the threadable edges are branching on an undefined value, we get to pick
1721 // the destination that these predecessors should get to.
1722 if (!MostPopularDest)
1723 MostPopularDest = BB->getTerminator()->
1724 getSuccessor(getBestDestForJumpOnUndef(BB));
1726 // Ok, try to thread it!
1727 return tryThreadEdge(BB, PredsToFactor, MostPopularDest);
1730 /// processBranchOnPHI - We have an otherwise unthreadable conditional branch on
1731 /// a PHI node (or freeze PHI) in the current block. See if there are any
1732 /// simplifications we can do based on inputs to the phi node.
1733 bool JumpThreadingPass::processBranchOnPHI(PHINode *PN) {
1734 BasicBlock *BB = PN->getParent();
1736 // TODO: We could make use of this to do it once for blocks with common PHI
1737 // values.
1738 SmallVector<BasicBlock*, 1> PredBBs;
1739 PredBBs.resize(1);
1741 // If any of the predecessor blocks end in an unconditional branch, we can
1742 // *duplicate* the conditional branch into that block in order to further
1743 // encourage jump threading and to eliminate cases where we have branch on a
1744 // phi of an icmp (branch on icmp is much better).
1745 // This is still beneficial when a frozen phi is used as the branch condition
1746 // because it allows CodeGenPrepare to further canonicalize br(freeze(icmp))
1747 // to br(icmp(freeze ...)).
1748 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1749 BasicBlock *PredBB = PN->getIncomingBlock(i);
1750 if (BranchInst *PredBr = dyn_cast<BranchInst>(PredBB->getTerminator()))
1751 if (PredBr->isUnconditional()) {
1752 PredBBs[0] = PredBB;
1753 // Try to duplicate BB into PredBB.
1754 if (duplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1755 return true;
1759 return false;
1762 /// processBranchOnXOR - We have an otherwise unthreadable conditional branch on
1763 /// a xor instruction in the current block. See if there are any
1764 /// simplifications we can do based on inputs to the xor.
1765 bool JumpThreadingPass::processBranchOnXOR(BinaryOperator *BO) {
1766 BasicBlock *BB = BO->getParent();
1768 // If either the LHS or RHS of the xor is a constant, don't do this
1769 // optimization.
1770 if (isa<ConstantInt>(BO->getOperand(0)) ||
1771 isa<ConstantInt>(BO->getOperand(1)))
1772 return false;
1774 // If the first instruction in BB isn't a phi, we won't be able to infer
1775 // anything special about any particular predecessor.
1776 if (!isa<PHINode>(BB->front()))
1777 return false;
1779 // If this BB is a landing pad, we won't be able to split the edge into it.
1780 if (BB->isEHPad())
1781 return false;
1783 // If we have a xor as the branch input to this block, and we know that the
1784 // LHS or RHS of the xor in any predecessor is true/false, then we can clone
1785 // the condition into the predecessor and fix that value to true, saving some
1786 // logical ops on that path and encouraging other paths to simplify.
1788 // This copies something like this:
1790 // BB:
1791 // %X = phi i1 [1], [%X']
1792 // %Y = icmp eq i32 %A, %B
1793 // %Z = xor i1 %X, %Y
1794 // br i1 %Z, ...
1796 // Into:
1797 // BB':
1798 // %Y = icmp ne i32 %A, %B
1799 // br i1 %Y, ...
1801 PredValueInfoTy XorOpValues;
1802 bool isLHS = true;
1803 if (!computeValueKnownInPredecessors(BO->getOperand(0), BB, XorOpValues,
1804 WantInteger, BO)) {
1805 assert(XorOpValues.empty());
1806 if (!computeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
1807 WantInteger, BO))
1808 return false;
1809 isLHS = false;
1812 assert(!XorOpValues.empty() &&
1813 "computeValueKnownInPredecessors returned true with no values");
1815 // Scan the information to see which is most popular: true or false. The
1816 // predecessors can be of the set true, false, or undef.
1817 unsigned NumTrue = 0, NumFalse = 0;
1818 for (const auto &XorOpValue : XorOpValues) {
1819 if (isa<UndefValue>(XorOpValue.first))
1820 // Ignore undefs for the count.
1821 continue;
1822 if (cast<ConstantInt>(XorOpValue.first)->isZero())
1823 ++NumFalse;
1824 else
1825 ++NumTrue;
1828 // Determine which value to split on, true, false, or undef if neither.
1829 ConstantInt *SplitVal = nullptr;
1830 if (NumTrue > NumFalse)
1831 SplitVal = ConstantInt::getTrue(BB->getContext());
1832 else if (NumTrue != 0 || NumFalse != 0)
1833 SplitVal = ConstantInt::getFalse(BB->getContext());
1835 // Collect all of the blocks that this can be folded into so that we can
1836 // factor this once and clone it once.
1837 SmallVector<BasicBlock*, 8> BlocksToFoldInto;
1838 for (const auto &XorOpValue : XorOpValues) {
1839 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1840 continue;
1842 BlocksToFoldInto.push_back(XorOpValue.second);
1845 // If we inferred a value for all of the predecessors, then duplication won't
1846 // help us. However, we can just replace the LHS or RHS with the constant.
1847 if (BlocksToFoldInto.size() ==
1848 cast<PHINode>(BB->front()).getNumIncomingValues()) {
1849 if (!SplitVal) {
1850 // If all preds provide undef, just nuke the xor, because it is undef too.
1851 BO->replaceAllUsesWith(UndefValue::get(BO->getType()));
1852 BO->eraseFromParent();
1853 } else if (SplitVal->isZero() && BO != BO->getOperand(isLHS)) {
1854 // If all preds provide 0, replace the xor with the other input.
1855 BO->replaceAllUsesWith(BO->getOperand(isLHS));
1856 BO->eraseFromParent();
1857 } else {
1858 // If all preds provide 1, set the computed value to 1.
1859 BO->setOperand(!isLHS, SplitVal);
1862 return true;
1865 // If any of predecessors end with an indirect goto, we can't change its
1866 // destination.
1867 if (any_of(BlocksToFoldInto, [](BasicBlock *Pred) {
1868 return isa<IndirectBrInst>(Pred->getTerminator());
1870 return false;
1872 // Try to duplicate BB into PredBB.
1873 return duplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1876 /// addPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new
1877 /// predecessor to the PHIBB block. If it has PHI nodes, add entries for
1878 /// NewPred using the entries from OldPred (suitably mapped).
1879 static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB,
1880 BasicBlock *OldPred,
1881 BasicBlock *NewPred,
1882 DenseMap<Instruction*, Value*> &ValueMap) {
1883 for (PHINode &PN : PHIBB->phis()) {
1884 // Ok, we have a PHI node. Figure out what the incoming value was for the
1885 // DestBlock.
1886 Value *IV = PN.getIncomingValueForBlock(OldPred);
1888 // Remap the value if necessary.
1889 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1890 DenseMap<Instruction*, Value*>::iterator I = ValueMap.find(Inst);
1891 if (I != ValueMap.end())
1892 IV = I->second;
1895 PN.addIncoming(IV, NewPred);
1899 /// Merge basic block BB into its sole predecessor if possible.
1900 bool JumpThreadingPass::maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB) {
1901 BasicBlock *SinglePred = BB->getSinglePredecessor();
1902 if (!SinglePred)
1903 return false;
1905 const Instruction *TI = SinglePred->getTerminator();
1906 if (TI->isSpecialTerminator() || TI->getNumSuccessors() != 1 ||
1907 SinglePred == BB || hasAddressTakenAndUsed(BB))
1908 return false;
1910 // If SinglePred was a loop header, BB becomes one.
1911 if (LoopHeaders.erase(SinglePred))
1912 LoopHeaders.insert(BB);
1914 LVI->eraseBlock(SinglePred);
1915 MergeBasicBlockIntoOnlyPred(BB, DTU.get());
1917 // Now that BB is merged into SinglePred (i.e. SinglePred code followed by
1918 // BB code within one basic block `BB`), we need to invalidate the LVI
1919 // information associated with BB, because the LVI information need not be
1920 // true for all of BB after the merge. For example,
1921 // Before the merge, LVI info and code is as follows:
1922 // SinglePred: <LVI info1 for %p val>
1923 // %y = use of %p
1924 // call @exit() // need not transfer execution to successor.
1925 // assume(%p) // from this point on %p is true
1926 // br label %BB
1927 // BB: <LVI info2 for %p val, i.e. %p is true>
1928 // %x = use of %p
1929 // br label exit
1931 // Note that this LVI info for blocks BB and SinglPred is correct for %p
1932 // (info2 and info1 respectively). After the merge and the deletion of the
1933 // LVI info1 for SinglePred. We have the following code:
1934 // BB: <LVI info2 for %p val>
1935 // %y = use of %p
1936 // call @exit()
1937 // assume(%p)
1938 // %x = use of %p <-- LVI info2 is correct from here onwards.
1939 // br label exit
1940 // LVI info2 for BB is incorrect at the beginning of BB.
1942 // Invalidate LVI information for BB if the LVI is not provably true for
1943 // all of BB.
1944 if (!isGuaranteedToTransferExecutionToSuccessor(BB))
1945 LVI->eraseBlock(BB);
1946 return true;
1949 /// Update the SSA form. NewBB contains instructions that are copied from BB.
1950 /// ValueMapping maps old values in BB to new ones in NewBB.
1951 void JumpThreadingPass::updateSSA(
1952 BasicBlock *BB, BasicBlock *NewBB,
1953 DenseMap<Instruction *, Value *> &ValueMapping) {
1954 // If there were values defined in BB that are used outside the block, then we
1955 // now have to update all uses of the value to use either the original value,
1956 // the cloned value, or some PHI derived value. This can require arbitrary
1957 // PHI insertion, of which we are prepared to do, clean these up now.
1958 SSAUpdater SSAUpdate;
1959 SmallVector<Use *, 16> UsesToRename;
1960 SmallVector<DbgValueInst *, 4> DbgValues;
1961 SmallVector<DPValue *, 4> DPValues;
1963 for (Instruction &I : *BB) {
1964 // Scan all uses of this instruction to see if it is used outside of its
1965 // block, and if so, record them in UsesToRename.
1966 for (Use &U : I.uses()) {
1967 Instruction *User = cast<Instruction>(U.getUser());
1968 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1969 if (UserPN->getIncomingBlock(U) == BB)
1970 continue;
1971 } else if (User->getParent() == BB)
1972 continue;
1974 UsesToRename.push_back(&U);
1977 // Find debug values outside of the block
1978 findDbgValues(DbgValues, &I, &DPValues);
1979 llvm::erase_if(DbgValues, [&](const DbgValueInst *DbgVal) {
1980 return DbgVal->getParent() == BB;
1982 llvm::erase_if(DPValues, [&](const DPValue *DPVal) {
1983 return DPVal->getParent() == BB;
1986 // If there are no uses outside the block, we're done with this instruction.
1987 if (UsesToRename.empty() && DbgValues.empty() && DPValues.empty())
1988 continue;
1989 LLVM_DEBUG(dbgs() << "JT: Renaming non-local uses of: " << I << "\n");
1991 // We found a use of I outside of BB. Rename all uses of I that are outside
1992 // its block to be uses of the appropriate PHI node etc. See ValuesInBlocks
1993 // with the two values we know.
1994 SSAUpdate.Initialize(I.getType(), I.getName());
1995 SSAUpdate.AddAvailableValue(BB, &I);
1996 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
1998 while (!UsesToRename.empty())
1999 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
2000 if (!DbgValues.empty() || !DPValues.empty()) {
2001 SSAUpdate.UpdateDebugValues(&I, DbgValues);
2002 SSAUpdate.UpdateDebugValues(&I, DPValues);
2003 DbgValues.clear();
2004 DPValues.clear();
2007 LLVM_DEBUG(dbgs() << "\n");
2011 /// Clone instructions in range [BI, BE) to NewBB. For PHI nodes, we only clone
2012 /// arguments that come from PredBB. Return the map from the variables in the
2013 /// source basic block to the variables in the newly created basic block.
2014 DenseMap<Instruction *, Value *>
2015 JumpThreadingPass::cloneInstructions(BasicBlock::iterator BI,
2016 BasicBlock::iterator BE, BasicBlock *NewBB,
2017 BasicBlock *PredBB) {
2018 // We are going to have to map operands from the source basic block to the new
2019 // copy of the block 'NewBB'. If there are PHI nodes in the source basic
2020 // block, evaluate them to account for entry from PredBB.
2021 DenseMap<Instruction *, Value *> ValueMapping;
2023 // Retargets llvm.dbg.value to any renamed variables.
2024 auto RetargetDbgValueIfPossible = [&](Instruction *NewInst) -> bool {
2025 auto DbgInstruction = dyn_cast<DbgValueInst>(NewInst);
2026 if (!DbgInstruction)
2027 return false;
2029 SmallSet<std::pair<Value *, Value *>, 16> OperandsToRemap;
2030 for (auto DbgOperand : DbgInstruction->location_ops()) {
2031 auto DbgOperandInstruction = dyn_cast<Instruction>(DbgOperand);
2032 if (!DbgOperandInstruction)
2033 continue;
2035 auto I = ValueMapping.find(DbgOperandInstruction);
2036 if (I != ValueMapping.end()) {
2037 OperandsToRemap.insert(
2038 std::pair<Value *, Value *>(DbgOperand, I->second));
2042 for (auto &[OldOp, MappedOp] : OperandsToRemap)
2043 DbgInstruction->replaceVariableLocationOp(OldOp, MappedOp);
2044 return true;
2047 // Duplicate implementation of the above dbg.value code, using DPValues
2048 // instead.
2049 auto RetargetDPValueIfPossible = [&](DPValue *DPV) {
2050 SmallSet<std::pair<Value *, Value *>, 16> OperandsToRemap;
2051 for (auto *Op : DPV->location_ops()) {
2052 Instruction *OpInst = dyn_cast<Instruction>(Op);
2053 if (!OpInst)
2054 continue;
2056 auto I = ValueMapping.find(OpInst);
2057 if (I != ValueMapping.end())
2058 OperandsToRemap.insert({OpInst, I->second});
2061 for (auto &[OldOp, MappedOp] : OperandsToRemap)
2062 DPV->replaceVariableLocationOp(OldOp, MappedOp);
2065 BasicBlock *RangeBB = BI->getParent();
2067 // Clone the phi nodes of the source basic block into NewBB. The resulting
2068 // phi nodes are trivial since NewBB only has one predecessor, but SSAUpdater
2069 // might need to rewrite the operand of the cloned phi.
2070 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2071 PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB);
2072 NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB);
2073 ValueMapping[PN] = NewPN;
2076 // Clone noalias scope declarations in the threaded block. When threading a
2077 // loop exit, we would otherwise end up with two idential scope declarations
2078 // visible at the same time.
2079 SmallVector<MDNode *> NoAliasScopes;
2080 DenseMap<MDNode *, MDNode *> ClonedScopes;
2081 LLVMContext &Context = PredBB->getContext();
2082 identifyNoAliasScopesToClone(BI, BE, NoAliasScopes);
2083 cloneNoAliasScopes(NoAliasScopes, ClonedScopes, "thread", Context);
2085 auto CloneAndRemapDbgInfo = [&](Instruction *NewInst, Instruction *From) {
2086 auto DPVRange = NewInst->cloneDebugInfoFrom(From);
2087 for (DPValue &DPV : DPVRange)
2088 RetargetDPValueIfPossible(&DPV);
2091 // Clone the non-phi instructions of the source basic block into NewBB,
2092 // keeping track of the mapping and using it to remap operands in the cloned
2093 // instructions.
2094 for (; BI != BE; ++BI) {
2095 Instruction *New = BI->clone();
2096 New->setName(BI->getName());
2097 New->insertInto(NewBB, NewBB->end());
2098 ValueMapping[&*BI] = New;
2099 adaptNoAliasScopes(New, ClonedScopes, Context);
2101 CloneAndRemapDbgInfo(New, &*BI);
2103 if (RetargetDbgValueIfPossible(New))
2104 continue;
2106 // Remap operands to patch up intra-block references.
2107 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2108 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2109 DenseMap<Instruction *, Value *>::iterator I = ValueMapping.find(Inst);
2110 if (I != ValueMapping.end())
2111 New->setOperand(i, I->second);
2115 // There may be DPValues on the terminator, clone directly from marker
2116 // to marker as there isn't an instruction there.
2117 if (BE != RangeBB->end() && BE->hasDbgValues()) {
2118 // Dump them at the end.
2119 DPMarker *Marker = RangeBB->getMarker(BE);
2120 DPMarker *EndMarker = NewBB->createMarker(NewBB->end());
2121 auto DPVRange = EndMarker->cloneDebugInfoFrom(Marker, std::nullopt);
2122 for (DPValue &DPV : DPVRange)
2123 RetargetDPValueIfPossible(&DPV);
2126 return ValueMapping;
2129 /// Attempt to thread through two successive basic blocks.
2130 bool JumpThreadingPass::maybethreadThroughTwoBasicBlocks(BasicBlock *BB,
2131 Value *Cond) {
2132 // Consider:
2134 // PredBB:
2135 // %var = phi i32* [ null, %bb1 ], [ @a, %bb2 ]
2136 // %tobool = icmp eq i32 %cond, 0
2137 // br i1 %tobool, label %BB, label ...
2139 // BB:
2140 // %cmp = icmp eq i32* %var, null
2141 // br i1 %cmp, label ..., label ...
2143 // We don't know the value of %var at BB even if we know which incoming edge
2144 // we take to BB. However, once we duplicate PredBB for each of its incoming
2145 // edges (say, PredBB1 and PredBB2), we know the value of %var in each copy of
2146 // PredBB. Then we can thread edges PredBB1->BB and PredBB2->BB through BB.
2148 // Require that BB end with a Branch for simplicity.
2149 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2150 if (!CondBr)
2151 return false;
2153 // BB must have exactly one predecessor.
2154 BasicBlock *PredBB = BB->getSinglePredecessor();
2155 if (!PredBB)
2156 return false;
2158 // Require that PredBB end with a conditional Branch. If PredBB ends with an
2159 // unconditional branch, we should be merging PredBB and BB instead. For
2160 // simplicity, we don't deal with a switch.
2161 BranchInst *PredBBBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2162 if (!PredBBBranch || PredBBBranch->isUnconditional())
2163 return false;
2165 // If PredBB has exactly one incoming edge, we don't gain anything by copying
2166 // PredBB.
2167 if (PredBB->getSinglePredecessor())
2168 return false;
2170 // Don't thread through PredBB if it contains a successor edge to itself, in
2171 // which case we would infinite loop. Suppose we are threading an edge from
2172 // PredPredBB through PredBB and BB to SuccBB with PredBB containing a
2173 // successor edge to itself. If we allowed jump threading in this case, we
2174 // could duplicate PredBB and BB as, say, PredBB.thread and BB.thread. Since
2175 // PredBB.thread has a successor edge to PredBB, we would immediately come up
2176 // with another jump threading opportunity from PredBB.thread through PredBB
2177 // and BB to SuccBB. This jump threading would repeatedly occur. That is, we
2178 // would keep peeling one iteration from PredBB.
2179 if (llvm::is_contained(successors(PredBB), PredBB))
2180 return false;
2182 // Don't thread across a loop header.
2183 if (LoopHeaders.count(PredBB))
2184 return false;
2186 // Avoid complication with duplicating EH pads.
2187 if (PredBB->isEHPad())
2188 return false;
2190 // Find a predecessor that we can thread. For simplicity, we only consider a
2191 // successor edge out of BB to which we thread exactly one incoming edge into
2192 // PredBB.
2193 unsigned ZeroCount = 0;
2194 unsigned OneCount = 0;
2195 BasicBlock *ZeroPred = nullptr;
2196 BasicBlock *OnePred = nullptr;
2197 for (BasicBlock *P : predecessors(PredBB)) {
2198 // If PredPred ends with IndirectBrInst, we can't handle it.
2199 if (isa<IndirectBrInst>(P->getTerminator()))
2200 continue;
2201 if (ConstantInt *CI = dyn_cast_or_null<ConstantInt>(
2202 evaluateOnPredecessorEdge(BB, P, Cond))) {
2203 if (CI->isZero()) {
2204 ZeroCount++;
2205 ZeroPred = P;
2206 } else if (CI->isOne()) {
2207 OneCount++;
2208 OnePred = P;
2213 // Disregard complicated cases where we have to thread multiple edges.
2214 BasicBlock *PredPredBB;
2215 if (ZeroCount == 1) {
2216 PredPredBB = ZeroPred;
2217 } else if (OneCount == 1) {
2218 PredPredBB = OnePred;
2219 } else {
2220 return false;
2223 BasicBlock *SuccBB = CondBr->getSuccessor(PredPredBB == ZeroPred);
2225 // If threading to the same block as we come from, we would infinite loop.
2226 if (SuccBB == BB) {
2227 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
2228 << "' - would thread to self!\n");
2229 return false;
2232 // If threading this would thread across a loop header, don't thread the edge.
2233 // See the comments above findLoopHeaders for justifications and caveats.
2234 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2235 LLVM_DEBUG({
2236 bool BBIsHeader = LoopHeaders.count(BB);
2237 bool SuccIsHeader = LoopHeaders.count(SuccBB);
2238 dbgs() << " Not threading across "
2239 << (BBIsHeader ? "loop header BB '" : "block BB '")
2240 << BB->getName() << "' to dest "
2241 << (SuccIsHeader ? "loop header BB '" : "block BB '")
2242 << SuccBB->getName()
2243 << "' - it might create an irreducible loop!\n";
2245 return false;
2248 // Compute the cost of duplicating BB and PredBB.
2249 unsigned BBCost = getJumpThreadDuplicationCost(
2250 TTI, BB, BB->getTerminator(), BBDupThreshold);
2251 unsigned PredBBCost = getJumpThreadDuplicationCost(
2252 TTI, PredBB, PredBB->getTerminator(), BBDupThreshold);
2254 // Give up if costs are too high. We need to check BBCost and PredBBCost
2255 // individually before checking their sum because getJumpThreadDuplicationCost
2256 // return (unsigned)~0 for those basic blocks that cannot be duplicated.
2257 if (BBCost > BBDupThreshold || PredBBCost > BBDupThreshold ||
2258 BBCost + PredBBCost > BBDupThreshold) {
2259 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()
2260 << "' - Cost is too high: " << PredBBCost
2261 << " for PredBB, " << BBCost << "for BB\n");
2262 return false;
2265 // Now we are ready to duplicate PredBB.
2266 threadThroughTwoBasicBlocks(PredPredBB, PredBB, BB, SuccBB);
2267 return true;
2270 void JumpThreadingPass::threadThroughTwoBasicBlocks(BasicBlock *PredPredBB,
2271 BasicBlock *PredBB,
2272 BasicBlock *BB,
2273 BasicBlock *SuccBB) {
2274 LLVM_DEBUG(dbgs() << " Threading through '" << PredBB->getName() << "' and '"
2275 << BB->getName() << "'\n");
2277 // Build BPI/BFI before any changes are made to IR.
2278 bool HasProfile = doesBlockHaveProfileData(BB);
2279 auto *BFI = getOrCreateBFI(HasProfile);
2280 auto *BPI = getOrCreateBPI(BFI != nullptr);
2282 BranchInst *CondBr = cast<BranchInst>(BB->getTerminator());
2283 BranchInst *PredBBBranch = cast<BranchInst>(PredBB->getTerminator());
2285 BasicBlock *NewBB =
2286 BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread",
2287 PredBB->getParent(), PredBB);
2288 NewBB->moveAfter(PredBB);
2290 // Set the block frequency of NewBB.
2291 if (BFI) {
2292 assert(BPI && "It's expected BPI to exist along with BFI");
2293 auto NewBBFreq = BFI->getBlockFreq(PredPredBB) *
2294 BPI->getEdgeProbability(PredPredBB, PredBB);
2295 BFI->setBlockFreq(NewBB, NewBBFreq);
2298 // We are going to have to map operands from the original BB block to the new
2299 // copy of the block 'NewBB'. If there are PHI nodes in PredBB, evaluate them
2300 // to account for entry from PredPredBB.
2301 DenseMap<Instruction *, Value *> ValueMapping =
2302 cloneInstructions(PredBB->begin(), PredBB->end(), NewBB, PredPredBB);
2304 // Copy the edge probabilities from PredBB to NewBB.
2305 if (BPI)
2306 BPI->copyEdgeProbabilities(PredBB, NewBB);
2308 // Update the terminator of PredPredBB to jump to NewBB instead of PredBB.
2309 // This eliminates predecessors from PredPredBB, which requires us to simplify
2310 // any PHI nodes in PredBB.
2311 Instruction *PredPredTerm = PredPredBB->getTerminator();
2312 for (unsigned i = 0, e = PredPredTerm->getNumSuccessors(); i != e; ++i)
2313 if (PredPredTerm->getSuccessor(i) == PredBB) {
2314 PredBB->removePredecessor(PredPredBB, true);
2315 PredPredTerm->setSuccessor(i, NewBB);
2318 addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB,
2319 ValueMapping);
2320 addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB,
2321 ValueMapping);
2323 DTU->applyUpdatesPermissive(
2324 {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)},
2325 {DominatorTree::Insert, NewBB, CondBr->getSuccessor(1)},
2326 {DominatorTree::Insert, PredPredBB, NewBB},
2327 {DominatorTree::Delete, PredPredBB, PredBB}});
2329 updateSSA(PredBB, NewBB, ValueMapping);
2331 // Clean up things like PHI nodes with single operands, dead instructions,
2332 // etc.
2333 SimplifyInstructionsInBlock(NewBB, TLI);
2334 SimplifyInstructionsInBlock(PredBB, TLI);
2336 SmallVector<BasicBlock *, 1> PredsToFactor;
2337 PredsToFactor.push_back(NewBB);
2338 threadEdge(BB, PredsToFactor, SuccBB);
2341 /// tryThreadEdge - Thread an edge if it's safe and profitable to do so.
2342 bool JumpThreadingPass::tryThreadEdge(
2343 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs,
2344 BasicBlock *SuccBB) {
2345 // If threading to the same block as we come from, we would infinite loop.
2346 if (SuccBB == BB) {
2347 LLVM_DEBUG(dbgs() << " Not threading across BB '" << BB->getName()
2348 << "' - would thread to self!\n");
2349 return false;
2352 // If threading this would thread across a loop header, don't thread the edge.
2353 // See the comments above findLoopHeaders for justifications and caveats.
2354 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
2355 LLVM_DEBUG({
2356 bool BBIsHeader = LoopHeaders.count(BB);
2357 bool SuccIsHeader = LoopHeaders.count(SuccBB);
2358 dbgs() << " Not threading across "
2359 << (BBIsHeader ? "loop header BB '" : "block BB '") << BB->getName()
2360 << "' to dest " << (SuccIsHeader ? "loop header BB '" : "block BB '")
2361 << SuccBB->getName() << "' - it might create an irreducible loop!\n";
2363 return false;
2366 unsigned JumpThreadCost = getJumpThreadDuplicationCost(
2367 TTI, BB, BB->getTerminator(), BBDupThreshold);
2368 if (JumpThreadCost > BBDupThreshold) {
2369 LLVM_DEBUG(dbgs() << " Not threading BB '" << BB->getName()
2370 << "' - Cost is too high: " << JumpThreadCost << "\n");
2371 return false;
2374 threadEdge(BB, PredBBs, SuccBB);
2375 return true;
2378 /// threadEdge - We have decided that it is safe and profitable to factor the
2379 /// blocks in PredBBs to one predecessor, then thread an edge from it to SuccBB
2380 /// across BB. Transform the IR to reflect this change.
2381 void JumpThreadingPass::threadEdge(BasicBlock *BB,
2382 const SmallVectorImpl<BasicBlock *> &PredBBs,
2383 BasicBlock *SuccBB) {
2384 assert(SuccBB != BB && "Don't create an infinite loop");
2386 assert(!LoopHeaders.count(BB) && !LoopHeaders.count(SuccBB) &&
2387 "Don't thread across loop headers");
2389 // Build BPI/BFI before any changes are made to IR.
2390 bool HasProfile = doesBlockHaveProfileData(BB);
2391 auto *BFI = getOrCreateBFI(HasProfile);
2392 auto *BPI = getOrCreateBPI(BFI != nullptr);
2394 // And finally, do it! Start by factoring the predecessors if needed.
2395 BasicBlock *PredBB;
2396 if (PredBBs.size() == 1)
2397 PredBB = PredBBs[0];
2398 else {
2399 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()
2400 << " common predecessors.\n");
2401 PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
2404 // And finally, do it!
2405 LLVM_DEBUG(dbgs() << " Threading edge from '" << PredBB->getName()
2406 << "' to '" << SuccBB->getName()
2407 << ", across block:\n " << *BB << "\n");
2409 LVI->threadEdge(PredBB, BB, SuccBB);
2411 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(),
2412 BB->getName()+".thread",
2413 BB->getParent(), BB);
2414 NewBB->moveAfter(PredBB);
2416 // Set the block frequency of NewBB.
2417 if (BFI) {
2418 assert(BPI && "It's expected BPI to exist along with BFI");
2419 auto NewBBFreq =
2420 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
2421 BFI->setBlockFreq(NewBB, NewBBFreq);
2424 // Copy all the instructions from BB to NewBB except the terminator.
2425 DenseMap<Instruction *, Value *> ValueMapping =
2426 cloneInstructions(BB->begin(), std::prev(BB->end()), NewBB, PredBB);
2428 // We didn't copy the terminator from BB over to NewBB, because there is now
2429 // an unconditional jump to SuccBB. Insert the unconditional jump.
2430 BranchInst *NewBI = BranchInst::Create(SuccBB, NewBB);
2431 NewBI->setDebugLoc(BB->getTerminator()->getDebugLoc());
2433 // Check to see if SuccBB has PHI nodes. If so, we need to add entries to the
2434 // PHI nodes for NewBB now.
2435 addPHINodeEntriesForMappedBlock(SuccBB, BB, NewBB, ValueMapping);
2437 // Update the terminator of PredBB to jump to NewBB instead of BB. This
2438 // eliminates predecessors from BB, which requires us to simplify any PHI
2439 // nodes in BB.
2440 Instruction *PredTerm = PredBB->getTerminator();
2441 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i)
2442 if (PredTerm->getSuccessor(i) == BB) {
2443 BB->removePredecessor(PredBB, true);
2444 PredTerm->setSuccessor(i, NewBB);
2447 // Enqueue required DT updates.
2448 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB},
2449 {DominatorTree::Insert, PredBB, NewBB},
2450 {DominatorTree::Delete, PredBB, BB}});
2452 updateSSA(BB, NewBB, ValueMapping);
2454 // At this point, the IR is fully up to date and consistent. Do a quick scan
2455 // over the new instructions and zap any that are constants or dead. This
2456 // frequently happens because of phi translation.
2457 SimplifyInstructionsInBlock(NewBB, TLI);
2459 // Update the edge weight from BB to SuccBB, which should be less than before.
2460 updateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB, BFI, BPI, HasProfile);
2462 // Threaded an edge!
2463 ++NumThreads;
2466 /// Create a new basic block that will be the predecessor of BB and successor of
2467 /// all blocks in Preds. When profile data is available, update the frequency of
2468 /// this new block.
2469 BasicBlock *JumpThreadingPass::splitBlockPreds(BasicBlock *BB,
2470 ArrayRef<BasicBlock *> Preds,
2471 const char *Suffix) {
2472 SmallVector<BasicBlock *, 2> NewBBs;
2474 // Collect the frequencies of all predecessors of BB, which will be used to
2475 // update the edge weight of the result of splitting predecessors.
2476 DenseMap<BasicBlock *, BlockFrequency> FreqMap;
2477 auto *BFI = getBFI();
2478 if (BFI) {
2479 auto *BPI = getOrCreateBPI(true);
2480 for (auto *Pred : Preds)
2481 FreqMap.insert(std::make_pair(
2482 Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
2485 // In the case when BB is a LandingPad block we create 2 new predecessors
2486 // instead of just one.
2487 if (BB->isLandingPad()) {
2488 std::string NewName = std::string(Suffix) + ".split-lp";
2489 SplitLandingPadPredecessors(BB, Preds, Suffix, NewName.c_str(), NewBBs);
2490 } else {
2491 NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix));
2494 std::vector<DominatorTree::UpdateType> Updates;
2495 Updates.reserve((2 * Preds.size()) + NewBBs.size());
2496 for (auto *NewBB : NewBBs) {
2497 BlockFrequency NewBBFreq(0);
2498 Updates.push_back({DominatorTree::Insert, NewBB, BB});
2499 for (auto *Pred : predecessors(NewBB)) {
2500 Updates.push_back({DominatorTree::Delete, Pred, BB});
2501 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
2502 if (BFI) // Update frequencies between Pred -> NewBB.
2503 NewBBFreq += FreqMap.lookup(Pred);
2505 if (BFI) // Apply the summed frequency to NewBB.
2506 BFI->setBlockFreq(NewBB, NewBBFreq);
2509 DTU->applyUpdatesPermissive(Updates);
2510 return NewBBs[0];
2513 bool JumpThreadingPass::doesBlockHaveProfileData(BasicBlock *BB) {
2514 const Instruction *TI = BB->getTerminator();
2515 if (!TI || TI->getNumSuccessors() < 2)
2516 return false;
2518 return hasValidBranchWeightMD(*TI);
2521 /// Update the block frequency of BB and branch weight and the metadata on the
2522 /// edge BB->SuccBB. This is done by scaling the weight of BB->SuccBB by 1 -
2523 /// Freq(PredBB->BB) / Freq(BB->SuccBB).
2524 void JumpThreadingPass::updateBlockFreqAndEdgeWeight(BasicBlock *PredBB,
2525 BasicBlock *BB,
2526 BasicBlock *NewBB,
2527 BasicBlock *SuccBB,
2528 BlockFrequencyInfo *BFI,
2529 BranchProbabilityInfo *BPI,
2530 bool HasProfile) {
2531 assert(((BFI && BPI) || (!BFI && !BFI)) &&
2532 "Both BFI & BPI should either be set or unset");
2534 if (!BFI) {
2535 assert(!HasProfile &&
2536 "It's expected to have BFI/BPI when profile info exists");
2537 return;
2540 // As the edge from PredBB to BB is deleted, we have to update the block
2541 // frequency of BB.
2542 auto BBOrigFreq = BFI->getBlockFreq(BB);
2543 auto NewBBFreq = BFI->getBlockFreq(NewBB);
2544 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
2545 auto BBNewFreq = BBOrigFreq - NewBBFreq;
2546 BFI->setBlockFreq(BB, BBNewFreq);
2548 // Collect updated outgoing edges' frequencies from BB and use them to update
2549 // edge probabilities.
2550 SmallVector<uint64_t, 4> BBSuccFreq;
2551 for (BasicBlock *Succ : successors(BB)) {
2552 auto SuccFreq = (Succ == SuccBB)
2553 ? BB2SuccBBFreq - NewBBFreq
2554 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
2555 BBSuccFreq.push_back(SuccFreq.getFrequency());
2558 uint64_t MaxBBSuccFreq =
2559 *std::max_element(BBSuccFreq.begin(), BBSuccFreq.end());
2561 SmallVector<BranchProbability, 4> BBSuccProbs;
2562 if (MaxBBSuccFreq == 0)
2563 BBSuccProbs.assign(BBSuccFreq.size(),
2564 {1, static_cast<unsigned>(BBSuccFreq.size())});
2565 else {
2566 for (uint64_t Freq : BBSuccFreq)
2567 BBSuccProbs.push_back(
2568 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
2569 // Normalize edge probabilities so that they sum up to one.
2570 BranchProbability::normalizeProbabilities(BBSuccProbs.begin(),
2571 BBSuccProbs.end());
2574 // Update edge probabilities in BPI.
2575 BPI->setEdgeProbability(BB, BBSuccProbs);
2577 // Update the profile metadata as well.
2579 // Don't do this if the profile of the transformed blocks was statically
2580 // estimated. (This could occur despite the function having an entry
2581 // frequency in completely cold parts of the CFG.)
2583 // In this case we don't want to suggest to subsequent passes that the
2584 // calculated weights are fully consistent. Consider this graph:
2586 // check_1
2587 // 50% / |
2588 // eq_1 | 50%
2589 // \ |
2590 // check_2
2591 // 50% / |
2592 // eq_2 | 50%
2593 // \ |
2594 // check_3
2595 // 50% / |
2596 // eq_3 | 50%
2597 // \ |
2599 // Assuming the blocks check_* all compare the same value against 1, 2 and 3,
2600 // the overall probabilities are inconsistent; the total probability that the
2601 // value is either 1, 2 or 3 is 150%.
2603 // As a consequence if we thread eq_1 -> check_2 to check_3, check_2->check_3
2604 // becomes 0%. This is even worse if the edge whose probability becomes 0% is
2605 // the loop exit edge. Then based solely on static estimation we would assume
2606 // the loop was extremely hot.
2608 // FIXME this locally as well so that BPI and BFI are consistent as well. We
2609 // shouldn't make edges extremely likely or unlikely based solely on static
2610 // estimation.
2611 if (BBSuccProbs.size() >= 2 && HasProfile) {
2612 SmallVector<uint32_t, 4> Weights;
2613 for (auto Prob : BBSuccProbs)
2614 Weights.push_back(Prob.getNumerator());
2616 auto TI = BB->getTerminator();
2617 setBranchWeights(*TI, Weights);
2621 /// duplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch
2622 /// to BB which contains an i1 PHI node and a conditional branch on that PHI.
2623 /// If we can duplicate the contents of BB up into PredBB do so now, this
2624 /// improves the odds that the branch will be on an analyzable instruction like
2625 /// a compare.
2626 bool JumpThreadingPass::duplicateCondBranchOnPHIIntoPred(
2627 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs) {
2628 assert(!PredBBs.empty() && "Can't handle an empty set");
2630 // If BB is a loop header, then duplicating this block outside the loop would
2631 // cause us to transform this into an irreducible loop, don't do this.
2632 // See the comments above findLoopHeaders for justifications and caveats.
2633 if (LoopHeaders.count(BB)) {
2634 LLVM_DEBUG(dbgs() << " Not duplicating loop header '" << BB->getName()
2635 << "' into predecessor block '" << PredBBs[0]->getName()
2636 << "' - it might create an irreducible loop!\n");
2637 return false;
2640 unsigned DuplicationCost = getJumpThreadDuplicationCost(
2641 TTI, BB, BB->getTerminator(), BBDupThreshold);
2642 if (DuplicationCost > BBDupThreshold) {
2643 LLVM_DEBUG(dbgs() << " Not duplicating BB '" << BB->getName()
2644 << "' - Cost is too high: " << DuplicationCost << "\n");
2645 return false;
2648 // And finally, do it! Start by factoring the predecessors if needed.
2649 std::vector<DominatorTree::UpdateType> Updates;
2650 BasicBlock *PredBB;
2651 if (PredBBs.size() == 1)
2652 PredBB = PredBBs[0];
2653 else {
2654 LLVM_DEBUG(dbgs() << " Factoring out " << PredBBs.size()
2655 << " common predecessors.\n");
2656 PredBB = splitBlockPreds(BB, PredBBs, ".thr_comm");
2658 Updates.push_back({DominatorTree::Delete, PredBB, BB});
2660 // Okay, we decided to do this! Clone all the instructions in BB onto the end
2661 // of PredBB.
2662 LLVM_DEBUG(dbgs() << " Duplicating block '" << BB->getName()
2663 << "' into end of '" << PredBB->getName()
2664 << "' to eliminate branch on phi. Cost: "
2665 << DuplicationCost << " block is:" << *BB << "\n");
2667 // Unless PredBB ends with an unconditional branch, split the edge so that we
2668 // can just clone the bits from BB into the end of the new PredBB.
2669 BranchInst *OldPredBranch = dyn_cast<BranchInst>(PredBB->getTerminator());
2671 if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
2672 BasicBlock *OldPredBB = PredBB;
2673 PredBB = SplitEdge(OldPredBB, BB);
2674 Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB});
2675 Updates.push_back({DominatorTree::Insert, PredBB, BB});
2676 Updates.push_back({DominatorTree::Delete, OldPredBB, BB});
2677 OldPredBranch = cast<BranchInst>(PredBB->getTerminator());
2680 // We are going to have to map operands from the original BB block into the
2681 // PredBB block. Evaluate PHI nodes in BB.
2682 DenseMap<Instruction*, Value*> ValueMapping;
2684 BasicBlock::iterator BI = BB->begin();
2685 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
2686 ValueMapping[PN] = PN->getIncomingValueForBlock(PredBB);
2687 // Clone the non-phi instructions of BB into PredBB, keeping track of the
2688 // mapping and using it to remap operands in the cloned instructions.
2689 for (; BI != BB->end(); ++BI) {
2690 Instruction *New = BI->clone();
2691 New->insertInto(PredBB, OldPredBranch->getIterator());
2693 // Remap operands to patch up intra-block references.
2694 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2695 if (Instruction *Inst = dyn_cast<Instruction>(New->getOperand(i))) {
2696 DenseMap<Instruction*, Value*>::iterator I = ValueMapping.find(Inst);
2697 if (I != ValueMapping.end())
2698 New->setOperand(i, I->second);
2701 // If this instruction can be simplified after the operands are updated,
2702 // just use the simplified value instead. This frequently happens due to
2703 // phi translation.
2704 if (Value *IV = simplifyInstruction(
2705 New,
2706 {BB->getModule()->getDataLayout(), TLI, nullptr, nullptr, New})) {
2707 ValueMapping[&*BI] = IV;
2708 if (!New->mayHaveSideEffects()) {
2709 New->eraseFromParent();
2710 New = nullptr;
2711 // Clone debug-info on the elided instruction to the destination
2712 // position.
2713 OldPredBranch->cloneDebugInfoFrom(&*BI, std::nullopt, true);
2715 } else {
2716 ValueMapping[&*BI] = New;
2718 if (New) {
2719 // Otherwise, insert the new instruction into the block.
2720 New->setName(BI->getName());
2721 // Clone across any debug-info attached to the old instruction.
2722 New->cloneDebugInfoFrom(&*BI);
2723 // Update Dominance from simplified New instruction operands.
2724 for (unsigned i = 0, e = New->getNumOperands(); i != e; ++i)
2725 if (BasicBlock *SuccBB = dyn_cast<BasicBlock>(New->getOperand(i)))
2726 Updates.push_back({DominatorTree::Insert, PredBB, SuccBB});
2730 // Check to see if the targets of the branch had PHI nodes. If so, we need to
2731 // add entries to the PHI nodes for branch from PredBB now.
2732 BranchInst *BBBranch = cast<BranchInst>(BB->getTerminator());
2733 addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
2734 ValueMapping);
2735 addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
2736 ValueMapping);
2738 updateSSA(BB, PredBB, ValueMapping);
2740 // PredBB no longer jumps to BB, remove entries in the PHI node for the edge
2741 // that we nuked.
2742 BB->removePredecessor(PredBB, true);
2744 // Remove the unconditional branch at the end of the PredBB block.
2745 OldPredBranch->eraseFromParent();
2746 if (auto *BPI = getBPI())
2747 BPI->copyEdgeProbabilities(BB, PredBB);
2748 DTU->applyUpdatesPermissive(Updates);
2750 ++NumDupes;
2751 return true;
2754 // Pred is a predecessor of BB with an unconditional branch to BB. SI is
2755 // a Select instruction in Pred. BB has other predecessors and SI is used in
2756 // a PHI node in BB. SI has no other use.
2757 // A new basic block, NewBB, is created and SI is converted to compare and
2758 // conditional branch. SI is erased from parent.
2759 void JumpThreadingPass::unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB,
2760 SelectInst *SI, PHINode *SIUse,
2761 unsigned Idx) {
2762 // Expand the select.
2764 // Pred --
2765 // | v
2766 // | NewBB
2767 // | |
2768 // |-----
2769 // v
2770 // BB
2771 BranchInst *PredTerm = cast<BranchInst>(Pred->getTerminator());
2772 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
2773 BB->getParent(), BB);
2774 // Move the unconditional branch to NewBB.
2775 PredTerm->removeFromParent();
2776 PredTerm->insertInto(NewBB, NewBB->end());
2777 // Create a conditional branch and update PHI nodes.
2778 auto *BI = BranchInst::Create(NewBB, BB, SI->getCondition(), Pred);
2779 BI->applyMergedLocation(PredTerm->getDebugLoc(), SI->getDebugLoc());
2780 BI->copyMetadata(*SI, {LLVMContext::MD_prof});
2781 SIUse->setIncomingValue(Idx, SI->getFalseValue());
2782 SIUse->addIncoming(SI->getTrueValue(), NewBB);
2784 uint64_t TrueWeight = 1;
2785 uint64_t FalseWeight = 1;
2786 // Copy probabilities from 'SI' to created conditional branch in 'Pred'.
2787 if (extractBranchWeights(*SI, TrueWeight, FalseWeight) &&
2788 (TrueWeight + FalseWeight) != 0) {
2789 SmallVector<BranchProbability, 2> BP;
2790 BP.emplace_back(BranchProbability::getBranchProbability(
2791 TrueWeight, TrueWeight + FalseWeight));
2792 BP.emplace_back(BranchProbability::getBranchProbability(
2793 FalseWeight, TrueWeight + FalseWeight));
2794 // Update BPI if exists.
2795 if (auto *BPI = getBPI())
2796 BPI->setEdgeProbability(Pred, BP);
2798 // Set the block frequency of NewBB.
2799 if (auto *BFI = getBFI()) {
2800 if ((TrueWeight + FalseWeight) == 0) {
2801 TrueWeight = 1;
2802 FalseWeight = 1;
2804 BranchProbability PredToNewBBProb = BranchProbability::getBranchProbability(
2805 TrueWeight, TrueWeight + FalseWeight);
2806 auto NewBBFreq = BFI->getBlockFreq(Pred) * PredToNewBBProb;
2807 BFI->setBlockFreq(NewBB, NewBBFreq);
2810 // The select is now dead.
2811 SI->eraseFromParent();
2812 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, BB},
2813 {DominatorTree::Insert, Pred, NewBB}});
2815 // Update any other PHI nodes in BB.
2816 for (BasicBlock::iterator BI = BB->begin();
2817 PHINode *Phi = dyn_cast<PHINode>(BI); ++BI)
2818 if (Phi != SIUse)
2819 Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
2822 bool JumpThreadingPass::tryToUnfoldSelect(SwitchInst *SI, BasicBlock *BB) {
2823 PHINode *CondPHI = dyn_cast<PHINode>(SI->getCondition());
2825 if (!CondPHI || CondPHI->getParent() != BB)
2826 return false;
2828 for (unsigned I = 0, E = CondPHI->getNumIncomingValues(); I != E; ++I) {
2829 BasicBlock *Pred = CondPHI->getIncomingBlock(I);
2830 SelectInst *PredSI = dyn_cast<SelectInst>(CondPHI->getIncomingValue(I));
2832 // The second and third condition can be potentially relaxed. Currently
2833 // the conditions help to simplify the code and allow us to reuse existing
2834 // code, developed for tryToUnfoldSelect(CmpInst *, BasicBlock *)
2835 if (!PredSI || PredSI->getParent() != Pred || !PredSI->hasOneUse())
2836 continue;
2838 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2839 if (!PredTerm || !PredTerm->isUnconditional())
2840 continue;
2842 unfoldSelectInstr(Pred, BB, PredSI, CondPHI, I);
2843 return true;
2845 return false;
2848 /// tryToUnfoldSelect - Look for blocks of the form
2849 /// bb1:
2850 /// %a = select
2851 /// br bb2
2853 /// bb2:
2854 /// %p = phi [%a, %bb1] ...
2855 /// %c = icmp %p
2856 /// br i1 %c
2858 /// And expand the select into a branch structure if one of its arms allows %c
2859 /// to be folded. This later enables threading from bb1 over bb2.
2860 bool JumpThreadingPass::tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB) {
2861 BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
2862 PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
2863 Constant *CondRHS = cast<Constant>(CondCmp->getOperand(1));
2865 if (!CondBr || !CondBr->isConditional() || !CondLHS ||
2866 CondLHS->getParent() != BB)
2867 return false;
2869 for (unsigned I = 0, E = CondLHS->getNumIncomingValues(); I != E; ++I) {
2870 BasicBlock *Pred = CondLHS->getIncomingBlock(I);
2871 SelectInst *SI = dyn_cast<SelectInst>(CondLHS->getIncomingValue(I));
2873 // Look if one of the incoming values is a select in the corresponding
2874 // predecessor.
2875 if (!SI || SI->getParent() != Pred || !SI->hasOneUse())
2876 continue;
2878 BranchInst *PredTerm = dyn_cast<BranchInst>(Pred->getTerminator());
2879 if (!PredTerm || !PredTerm->isUnconditional())
2880 continue;
2882 // Now check if one of the select values would allow us to constant fold the
2883 // terminator in BB. We don't do the transform if both sides fold, those
2884 // cases will be threaded in any case.
2885 LazyValueInfo::Tristate LHSFolds =
2886 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(1),
2887 CondRHS, Pred, BB, CondCmp);
2888 LazyValueInfo::Tristate RHSFolds =
2889 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
2890 CondRHS, Pred, BB, CondCmp);
2891 if ((LHSFolds != LazyValueInfo::Unknown ||
2892 RHSFolds != LazyValueInfo::Unknown) &&
2893 LHSFolds != RHSFolds) {
2894 unfoldSelectInstr(Pred, BB, SI, CondLHS, I);
2895 return true;
2898 return false;
2901 /// tryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the
2902 /// same BB in the form
2903 /// bb:
2904 /// %p = phi [false, %bb1], [true, %bb2], [false, %bb3], [true, %bb4], ...
2905 /// %s = select %p, trueval, falseval
2907 /// or
2909 /// bb:
2910 /// %p = phi [0, %bb1], [1, %bb2], [0, %bb3], [1, %bb4], ...
2911 /// %c = cmp %p, 0
2912 /// %s = select %c, trueval, falseval
2914 /// And expand the select into a branch structure. This later enables
2915 /// jump-threading over bb in this pass.
2917 /// Using the similar approach of SimplifyCFG::FoldCondBranchOnPHI(), unfold
2918 /// select if the associated PHI has at least one constant. If the unfolded
2919 /// select is not jump-threaded, it will be folded again in the later
2920 /// optimizations.
2921 bool JumpThreadingPass::tryToUnfoldSelectInCurrBB(BasicBlock *BB) {
2922 // This transform would reduce the quality of msan diagnostics.
2923 // Disable this transform under MemorySanitizer.
2924 if (BB->getParent()->hasFnAttribute(Attribute::SanitizeMemory))
2925 return false;
2927 // If threading this would thread across a loop header, don't thread the edge.
2928 // See the comments above findLoopHeaders for justifications and caveats.
2929 if (LoopHeaders.count(BB))
2930 return false;
2932 for (BasicBlock::iterator BI = BB->begin();
2933 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2934 // Look for a Phi having at least one constant incoming value.
2935 if (llvm::all_of(PN->incoming_values(),
2936 [](Value *V) { return !isa<ConstantInt>(V); }))
2937 continue;
2939 auto isUnfoldCandidate = [BB](SelectInst *SI, Value *V) {
2940 using namespace PatternMatch;
2942 // Check if SI is in BB and use V as condition.
2943 if (SI->getParent() != BB)
2944 return false;
2945 Value *Cond = SI->getCondition();
2946 bool IsAndOr = match(SI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()));
2947 return Cond && Cond == V && Cond->getType()->isIntegerTy(1) && !IsAndOr;
2950 SelectInst *SI = nullptr;
2951 for (Use &U : PN->uses()) {
2952 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
2953 // Look for a ICmp in BB that compares PN with a constant and is the
2954 // condition of a Select.
2955 if (Cmp->getParent() == BB && Cmp->hasOneUse() &&
2956 isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
2957 if (SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
2958 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
2959 SI = SelectI;
2960 break;
2962 } else if (SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
2963 // Look for a Select in BB that uses PN as condition.
2964 if (isUnfoldCandidate(SelectI, U.get())) {
2965 SI = SelectI;
2966 break;
2971 if (!SI)
2972 continue;
2973 // Expand the select.
2974 Value *Cond = SI->getCondition();
2975 if (!isGuaranteedNotToBeUndefOrPoison(Cond, nullptr, SI))
2976 Cond = new FreezeInst(Cond, "cond.fr", SI);
2977 MDNode *BranchWeights = getBranchWeightMDNode(*SI);
2978 Instruction *Term =
2979 SplitBlockAndInsertIfThen(Cond, SI, false, BranchWeights);
2980 BasicBlock *SplitBB = SI->getParent();
2981 BasicBlock *NewBB = Term->getParent();
2982 PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI);
2983 NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
2984 NewPN->addIncoming(SI->getFalseValue(), BB);
2985 SI->replaceAllUsesWith(NewPN);
2986 SI->eraseFromParent();
2987 // NewBB and SplitBB are newly created blocks which require insertion.
2988 std::vector<DominatorTree::UpdateType> Updates;
2989 Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
2990 Updates.push_back({DominatorTree::Insert, BB, SplitBB});
2991 Updates.push_back({DominatorTree::Insert, BB, NewBB});
2992 Updates.push_back({DominatorTree::Insert, NewBB, SplitBB});
2993 // BB's successors were moved to SplitBB, update DTU accordingly.
2994 for (auto *Succ : successors(SplitBB)) {
2995 Updates.push_back({DominatorTree::Delete, BB, Succ});
2996 Updates.push_back({DominatorTree::Insert, SplitBB, Succ});
2998 DTU->applyUpdatesPermissive(Updates);
2999 return true;
3001 return false;
3004 /// Try to propagate a guard from the current BB into one of its predecessors
3005 /// in case if another branch of execution implies that the condition of this
3006 /// guard is always true. Currently we only process the simplest case that
3007 /// looks like:
3009 /// Start:
3010 /// %cond = ...
3011 /// br i1 %cond, label %T1, label %F1
3012 /// T1:
3013 /// br label %Merge
3014 /// F1:
3015 /// br label %Merge
3016 /// Merge:
3017 /// %condGuard = ...
3018 /// call void(i1, ...) @llvm.experimental.guard( i1 %condGuard )[ "deopt"() ]
3020 /// And cond either implies condGuard or !condGuard. In this case all the
3021 /// instructions before the guard can be duplicated in both branches, and the
3022 /// guard is then threaded to one of them.
3023 bool JumpThreadingPass::processGuards(BasicBlock *BB) {
3024 using namespace PatternMatch;
3026 // We only want to deal with two predecessors.
3027 BasicBlock *Pred1, *Pred2;
3028 auto PI = pred_begin(BB), PE = pred_end(BB);
3029 if (PI == PE)
3030 return false;
3031 Pred1 = *PI++;
3032 if (PI == PE)
3033 return false;
3034 Pred2 = *PI++;
3035 if (PI != PE)
3036 return false;
3037 if (Pred1 == Pred2)
3038 return false;
3040 // Try to thread one of the guards of the block.
3041 // TODO: Look up deeper than to immediate predecessor?
3042 auto *Parent = Pred1->getSinglePredecessor();
3043 if (!Parent || Parent != Pred2->getSinglePredecessor())
3044 return false;
3046 if (auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
3047 for (auto &I : *BB)
3048 if (isGuard(&I) && threadGuard(BB, cast<IntrinsicInst>(&I), BI))
3049 return true;
3051 return false;
3054 /// Try to propagate the guard from BB which is the lower block of a diamond
3055 /// to one of its branches, in case if diamond's condition implies guard's
3056 /// condition.
3057 bool JumpThreadingPass::threadGuard(BasicBlock *BB, IntrinsicInst *Guard,
3058 BranchInst *BI) {
3059 assert(BI->getNumSuccessors() == 2 && "Wrong number of successors?");
3060 assert(BI->isConditional() && "Unconditional branch has 2 successors?");
3061 Value *GuardCond = Guard->getArgOperand(0);
3062 Value *BranchCond = BI->getCondition();
3063 BasicBlock *TrueDest = BI->getSuccessor(0);
3064 BasicBlock *FalseDest = BI->getSuccessor(1);
3066 auto &DL = BB->getModule()->getDataLayout();
3067 bool TrueDestIsSafe = false;
3068 bool FalseDestIsSafe = false;
3070 // True dest is safe if BranchCond => GuardCond.
3071 auto Impl = isImpliedCondition(BranchCond, GuardCond, DL);
3072 if (Impl && *Impl)
3073 TrueDestIsSafe = true;
3074 else {
3075 // False dest is safe if !BranchCond => GuardCond.
3076 Impl = isImpliedCondition(BranchCond, GuardCond, DL, /* LHSIsTrue */ false);
3077 if (Impl && *Impl)
3078 FalseDestIsSafe = true;
3081 if (!TrueDestIsSafe && !FalseDestIsSafe)
3082 return false;
3084 BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
3085 BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
3087 ValueToValueMapTy UnguardedMapping, GuardedMapping;
3088 Instruction *AfterGuard = Guard->getNextNode();
3089 unsigned Cost =
3090 getJumpThreadDuplicationCost(TTI, BB, AfterGuard, BBDupThreshold);
3091 if (Cost > BBDupThreshold)
3092 return false;
3093 // Duplicate all instructions before the guard and the guard itself to the
3094 // branch where implication is not proved.
3095 BasicBlock *GuardedBlock = DuplicateInstructionsInSplitBetween(
3096 BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU);
3097 assert(GuardedBlock && "Could not create the guarded block?");
3098 // Duplicate all instructions before the guard in the unguarded branch.
3099 // Since we have successfully duplicated the guarded block and this block
3100 // has fewer instructions, we expect it to succeed.
3101 BasicBlock *UnguardedBlock = DuplicateInstructionsInSplitBetween(
3102 BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU);
3103 assert(UnguardedBlock && "Could not create the unguarded block?");
3104 LLVM_DEBUG(dbgs() << "Moved guard " << *Guard << " to block "
3105 << GuardedBlock->getName() << "\n");
3106 // Some instructions before the guard may still have uses. For them, we need
3107 // to create Phi nodes merging their copies in both guarded and unguarded
3108 // branches. Those instructions that have no uses can be just removed.
3109 SmallVector<Instruction *, 4> ToRemove;
3110 for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
3111 if (!isa<PHINode>(&*BI))
3112 ToRemove.push_back(&*BI);
3114 BasicBlock::iterator InsertionPoint = BB->getFirstInsertionPt();
3115 assert(InsertionPoint != BB->end() && "Empty block?");
3116 // Substitute with Phis & remove.
3117 for (auto *Inst : reverse(ToRemove)) {
3118 if (!Inst->use_empty()) {
3119 PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
3120 NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
3121 NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
3122 NewPN->insertBefore(InsertionPoint);
3123 Inst->replaceAllUsesWith(NewPN);
3125 Inst->dropDbgValues();
3126 Inst->eraseFromParent();
3128 return true;
3131 PreservedAnalyses JumpThreadingPass::getPreservedAnalysis() const {
3132 PreservedAnalyses PA;
3133 PA.preserve<LazyValueAnalysis>();
3134 PA.preserve<DominatorTreeAnalysis>();
3136 // TODO: We would like to preserve BPI/BFI. Enable once all paths update them.
3137 // TODO: Would be nice to verify BPI/BFI consistency as well.
3138 return PA;
3141 template <typename AnalysisT>
3142 typename AnalysisT::Result *JumpThreadingPass::runExternalAnalysis() {
3143 assert(FAM && "Can't run external analysis without FunctionAnalysisManager");
3145 // If there were no changes since last call to 'runExternalAnalysis' then all
3146 // analysis is either up to date or explicitly invalidated. Just go ahead and
3147 // run the "external" analysis.
3148 if (!ChangedSinceLastAnalysisUpdate) {
3149 assert(!DTU->hasPendingUpdates() &&
3150 "Lost update of 'ChangedSinceLastAnalysisUpdate'?");
3151 // Run the "external" analysis.
3152 return &FAM->getResult<AnalysisT>(*F);
3154 ChangedSinceLastAnalysisUpdate = false;
3156 auto PA = getPreservedAnalysis();
3157 // TODO: This shouldn't be needed once 'getPreservedAnalysis' reports BPI/BFI
3158 // as preserved.
3159 PA.preserve<BranchProbabilityAnalysis>();
3160 PA.preserve<BlockFrequencyAnalysis>();
3161 // Report everything except explicitly preserved as invalid.
3162 FAM->invalidate(*F, PA);
3163 // Update DT/PDT.
3164 DTU->flush();
3165 // Make sure DT/PDT are valid before running "external" analysis.
3166 assert(DTU->getDomTree().verify(DominatorTree::VerificationLevel::Fast));
3167 assert((!DTU->hasPostDomTree() ||
3168 DTU->getPostDomTree().verify(
3169 PostDominatorTree::VerificationLevel::Fast)));
3170 // Run the "external" analysis.
3171 auto *Result = &FAM->getResult<AnalysisT>(*F);
3172 // Update analysis JumpThreading depends on and not explicitly preserved.
3173 TTI = &FAM->getResult<TargetIRAnalysis>(*F);
3174 TLI = &FAM->getResult<TargetLibraryAnalysis>(*F);
3175 AA = &FAM->getResult<AAManager>(*F);
3177 return Result;
3180 BranchProbabilityInfo *JumpThreadingPass::getBPI() {
3181 if (!BPI) {
3182 assert(FAM && "Can't create BPI without FunctionAnalysisManager");
3183 BPI = FAM->getCachedResult<BranchProbabilityAnalysis>(*F);
3185 return *BPI;
3188 BlockFrequencyInfo *JumpThreadingPass::getBFI() {
3189 if (!BFI) {
3190 assert(FAM && "Can't create BFI without FunctionAnalysisManager");
3191 BFI = FAM->getCachedResult<BlockFrequencyAnalysis>(*F);
3193 return *BFI;
3196 // Important note on validity of BPI/BFI. JumpThreading tries to preserve
3197 // BPI/BFI as it goes. Thus if cached instance exists it will be updated.
3198 // Otherwise, new instance of BPI/BFI is created (up to date by definition).
3199 BranchProbabilityInfo *JumpThreadingPass::getOrCreateBPI(bool Force) {
3200 auto *Res = getBPI();
3201 if (Res)
3202 return Res;
3204 if (Force)
3205 BPI = runExternalAnalysis<BranchProbabilityAnalysis>();
3207 return *BPI;
3210 BlockFrequencyInfo *JumpThreadingPass::getOrCreateBFI(bool Force) {
3211 auto *Res = getBFI();
3212 if (Res)
3213 return Res;
3215 if (Force)
3216 BFI = runExternalAnalysis<BlockFrequencyAnalysis>();
3218 return *BFI;