LLVM 24.0.0git
RelLookupTableConverter.cpp
Go to the documentation of this file.
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
15#include "llvm/ADT/SetVector.h"
18#include "llvm/IR/BasicBlock.h"
19#include "llvm/IR/IRBuilder.h"
21#include "llvm/IR/Module.h"
22
23using namespace llvm;
24
29
35
39
40 bool operator==(const AccessPattern &Other) const {
41 return Stride == Other.Stride && ElemType == Other.ElemType;
42 }
43 bool operator!=(const AccessPattern &Other) const {
44 return !(*this == Other);
45 }
46};
47
49 LookupTableUse &UseInfo, User *Usr) {
50 // TODO: Allow multiple load users of GEP.
51 UseInfo.GEP = dyn_cast<GetElementPtrInst>(Usr);
52 if (!UseInfo.GEP || !UseInfo.GEP->hasOneUse())
53 return false;
54
55 UseInfo.Load = dyn_cast<LoadInst>(UseInfo.GEP->use_begin()->getUser());
56 if (!UseInfo.Load || UseInfo.Load->isVolatile())
57 return false;
58
59 // If values are not 64-bit pointers, do not generate a relative lookup table.
60 const DataLayout &DL = UseInfo.Load->getDataLayout();
61 Pattern.ElemType = UseInfo.Load->getType();
62 if (!Pattern.ElemType->isPointerTy() ||
63 DL.getPointerTypeSizeInBits(Pattern.ElemType) != 64)
64 return false;
65
66 // Make sure this is a gep of the form GV + scale*var.
67 unsigned IndexWidth = DL.getIndexTypeSizeInBits(UseInfo.GEP->getType());
69 APInt ConstOffset(IndexWidth, 0);
70 if (!UseInfo.GEP->collectOffset(DL, IndexWidth, VarOffsets, ConstOffset) ||
71 !ConstOffset.isZero() || VarOffsets.size() != 1)
72 return false;
73
74 // This can't be a pointer lookup table if the stride is smaller than a
75 // pointer.
76 UseInfo.Index = VarOffsets.front().first;
77 Pattern.Stride = VarOffsets.front().second;
78 if (Pattern.Stride.ult(DL.getTypeStoreSize(Pattern.ElemType)))
79 return false;
80
81 return true;
82}
83
85 // If the original lookup table does not have local linkage and is
86 // not dso_local, do not generate a relative lookup table.
87 // This optimization creates a relative lookup table that consists of
88 // offsets between the start of the lookup table and its elements.
89 // To be able to generate these offsets, relative lookup table and
90 // its elements should have internal linkage and be dso_local, which means
91 // that they should resolve to symbols within the same linkage unit.
92 return GV.hasInitializer() && GV.isConstant() && GV.hasLocalLinkage() &&
93 GV.isDSOLocal() && GV.isImplicitDSOLocal();
94}
95
98 GlobalVariable &GV) {
99 Module *M = GV.getParent();
100 Triple TT = M->getTargetTriple();
101 // FIXME: This should be removed in the future.
102 bool ShouldDropUnnamedAddr =
103 // Drop unnamed_addr to avoid matching pattern in
104 // `handleIndirectSymViaGOTPCRel`, which generates GOTPCREL relocations
105 // not supported by the GNU linker and LLD versions below 18 on aarch64.
106 TT.isAArch64()
107 // Apple's ld64 (and ld-prime on Xcode 15.2) miscompile something on
108 // x86_64-apple-darwin. See
109 // https://github.com/rust-lang/rust/issues/140686 and
110 // https://github.com/rust-lang/rust/issues/141306.
111 || (TT.isX86() && TT.isOSDarwin());
112
113 const DataLayout &DL = M->getDataLayout();
114 APInt Offset(Pattern.Stride.getBitWidth(), 0);
115 uint64_t GVSize = GV.getGlobalSize(DL);
116 bool HasNonPoison = false;
117 for (; Offset.ult(GVSize); Offset += Pattern.Stride) {
119 Pattern.ElemType, Offset, DL);
120 if (!C)
121 return false;
122
123 if (isa<PoisonValue>(C)) {
124 Info.Ptrs.push_back(C);
125 continue;
126 }
127
128 GlobalValue *GVOp;
129 APInt GVOffset;
130
131 // If an operand is not a constant offset from a lookup table,
132 // do not generate a relative lookup table.
133 if (!IsConstantOffsetFromGlobal(C, GVOp, GVOffset, DL))
134 return false;
135
136 // If operand is mutable, do not generate a relative lookup table.
137 auto *GlobalVarOp = dyn_cast<GlobalVariable>(GVOp);
138 if (!GlobalVarOp || !GlobalVarOp->isConstant())
139 return false;
140
141 // Weak declarations have to be excluded because they may be null.
142 // Weak definitions are excluded because the assembler currently incorrectly
143 // resolves them against the local symbol, instead of emitting a relocation
144 // (https://github.com/llvm/llvm-project/issues/244540).
145 // Non-implicit dso_local is excluded because we currently do not convey to
146 // the linker that the symbol is non-preemptible, which may result in a
147 // relocation error.
148 if (GlobalVarOp->isWeakForLinker() || !GlobalVarOp->isImplicitDSOLocal())
149 return false;
150
151 // On AArch64 small code model, the text-to-data span can be up to 4GB,
152 // which exceeds 32-bit signed relative offsets. Avoid converting if the
153 // target operand requires dynamic relocations (placing it in .data.rel.ro
154 // in the data segment rather than .rodata in the text segment).
155 if (TT.isAArch64() &&
156 (!GlobalVarOp->hasInitializer() ||
157 GlobalVarOp->getInitializer()->needsDynamicRelocation()))
158 return false;
159
160 if (ShouldDropUnnamedAddr)
161 Info.DropUnnamedAddrGVs.push_back(GlobalVarOp);
162
163 HasNonPoison = true;
164 Info.Ptrs.push_back(C);
165 }
166
167 return HasNonPoison;
168}
169
171 GlobalVariable &LookupTable) {
172 for (auto *GV : Info.DropUnnamedAddrGVs)
174
175 Module &M = *LookupTable.getParent();
176 ArrayType *IntArrayTy =
177 ArrayType::get(Type::getInt32Ty(M.getContext()), Info.Ptrs.size());
178
179 GlobalVariable *RelLookupTable = new GlobalVariable(
180 M, IntArrayTy, LookupTable.isConstant(), LookupTable.getLinkage(),
181 nullptr, LookupTable.getName() + ".rel", &LookupTable,
182 LookupTable.getThreadLocalMode(), LookupTable.getAddressSpace(),
183 LookupTable.isExternallyInitialized());
184
185 Type *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext());
186 Type *Int32Ty = Type::getInt32Ty(M.getContext());
188
189 uint64_t Idx = 0;
190 SmallVector<Constant *, 64> RelLookupTableContents(Info.Ptrs.size());
191
192 for (Constant *Element : Info.Ptrs) {
193 if (isa<PoisonValue>(Element)) {
194 RelLookupTableContents[Idx++] = PoisonValue::get(Int32Ty);
195 continue;
196 }
197
200 Constant *RelOffset = ConstantExpr::getTrunc(Sub, Int32Ty);
201 RelLookupTableContents[Idx++] = RelOffset;
202 }
203
204 Constant *Initializer =
205 ConstantArray::get(IntArrayTy, RelLookupTableContents);
206 RelLookupTable->setInitializer(Initializer);
208 RelLookupTable->setAlignment(llvm::Align(4));
209 return RelLookupTable;
210}
211
212static void convertLookupTableUse(const LookupTableUse &UseInfo) {
213 BasicBlock *BB = UseInfo.GEP->getParent();
214 Module *M = BB->getModule();
215 IRBuilder<> Builder(BB);
216
217 // Place new instruction sequence before GEP.
218 Builder.SetInsertPoint(UseInfo.GEP);
219 IntegerType *IntTy = cast<IntegerType>(UseInfo.Index->getType());
220 Value *Offset = Builder.CreateShl(UseInfo.Index, ConstantInt::get(IntTy, 2),
221 "reltable.shift");
222
223 // Insert the call to load.relative intrinsic before LOAD.
224 // GEP might not be immediately followed by a LOAD, like it can be hoisted
225 // outside the loop or another instruction might be inserted them in
226 // between.
227 Builder.SetInsertPoint(UseInfo.Load);
229 M, Intrinsic::load_relative, {UseInfo.Index->getType()});
230
231 // Create a call to load.relative intrinsic that computes the target address
232 // by adding base address (lookup table address) and relative offset.
233 Value *Result = Builder.CreateCall(LoadRelIntrinsic,
234 {UseInfo.GEP->getPointerOperand(), Offset},
235 "reltable.intrinsic");
236
237 // Replace load instruction with the new generated instruction sequence.
238 UseInfo.Load->replaceAllUsesWith(Result);
239 // Remove Load and GEP instructions.
240 UseInfo.Load->eraseFromParent();
241 UseInfo.GEP->eraseFromParent();
242}
243
244// Convert lookup tables to relative lookup tables in the module.
247 for (Function &F : M) {
248 if (F.isDeclaration())
249 continue;
250
251 // Check if we have a target that supports relative lookup tables.
252 if (!GetTTI(F).shouldBuildRelLookupTables())
253 return false;
254
255 // We assume that the result is independent of the checked function.
256 break;
257 }
258
259 bool Changed = false;
261 auto AnalyzeGlobal = [&](GlobalVariable &GV) {
263 return;
264
266 GVs.try_emplace(&GV);
267
268 std::optional<AccessPattern> Pattern;
271 Worklist.insert(GV.user_begin(), GV.user_end());
272 for (unsigned I = 0; I < Worklist.size(); ++I) {
273 User *Usr = Worklist[I];
274 if (isa<PHINode, SelectInst>(Usr)) {
275 // Look through phi/select. In that case, make sure that all the
276 // operands are eligible for lookup table conversion and collect them.
277 for (Value *Op : drop_begin(Usr->operands(), isa<SelectInst>(Usr))) {
278 // TODO: This could be extended to handle nested selects/phis.
279 auto *OpGV = dyn_cast<GlobalVariable>(Op);
280 if (!OpGV || !isEligibleForRelLookupTable(*OpGV))
281 return;
282
283 GVs.try_emplace(OpGV);
284 Worklist.insert(OpGV->user_begin(), OpGV->user_end());
285 }
286
287 Worklist.insert(Usr->user_begin(), Usr->user_end());
288 } else {
289 // Make sure the access pattern is always the same and collect uses.
290 AccessPattern CurPattern;
291 LookupTableUse CurUse;
292 if (!analyzeLookupTableUse(CurPattern, CurUse, Usr))
293 return;
294
295 if (!Pattern)
296 Pattern = CurPattern;
297 else if (*Pattern != CurPattern)
298 return;
299
300 Uses.push_back(CurUse);
301 }
302 }
303
304 if (!Pattern)
305 return;
306
307 for (auto &[GV, Info] : GVs)
308 if (!analyzeLookupTable(Info, *Pattern, *GV))
309 return;
310
311 // Convert the uses, while still referencing the old lookup tables.
312 for (LookupTableUse &UseInfo : Uses)
313 convertLookupTableUse(UseInfo);
314
315 // Replace the actual lookup tables.
316 for (auto &[GV, Info] : GVs) {
317 GlobalVariable *RelLookupTable = createRelLookupTable(Info, *GV);
318 GV->replaceAllUsesWith(RelLookupTable);
319 DeadGVs.push_back(GV);
320 }
321
322 Changed = true;
323 };
324
325 for (GlobalVariable &GV : M.globals())
326 AnalyzeGlobal(GV);
327
328 // Remove the original lookup tables.
329 for (GlobalVariable *DeadGV : DeadGVs)
330 DeadGV->eraseFromParent();
331
332 return Changed;
333}
334
339
340 auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
341 return FAM.getResult<TargetIRAnalysis>(F);
342 };
343
344 if (!convertToRelativeLookupTables(M, GetTTI))
345 return PreservedAnalyses::all();
346
349 return PA;
350}
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
FunctionAnalysisManager FAM
static bool isEligibleForRelLookupTable(const GlobalVariable &GV)
static bool convertToRelativeLookupTables(Module &M, function_ref< TargetTransformInfo &(Function &)> GetTTI)
static bool analyzeLookupTable(LookupTableInfo &Info, const AccessPattern &Pattern, GlobalVariable &GV)
static GlobalVariable * createRelLookupTable(const LookupTableInfo &Info, GlobalVariable &LookupTable)
static bool analyzeLookupTableUse(AccessPattern &Pattern, LookupTableUse &UseInfo, User *Usr)
static void convertLookupTableUse(const LookupTableUse &UseInfo)
This file implements relative lookup table converter that converts lookup tables to relative lookup t...
Remove Loads Into Fake Uses
This file implements a set that has insertion order iteration characteristics.
This pass exposes codegen information to IR-level passes.
Class for arbitrary precision integers.
Definition APInt.h:78
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
static LLVM_ABI ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
LLVM Basic Block Representation.
Definition BasicBlock.h:61
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:212
LLVM_ABI const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
static LLVM_ABI Constant * get(ArrayType *T, ArrayRef< Constant * > V)
static LLVM_ABI Constant * getSub(Constant *C1, Constant *C2, bool HasNUW=false, bool HasNSW=false)
static LLVM_ABI Constant * getPtrToInt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
static LLVM_ABI Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
This is an important base class in LLVM.
Definition Constant.h:44
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
bool isDSOLocal() const
bool isImplicitDSOLocal() const
void setUnnamedAddr(UnnamedAddr Val)
bool hasLocalLinkage() const
Module * getParent()
Get the module that this global value is contained inside of...
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
LLVM_ABI void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition Globals.cpp:613
bool hasInitializer() const
Definitions have initializers, declarations don't.
LLVM_ABI uint64_t getGlobalSize(const DataLayout &DL) const
Get the size of this global variable in bytes.
Definition Globals.cpp:640
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalVariable.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition IRBuilder.h:2990
Class to represent integer types.
An instruction for reading from memory.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:119
size_type size() const
Definition MapVector.h:59
std::pair< KeyT, ValueT > & front()
Definition MapVector.h:82
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
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 & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
size_type size() const
Determine the number of elements in the SetVector.
Definition SetVector.h:103
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
A SetVector that performs no allocations if smaller than a certain size.
Definition SetVector.h:346
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
Target - Wrapper for Target specific information.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt32Ty(LLVMContext &C)
Definition Type.cpp:294
op_range operands()
Definition User.h:267
LLVM Value Representation.
Definition Value.h:75
user_iterator user_begin()
Definition Value.h:404
user_iterator user_end()
Definition Value.h:412
An efficient, type-erasing, non-owning reference to a callable.
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV, APInt &Offset, const DataLayout &DL, DSOLocalEquivalent **DSOEquiv=nullptr)
If this constant is a constant offset from a global, return the global and the constant.
InnerAnalysisManagerProxy< FunctionAnalysisManager, Module > FunctionAnalysisManagerModuleProxy
Provide the FunctionAnalysisManager to Module proxy.
LLVM_ABI Constant * ConstantFoldLoadFromConst(Constant *C, Type *Ty, const APInt &Offset, const DataLayout &DL)
Extract value of C at the given Offset reinterpreted as Ty.
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
@ Other
Any other memory.
Definition ModRef.h:68
@ Sub
Subtraction of integers.
IntPtrTy
Definition InstrProf.h:82
DWARFExpression::Operation Op
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.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
bool operator!=(const AccessPattern &Other) const
bool operator==(const AccessPattern &Other) const
SmallVector< Constant * > Ptrs
SmallVector< GlobalVariable * > DropUnnamedAddrGVs
GetElementPtrInst * GEP
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:344