LLVM 24.0.0git
JumpThreading.cpp
Go to the documentation of this file.
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
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"
21#include "llvm/ADT/Statistic.h"
26#include "llvm/Analysis/CFG.h"
32#include "llvm/Analysis/Loads.h"
39#include "llvm/IR/BasicBlock.h"
40#include "llvm/IR/CFG.h"
41#include "llvm/IR/Constant.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"
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"
60#include "llvm/IR/Type.h"
61#include "llvm/IR/Use.h"
62#include "llvm/IR/Value.h"
67#include "llvm/Support/Debug.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 {
91}
92
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//
134 if (!CondBr)
135 return;
136
137 uint64_t TrueWeight, FalseWeight;
138 if (!extractBranchWeights(*CondBr, TrueWeight, 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;
155 while (true) {
156 if (isa<CondBrInst>(PredBB->getTerminator()))
157 return {PredBB, SuccBB};
158 Visited.insert(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(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>(PhiOpnd);
176
177 if (!CI || !CI->getType()->isIntegerTy(1))
178 continue;
179
182 TrueWeight, TrueWeight + FalseWeight)
184 FalseWeight, 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>(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(*PredBr, PredTrueWeight, 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(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(*PredBr, Weights, hasBranchWeightOrigin(*PredBr));
217 }
218}
219
222 auto &TTI = AM.getResult<TargetIRAnalysis>(F);
223 // Jump Threading has no sense for the targets with divergent CF
224 if (TTI.hasBranchDivergence(&F))
225 return PreservedAnalyses::all();
226 auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
227 auto &LVI = AM.getResult<LazyValueAnalysis>(F);
228 auto &AA = AM.getResult<AAManager>(F);
229 auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
230
231 bool Changed =
232 runImpl(F, &AM, &TLI, &TTI, &LVI, &AA,
233 std::make_unique<DomTreeUpdater>(
234 &DT, nullptr, DomTreeUpdater::UpdateStrategy::Lazy),
235 nullptr, nullptr);
236
237 if (!Changed)
238 return PreservedAnalyses::all();
239
240
242
243#if defined(EXPENSIVE_CHECKS)
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
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
265 TargetLibraryInfo *TLI_,
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_);
273 F = &F_;
274 FAM = FAM_;
275 TLI = TLI_;
276 TTI = TTI_;
277 LVI = LVI_;
278 AA = AA_;
279 AC = FAM->getCachedResult<AssumptionAnalysis>(F_);
280 DTU = std::move(DTU_);
281 BFI = BFI_;
282 BPI = BPI_;
283 auto *GuardDecl = Intrinsic::getDeclarationIfExists(
284 F->getParent(), 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(&BB))
303 Unreachable.insert(&BB);
304
305 if (!Opts->jump_threading_across_loop_headers)
306 findLoopHeaders(*F);
307
308 bool EverChanged = false;
309 bool Changed;
310 do {
311 Changed = false;
312 for (auto &BB : *F) {
313 if (Unreachable.count(&BB))
314 continue;
315 while (processBlock(&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(&BB))
322 continue;
323
324 if (pred_empty(&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(&BB);
331 LVI->eraseBlock(&BB);
332 DeleteDeadBlock(&BB, 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>(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(&BB) && !LoopHeaders.count(Succ) &&
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);
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) {
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.
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)
385 for (Instruction &I : reverse(*KnownAtEndOfBB)) {
386 // Replace any debug-info record users of Cond with ToVal.
387 for (DbgVariableRecord &DVR : filterDbgVars(I.getDbgRecordRange()))
388 DVR.replaceVariableLocationOp(Cond, ToVal, 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.
397 break;
398 Changed |= I.replaceUsesOfWith(Cond, 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,
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>(&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>(StopAt))
443 Bonus = 6;
444
445 // The same holds for indirect branches, but slightly more so.
446 if (isa<IndirectBrInst>(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>(I))
471 if (CI->cannotDuplicate() || CI->isConvergent())
472 return ~0U;
473
474 if (TTI->getInstructionCost(&*I, TargetTransformInfo::TCK_SizeAndLatency) ==
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>(I)) {
486 if (!isa<IntrinsicInst>(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.
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.
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)
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.
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(V).second)
552 return false;
553
554 // If V is a constant, then it is known in all predecessors.
555 if (Constant *KC = getKnownConstant(V, Preference)) {
556 for (BasicBlock *Pred : predecessors(BB))
557 Result.emplace_back(KC, 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.
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, P, 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, m_Cmp(Pred, m_Value(Val), m_Constant(Cst))))
582 PredCst = LVI->getPredicateOnEdge(Pred, Val, Cst, P, BB, CtxI);
583 if (Constant *KC = getKnownConstant(PredCst, Preference))
584 Result.emplace_back(KC, 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>(I)) {
592 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
593 Value *InVal = PN->getIncomingValue(i);
594 if (Constant *KC = getKnownConstant(InVal, Preference)) {
595 Result.emplace_back(KC, PN->getIncomingBlock(i));
596 } else {
597 Constant *CI = LVI->getConstantOnEdge(InVal,
598 PN->getIncomingBlock(i),
599 BB, CtxI);
600 if (Constant *KC = getKnownConstant(CI, Preference))
601 Result.emplace_back(KC, PN->getIncomingBlock(i));
602 }
603 }
604
605 return !Result.empty();
606 }
607
608 // Handle Cast instructions.
609 if (CastInst *CI = dyn_cast<CastInst>(I)) {
610 Value *Source = CI->getOperand(0);
611 PredValueInfoTy Vals;
612 computeValueKnownInPredecessorsImpl(Source, BB, 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(CI->getOpcode(), Val.first,
620 CI->getType(), DL))
621 Result.emplace_back(Folded, Val.second);
622
623 return !Result.empty();
624 }
625
626 if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
627 Value *Source = FI->getOperand(0);
628 computeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
629 RecursionSet, CtxI);
630
631 erase_if(Result, [](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(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))) ||
647 match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
648 PredValueInfoTy LHSVals, RHSVals;
649
651 RecursionSet, CtxI);
653 RecursionSet, CtxI);
654
655 if (LHSVals.empty() && RHSVals.empty())
656 return false;
657
658 ConstantInt *InterestingVal;
659 if (match(I, m_LogicalOr()))
660 InterestingVal = ConstantInt::getTrue(I->getContext());
661 else
662 InterestingVal = ConstantInt::getFalse(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>(LHSVal.first)) {
670 Result.emplace_back(InterestingVal, LHSVal.second);
671 LHSKnownBBs.insert(LHSVal.second);
672 }
673 for (const auto &RHSVal : RHSVals)
674 if (RHSVal.first == InterestingVal || isa<UndefValue>(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(RHSVal.second))
678 Result.emplace_back(InterestingVal, 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>(I->getOperand(1)) &&
687 cast<ConstantInt>(I->getOperand(1))->isOne()) {
688 computeValueKnownInPredecessorsImpl(I->getOperand(0), BB, Result,
689 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(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>(I)) {
702 if (Preference != WantInteger)
703 return false;
704 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
705 PredValueInfoTy LHSVals;
706 computeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
707 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;
713 ConstantFoldBinaryOpOperands(BO->getOpcode(), V, CI, DL);
714
716 Result.emplace_back(KC, 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>(I)) {
725 if (Preference != WantInteger)
726 return false;
727 Type *CmpType = Cmp->getType();
728 Value *CmpLHS = Cmp->getOperand(0);
729 Value *CmpRHS = Cmp->getOperand(1);
730 CmpInst::Predicate Pred = Cmp->getPredicate();
731
732 PHINode *PN = dyn_cast<PHINode>(CmpLHS);
733 if (!PN)
734 PN = dyn_cast<PHINode>(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(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(BB, PredBB);
748 } else {
749 LHS = CmpLHS->DoPHITranslation(BB, PredBB);
750 RHS = PN->getIncomingValue(i);
751 }
752 Value *Res = simplifyCmpInst(Pred, LHS, RHS, {DL});
753 if (!Res) {
754 if (!isa<Constant>(RHS))
755 continue;
756
757 // getPredicateOnEdge call will make no sense if LHS is defined in BB.
758 auto LHSInst = dyn_cast<Instruction>(LHS);
759 if (LHSInst && LHSInst->getParent() == BB)
760 continue;
761
762 Res = LVI->getPredicateOnEdge(Pred, LHS, cast<Constant>(RHS), PredBB,
763 BB, CtxI ? CtxI : Cmp);
764 }
765
766 if (Constant *KC = getKnownConstant(Res, WantInteger))
767 Result.emplace_back(KC, 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>(CmpRHS) && !CmpType->isVectorTy()) {
776 Constant *CmpConst = cast<Constant>(CmpRHS);
777
778 if (!isa<Instruction>(CmpLHS) ||
779 cast<Instruction>(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, CmpLHS, CmpConst, P, BB,
784 CtxI ? CtxI : Cmp);
785 if (Constant *KC = getKnownConstant(Res, WantInteger))
786 Result.emplace_back(KC, 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>(CmpConst) &&
801 match(CmpLHS, m_Add(m_Value(AddLHS), m_ConstantInt(AddConst)))) {
802 if (!isa<Instruction>(AddLHS) ||
803 cast<Instruction>(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 AddLHS, P, BB, CtxI ? CtxI : cast<Instruction>(CmpLHS));
810 // Propagate the range through the addition.
811 CR = CR.add(AddConst->getValue());
812
813 // Get the range where the compare returns true.
815 Pred, cast<ConstantInt>(CmpConst)->getValue());
816
817 Constant *ResC;
818 if (CmpRange.contains(CR))
819 ResC = ConstantInt::getTrue(CmpType);
820 else if (CmpRange.inverse().contains(CR))
821 ResC = ConstantInt::getFalse(CmpType);
822 else
823 continue;
824
825 Result.emplace_back(ResC, 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(I->getOperand(0), BB, LHSVals,
837 WantInteger, RecursionSet, CtxI);
838
839 for (const auto &LHSVal : LHSVals) {
840 Constant *V = LHSVal.first;
842 ConstantFoldCompareInstOperands(Pred, V, CmpConst, DL);
844 Result.emplace_back(KC, LHSVal.second);
845 }
846
847 return !Result.empty();
848 }
849 }
850
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(SI->getTrueValue(), Preference);
855 Constant *FalseVal = getKnownConstant(SI->getFalseValue(), Preference);
856 PredValueInfoTy Conds;
857 if ((TrueVal || FalseVal) &&
858 computeValueKnownInPredecessorsImpl(SI->getCondition(), BB, Conds,
859 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;
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(Val, 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(CI, Preference)) {
889 for (BasicBlock *Pred : predecessors(BB))
890 Result.emplace_back(KC, 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.
902 Instruction *BBTerm = BB->getTerminator();
903 unsigned MinSucc = 0;
904 BasicBlock *TestBB = BBTerm->getSuccessor(MinSucc);
905 // Compute the successor with the minimum number of predecessors.
906 unsigned MinNumPreds = pred_size(TestBB);
907 for (unsigned i = 1, e = BBTerm->getNumSuccessors(); i != e; ++i) {
908 TestBB = BBTerm->getSuccessor(i);
909 unsigned NumPreds = pred_size(TestBB);
910 if (NumPreds < MinNumPreds) {
911 MinSucc = i;
912 MinNumPreds = NumPreds;
913 }
914 }
915
916 return MinSucc;
917}
918
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.
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.
932 // If the block is trivially dead, just return and let the caller nuke it.
933 // This simplifies other transformations.
934 if (DTU->isBBPendingDeletion(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.
943 return true;
944
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>(Terminator)) {
960 Condition = BI->getCondition();
961 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(Terminator)) {
962 Condition = SI->getCondition();
963 } else if (IndirectBrInst *IB = dyn_cast<IndirectBrInst>(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>(Condition)) {
978 Value *SimpleVal =
980 if (SimpleVal) {
981 I->replaceAllUsesWith(SimpleVal);
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>(Condition);
992 if (isa<UndefValue>(Condition) ||
993 (FI && isa<UndefValue>(FI->getOperand(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(BBTerm->getNumSuccessors());
1000 for (unsigned i = 0, e = BBTerm->getNumSuccessors(); i != e; ++i) {
1001 if (i == BestSucc) continue;
1002 BasicBlock *Succ = BBTerm->getSuccessor(i);
1003 Succ->removePredecessor(BB, true);
1004 Updates.push_back({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(BBTerm->getSuccessor(BestSucc),
1010 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(Condition, Preference)) {
1024 LLVM_DEBUG(dbgs() << " In block '" << BB->getName()
1025 << "' folding terminator: " << *BB->getTerminator()
1026 << '\n');
1027 ++NumFolds;
1028 ConstantFoldTerminator(BB, true, nullptr, DTU.get());
1029 if (auto *BPI = getBPI())
1030 BPI->eraseBlock(BB);
1031 return true;
1032 }
1033
1034 Instruction *CondInst = dyn_cast<Instruction>(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(Condition, BB, Preference, 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>(CondInst))
1047 CondWithoutFreeze = FI->getOperand(0);
1048
1049 if (CmpInst *CondCmp = dyn_cast<CmpInst>(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>(CondCmp->getOperand(1))) {
1054 Constant *Res =
1055 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
1056 CondConst, 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(CondCmp, Res, 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
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>(SimplifyValue))
1088 if (isa<Constant>(CondCmp->getOperand(1)))
1089 SimplifyValue = CondCmp->getOperand(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>(SimplifyValue))
1095 return true;
1096
1097 // Before threading, try to propagate profile data backwards:
1098 if (PHINode *PN = dyn_cast<PHINode>(CondInst))
1099 if (PN->getParent() == BB && isa<CondBrInst>(BB->getTerminator()))
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(CondInst, BB, Preference, 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>(CondWithoutFreeze);
1111 if (PN && PN->getParent() == BB && isa<CondBrInst>(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>(BB->getTerminator()))
1117 return processBranchOnXOR(cast<BinaryOperator>(CondInst));
1118
1119 // Search for a stronger dominating condition that can be used to simplify a
1120 // conditional branch leaving BB.
1122 return true;
1123
1124 return false;
1125}
1126
1128 auto *BI = dyn_cast<CondBrInst>(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>(Cond);
1139 if (FICond && FICond->hasOneUse())
1140 Cond = FICond->getOperand(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>(CurrentPred->getTerminator());
1153 if (!PBI)
1154 return false;
1155 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1156 return false;
1157
1158 bool CondIsTrue = PBI->getSuccessor(0) == CurrentBB;
1159 std::optional<bool> Implication =
1160 isImpliedCondition(PBI->getCondition(), Cond, DL, 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>(PBI->getCondition())) {
1165 if (cast<FreezeInst>(PBI->getCondition())->getOperand(0) ==
1166 FICond->getOperand(0))
1167 Implication = CondIsTrue;
1168 }
1169
1170 if (Implication) {
1171 BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
1172 BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
1173 RemoveSucc->removePredecessor(BB);
1174 UncondBrInst *UncondBI =
1175 UncondBrInst::Create(KeepSucc, BI->getIterator());
1176 UncondBI->setDebugLoc(BI->getDebugLoc());
1177 ++NumFolds;
1178 BI->eraseFromParent();
1179 if (FICond)
1180 FICond->eraseFromParent();
1181
1182 DTU->applyUpdatesPermissive({{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.
1196 if (Instruction *OpInst = dyn_cast<Instruction>(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.
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(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(LoadedPtr, LoadBB) && !isa<PHINode>(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 LoadI, LoadBB, BBIt, DefMaxInstsToScan, &BatchAA, &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>(AvailableVal);
1243 combineMetadataForCSE(NLoadI, LoadI, false);
1244 LVI->forgetValue(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(LoadI->getType());
1251 if (AvailableVal->getType() != LoadI->getType()) {
1252 AvailableVal = CastInst::CreateBitOrPointerCast(
1253 AvailableVal, LoadI->getType(), "", LoadI->getIterator());
1254 cast<Instruction>(AvailableVal)->setDebugLoc(LoadI->getDebugLoc());
1255 }
1256 LoadI->replaceAllUsesWith(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;
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(LoadBB)) {
1282 // If we already scanned this predecessor, skip it.
1283 if (!PredsScanned.insert(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(LoadBB, PredBB),
1298 LocationSize::precise(DL.getTypeStoreSize(AccessTy)),
1299 AATags);
1300 PredAvailable = findAvailablePtrLoadStore(
1301 Loc, AccessTy, LoadI->getProperties(), PredBB, BBIt, DefMaxInstsToScan,
1302 &BatchAA, &IsLoadCSE, &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, LoadI->getProperties(), SinglePredBB, BBIt,
1314 (DefMaxInstsToScan - NumScanedInst), &BatchAA, &IsLoadCSE,
1315 &NumScanedInst);
1316 }
1317 }
1318
1319 if (!PredAvailable) {
1320 OneUnavailablePred = PredBB;
1321 continue;
1322 }
1323
1324 if (IsLoadCSE)
1325 CSELoads.push_back(cast<LoadInst>(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(PredBB, 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(LoadI, Pred->getTerminator()))
1354 return true;
1355
1356 if (!GuaranteedToTransfer)
1357 GuaranteedToTransfer = isGuaranteedToTransferExecutionToSuccessor(
1358 LoadBB->begin(), 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(AvailablePreds));
1376
1377 // Add all the unavailable predecessors to the PredsToSplit list.
1378 for (BasicBlock *P : predecessors(LoadBB)) {
1379 // If the predecessor is an indirect goto, we can't split the edge.
1380 if (isa<IndirectBrInst>(P->getTerminator()))
1381 return false;
1382
1383 if (!AvailablePredSet.count(P)) {
1384 if (!CanSpeculateInto(P))
1385 return false;
1386 PredsToSplit.push_back(P);
1387 }
1388 }
1389
1390 // Split them out to their own block.
1391 UnavailablePred = splitBlockPreds(LoadBB, PredsToSplit, "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(LoadBB, 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(UnavailablePred, 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(AvailablePreds.begin(), 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(LoadI->getType(), pred_size(LoadBB), "");
1418 PN->insertBefore(LoadBB->begin());
1419 PN->takeName(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(LoadBB)) {
1425 AvailablePredsTy::iterator I =
1426 llvm::lower_bound(AvailablePreds, std::make_pair(P, (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()) {
1438 PredV, LoadI->getType(), "", 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()
1446 cast<CastInst>(PredV)->setDebugLoc(DL);
1447 }
1448
1449 PN->addIncoming(PredV, I->first);
1450 }
1451
1452 for (LoadInst *PredLoadI : CSELoads) {
1453 combineMetadataForCSE(PredLoadI, LoadI, true);
1454 LVI->forgetValue(PredLoadI);
1455 }
1456
1457 LoadI->replaceAllUsesWith(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 *
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(DestPopularity, 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.
1500 BasicBlock *PredPredBB,
1501 Value *V,
1502 const DataLayout &DL) {
1504 return evaluateOnPredecessorEdge(BB, PredPredBB, V, DL, Visited);
1505}
1506
1508 BasicBlock *BB, BasicBlock *PredPredBB, Value *V, const DataLayout &DL,
1509 SmallPtrSet<Value *, 8> &Visited) {
1510 if (!Visited.insert(V).second)
1511 return nullptr;
1512 llvm::scope_exit _([&Visited, V]() { Visited.erase(V); });
1513
1514 BasicBlock *PredBB = BB->getSinglePredecessor();
1515 assert(PredBB && "Expected a single predecessor");
1516
1517 if (Constant *Cst = dyn_cast<Constant>(V)) {
1518 return Cst;
1519 }
1520
1521 // Consult LVI if V is not an instruction in BB or PredBB.
1523 if (!I || (I->getParent() != BB && I->getParent() != PredBB)) {
1524 return LVI->getConstantOnEdge(V, PredPredBB, PredBB, nullptr);
1525 }
1526
1527 // Look into a PHI argument.
1528 if (PHINode *PHI = dyn_cast<PHINode>(V)) {
1529 if (PHI->getParent() == PredBB)
1530 return dyn_cast<Constant>(PHI->getIncomingValueForBlock(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>(V)) {
1540 if (CondCmp->getParent() == BB) {
1542 BB, PredPredBB, CondCmp->getOperand(0), DL, Visited);
1544 BB, PredPredBB, CondCmp->getOperand(1), DL, Visited);
1545 if (Op0 && Op1) {
1546 return ConstantFoldCompareInstOperands(CondCmp->getPredicate(), Op0,
1547 Op1, DL);
1548 }
1549 }
1550 return nullptr;
1551 }
1552
1553 return nullptr;
1554}
1555
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(BB))
1562 return false;
1563
1564 PredValueInfoTy PredValues;
1565 if (!computeValueKnownInPredecessors(Cond, BB, 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.
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).
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(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>(BB->getTerminator())) {
1605 assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1606 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->isZero());
1607 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
1608 assert(isa<ConstantInt>(Val) && "Expecting a constant integer");
1609 DestBB = SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
1610 } else {
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>(Pred->getTerminator()))
1633 continue;
1634
1635 PredToDestList.emplace_back(Pred, 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(PredToDestList.size())) {
1647 bool SeenFirstBranchToOnlyDest = false;
1648 std::vector <DominatorTree::UpdateType> Updates;
1649 Updates.reserve(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(BB, true); // This is unreachable successor.
1655 Updates.push_back({DominatorTree::Delete, BB, SuccBB});
1656 }
1657 }
1658
1659 // Finally update the terminator.
1660 Instruction *Term = BB->getTerminator();
1661 Instruction *NewBI = UncondBrInst::Create(OnlyDest, 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>(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(CondInst, OnlyVal, 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(PredToDestList,
1699 [&](const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1700 return LoopHeaders.contains(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(Pred))
1720 if (Succ == BB)
1721 PredsToFactor.push_back(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(getBestDestForJumpOnUndef(BB));
1729
1730 // Ok, try to thread it!
1731 return tryThreadEdge(BB, PredsToFactor, 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.
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.
1743 PredBBs.resize(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>(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.
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>(BO->getOperand(0)) ||
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>(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(BO->getOperand(0), BB, XorOpValues,
1807 WantInteger, BO)) {
1808 assert(XorOpValues.empty());
1809 if (!computeValueKnownInPredecessors(BO->getOperand(1), BB, XorOpValues,
1810 WantInteger, 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>(XorOpValue.first))
1823 // Ignore undefs for the count.
1824 continue;
1825 if (cast<ConstantInt>(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(BB->getContext());
1835 else if (NumTrue != 0 || NumFalse != 0)
1836 SplitVal = ConstantInt::getFalse(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>(XorOpValue.first))
1843 continue;
1844
1845 BlocksToFoldInto.push_back(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>(BB->front()).getNumIncomingValues()) {
1852 if (!SplitVal) {
1853 // If all preds provide undef, just nuke the xor, because it is undef too.
1855 BO->eraseFromParent();
1856 } else if (SplitVal->isZero() && BO != BO->getOperand(isLHS)) {
1857 // If all preds provide 0, replace the xor with the other input.
1858 BO->replaceAllUsesWith(BO->getOperand(isLHS));
1859 BO->eraseFromParent();
1860 } else {
1861 // If all preds provide 1, set the computed value to 1.
1862 BO->setOperand(!isLHS, 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(BlocksToFoldInto, [](BasicBlock *Pred) {
1871 return isa<IndirectBrInst>(Pred->getTerminator());
1872 }))
1873 return false;
1874
1875 // Try to duplicate BB into PredBB.
1876 return duplicateCondBranchOnPHIIntoPred(BB, 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).
1883 BasicBlock *OldPred,
1884 BasicBlock *NewPred,
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(OldPred);
1890
1891 // Remap the value if necessary.
1892 if (Instruction *Inst = dyn_cast<Instruction>(IV)) {
1894 if (I != ValueMap.end())
1895 IV = I->second;
1896 }
1897
1898 PN.addIncoming(IV, NewPred);
1899 }
1900}
1901
1902/// Merge basic block BB into its sole predecessor if possible.
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(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.
1923 return false;
1924
1925 // If SinglePred was a loop header, BB becomes one.
1926 if (LoopHeaders.erase(SinglePred))
1927 LoopHeaders.insert(BB);
1928
1929 LVI->eraseBlock(SinglePred);
1930 MergeBasicBlockIntoOnlyPred(BB, 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.
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.
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>(U.getUser());
1983 if (User->isLifetimeStartOrEnd()) {
1984 LifetimeMarkers.push_back(User);
1985 } else {
1986 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
1987 if (UserPN->getIncomingBlock(U) == BB)
1988 continue;
1989 } else if (User->getParent() == BB)
1990 continue;
1991 }
1992 UsesToRename.push_back(&U);
1993 }
1994
1995 // Find debug values outside of the block
1996 findDbgValues(&I, DbgVariableRecords);
1997 llvm::erase_if(DbgVariableRecords, [&](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(I.getType(), I.getName());
2010 SSAUpdate.AddAvailableValue(BB, &I);
2011 SSAUpdate.AddAvailableValue(NewBB, ValueMapping[&I]);
2012
2013 while (!UsesToRename.empty())
2014 SSAUpdate.RewriteUse(*UsesToRename.pop_back_val());
2015 if (!DbgVariableRecords.empty()) {
2016 SSAUpdate.UpdateDebugValues(&I, 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(LifetimeMarkers, [](Instruction *User) {
2023 return isa<PHINode>(cast<CallBase>(User)->getOperand(0));
2024 });
2025 if (HasPhiArg) {
2026 for (Instruction *User : LifetimeMarkers)
2027 User->eraseFromParent();
2028 }
2029 LLVM_DEBUG(dbgs() << "\n");
2030 }
2031}
2032
2035 if (VM.AtomMap.empty())
2036 return;
2037 for (auto It = Begin; It != End; ++It)
2038 RemapSourceAtom(&*It, VM);
2039}
2040
2041/// Register \p New in \p AC if it is an assume.
2043 if (auto *Assume = dyn_cast<AssumeInst>(&New))
2044 AC.registerAssumption(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
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()) {
2065 if (!OpInst)
2066 continue;
2067
2068 auto I = ValueMapping.find(OpInst);
2069 if (I != ValueMapping.end())
2070 OperandsToRemap.insert({OpInst, I->second});
2071 }
2072
2073 for (auto &[OldOp, MappedOp] : OperandsToRemap)
2074 DVR->replaceVariableLocationOp(OldOp, 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>(BI); ++BI) {
2083 PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName(), NewBB);
2084 NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), PredBB);
2085 ValueMapping[PN] = NewPN;
2086 if (const DebugLoc &DL = PN->getDebugLoc())
2087 mapAtomInstance(DL, 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;
2096 LLVMContext &Context = PredBB->getContext();
2097 identifyNoAliasScopesToClone(BI, BE, NoAliasScopes);
2098 cloneNoAliasScopes(NoAliasScopes, ClonedScopes, ClonedDomains, "thread",
2099 Context);
2100
2101 auto CloneAndRemapDbgInfo = [&](Instruction *NewInst, Instruction *From) {
2102 auto DVRRange = NewInst->cloneDebugInfoFrom(From);
2103 for (DbgVariableRecord &DVR : filterDbgVars(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(NewBB, NewBB->end());
2114 ValueMapping[&*BI] = New;
2115 if (AC)
2116 registerClonedAssume(*New, *AC);
2117 adaptNoAliasScopes(New, ClonedScopes, ClonedDomains, "thread", Context);
2118
2119 CloneAndRemapDbgInfo(New, &*BI);
2120 if (const DebugLoc &DL = New->getDebugLoc())
2121 mapAtomInstance(DL, 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>(New->getOperand(i))) {
2126 ValueToValueMapTy::iterator I = ValueMapping.find(Inst);
2127 if (I != ValueMapping.end())
2128 New->setOperand(i, 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(BE);
2137 DbgMarker *EndMarker = NewBB->createMarker(NewBB->end());
2138 auto DVRRange = EndMarker->cloneDebugInfoFrom(Marker, std::nullopt);
2139 for (DbgVariableRecord &DVR : filterDbgVars(DVRRange))
2140 RetargetDbgVariableRecordIfPossible(&DVR);
2141 }
2142}
2143
2144/// Attempt to thread through two successive basic blocks.
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.
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>(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(successors(PredBB), PredBB))
2195 return false;
2196
2197 // Don't thread across a loop header.
2198 if (LoopHeaders.count(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(PredBB)) {
2214 // If PredPred ends with IndirectBrInst, we can't handle it.
2215 if (isa<IndirectBrInst>(P->getTerminator()))
2216 continue;
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(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(BB) || LoopHeaders.count(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, TTI, BB, BB->getTerminator(), BBDupThreshold);
2267 unsigned PredBBCost = getJumpThreadDuplicationCost(
2268 *Opts, TTI, PredBB, PredBB->getTerminator(), 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
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(HasProfile);
2296 auto *BPI = getOrCreateBPI(BFI != nullptr);
2297
2298 CondBrInst *CondBr = cast<CondBrInst>(BB->getTerminator());
2299 CondBrInst *PredBBBranch = cast<CondBrInst>(PredBB->getTerminator());
2300
2301 BasicBlock *NewBB =
2302 BasicBlock::Create(PredBB->getContext(), PredBB->getName() + ".thread",
2303 PredBB->getParent(), PredBB);
2304 NewBB->moveAfter(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(PredPredBB) *
2310 BPI->getEdgeProbability(PredPredBB, PredBB);
2311 BFI->setBlockFreq(NewBB, 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, PredBB->begin(), PredBB->end(), NewBB,
2319 PredPredBB);
2320
2321 // Copy the edge probabilities from PredBB to NewBB.
2322 if (BPI)
2323 BPI->copyEdgeProbabilities(PredBB, 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(i) == PredBB) {
2331 PredBB->removePredecessor(PredPredBB, true);
2332 PredPredTerm->setSuccessor(i, NewBB);
2333 }
2334
2335 addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(0), PredBB, NewBB,
2336 ValueMapping);
2337 addPHINodeEntriesForMappedBlock(PredBBBranch->getSuccessor(1), PredBB, NewBB,
2338 ValueMapping);
2339
2340 DTU->applyUpdatesPermissive(
2341 {{DominatorTree::Insert, NewBB, CondBr->getSuccessor(0)},
2342 {DominatorTree::Insert, NewBB, CondBr->getSuccessor(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(ValueMapping, NewBB->begin(), NewBB->end());
2348
2349 updateSSA(PredBB, NewBB, ValueMapping);
2350
2351 // Clean up things like PHI nodes with single operands, dead instructions,
2352 // etc.
2353 SimplifyInstructionsInBlock(NewBB, TLI);
2354 SimplifyInstructionsInBlock(PredBB, TLI);
2355
2356 SmallVector<BasicBlock *, 1> PredsToFactor;
2357 PredsToFactor.push_back(NewBB);
2358 threadEdge(BB, PredsToFactor, SuccBB);
2359}
2360
2361/// tryThreadEdge - Thread an edge if it's safe and profitable to do so.
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(BB) || LoopHeaders.count(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, TTI, BB, BB->getTerminator(), 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.
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(HasProfile);
2412 auto *BPI = getOrCreateBPI(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, PredBBs, ".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, BB, SuccBB);
2430
2432 BB->getName()+".thread",
2433 BB->getParent(), BB);
2434 NewBB->moveAfter(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(PredBB) * BPI->getEdgeProbability(PredBB, BB);
2441 BFI->setBlockFreq(NewBB, NewBBFreq);
2442 }
2443
2444 // Copy all the instructions from BB to NewBB except the terminator.
2445 ValueToValueMapTy ValueMapping;
2446 cloneInstructions(ValueMapping, BB->begin(), std::prev(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(SuccBB, 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(SuccBB, BB, NewBB, 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(i) == BB) {
2464 BB->removePredecessor(PredBB, true);
2465 PredTerm->setSuccessor(i, NewBB);
2466 }
2467
2468 // Enqueue required DT updates.
2469 DTU->applyUpdatesPermissive({{DominatorTree::Insert, NewBB, SuccBB},
2470 {DominatorTree::Insert, PredBB, NewBB},
2471 {DominatorTree::Delete, PredBB, BB}});
2472
2473 remapSourceAtoms(ValueMapping, NewBB->begin(), 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(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,
2493 const char *Suffix) {
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.
2499 auto *BFI = getBFI();
2500 if (BFI) {
2501 auto *BPI = getOrCreateBPI(true);
2502 for (auto *Pred : Preds)
2503 FreqMap.insert(std::make_pair(
2504 Pred, BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, 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(BB, Preds, Suffix, NewName.c_str(), NewBBs);
2512 } else {
2513 NewBBs.push_back(SplitBlockPredecessors(BB, Preds, Suffix));
2514 }
2515
2516 std::vector<DominatorTree::UpdateType> Updates;
2517 Updates.reserve((2 * Preds.size()) + NewBBs.size());
2518 for (auto *NewBB : NewBBs) {
2519 BlockFrequency NewBBFreq(0);
2520 Updates.push_back({DominatorTree::Insert, NewBB, BB});
2521 for (auto *Pred : predecessors(NewBB)) {
2522 Updates.push_back({DominatorTree::Delete, Pred, BB});
2523 Updates.push_back({DominatorTree::Insert, Pred, NewBB});
2524 if (BFI) // Update frequencies between Pred -> NewBB.
2525 NewBBFreq += FreqMap.lookup(Pred);
2526 }
2527 if (BFI) // Apply the summed frequency to NewBB.
2528 BFI->setBlockFreq(NewBB, 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(*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,
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(NewBB);
2566 auto BBNewFreq = BBOrigFreq - NewBBFreq;
2567 BFI->setBlockFreq(BB, 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(successors(BB))) {
2573 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, It.index());
2574 auto SuccFreq =
2575 (It.value() == SuccBB) ? BB2SuccBBFreq - NewBBFreq : BB2SuccBBFreq;
2576 BBSuccFreq.push_back(SuccFreq.getFrequency());
2577 }
2578
2579 uint64_t MaxBBSuccFreq = *llvm::max_element(BBSuccFreq);
2580
2582 if (MaxBBSuccFreq == 0)
2583 BBSuccProbs.assign(BBSuccFreq.size(),
2584 {1, static_cast<unsigned>(BBSuccFreq.size())});
2585 else {
2586 for (uint64_t Freq : BBSuccFreq)
2587 BBSuccProbs.push_back(
2588 BranchProbability::getBranchProbability(Freq, MaxBBSuccFreq));
2589 // Normalize edge probabilities so that they sum up to one.
2591 BBSuccProbs.end());
2592 }
2593
2594 // Update edge probabilities in BPI.
2595 BPI->setEdgeProbability(BB, 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(Prob.getNumerator());
2635
2636 auto TI = BB->getTerminator();
2637 setBranchWeights(*TI, Weights, hasBranchWeightOrigin(*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.
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(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, TTI, BB, BB->getTerminator(), 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, PredBBs, ".thr_comm");
2677 }
2678 Updates.push_back({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>(PredBB->getTerminator());
2693 if (isa<PHINode>(BB->front()) || !OldPredBranch) {
2694 PredBB = SplitEdge(OldPredBB, BB);
2695 Updates.push_back({DominatorTree::Insert, OldPredBB, PredBB});
2696 Updates.push_back({DominatorTree::Insert, PredBB, BB});
2697 OldPredBranch = cast<UncondBrInst>(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(OldPredBranch->getReverseIterator());
2706
2707 BasicBlock::iterator BI = BB->begin();
2708 for (; PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2709 PHINode *NewPN = PHINode::Create(PN->getType(), 1, PN->getName() + ".dup");
2710 NewPN->insertBefore(OldPredBranch->getIterator());
2711 NewPN->addIncoming(PN->getIncomingValueForBlock(PredBB), 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;
2721 LLVMContext &Context = PredBB->getContext();
2722 identifyNoAliasScopesToClone(BI, BB->end(), NoAliasScopes);
2723 cloneNoAliasScopes(NoAliasScopes, ClonedScopes, ClonedDomains, "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(PredBB, OldPredBranch->getIterator());
2731 adaptNoAliasScopes(New, ClonedScopes, ClonedDomains, "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>(New->getOperand(i))) {
2736 ValueToValueMapTy::iterator I = ValueMapping.find(Inst);
2737 if (I != ValueMapping.end())
2738 New->setOperand(i, I->second);
2739 }
2740
2741 // Remap debug variable operands.
2742 remapDebugVariable(ValueMapping, New);
2743 if (const DebugLoc &DL = New->getDebugLoc())
2744 mapAtomInstance(DL, 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.
2750 New,
2751 {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(&*BI, std::nullopt, 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(&*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>(New->getOperand(i)))
2771 Updates.push_back({DominatorTree::Insert, PredBB, SuccBB});
2772
2773 if (AC)
2774 registerClonedAssume(*New, *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>(BB->getTerminator());
2781 addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(0), BB, PredBB,
2782 ValueMapping);
2783 addPHINodeEntriesForMappedBlock(BBBranch->getSuccessor(1), BB, PredBB,
2784 ValueMapping);
2785
2786 // KeyInstructions: Remap the cloned instructions' atoms only.
2787 remapSourceAtoms(ValueMapping, std::prev(RItBeforeInsertPt)->getIterator(),
2788 OldPredBranch->getIterator());
2789
2790 updateSSA(BB, 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(PredBB, 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(PredBB, DTU.get()))
2802 ThreadBB = OldPredBB;
2803
2804 if (auto *BPI = getBPI())
2805 BPI->copyEdgeProbabilities(BB, 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.
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>(Pred->getTerminator());
2829 BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "select.unfold",
2830 BB->getParent(), BB);
2831 // Move the unconditional branch to NewBB.
2832 PredTerm->removeFromParent();
2833 PredTerm->insertInto(NewBB, 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(SI->getCondition(), NewBB, BB, Pred);
2842 BI->applyMergedLocation(PredTerm->getDebugLoc(), SI->getDebugLoc());
2843 BI->copyMetadata(*SI, {LLVMContext::MD_prof});
2844 SIUse->setIncomingValue(Idx, SI->getFalseValue());
2845 SIUse->addIncoming(SI->getTrueValue(), 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(*SI, TrueWeight, FalseWeight) &&
2851 (TrueWeight + FalseWeight) != 0) {
2854 TrueWeight, TrueWeight + FalseWeight));
2856 FalseWeight, TrueWeight + FalseWeight));
2857 // Update BPI if exists.
2858 if (auto *BPI = getBPI())
2859 BPI->setEdgeProbability(Pred, 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 }
2868 TrueWeight, TrueWeight + FalseWeight);
2869 auto NewBBFreq = BFI->getBlockFreq(Pred) * PredToNewBBProb;
2870 BFI->setBlockFreq(NewBB, NewBBFreq);
2871 }
2872
2873 // The select is now dead.
2874 SI->eraseFromParent();
2875 DTU->applyUpdatesPermissive({{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>(BI); ++BI)
2881 if (Phi != SIUse)
2882 Phi->addIncoming(Phi->getIncomingValueForBlock(Pred), NewBB);
2883}
2884
2886 PHINode *CondPHI = dyn_cast<PHINode>(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);
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>(Pred->getTerminator());
2902 if (!PredTerm)
2903 continue;
2904
2905 unfoldSelectInstr(Pred, BB, PredSI, CondPHI, 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.
2925 PHINode *CondLHS = dyn_cast<PHINode>(CondCmp->getOperand(0));
2926 Constant *CondRHS = cast<Constant>(CondCmp->getOperand(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);
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>(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(CondCmp->getPredicate(), SI->getOperand(1),
2949 CondRHS, Pred, BB, CondCmp);
2950 Constant *RHSRes =
2951 LVI->getPredicateOnEdge(CondCmp->getPredicate(), SI->getOperand(2),
2952 CondRHS, Pred, BB, CondCmp);
2953 if ((LHSRes || RHSRes) && LHSRes != RHSRes) {
2954 unfoldSelectInstr(Pred, BB, SI, CondLHS, 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.
2982 // This transform would reduce the quality of msan diagnostics.
2983 // Disable this transform under MemorySanitizer.
2984 if (BB->getParent()->hasFnAttribute(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(BB))
2990 return false;
2991
2992 for (BasicBlock::iterator BI = BB->begin();
2993 PHINode *PN = dyn_cast<PHINode>(BI); ++BI) {
2994 // Look for a Phi having at least one constant incoming value.
2995 if (llvm::all_of(PN->incoming_values(),
2996 [](Value *V) { return !isa<ConstantInt>(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(SI, m_CombineOr(m_LogicalAnd(), m_LogicalOr()));
3007 return Cond && Cond == V && Cond->getType()->isIntegerTy(1) && !IsAndOr;
3008 };
3009
3010 SelectInst *SI = nullptr;
3011 for (Use &U : PN->uses()) {
3012 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(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>(Cmp->getOperand(1 - U.getOperandNo())))
3017 if (SelectInst *SelectI = dyn_cast<SelectInst>(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>(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(Cond, nullptr, SI)) {
3036 Cond = new FreezeInst(Cond, "cond.fr", SI->getIterator());
3038 }
3039 MDNode *BranchWeights = getBranchWeightMDNode(*SI);
3040 Instruction *Term =
3041 SplitBlockAndInsertIfThen(Cond, SI, false, BranchWeights);
3042 BasicBlock *SplitBB = SI->getParent();
3043 BasicBlock *NewBB = Term->getParent();
3044 PHINode *NewPN = PHINode::Create(SI->getType(), 2, "", SI->getIterator());
3045 NewPN->addIncoming(SI->getTrueValue(), Term->getParent());
3046 NewPN->addIncoming(SI->getFalseValue(), BB);
3047 NewPN->setDebugLoc(SI->getDebugLoc());
3048 SI->replaceAllUsesWith(NewPN);
3049
3050 auto *BPI = getBPI();
3051 auto *BFI = getBFI();
3052 if (!ProfcheckDisableMetadataFixes && BranchWeights) {
3054 [[maybe_unused]] bool Extracted = extractBranchWeights(BranchWeights, BW);
3055 assert(Extracted);
3056 uint64_t Denominator =
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(BW[0], Denominator);
3063 BranchProbability FalseProb =
3064 BranchProbability::getBranchProbability(BW[1], Denominator);
3065 SmallVector<BranchProbability, 2> BP = {TrueProb, FalseProb};
3066
3067 if (BPI)
3068 BPI->setEdgeProbability(BB, BP);
3069
3070 if (BFI) {
3071 auto BBOrigFreq = BFI->getBlockFreq(BB);
3072 auto NewBBFreq = BBOrigFreq * TrueProb;
3073 BFI->setBlockFreq(NewBB, NewBBFreq);
3074 BFI->setBlockFreq(SplitBB, BBOrigFreq);
3075 }
3076 } else {
3078 DEBUG_TYPE);
3079 }
3080 } else {
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((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
3088 Updates.push_back({DominatorTree::Insert, BB, SplitBB});
3089 Updates.push_back({DominatorTree::Insert, BB, NewBB});
3090 Updates.push_back({DominatorTree::Insert, NewBB, SplitBB});
3091 // BB's successors were moved to SplitBB, update DTU accordingly.
3092 for (auto *Succ : successors(SplitBB)) {
3093 Updates.push_back({DominatorTree::Delete, BB, Succ});
3094 Updates.push_back({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.
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>(Parent->getTerminator()))
3145 for (auto &I : *BB)
3146 if (isGuard(&I) && threadGuard(BB, cast<IntrinsicInst>(&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.
3156 CondBrInst *BI) {
3157 Value *GuardCond = Guard->getArgOperand(0);
3158 Value *BranchCond = BI->getCondition();
3159 BasicBlock *TrueDest = BI->getSuccessor(0);
3160 BasicBlock *FalseDest = BI->getSuccessor(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(BranchCond, GuardCond, DL);
3168 if (Impl && *Impl)
3169 TrueDestIsSafe = true;
3170 else {
3171 // False dest is safe if !BranchCond => GuardCond.
3172 Impl = isImpliedCondition(BranchCond, 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, TTI, BB, AfterGuard, 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.
3192 BB, PredGuardedBlock, AfterGuard, GuardedMapping, *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.
3198 BB, PredUnguardedBlock, Guard, UnguardedMapping, *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.
3206 for (auto BI = BB->begin(); &*BI != AfterGuard; ++BI)
3207 if (!isa<PHINode>(&*BI))
3208 ToRemove.push_back(&*BI);
3209
3211 assert(InsertionPoint != BB->end() && "Empty block?");
3212 // Substitute with Phis & remove.
3213 for (auto *Inst : reverse(ToRemove)) {
3214 if (!Inst->use_empty()) {
3215 PHINode *NewPN = PHINode::Create(Inst->getType(), 2);
3216 NewPN->addIncoming(UnguardedMapping[Inst], UnguardedBlock);
3217 NewPN->addIncoming(GuardedMapping[Inst], GuardedBlock);
3218 NewPN->setDebugLoc(Inst->getDebugLoc());
3220 Inst->replaceAllUsesWith(NewPN);
3221 }
3222 Inst->dropDbgRecords();
3223 Inst->eraseFromParent();
3224 }
3225 return true;
3226}
3227
3228PreservedAnalyses JumpThreadingPass::getPreservedAnalysis() const {
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(*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>(*F);
3271 TLI = &FAM->getResult<TargetLibraryAnalysis>(*F);
3272 AA = &FAM->getResult<AAManager>(*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>(*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>(*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}
SDValue Pred
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
Rewrite undef for PHI
ReachingDefInfo InstSet & ToRemove
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
#define DEBUG_TYPE
This is the interface for a simple mod/ref and alias analysis over globals.
#define _
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
This defines the Use class.
static constexpr Value * getValue(Ty &ValueOrUse)
static unsigned getBestDestForJumpOnUndef(BasicBlock *BB)
GetBestDestForBranchOnUndef - If we determine that the specified block ends in an undefined jump,...
static bool replaceFoldableUses(Instruction *Cond, Value *ToVal, BasicBlock *KnownAtEndOfBB)
static unsigned getJumpThreadDuplicationCost(const ScalarOptions &Opts, const TargetTransformInfo *TTI, BasicBlock *BB, Instruction *StopAt, unsigned Threshold)
Return the cost of duplicating a piece of this block from first non-phi and before StopAt instruction...
static void remapSourceAtoms(ValueToValueMapTy &VM, BasicBlock::iterator Begin, BasicBlock::iterator End)
static void addPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, BasicBlock *OldPred, BasicBlock *NewPred, ValueToValueMapTy &ValueMap)
addPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new predecessor to the PHIBB block.
static BasicBlock * findMostPopularDest(BasicBlock *BB, const SmallVectorImpl< std::pair< BasicBlock *, BasicBlock * > > &PredToDestList)
findMostPopularDest - The specified list contains multiple possible threadable destinations.
static Constant * getKnownConstant(Value *Val, ConstantPreference Preference)
getKnownConstant - Helper method to determine if we can thread over a terminator with the given value...
static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB)
Return true if Op is an instruction defined in the given block.
static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB)
static bool hasAddressTakenAndUsed(BasicBlock *BB)
static void registerClonedAssume(Instruction &New, AssumptionCache &AC)
Register New in AC if it is an assume.
See the comments on JumpThreadingPass.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition Lint.cpp:550
#define I(x, y, z)
Definition MD5.cpp:57
This file implements a map that provides insertion order iteration.
This file provides utility analysis objects describing memory locations.
This file contains the declarations for metadata subclasses.
#define T
#define P(N)
ppc ctr loops verify
FunctionAnalysisManager FAM
This file contains the declarations for profiling metadata utility functions.
MachineBasicBlock * Folded
SmallVector< MachineOperand, 4 > Cond
static DominatorTree getDomTree(Function &F)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
This pass exposes codegen information to IR-level passes.
static const uint32_t IV[8]
Definition blake3_impl.h:83
A manager for alias analyses.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator end()
Definition BasicBlock.h:453
iterator begin()
Instruction iterator methods.
Definition BasicBlock.h:440
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
Definition BasicBlock.h:509
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
LLVM_ABI DbgMarker * createMarker(Instruction *I)
Attach a DbgMarker to the given instruction.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches,...
Definition BasicBlock.h:666
InstListType::const_iterator const_iterator
Definition BasicBlock.h:171
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:206
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
LLVM_ABI const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
const Instruction & front() const
Definition BasicBlock.h:463
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this basic block belongs to.
LLVM_ABI DbgMarker * getMarker(InstListType::iterator It)
Return the DbgMarker for the position given by It, so that DbgRecords can be inserted there.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
LLVM_ABI bool isLandingPad() const
Return true if this basic block is a landing pad.
bool isEHPad() const
Return true if this basic block is an exception handling block.
Definition BasicBlock.h:683
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:237
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
void disableDominatorTree()
Disable the use of the dominator tree during alias analysis queries.
The address of a basic block.
Definition Constants.h:1088
static LLVM_ABI BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
Analysis providing branch probability information.
LLVM_ABI BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
uint32_t getNumerator() const
BranchProbability getCompl() const
static void normalizeProbabilities(ProbabilityIter Begin, ProbabilityIter End)
Value * getArgOperand(unsigned i) const
This class represents a function call, abstracting a target machine's calling convention.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
Predicate getPredicate() const
Return the predicate for this instruction.
Definition InstrTypes.h:828
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Conditional Branch instruction.
static CondBrInst * Create(Value *Cond, BasicBlock *IfTrue, BasicBlock *IfFalse, InsertPosition InsertBefore=nullptr)
Value * getCondition() const
BasicBlock * getSuccessor(unsigned i) const
static LLVM_ABI Constant * getNot(Constant *C)
This is the shared class of boolean and integer constants.
Definition Constants.h:87
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Definition Constants.h:225
static LLVM_ABI ConstantInt * getTrue(LLVMContext &Context)
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
Definition Constants.h:219
static LLVM_ABI ConstantInt * getFalse(LLVMContext &Context)
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This class represents a range of values.
LLVM_ABI ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
static LLVM_ABI ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
LLVM_ABI ConstantRange inverse() const
Return a new range that is the logical not of the current set.
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
This is an important base class in LLVM.
Definition Constant.h:44
LLVM_ABI void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Per-instruction record of debug-info.
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(DbgMarker *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere, bool InsertAtHead=false)
Clone all DbgMarkers from From into this marker.
LLVM_ABI BasicBlock * getParent()
Record of a variable value-assignment, aka a non instruction representation of the dbg....
A debug info location.
Definition DebugLoc.h:127
static DebugLoc getTemporary()
Definition DebugLoc.h:153
static DebugLoc getDropped()
Definition DebugLoc.h:156
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition DenseMap.h:827
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
This class represents a freeze function that returns random concrete value if an operand is either a ...
const BasicBlock & getEntryBlock() const
Definition Function.h:803
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
Definition Function.cpp:731
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
This instruction compares its operands according to the predicate given to the constructor.
Indirect Branch Instruction.
LLVM_ABI void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
LLVM_ABI iterator_range< simple_ilist< DbgRecord >::iterator > cloneDebugInfoFrom(const Instruction *From, std::optional< simple_ilist< DbgRecord >::iterator > FromHere=std::nullopt, bool InsertAtHead=false)
Clone any debug-info attached to From onto this instruction.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this instruction belongs to.
bool isSpecialTerminator() const
LLVM_ABI InstListType::iterator insertInto(BasicBlock *ParentBB, InstListType::iterator It)
Inserts an unlinked instruction into ParentBB at position It and returns the iterator of the inserted...
A wrapper class for inspecting calls to intrinsic functions.
LLVM_ABI bool simplifyPartiallyRedundantLoad(LoadInst *LI)
simplifyPartiallyRedundantLoad - If LoadI is an obviously partially redundant load instruction,...
LLVM_ABI bool processBranchOnXOR(BinaryOperator *BO)
processBranchOnXOR - We have an otherwise unthreadable conditional branch on a xor instruction in the...
LLVM_ABI bool processGuards(BasicBlock *BB)
Try to propagate a guard from the current BB into one of its predecessors in case if another branch o...
LLVM_ABI void updateSSA(BasicBlock *BB, BasicBlock *NewBB, ValueToValueMapTy &ValueMapping)
Update the SSA form.
LLVM_ABI void findLoopHeaders(Function &F)
findLoopHeaders - We do not want jump threading to turn proper loop structures into irreducible loops...
LLVM_ABI bool maybeMergeBasicBlockIntoOnlyPred(BasicBlock *BB)
Merge basic block BB into its sole predecessor if possible.
LLVM_ABI bool computeValueKnownInPredecessorsImpl(Value *V, BasicBlock *BB, jumpthreading::PredValueInfo &Result, jumpthreading::ConstantPreference Preference, SmallPtrSet< Value *, 4 > &RecursionSet, Instruction *CtxI=nullptr)
computeValueKnownInPredecessors - Given a basic block BB and a value V, see if we can infer that the ...
LLVM_ABI JumpThreadingPass(int T=-1)
LLVM_ABI void cloneInstructions(ValueToValueMapTy &ValueMapping, BasicBlock::iterator BI, BasicBlock::iterator BE, BasicBlock *NewBB, BasicBlock *PredBB)
Clone instructions in range [BI, BE) to NewBB.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
LLVM_ABI Constant * evaluateOnPredecessorEdge(BasicBlock *BB, BasicBlock *PredPredBB, Value *cond, const DataLayout &DL)
LLVM_ABI bool processBranchOnPHI(PHINode *PN)
processBranchOnPHI - We have an otherwise unthreadable conditional branch on a PHI node (or freeze PH...
LLVM_ABI bool maybethreadThroughTwoBasicBlocks(BasicBlock *BB, Value *Cond)
Attempt to thread through two successive basic blocks.
LLVM_ABI void unfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB, SelectInst *SI, PHINode *SIUse, unsigned Idx)
DomTreeUpdater * getDomTreeUpdater() const
LLVM_ABI bool runImpl(Function &F, FunctionAnalysisManager *FAM, TargetLibraryInfo *TLI, TargetTransformInfo *TTI, LazyValueInfo *LVI, AAResults *AA, std::unique_ptr< DomTreeUpdater > DTU, BlockFrequencyInfo *BFI, BranchProbabilityInfo *BPI)
LLVM_ABI bool processThreadableEdges(Value *Cond, BasicBlock *BB, jumpthreading::ConstantPreference Preference, Instruction *CtxI=nullptr)
LLVM_ABI bool threadGuard(BasicBlock *BB, IntrinsicInst *Guard, CondBrInst *BI)
Try to propagate the guard from BB which is the lower block of a diamond to one of its branches,...
LLVM_ABI bool processBlock(BasicBlock *BB)
processBlock - If there are any predecessors whose control can be threaded through to a successor,...
LLVM_ABI bool processImpliedCondition(BasicBlock *BB)
LLVM_ABI bool duplicateCondBranchOnPHIIntoPred(BasicBlock *BB, const SmallVectorImpl< BasicBlock * > &PredBBs)
duplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch to BB which contains an i1...
LLVM_ABI void threadThroughTwoBasicBlocks(BasicBlock *PredPredBB, BasicBlock *PredBB, BasicBlock *BB, BasicBlock *SuccBB)
LLVM_ABI bool tryThreadEdge(BasicBlock *BB, const SmallVectorImpl< BasicBlock * > &PredBBs, BasicBlock *SuccBB)
tryThreadEdge - Thread an edge if it's safe and profitable to do so.
LLVM_ABI bool tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB)
tryToUnfoldSelect - Look for blocks of the form bb1: a = select br bb2
LLVM_ABI bool tryToUnfoldSelectInCurrBB(BasicBlock *BB)
tryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the same BB in the form bb: p = ...
bool computeValueKnownInPredecessors(Value *V, BasicBlock *BB, jumpthreading::PredValueInfo &Result, jumpthreading::ConstantPreference Preference, Instruction *CtxI=nullptr)
LLVM_ABI void threadEdge(BasicBlock *BB, const SmallVectorImpl< BasicBlock * > &PredBBs, BasicBlock *SuccBB)
threadEdge - We have decided that it is safe and profitable to factor the blocks in PredBBs to one pr...
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Analysis to compute lazy value information.
This pass computes, caches, and vends lazy value constraint information.
An instruction for reading from memory.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
bool isUnordered() const
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
LoadStoreInstProperties getProperties() const
Returns the properties of this load instruction.
Align getAlign() const
Return the alignment of the access that is being performed.
static LocationSize precise(uint64_t Value)
Metadata node.
Definition Metadata.h:1087
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
Representation for a specific memory location.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
void setIncomingValue(unsigned i, Value *V)
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:133
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition SSAUpdater.h:39
LLVM_ABI void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
LLVM_ABI void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
LLVM_ABI void UpdateDebugValues(Instruction *I)
Rewrite debug value intrinsics to conform to a new SSA form.
LLVM_ABI void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
This class represents the LLVM 'select' instruction.
size_type size() const
bool erase(PtrType Ptr)
Remove pointer from the set.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition SmallSet.h:134
std::pair< const_iterator, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Definition SmallSet.h:184
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Multiway switch.
Analysis pass providing the TargetTransformInfo.
Analysis pass providing the TargetLibraryInfo.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
@ TCK_SizeAndLatency
The weighted sum of size and latency.
@ TCC_Free
Expected to fold away in lowering.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:283
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
'undef' values are things that do not have specified contents.
Definition Constants.h:1657
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
void setOperand(unsigned i, Value *Val)
Definition User.h:212
Value * getOperand(unsigned i) const
Definition User.h:207
See the file comment.
Definition ValueMap.h:84
iterator find(const KeyT &Val)
Definition ValueMap.h:160
iterator end()
Definition ValueMap.h:139
ValueMapIteratorImpl< MapT, const Value *, false > iterator
Definition ValueMap.h:135
DMAtomT AtomMap
Map {(InlinedAt, old atom number) -> new atom number}.
Definition ValueMap.h:123
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
LLVM_ABI const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
Definition Value.cpp:1117
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
bool use_empty() const
Definition Value.h:348
iterator_range< use_iterator > uses()
Definition Value.h:382
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
Definition Value.cpp:395
const ParentTy * getParent() const
Definition ilist_node.h:34
reverse_self_iterator getReverseIterator()
Definition ilist_node.h:126
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
LLVM_ABI Function * getDeclarationIfExists(const Module *M, ID id)
Look up the Function declaration of the intrinsic id in the Module M and return it if it exists.
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Constant()
Match an arbitrary Constant and ignore it.
auto m_LogicalOr()
Matches L || R where L and R are arbitrary values.
auto m_LogicalAnd()
Matches L && R where L and R are arbitrary values.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
A private "module" namespace for types and utilities used by JumpThreading.
SmallVector< std::pair< Constant *, BasicBlock * >, 8 > PredValueInfoTy
SmallVectorImpl< std::pair< Constant *, BasicBlock * > > PredValueInfo
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI bool RemoveRedundantDbgInstrs(BasicBlock *BB)
Try to remove redundant dbg.value instructions from given basic block.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
Definition Local.cpp:133
InstructionCost Cost
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
auto pred_end(const MachineBasicBlock *BB)
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
LLVM_ABI unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
Definition Local.cpp:3324
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
auto successors(const MachineBasicBlock *BB)
LLVM_ABI Constant * ConstantFoldInstruction(const Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
constexpr from_range_t from_range
LLVM_ABI MDNode * getBranchWeightMDNode(const Instruction &I)
Get the branch weights metadata node.
LLVM_ABI void remapDebugVariable(ValueToValueMapTy &Mapping, Instruction *Inst)
Remap the operands of the debug records attached to Inst, and the operands of Inst itself if it's a d...
Definition Local.cpp:3555
auto pred_size(const MachineBasicBlock *BB)
LLVM_ABI bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Definition Local.cpp:715
LLVM_ABI void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, bool KeepOneInputPHIs=false)
Delete the specified block, which must have no predecessors.
LLVM_ABI Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
Definition Loads.cpp:554
const ScalarOptions & getScalarOptions(const LLVMContext &C)
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI bool hasBranchWeightOrigin(const Instruction &I)
Check if Branch Weight Metadata has an "expected" field from an llvm.expect* intrinsic.
LLVM_ABI BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
auto map_range(ContainerTy &&C, FuncTy F)
Return a range that applies F to the elements of C.
Definition STLExtras.h:366
LLVM_ABI Value * simplifyInstruction(Instruction *I, const SimplifyQuery &Q)
See if we can compute a simplified version of this instruction.
LLVM_ABI void setBranchWeights(Instruction &I, ArrayRef< uint32_t > Weights, bool IsExpected, bool ElideAllZero=false)
Create a new branch_weights metadata node and add or overwrite a prof metadata reference to instructi...
LLVM_ABI Constant * ConstantFoldCompareInstOperands(unsigned Predicate, Constant *LHS, Constant *RHS, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr, const Function *CtxF=nullptr)
Attempt to constant fold a compare instruction (icmp/fcmp) with the specified operands.
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition Local.cpp:408
constexpr detail::StaticCastFunc< To > StaticCastTo
Function objects corresponding to the Cast types defined above.
Definition Casting.h:882
LLVM_ABI bool isGuard(const User *U)
Returns true iff U has semantics of a guard expressed in a form of call of llvm.experimental....
LLVM_ABI bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes,...
Definition Local.cpp:1185
LLVM_ABI bool HasLoopOrEntryConvergenceToken(const BasicBlock *BB)
Check if the given basic block contains any loop or entry convergent intrinsic instructions.
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
LLVM_ABI bool hasValidBranchWeightMD(const Instruction &I)
Checks if an instructions has valid Branch Weight Metadata.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
auto make_first_range(ContainerTy &&c)
Given a container of pairs, return a range over the first elements.
Definition STLExtras.h:1415
LLVM_ABI Constant * ConstantFoldCastOperand(unsigned Opcode, Constant *C, Type *DestTy, const DataLayout &DL)
Attempt to constant fold a cast with the specified operand.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI void cloneNoAliasScopes(ArrayRef< MDNode * > NoAliasDeclScopes, DenseMap< MDNode *, MDNode * > &ClonedScopes, DenseMap< const MDNode *, MDNode * > &ClonedDomains, StringRef Ext, LLVMContext &Context)
Duplicate the specified list of noalias decl scopes.
LLVM_ABI void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock * > Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock * > &NewBBs, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3186
LLVM_ABI BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock * > Preds, const char *Suffix, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
TargetTransformInfo TTI
LLVM_ABI void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!...
Definition Local.cpp:755
LLVM_ABI bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false, DominatorTree *DT=nullptr)
Attempts to merge a block into its predecessor, if possible.
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2068
DWARFExpression::Operation Op
auto max_element(R &&Range)
Provide wrappers to std::max_element which take ranges instead of having to pass begin/end explicitly...
Definition STLExtras.h:2104
LLVM_ABI bool isGuaranteedNotToBeUndefOrPoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Return true if this function can prove that V does not have undef bits and is never poison.
auto make_second_range(ContainerTy &&c)
Given a container of pairs, return a range over the second elements.
Definition STLExtras.h:1425
auto sum_of(R &&Range, E Init=E{0})
Returns the sum of all values in Range with Init initial value.
Definition STLExtras.h:1733
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
auto pred_begin(const MachineBasicBlock *BB)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition STLExtras.h:2210
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI void adaptNoAliasScopes(llvm::Instruction *I, DenseMap< MDNode *, MDNode * > &ClonedScopes, const DenseMap< const MDNode *, MDNode * > &ClonedDomains, StringRef Ext, LLVMContext &Context)
Adapt the metadata for the specified instruction according to the provided mapping.
LLVM_ABI Instruction * SplitBlockAndInsertIfThen(Value *Cond, BasicBlock::iterator SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, BasicBlock *ThenBlock=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
LLVM_ABI Value * simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
Definition STLExtras.h:1612
LLVM_ABI void identifyNoAliasScopesToClone(ArrayRef< BasicBlock * > BBs, SmallVectorImpl< MDNode * > &NoAliasDeclScopes)
Find the 'llvm.experimental.noalias.scope.decl' intrinsics in the specified basic blocks and extract ...
LLVM_ABI BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the edge connecting the specified blocks, and return the newly created basic block between From...
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
AAResults AliasAnalysis
Temporary typedef for legacy code that uses a generic AliasAnalysis pointer or reference.
LLVM_ABI Value * findAvailablePtrLoadStore(const MemoryLocation &Loc, Type *AccessTy, const LoadStoreInstProperties &AccessProps, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan, BatchAAResults *AA, bool *IsLoadCSE, unsigned *NumScanedInst)
Scan backwards to see if we have the value of the given pointer available locally within a small numb...
Definition Loads.cpp:715
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI void FindFunctionBackedges(const Function &F, SmallVectorImpl< std::pair< const BasicBlock *, const BasicBlock * > > &Result)
Analyze the specified function to find all of the loop backedges in the function and return them.
Definition CFG.cpp:36
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
LLVM_ABI std::optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
LLVM_ABI void mapAtomInstance(const DebugLoc &DL, ValueToValueMapTy &VMap)
Mark a cloned instruction as a new instance so that its source loc can be updated when remapped.
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition Metadata.h:775
Function object to check whether the second component of a container supported by std::get (like std:...
Definition STLExtras.h:1464