xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/Utils/RelLookupTableConverter.cpp (revision 349cc55c9796c4596a5b9904cd3281af295f878f)
1fe6060f1SDimitry Andric //===- RelLookupTableConverterPass - Rel Table Conv -----------------------===//
2fe6060f1SDimitry Andric //
3fe6060f1SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4fe6060f1SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5fe6060f1SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6fe6060f1SDimitry Andric //
7fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
8fe6060f1SDimitry Andric //
9fe6060f1SDimitry Andric // This file implements relative lookup table converter that converts
10fe6060f1SDimitry Andric // lookup tables to relative lookup tables to make them PIC-friendly.
11fe6060f1SDimitry Andric //
12fe6060f1SDimitry Andric //===----------------------------------------------------------------------===//
13fe6060f1SDimitry Andric 
14fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/RelLookupTableConverter.h"
15fe6060f1SDimitry Andric #include "llvm/Analysis/ConstantFolding.h"
16fe6060f1SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
17fe6060f1SDimitry Andric #include "llvm/IR/BasicBlock.h"
18fe6060f1SDimitry Andric #include "llvm/IR/IRBuilder.h"
19fe6060f1SDimitry Andric #include "llvm/IR/Instructions.h"
20fe6060f1SDimitry Andric #include "llvm/IR/Module.h"
21fe6060f1SDimitry Andric #include "llvm/InitializePasses.h"
22fe6060f1SDimitry Andric #include "llvm/Pass.h"
23fe6060f1SDimitry Andric #include "llvm/Transforms/Utils/BasicBlockUtils.h"
24fe6060f1SDimitry Andric 
25fe6060f1SDimitry Andric using namespace llvm;
26fe6060f1SDimitry Andric 
27fe6060f1SDimitry Andric static bool shouldConvertToRelLookupTable(Module &M, GlobalVariable &GV) {
28fe6060f1SDimitry Andric   // If lookup table has more than one user,
29fe6060f1SDimitry Andric   // do not generate a relative lookup table.
30fe6060f1SDimitry Andric   // This is to simplify the analysis that needs to be done for this pass.
31fe6060f1SDimitry Andric   // TODO: Add support for lookup tables with multiple uses.
32fe6060f1SDimitry Andric   // For ex, this can happen when a function that uses a lookup table gets
33fe6060f1SDimitry Andric   // inlined into multiple call sites.
34fe6060f1SDimitry Andric   if (!GV.hasInitializer() ||
35fe6060f1SDimitry Andric       !GV.isConstant() ||
36fe6060f1SDimitry Andric       !GV.hasOneUse())
37fe6060f1SDimitry Andric     return false;
38fe6060f1SDimitry Andric 
39fe6060f1SDimitry Andric   GetElementPtrInst *GEP =
40fe6060f1SDimitry Andric       dyn_cast<GetElementPtrInst>(GV.use_begin()->getUser());
41fe6060f1SDimitry Andric   if (!GEP || !GEP->hasOneUse())
42fe6060f1SDimitry Andric     return false;
43fe6060f1SDimitry Andric 
44fe6060f1SDimitry Andric   LoadInst *Load = dyn_cast<LoadInst>(GEP->use_begin()->getUser());
45fe6060f1SDimitry Andric   if (!Load || !Load->hasOneUse())
46fe6060f1SDimitry Andric     return false;
47fe6060f1SDimitry Andric 
48fe6060f1SDimitry Andric   // If the original lookup table does not have local linkage and is
49fe6060f1SDimitry Andric   // not dso_local, do not generate a relative lookup table.
50fe6060f1SDimitry Andric   // This optimization creates a relative lookup table that consists of
51fe6060f1SDimitry Andric   // offsets between the start of the lookup table and its elements.
52fe6060f1SDimitry Andric   // To be able to generate these offsets, relative lookup table and
53fe6060f1SDimitry Andric   // its elements should have internal linkage and be dso_local, which means
54fe6060f1SDimitry Andric   // that they should resolve to symbols within the same linkage unit.
55fe6060f1SDimitry Andric   if (!GV.hasLocalLinkage() ||
56fe6060f1SDimitry Andric       !GV.isDSOLocal() ||
57fe6060f1SDimitry Andric       !GV.isImplicitDSOLocal())
58fe6060f1SDimitry Andric     return false;
59fe6060f1SDimitry Andric 
60fe6060f1SDimitry Andric   ConstantArray *Array = dyn_cast<ConstantArray>(GV.getInitializer());
61fe6060f1SDimitry Andric   // If values are not pointers, do not generate a relative lookup table.
62fe6060f1SDimitry Andric   if (!Array || !Array->getType()->getElementType()->isPointerTy())
63fe6060f1SDimitry Andric     return false;
64fe6060f1SDimitry Andric 
65fe6060f1SDimitry Andric   const DataLayout &DL = M.getDataLayout();
66fe6060f1SDimitry Andric   for (const Use &Op : Array->operands()) {
67fe6060f1SDimitry Andric     Constant *ConstOp = cast<Constant>(&Op);
68fe6060f1SDimitry Andric     GlobalValue *GVOp;
69fe6060f1SDimitry Andric     APInt Offset;
70fe6060f1SDimitry Andric 
71fe6060f1SDimitry Andric     // If an operand is not a constant offset from a lookup table,
72fe6060f1SDimitry Andric     // do not generate a relative lookup table.
73fe6060f1SDimitry Andric     if (!IsConstantOffsetFromGlobal(ConstOp, GVOp, Offset, DL))
74fe6060f1SDimitry Andric       return false;
75fe6060f1SDimitry Andric 
76fe6060f1SDimitry Andric     // If operand is mutable, do not generate a relative lookup table.
77fe6060f1SDimitry Andric     auto *GlovalVarOp = dyn_cast<GlobalVariable>(GVOp);
78fe6060f1SDimitry Andric     if (!GlovalVarOp || !GlovalVarOp->isConstant())
79fe6060f1SDimitry Andric       return false;
80fe6060f1SDimitry Andric 
81fe6060f1SDimitry Andric     if (!GlovalVarOp->hasLocalLinkage() ||
82fe6060f1SDimitry Andric         !GlovalVarOp->isDSOLocal() ||
83fe6060f1SDimitry Andric         !GlovalVarOp->isImplicitDSOLocal())
84fe6060f1SDimitry Andric       return false;
85fe6060f1SDimitry Andric   }
86fe6060f1SDimitry Andric 
87fe6060f1SDimitry Andric   return true;
88fe6060f1SDimitry Andric }
89fe6060f1SDimitry Andric 
90fe6060f1SDimitry Andric static GlobalVariable *createRelLookupTable(Function &Func,
91fe6060f1SDimitry Andric                                             GlobalVariable &LookupTable) {
92fe6060f1SDimitry Andric   Module &M = *Func.getParent();
93fe6060f1SDimitry Andric   ConstantArray *LookupTableArr =
94fe6060f1SDimitry Andric       cast<ConstantArray>(LookupTable.getInitializer());
95fe6060f1SDimitry Andric   unsigned NumElts = LookupTableArr->getType()->getNumElements();
96fe6060f1SDimitry Andric   ArrayType *IntArrayTy =
97fe6060f1SDimitry Andric       ArrayType::get(Type::getInt32Ty(M.getContext()), NumElts);
98fe6060f1SDimitry Andric 
99fe6060f1SDimitry Andric   GlobalVariable *RelLookupTable = new GlobalVariable(
100fe6060f1SDimitry Andric     M, IntArrayTy, LookupTable.isConstant(), LookupTable.getLinkage(),
101fe6060f1SDimitry Andric     nullptr, "reltable." + Func.getName(), &LookupTable,
102fe6060f1SDimitry Andric     LookupTable.getThreadLocalMode(), LookupTable.getAddressSpace(),
103fe6060f1SDimitry Andric     LookupTable.isExternallyInitialized());
104fe6060f1SDimitry Andric 
105fe6060f1SDimitry Andric   uint64_t Idx = 0;
106fe6060f1SDimitry Andric   SmallVector<Constant *, 64> RelLookupTableContents(NumElts);
107fe6060f1SDimitry Andric 
108fe6060f1SDimitry Andric   for (Use &Operand : LookupTableArr->operands()) {
109fe6060f1SDimitry Andric     Constant *Element = cast<Constant>(Operand);
110fe6060f1SDimitry Andric     Type *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext());
111fe6060f1SDimitry Andric     Constant *Base = llvm::ConstantExpr::getPtrToInt(RelLookupTable, IntPtrTy);
112fe6060f1SDimitry Andric     Constant *Target = llvm::ConstantExpr::getPtrToInt(Element, IntPtrTy);
113fe6060f1SDimitry Andric     Constant *Sub = llvm::ConstantExpr::getSub(Target, Base);
114fe6060f1SDimitry Andric     Constant *RelOffset =
115fe6060f1SDimitry Andric         llvm::ConstantExpr::getTrunc(Sub, Type::getInt32Ty(M.getContext()));
116fe6060f1SDimitry Andric     RelLookupTableContents[Idx++] = RelOffset;
117fe6060f1SDimitry Andric   }
118fe6060f1SDimitry Andric 
119fe6060f1SDimitry Andric   Constant *Initializer =
120fe6060f1SDimitry Andric       ConstantArray::get(IntArrayTy, RelLookupTableContents);
121fe6060f1SDimitry Andric   RelLookupTable->setInitializer(Initializer);
122fe6060f1SDimitry Andric   RelLookupTable->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
123fe6060f1SDimitry Andric   RelLookupTable->setAlignment(llvm::Align(4));
124fe6060f1SDimitry Andric   return RelLookupTable;
125fe6060f1SDimitry Andric }
126fe6060f1SDimitry Andric 
127fe6060f1SDimitry Andric static void convertToRelLookupTable(GlobalVariable &LookupTable) {
128fe6060f1SDimitry Andric   GetElementPtrInst *GEP =
129fe6060f1SDimitry Andric       cast<GetElementPtrInst>(LookupTable.use_begin()->getUser());
130fe6060f1SDimitry Andric   LoadInst *Load = cast<LoadInst>(GEP->use_begin()->getUser());
131fe6060f1SDimitry Andric 
132fe6060f1SDimitry Andric   Module &M = *LookupTable.getParent();
133fe6060f1SDimitry Andric   BasicBlock *BB = GEP->getParent();
134fe6060f1SDimitry Andric   IRBuilder<> Builder(BB);
135fe6060f1SDimitry Andric   Function &Func = *BB->getParent();
136fe6060f1SDimitry Andric 
137fe6060f1SDimitry Andric   // Generate an array that consists of relative offsets.
138fe6060f1SDimitry Andric   GlobalVariable *RelLookupTable = createRelLookupTable(Func, LookupTable);
139fe6060f1SDimitry Andric 
140fe6060f1SDimitry Andric   // Place new instruction sequence before GEP.
141fe6060f1SDimitry Andric   Builder.SetInsertPoint(GEP);
142fe6060f1SDimitry Andric   Value *Index = GEP->getOperand(2);
143fe6060f1SDimitry Andric   IntegerType *IntTy = cast<IntegerType>(Index->getType());
144fe6060f1SDimitry Andric   Value *Offset =
145fe6060f1SDimitry Andric       Builder.CreateShl(Index, ConstantInt::get(IntTy, 2), "reltable.shift");
146fe6060f1SDimitry Andric 
1475a925e46SDimitry Andric   // Insert the call to load.relative instrinsic before LOAD.
1485a925e46SDimitry Andric   // GEP might not be immediately followed by a LOAD, like it can be hoisted
1495a925e46SDimitry Andric   // outside the loop or another instruction might be inserted them in between.
1505a925e46SDimitry Andric   Builder.SetInsertPoint(Load);
151fe6060f1SDimitry Andric   Function *LoadRelIntrinsic = llvm::Intrinsic::getDeclaration(
152fe6060f1SDimitry Andric       &M, Intrinsic::load_relative, {Index->getType()});
153fe6060f1SDimitry Andric   Value *Base = Builder.CreateBitCast(RelLookupTable, Builder.getInt8PtrTy());
154fe6060f1SDimitry Andric 
155fe6060f1SDimitry Andric   // Create a call to load.relative intrinsic that computes the target address
156fe6060f1SDimitry Andric   // by adding base address (lookup table address) and relative offset.
157fe6060f1SDimitry Andric   Value *Result = Builder.CreateCall(LoadRelIntrinsic, {Base, Offset},
158fe6060f1SDimitry Andric                                      "reltable.intrinsic");
159fe6060f1SDimitry Andric 
160fe6060f1SDimitry Andric   // Create a bitcast instruction if necessary.
161fe6060f1SDimitry Andric   if (Load->getType() != Builder.getInt8PtrTy())
162fe6060f1SDimitry Andric     Result = Builder.CreateBitCast(Result, Load->getType(), "reltable.bitcast");
163fe6060f1SDimitry Andric 
164fe6060f1SDimitry Andric   // Replace load instruction with the new generated instruction sequence.
165fe6060f1SDimitry Andric   Load->replaceAllUsesWith(Result);
166fe6060f1SDimitry Andric   // Remove Load and GEP instructions.
167fe6060f1SDimitry Andric   Load->eraseFromParent();
168fe6060f1SDimitry Andric   GEP->eraseFromParent();
169fe6060f1SDimitry Andric }
170fe6060f1SDimitry Andric 
171fe6060f1SDimitry Andric // Convert lookup tables to relative lookup tables in the module.
172fe6060f1SDimitry Andric static bool convertToRelativeLookupTables(
173fe6060f1SDimitry Andric     Module &M, function_ref<TargetTransformInfo &(Function &)> GetTTI) {
174fe6060f1SDimitry Andric   Module::iterator FI = M.begin();
175fe6060f1SDimitry Andric   if (FI == M.end())
176fe6060f1SDimitry Andric     return false;
177fe6060f1SDimitry Andric 
178fe6060f1SDimitry Andric   // Check if we have a target that supports relative lookup tables.
179fe6060f1SDimitry Andric   if (!GetTTI(*FI).shouldBuildRelLookupTables())
180fe6060f1SDimitry Andric     return false;
181fe6060f1SDimitry Andric 
182fe6060f1SDimitry Andric   bool Changed = false;
183fe6060f1SDimitry Andric 
184*349cc55cSDimitry Andric   for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
185fe6060f1SDimitry Andric     if (!shouldConvertToRelLookupTable(M, GV))
186fe6060f1SDimitry Andric       continue;
187fe6060f1SDimitry Andric 
188fe6060f1SDimitry Andric     convertToRelLookupTable(GV);
189fe6060f1SDimitry Andric 
190fe6060f1SDimitry Andric     // Remove the original lookup table.
191fe6060f1SDimitry Andric     GV.eraseFromParent();
192fe6060f1SDimitry Andric 
193fe6060f1SDimitry Andric     Changed = true;
194fe6060f1SDimitry Andric   }
195fe6060f1SDimitry Andric 
196fe6060f1SDimitry Andric   return Changed;
197fe6060f1SDimitry Andric }
198fe6060f1SDimitry Andric 
199fe6060f1SDimitry Andric PreservedAnalyses RelLookupTableConverterPass::run(Module &M,
200fe6060f1SDimitry Andric                                                    ModuleAnalysisManager &AM) {
201fe6060f1SDimitry Andric   FunctionAnalysisManager &FAM =
202fe6060f1SDimitry Andric       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
203fe6060f1SDimitry Andric 
204fe6060f1SDimitry Andric   auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
205fe6060f1SDimitry Andric     return FAM.getResult<TargetIRAnalysis>(F);
206fe6060f1SDimitry Andric   };
207fe6060f1SDimitry Andric 
208fe6060f1SDimitry Andric   if (!convertToRelativeLookupTables(M, GetTTI))
209fe6060f1SDimitry Andric     return PreservedAnalyses::all();
210fe6060f1SDimitry Andric 
211fe6060f1SDimitry Andric   PreservedAnalyses PA;
212fe6060f1SDimitry Andric   PA.preserveSet<CFGAnalyses>();
213fe6060f1SDimitry Andric   return PA;
214fe6060f1SDimitry Andric }
215