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