LLVM 24.0.0git
JumpTableToSwitch.cpp
Go to the documentation of this file.
1//===- JumpTableToSwitch.cpp ----------------------------------------------===//
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
10#include "ScalarOptions.h"
11#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/Statistic.h"
16#include "llvm/Analysis/Loads.h"
19#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/LLVMContext.h"
24#include <limits>
25
26using namespace llvm;
27
28#define DEBUG_TYPE "jump-table-to-switch"
29
30STATISTIC(NumEligibleJumpTables, "The number of jump tables seen by the pass "
31 "that can be converted if deemed profitable.");
32STATISTIC(NumJumpTablesConverted,
33 "The number of jump tables converted into switches.");
34
35namespace {
36struct JumpTable {
37 Value *Index;
39};
40} // anonymous namespace
41
42static Function *getExpandableCallee(const ScalarOptions &Opts, Value *V,
43 FunctionType *CallFTy) {
44 auto *Func = dyn_cast<Function>(V);
45 if (!Func || Func->isDeclaration() || Func->getFunctionType() != CallFTy ||
46 Func->getInstructionCount() >
47 Opts.jump_table_to_switch_function_size_threshold)
48 return nullptr;
49 return Func;
50}
51
52static std::optional<JumpTable> parseJumpTable(const ScalarOptions &Opts,
53 LoadInst *LI, PointerType *PtrTy,
54 FunctionType *CallFTy,
55 IRBuilderBase &Builder) {
56 std::optional<ConstGlobalLoad> GlobalLoad = ConstGlobalLoad::fromLoadInst(LI);
57 if (!GlobalLoad)
58 return std::nullopt;
59
60 ++NumEligibleJumpTables;
61
62 uint64_t N = GlobalLoad->getElementCount();
63 if (N > Opts.jump_table_to_switch_size_threshold)
64 return std::nullopt;
65
66 Function &F = *LI->getParent()->getParent();
67
69 Funcs.reserve(N);
70
71 for (uint64_t Index = 0; Index < N; ++Index) {
72 Constant *C = GlobalLoad->getElementAt(Index);
73 if (!C)
74 return std::nullopt;
76 !NullPointerIsDefined(&F, PtrTy->getAddressSpace())) ||
78 continue;
79 Function *Func = getExpandableCallee(Opts, C, CallFTy);
80 if (!Func)
81 return std::nullopt;
82 Funcs.push_back({Index, Func});
83 }
84 // Empty table, or only values that are UB when called
85 if (Funcs.empty())
86 return std::nullopt;
87
88 return JumpTable{GlobalLoad->buildCanonicalIndex(Builder), std::move(Funcs)};
89}
90
91static BasicBlock *
95 GetGuidForFunction) {
96 ++NumJumpTablesConverted;
97 const bool IsVoid = CB->getType() == Type::getVoidTy(CB->getContext());
98
100 BasicBlock *BB = CB->getParent();
101 BasicBlock *Tail = SplitBlock(BB, CB, &DTU, nullptr, nullptr,
102 BB->getName() + Twine(".tail"));
103 DTUpdates.push_back({DominatorTree::Delete, BB, Tail});
105
106 Function &F = *BB->getParent();
107 BasicBlock *BBUnreachable = BasicBlock::Create(
108 F.getContext(), "default.switch.case.unreachable", &F, Tail);
109 IRBuilder<> BuilderUnreachable(BBUnreachable);
110 BuilderUnreachable.CreateUnreachable();
111
112 IRBuilder<> Builder(BB);
113 SwitchInst *Switch = Builder.CreateSwitch(JT.Index, BBUnreachable);
114 DTUpdates.push_back({DominatorTree::Insert, BB, BBUnreachable});
115
116 IRBuilder<> BuilderTail(CB);
117 PHINode *PHI =
118 IsVoid ? nullptr : BuilderTail.CreatePHI(CB->getType(), JT.Funcs.size());
119 const auto *ProfMD = CB->getMetadata(LLVMContext::MD_prof);
120
121 SmallVector<uint64_t> BranchWeights;
123 const bool HadProfile = isValueProfileMD(ProfMD);
124 if (HadProfile) {
125 // The assumptions, coming in, are that the functions in JT.Funcs are
126 // defined in this module (from parseJumpTable).
127 assert(llvm::all_of(JT.Funcs, [](auto &F) {
128 return F.second && !F.second->isDeclaration();
129 }));
130 BranchWeights.reserve(JT.Funcs.size() + 1);
131 // The first is the default target, which is the unreachable block created
132 // above.
133 BranchWeights.push_back(0U);
134 uint64_t TotalCount = 0;
135 auto Targets = getValueProfDataFromInst(
136 *CB, InstrProfValueKind::IPVK_IndirectCallTarget,
137 std::numeric_limits<uint32_t>::max(), TotalCount);
138
139 for (const auto &[G, C] : Targets) {
140 [[maybe_unused]] auto It = GuidToCounter.insert({G, C});
141 // We should always be inserting as it is verifier-enforced IR invariant
142 // that VP metadata does not have duplicate values.
143 assert(It.second);
144 }
145 }
146 for (auto [Index, Func] : JT.Funcs) {
147 BasicBlock *B = BasicBlock::Create(Func->getContext(),
148 "call." + Twine(Index), &F, Tail);
149 DTUpdates.push_back({DominatorTree::Insert, BB, B});
150 DTUpdates.push_back({DominatorTree::Insert, B, Tail});
151
153 // The MD_prof metadata (VP kind), if it existed, can be dropped, it doesn't
154 // make sense on a direct call. Note that the values are used for the branch
155 // weights of the switch.
156 Call->setMetadata(LLVMContext::MD_prof, nullptr);
157 Call->setCalledFunction(Func);
158 Call->insertInto(B, B->end());
159 Switch->addCase(
160 cast<ConstantInt>(ConstantInt::get(JT.Index->getType(), Index)), B);
161 GlobalValue::GUID FctID = GetGuidForFunction(*Func);
162 // It'd be OK to _not_ find target functions in GuidToCounter, e.g. suppose
163 // just some of the jump targets are taken (for the given profile).
164 BranchWeights.push_back(FctID == 0U ? 0U
165 : GuidToCounter.lookup_or(FctID, 0U));
166 UncondBrInst::Create(Tail, B);
167 if (PHI)
168 PHI->addIncoming(Call, B);
169 }
170 DTU.applyUpdates(DTUpdates);
171 ORE.emit([&]() {
172 return OptimizationRemark(DEBUG_TYPE, "ReplacedJumpTableWithSwitch", CB)
173 << "expanded indirect call into switch";
174 });
176 SmallVector<uint32_t, 2> SelectWeights;
177 // Only set branch weights on the switch if we have non-zero branch weights.
178 // We can have no non-zero branch weights while having VP metadata if for
179 // example, all of the functions are external and not instrumented.
180 if (HadProfile && llvm::any_of(BranchWeights, not_equal_to(0))) {
181 setBranchWeights(*Switch, downscaleWeights(BranchWeights),
182 /*IsExpected=*/false);
183 } else if (Select && extractBranchWeights(*Select, SelectWeights) &&
184 llvm::any_of(SelectWeights, not_equal_to(0))) {
185 // Switch branches:
186 // - default (never taken)
187 // - 0: false case (branch 1) of select
188 // - 1: true case (branch 0) of select
189 setBranchWeights(*Switch, {0, SelectWeights[1], SelectWeights[0]},
190 /*IsExpected=*/false);
191 } else
193 if (PHI)
195 CB->eraseFromParent();
196 return Tail;
197}
198
205 DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
206 const ScalarOptions &Opts = getScalarOptions(F);
207 bool Changed = false;
208 auto FuncToGuid = [&](const Function &Fct) {
209 if (const auto MaybeGUID = Fct.getGUIDIfAssigned(); MaybeGUID)
210 return *MaybeGUID;
211
213 getIRPGOObjectName(Fct, InLTO));
214 };
215
216 for (BasicBlock &BB : make_early_inc_range(F)) {
217 BasicBlock *CurrentBB = &BB;
218 while (CurrentBB) {
219 BasicBlock *SplittedOutTail = nullptr;
220 for (Instruction &I : make_early_inc_range(*CurrentBB)) {
221 auto *Call = dyn_cast<CallInst>(&I);
222 if (!Call || Call->getCalledFunction() || Call->isMustTailCall())
223 continue;
224 std::optional<JumpTable> JT;
225 if (auto *S = dyn_cast<SelectInst>(Call->getCalledOperand())) {
226 Function *F0 = getExpandableCallee(Opts, S->getFalseValue(),
227 Call->getFunctionType());
228 if (!F0)
229 continue;
230 Function *F1 = getExpandableCallee(Opts, S->getTrueValue(),
231 Call->getFunctionType());
232 if (!F1)
233 continue;
234 JT = JumpTable();
235 JT->Index = S->getCondition();
236 JT->Funcs.push_back({0, F0});
237 JT->Funcs.push_back({1, F1});
238 } else if (auto *L = dyn_cast<LoadInst>(Call->getCalledOperand())) {
239 if (!L)
240 continue;
241 auto *PtrTy = dyn_cast<PointerType>(L->getType());
242 assert(PtrTy && "call operand must be a pointer");
243 IRBuilder<> Builder(Call);
244 JT = parseJumpTable(Opts, L, PtrTy, Call->getFunctionType(), Builder);
245 }
246 if (!JT)
247 continue;
248 SplittedOutTail = expandToSwitch(Call, *JT, DTU, ORE, FuncToGuid);
249 Changed = true;
250 break;
251 }
252 CurrentBB = SplittedOutTail ? SplittedOutTail : nullptr;
253 }
254 }
255
256 if (!Changed)
257 return PreservedAnalyses::all();
258
260 if (DT)
262 if (PDT)
264 return PA;
265}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
AMDGPU Register Bank Select
Rewrite undef for PHI
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define DEBUG_TYPE
static Function * getExpandableCallee(const ScalarOptions &Opts, Value *V, FunctionType *CallFTy)
static std::optional< JumpTable > parseJumpTable(const ScalarOptions &Opts, LoadInst *LI, PointerType *PtrTy, FunctionType *CallFTy, IRBuilderBase &Builder)
static BasicBlock * expandToSwitch(CallBase *CB, const JumpTable &JT, DomTreeUpdater &DTU, OptimizationRemarkEmitter &ORE, llvm::function_ref< GlobalValue::GUID(const Function &)> GetGuidForFunction)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This file contains the declarations for profiling metadata utility functions.
This file contains some templates that are useful if you are working with the STL at all.
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:170
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
Definition BasicBlock.h:205
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Definition BasicBlock.h:236
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Value * getCalledOperand() const
static LLVM_ABI std::optional< ConstGlobalLoad > fromLoadInst(LoadInst *LI)
Analyze a load instruction to a linear expression that loads from a constant global.
Definition Loads.cpp:1073
This is an important base class in LLVM.
Definition Constant.h:44
ValueT lookup_or(const_arg_type_t< KeyT > Val, U &&Default) const
Definition DenseMap.h:803
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
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
UnreachableInst * CreateUnreachable()
Definition IRBuilder.h:1360
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2626
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
LLVM_ABI Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
An instruction for reading from memory.
The optimization diagnostic interface.
LLVM_ABI void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file.
Diagnostic information for applied optimization remarks.
Analysis pass which computes a PostDominatorTree.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
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:132
void reserve(size_type N)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Multiway switch.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
static LLVM_ABI Type * getVoidTy(LLVMContext &C)
Definition Type.cpp:267
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
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 void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:260
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
CallInst * Call
This is an optimization pass for GlobalISel generic memory operations.
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
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
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:649
LLVM_ABI std::string getIRPGOObjectName(const GlobalObject &GO, bool InLTO=false)
const ScalarOptions & getScalarOptions(const LLVMContext &C)
LLVM_ABI void setExplicitlyUnknownBranchWeights(Instruction &I, StringRef PassName)
Specify that the branch weights for this terminator cannot be known at compile time.
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...
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 NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
LLVM_ABI SmallVector< InstrProfValueData, 4 > getValueProfDataFromInst(const Instruction &Inst, InstrProfValueKind ValueKind, uint32_t MaxNumValueData, uint64_t &TotalC, bool GetNoICPValue=false)
Extract the value profile data from Inst and returns them if Inst is annotated with value profile dat...
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 bool isValueProfileMD(const MDNode *ProfileData)
Checks if an MDNode contains value profiling Metadata.
LLVM_ABI BasicBlock * SplitBlock(BasicBlock *Old, BasicBlock::iterator SplitPt, DominatorTree *DT, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, const Twine &BBName="")
Split the specified block at the specified instruction.
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI SmallVector< uint32_t > downscaleWeights(ArrayRef< uint64_t > Weights, std::optional< uint64_t > KnownMaxCount=std::nullopt)
downscale the given weights preserving the ratio.
#define N