LLVM 22.0.0git
JumpThreading.h
Go to the documentation of this file.
1//===- JumpThreading.h - thread control through conditional BBs -*- C++ -*-===//
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/// \file
10/// See the comments on JumpThreadingPass.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_SCALAR_JUMPTHREADING_H
15#define LLVM_TRANSFORMS_SCALAR_JUMPTHREADING_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/SmallSet.h"
24#include "llvm/IR/ValueHandle.h"
27#include <optional>
28#include <utility>
29
30namespace llvm {
31
32class AAResults;
33class BasicBlock;
34class BinaryOperator;
35class BranchInst;
36class CmpInst;
37class Constant;
38class Function;
39class Instruction;
40class IntrinsicInst;
41class LazyValueInfo;
42class LoadInst;
43class PHINode;
44class SelectInst;
45class SwitchInst;
46class TargetLibraryInfo;
47class TargetTransformInfo;
48class Value;
49
50/// A private "module" namespace for types and utilities used by
51/// JumpThreading.
52/// These are implementation details and should not be used by clients.
53namespace jumpthreading {
54
55// These are at global scope so static functions can use them too.
58
59// This is used to keep track of what kind of constant we're currently hoping
60// to find.
62
63} // end namespace jumpthreading
64
65/// This pass performs 'jump threading', which looks at blocks that have
66/// multiple predecessors and multiple successors. If one or more of the
67/// predecessors of the block can be proven to always jump to one of the
68/// successors, we forward the edge from the predecessor to the successor by
69/// duplicating the contents of this block.
70///
71/// An example of when this can occur is code like this:
72///
73/// if () { ...
74/// X = 4;
75/// }
76/// if (X < 3) {
77///
78/// In this case, the unconditional branch at the end of the first if can be
79/// revectored to the false side of the second if.
80class JumpThreadingPass : public PassInfoMixin<JumpThreadingPass> {
81 Function *F = nullptr;
82 FunctionAnalysisManager *FAM = nullptr;
83 TargetLibraryInfo *TLI = nullptr;
84 TargetTransformInfo *TTI = nullptr;
85 LazyValueInfo *LVI = nullptr;
86 AAResults *AA = nullptr;
87 std::unique_ptr<DomTreeUpdater> DTU;
88 BlockFrequencyInfo *BFI = nullptr;
89 BranchProbabilityInfo *BPI = nullptr;
90 bool ChangedSinceLastAnalysisUpdate = false;
91 bool HasGuards = false;
92#ifndef LLVM_ENABLE_ABI_BREAKING_CHECKS
94#else
96#endif
97
98 // JumpThreading must not processes blocks unreachable from entry. It's a
99 // waste of compute time and can potentially lead to hangs.
101
102 unsigned BBDupThreshold;
103 unsigned DefaultBBDupThreshold;
104
105public:
106 LLVM_ABI JumpThreadingPass(int T = -1);
107
108 // Glue for old PM.
111 LazyValueInfo *LVI, AAResults *AA,
112 std::unique_ptr<DomTreeUpdater> DTU,
114
116
117 DomTreeUpdater *getDomTreeUpdater() const { return DTU.get(); }
121 LLVM_ABI void updateSSA(BasicBlock *BB, BasicBlock *NewBB,
122 ValueToValueMapTy &ValueMapping);
126 BasicBlock *PredBB);
128 const SmallVectorImpl<BasicBlock *> &PredBBs,
129 BasicBlock *SuccBB);
131 const SmallVectorImpl<BasicBlock *> &PredBBs,
132 BasicBlock *SuccBB);
134 BasicBlock *BB, const SmallVectorImpl<BasicBlock *> &PredBBs);
135
139 SmallPtrSet<Value *, 4> &RecursionSet, Instruction *CxtI = nullptr);
140 bool
144 Instruction *CxtI = nullptr) {
145 SmallPtrSet<Value *, 4> RecursionSet;
146 return computeValueKnownInPredecessorsImpl(V, BB, Result, Preference,
147 RecursionSet, CxtI);
148 }
149
151 BasicBlock *PredPredBB,
152 Value *cond,
153 const DataLayout &DL);
156 BasicBlock *PredBB, BasicBlock *BB,
157 BasicBlock *SuccBB);
158 LLVM_ABI bool
161 Instruction *CxtI = nullptr);
162
166
169 SelectInst *SI, PHINode *SIUse, unsigned Idx);
170
171 LLVM_ABI bool tryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB);
174
177 BranchInst *BI);
178
179private:
180 BasicBlock *splitBlockPreds(BasicBlock *BB, ArrayRef<BasicBlock *> Preds,
181 const char *Suffix);
182 void updateBlockFreqAndEdgeWeight(BasicBlock *PredBB, BasicBlock *BB,
183 BasicBlock *NewBB, BasicBlock *SuccBB,
186 bool HasProfile);
187 /// Check if the block has profile metadata for its outgoing edges.
188 bool doesBlockHaveProfileData(BasicBlock *BB);
189
190 /// Returns analysis preserved by the pass.
191 PreservedAnalyses getPreservedAnalysis() const;
192
193 /// Helper function to run "external" analysis in the middle of JumpThreading.
194 /// It takes care of updating/invalidating other existing analysis
195 /// before/after running the "external" one.
196 template <typename AnalysisT>
197 typename AnalysisT::Result *runExternalAnalysis();
198
199 /// Returns an existing instance of BPI if any, otherwise nullptr. By
200 /// "existing" we mean either cached result provided by FunctionAnalysisManger
201 /// or created by preceding call to 'getOrCreateBPI'.
202 BranchProbabilityInfo *getBPI();
203
204 /// Returns an existing instance of BFI if any, otherwise nullptr. By
205 /// "existing" we mean either cached result provided by FunctionAnalysisManger
206 /// or created by preceding call to 'getOrCreateBFI'.
207 BlockFrequencyInfo *getBFI();
208
209 /// Returns an existing instance of BPI if any, otherwise:
210 /// if 'HasProfile' is true creates new instance through
211 /// FunctionAnalysisManager, otherwise nullptr.
212 BranchProbabilityInfo *getOrCreateBPI(bool Force = false);
213
214 /// Returns an existing instance of BFI if any, otherwise:
215 /// if 'HasProfile' is true creates new instance through
216 /// FunctionAnalysisManager, otherwise nullptr.
217 BlockFrequencyInfo *getOrCreateBFI(bool Force = false);
218
219 // Internal overload of evaluateOnPredecessorEdge().
221 Value *cond, const DataLayout &DL,
222 SmallPtrSet<Value *, 8> &Visited);
223};
224
225} // end namespace llvm
226
227#endif // LLVM_TRANSFORMS_SCALAR_JUMPTHREADING_H
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define LLVM_ABI
Definition: Compiler.h:213
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
This file defines the DenseSet and SmallDenseSet classes.
#define F(x, y, z)
Definition: MD5.cpp:55
FunctionAnalysisManager FAM
const SmallVectorImpl< MachineOperand > & Cond
This file defines the SmallSet class.
This file defines the SmallVector class.
A private abstract base class describing the concept of an individual alias analysis implementation.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:255
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:62
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:170
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
Conditional or Unconditional Branch instruction.
Analysis providing branch probability information.
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:666
This is an important base class in LLVM.
Definition: Constant.h:43
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:49
This pass performs 'jump threading', which looks at blocks that have multiple predecessors and multip...
Definition: JumpThreading.h:80
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.
bool computeValueKnownInPredecessors(Value *V, BasicBlock *BB, jumpthreading::PredValueInfo &Result, jumpthreading::ConstantPreference Preference, Instruction *CxtI=nullptr)
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 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 bool computeValueKnownInPredecessorsImpl(Value *V, BasicBlock *BB, jumpthreading::PredValueInfo &Result, jumpthreading::ConstantPreference Preference, SmallPtrSet< Value *, 4 > &RecursionSet, Instruction *CxtI=nullptr)
computeValueKnownInPredecessors - Given a basic block BB and a value V, see if we can infer that the ...
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 *CxtI=nullptr)
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 = ...
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...
LLVM_ABI bool threadGuard(BasicBlock *BB, IntrinsicInst *Guard, BranchInst *BI)
Try to propagate the guard from BB which is the lower block of a diamond to one of its branches,...
This pass computes, caches, and vends lazy value constraint information.
Definition: LazyValueInfo.h:32
An instruction for reading from memory.
Definition: Instructions.h:180
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:112
This class represents the LLVM 'select' instruction.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:541
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
Definition: SmallSet.h:134
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:574
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
Multiway switch.
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.
LLVM Value Representation.
Definition: Value.h:75
@ BasicBlock
Various leaf nodes.
Definition: ISDOpcodes.h:81
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
A CRTP mix-in to automatically provide informational APIs needed for passes.
Definition: PassManager.h:70