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