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
9#include "llvm/Transforms/Scalar/JumpTableToSwitch.h"
10#include "llvm/ADT/STLExtras.h"
11#include "llvm/ADT/SmallVector.h"
12#include "llvm/ADT/Statistic.h"
13#include "llvm/Analysis/ConstantFolding.h"
14#include "llvm/Analysis/DomTreeUpdater.h"
15#include "llvm/Analysis/OptimizationRemarkEmitter.h"
16#include "llvm/Analysis/PostDominators.h"
17#include "llvm/IR/IRBuilder.h"
18#include "llvm/IR/LLVMContext.h"
19#include "llvm/IR/ProfDataUtils.h"
20#include "llvm/ProfileData/InstrProf.h"
21#include "llvm/Support/CommandLine.h"
22#include "llvm/Transforms/Utils/BasicBlockUtils.h"
23#include <limits>
24
25using namespace llvm;
26
27static cl::opt<unsigned>
28 JumpTableSizeThreshold("jump-table-to-switch-size-threshold", cl::Hidden,
29 cl::desc("Only split jump tables with size less or "
30 "equal than JumpTableSizeThreshold."),
31 cl::init(Val: 10));
32
33// TODO: Consider adding a cost model for profitability analysis of this
34// transformation. Currently we replace a jump table with a switch if all the
35// functions in the jump table are smaller than the provided threshold.
36static cl::opt<unsigned> FunctionSizeThreshold(
37 "jump-table-to-switch-function-size-threshold", cl::Hidden,
38 cl::desc("Only split jump tables containing functions whose sizes are less "
39 "or equal than this threshold."),
40 cl::init(Val: 50));
41
42namespace llvm {
43extern cl::opt<bool> ProfcheckDisableMetadataFixes;
44} // end namespace llvm
45
46#define DEBUG_TYPE "jump-table-to-switch"
47
48STATISTIC(NumEligibleJumpTables, "The number of jump tables seen by the pass "
49 "that can be converted if deemed profitable.");
50STATISTIC(NumJumpTablesConverted,
51 "The number of jump tables converted into switches.");
52
53namespace {
54struct JumpTableTy {
55 Value *Index;
56 SmallVector<Function *, 10> Funcs;
57};
58} // anonymous namespace
59
60static std::optional<JumpTableTy> parseJumpTable(GetElementPtrInst *GEP,
61 PointerType *PtrTy,
62 FunctionType *CallFTy) {
63 Constant *Ptr = dyn_cast<Constant>(Val: GEP->getPointerOperand());
64 if (!Ptr)
65 return std::nullopt;
66
67 GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: Ptr);
68 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer())
69 return std::nullopt;
70
71 Function &F = *GEP->getParent()->getParent();
72 const DataLayout &DL = F.getDataLayout();
73 const unsigned BitWidth =
74 DL.getIndexSizeInBits(AS: GEP->getPointerAddressSpace());
75 SmallMapVector<Value *, APInt, 4> VariableOffsets;
76 APInt ConstantOffset(BitWidth, 0);
77 if (!GEP->collectOffset(DL, BitWidth, VariableOffsets, ConstantOffset))
78 return std::nullopt;
79 if (VariableOffsets.size() != 1)
80 return std::nullopt;
81 // TODO: consider supporting more general patterns
82 if (!ConstantOffset.isZero())
83 return std::nullopt;
84 APInt StrideBytes = VariableOffsets.front().second;
85 const uint64_t JumpTableSizeBytes = GV->getGlobalSize(DL);
86 if (JumpTableSizeBytes % StrideBytes.getZExtValue() != 0)
87 return std::nullopt;
88 ++NumEligibleJumpTables;
89 const uint64_t N = JumpTableSizeBytes / StrideBytes.getZExtValue();
90 if (N > JumpTableSizeThreshold)
91 return std::nullopt;
92
93 JumpTableTy JumpTable;
94 JumpTable.Index = VariableOffsets.front().first;
95 JumpTable.Funcs.reserve(N);
96 for (uint64_t Index = 0; Index < N; ++Index) {
97 // ConstantOffset is zero.
98 APInt Offset = Index * StrideBytes;
99 Constant *C =
100 ConstantFoldLoadFromConst(C: GV->getInitializer(), Ty: PtrTy, Offset, DL);
101 auto *Func = dyn_cast_or_null<Function>(Val: C);
102 if (!Func || Func->isDeclaration() || Func->getFunctionType() != CallFTy ||
103 Func->getInstructionCount() > FunctionSizeThreshold)
104 return std::nullopt;
105 JumpTable.Funcs.push_back(Elt: Func);
106 }
107 return JumpTable;
108}
109
110static BasicBlock *
111expandToSwitch(CallBase *CB, const JumpTableTy &JT, DomTreeUpdater &DTU,
112 OptimizationRemarkEmitter &ORE,
113 llvm::function_ref<GlobalValue::GUID(const Function &)>
114 GetGuidForFunction) {
115 ++NumJumpTablesConverted;
116 const bool IsVoid = CB->getType() == Type::getVoidTy(C&: CB->getContext());
117
118 SmallVector<DominatorTree::UpdateType, 8> DTUpdates;
119 BasicBlock *BB = CB->getParent();
120 BasicBlock *Tail = SplitBlock(Old: BB, SplitPt: CB, DTU: &DTU, LI: nullptr, MSSAU: nullptr,
121 BBName: BB->getName() + Twine(".tail"));
122 DTUpdates.push_back(Elt: {DominatorTree::Delete, BB, Tail});
123 BB->getTerminator()->eraseFromParent();
124
125 Function &F = *BB->getParent();
126 BasicBlock *BBUnreachable = BasicBlock::Create(
127 Context&: F.getContext(), Name: "default.switch.case.unreachable", Parent: &F, InsertBefore: Tail);
128 IRBuilder<> BuilderUnreachable(BBUnreachable);
129 BuilderUnreachable.CreateUnreachable();
130
131 IRBuilder<> Builder(BB);
132 SwitchInst *Switch = Builder.CreateSwitch(V: JT.Index, Dest: BBUnreachable);
133 DTUpdates.push_back(Elt: {DominatorTree::Insert, BB, BBUnreachable});
134
135 IRBuilder<> BuilderTail(CB);
136 PHINode *PHI =
137 IsVoid ? nullptr : BuilderTail.CreatePHI(Ty: CB->getType(), NumReservedValues: JT.Funcs.size());
138 const auto *ProfMD = CB->getMetadata(KindID: LLVMContext::MD_prof);
139
140 SmallVector<uint64_t> BranchWeights;
141 DenseMap<GlobalValue::GUID, uint64_t> GuidToCounter;
142 const bool HadProfile = isValueProfileMD(ProfileData: ProfMD);
143 if (HadProfile) {
144 // The assumptions, coming in, are that the functions in JT.Funcs are
145 // defined in this module (from parseJumpTable).
146 assert(llvm::all_of(
147 JT.Funcs, [](const Function *F) { return F && !F->isDeclaration(); }));
148 BranchWeights.reserve(N: JT.Funcs.size() + 1);
149 // The first is the default target, which is the unreachable block created
150 // above.
151 BranchWeights.push_back(Elt: 0U);
152 uint64_t TotalCount = 0;
153 auto Targets = getValueProfDataFromInst(
154 Inst: *CB, ValueKind: InstrProfValueKind::IPVK_IndirectCallTarget,
155 MaxNumValueData: std::numeric_limits<uint32_t>::max(), TotalC&: TotalCount);
156
157 for (const auto &[G, C] : Targets) {
158 [[maybe_unused]] auto It = GuidToCounter.insert(KV: {G, C});
159 // We should always be inserting as it is verifier-enforced IR invariant
160 // that VP metadata does not have duplicate values.
161 assert(It.second);
162 }
163 }
164 for (auto [Index, Func] : llvm::enumerate(First: JT.Funcs)) {
165 BasicBlock *B = BasicBlock::Create(Context&: Func->getContext(),
166 Name: "call." + Twine(Index), Parent: &F, InsertBefore: Tail);
167 DTUpdates.push_back(Elt: {DominatorTree::Insert, BB, B});
168 DTUpdates.push_back(Elt: {DominatorTree::Insert, B, Tail});
169
170 CallBase *Call = cast<CallBase>(Val: CB->clone());
171 // The MD_prof metadata (VP kind), if it existed, can be dropped, it doesn't
172 // make sense on a direct call. Note that the values are used for the branch
173 // weights of the switch.
174 Call->setMetadata(KindID: LLVMContext::MD_prof, Node: nullptr);
175 Call->setCalledFunction(Func);
176 Call->insertInto(ParentBB: B, It: B->end());
177 Switch->addCase(
178 OnVal: cast<ConstantInt>(Val: ConstantInt::get(Ty: JT.Index->getType(), V: Index)), Dest: B);
179 GlobalValue::GUID FctID = GetGuidForFunction(*Func);
180 // It'd be OK to _not_ find target functions in GuidToCounter, e.g. suppose
181 // just some of the jump targets are taken (for the given profile).
182 BranchWeights.push_back(Elt: FctID == 0U ? 0U
183 : GuidToCounter.lookup_or(Val: FctID, Default: 0U));
184 UncondBrInst::Create(Target: Tail, InsertBefore: B);
185 if (PHI)
186 PHI->addIncoming(V: Call, BB: B);
187 }
188 DTU.applyUpdates(Updates: DTUpdates);
189 ORE.emit(RemarkBuilder: [&]() {
190 return OptimizationRemark(DEBUG_TYPE, "ReplacedJumpTableWithSwitch", CB)
191 << "expanded indirect call into switch";
192 });
193 // Only set branch weights on the switch if we have non-zero branch weights.
194 // We can have no non-zero branch weights while having VP metadata if for
195 // example, all of the functions are external and not instrumented.
196 if (HadProfile && !ProfcheckDisableMetadataFixes &&
197 llvm::any_of(Range&: BranchWeights, P: not_equal_to(Arg: 0))) {
198 setBranchWeights(I&: *Switch, Weights: downscaleWeights(Weights: BranchWeights),
199 /*IsExpected=*/false);
200 } else
201 setExplicitlyUnknownBranchWeights(I&: *Switch, DEBUG_TYPE);
202 if (PHI)
203 CB->replaceAllUsesWith(V: PHI);
204 CB->eraseFromParent();
205 return Tail;
206}
207
208PreservedAnalyses JumpTableToSwitchPass::run(Function &F,
209 FunctionAnalysisManager &AM) {
210 OptimizationRemarkEmitter &ORE =
211 AM.getResult<OptimizationRemarkEmitterAnalysis>(IR&: F);
212 DominatorTree *DT = AM.getCachedResult<DominatorTreeAnalysis>(IR&: F);
213 PostDominatorTree *PDT = AM.getCachedResult<PostDominatorTreeAnalysis>(IR&: F);
214 DomTreeUpdater DTU(DT, PDT, DomTreeUpdater::UpdateStrategy::Lazy);
215 bool Changed = false;
216 auto FuncToGuid = [&](const Function &Fct) {
217 if (const auto MaybeGUID = Fct.getGUIDIfAssigned(); MaybeGUID)
218 return *MaybeGUID;
219
220 return Function::getGUIDAssumingExternalLinkage(
221 GlobalName: getIRPGOFuncName(F: Fct, InLTO));
222 };
223
224 for (BasicBlock &BB : make_early_inc_range(Range&: F)) {
225 BasicBlock *CurrentBB = &BB;
226 while (CurrentBB) {
227 BasicBlock *SplittedOutTail = nullptr;
228 for (Instruction &I : make_early_inc_range(Range&: *CurrentBB)) {
229 auto *Call = dyn_cast<CallInst>(Val: &I);
230 if (!Call || Call->getCalledFunction() || Call->isMustTailCall())
231 continue;
232 auto *L = dyn_cast<LoadInst>(Val: Call->getCalledOperand());
233 // Skip atomic or volatile loads.
234 if (!L || !L->isSimple())
235 continue;
236 auto *GEP = dyn_cast<GetElementPtrInst>(Val: L->getPointerOperand());
237 if (!GEP)
238 continue;
239 auto *PtrTy = dyn_cast<PointerType>(Val: L->getType());
240 assert(PtrTy && "call operand must be a pointer");
241 std::optional<JumpTableTy> JumpTable =
242 parseJumpTable(GEP, PtrTy, CallFTy: Call->getFunctionType());
243 if (!JumpTable)
244 continue;
245 SplittedOutTail =
246 expandToSwitch(CB: Call, JT: *JumpTable, DTU, ORE, GetGuidForFunction: FuncToGuid);
247 Changed = true;
248 break;
249 }
250 CurrentBB = SplittedOutTail ? SplittedOutTail : nullptr;
251 }
252 }
253
254 if (!Changed)
255 return PreservedAnalyses::all();
256
257 PreservedAnalyses PA;
258 if (DT)
259 PA.preserve<DominatorTreeAnalysis>();
260 if (PDT)
261 PA.preserve<PostDominatorTreeAnalysis>();
262 return PA;
263}
264