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