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
17#include "llvm/IR/BasicBlock.h"
18#include "llvm/IR/IRBuilder.h"
20#include "llvm/IR/Module.h"
21
22using namespace llvm;
23
27
33
37
38 bool operator==(const AccessPattern &Other) const {
39 return Stride == Other.Stride && ElemType == Other.ElemType;
40 }
41 bool operator!=(const AccessPattern &Other) const {
42 return !(*this == Other);
43 }
44};
45
47 LookupTableUse &UseInfo, User *Usr) {
48 // TODO: Allow multiple load users of GEP.
49 UseInfo.GEP = dyn_cast<GetElementPtrInst>(Usr);
50 if (!UseInfo.GEP || !UseInfo.GEP->hasOneUse())
51 return false;
52
53 UseInfo.Load = dyn_cast<LoadInst>(UseInfo.GEP->use_begin()->getUser());
54 if (!UseInfo.Load || UseInfo.Load->isVolatile())
55 return false;
56
57 // If values are not 64-bit pointers, do not generate a relative lookup table.
58 const DataLayout &DL = UseInfo.Load->getDataLayout();
59 Pattern.ElemType = UseInfo.Load->getType();
60 if (!Pattern.ElemType->isPointerTy() ||
61 DL.getPointerTypeSizeInBits(Pattern.ElemType) != 64)
62 return false;
63
64 // Make sure this is a gep of the form GV + scale*var.
65 unsigned IndexWidth = DL.getIndexTypeSizeInBits(UseInfo.GEP->getType());
67 APInt ConstOffset(IndexWidth, 0);
68 if (!UseInfo.GEP->collectOffset(DL, IndexWidth, VarOffsets, ConstOffset) ||
69 !ConstOffset.isZero() || VarOffsets.size() != 1)
70 return false;
71
72 // This can't be a pointer lookup table if the stride is smaller than a
73 // pointer.
74 UseInfo.Index = VarOffsets.front().first;
75 Pattern.Stride = VarOffsets.front().second;
76 if (Pattern.Stride.ult(DL.getTypeStoreSize(Pattern.ElemType)))
77 return false;
78
79 return true;
80}
81
84 Module &M, GlobalVariable &GV) {
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 if (!GV.hasInitializer() || !GV.isConstant() || !GV.hasLocalLinkage() ||
93 !GV.isDSOLocal() || !GV.isImplicitDSOLocal())
94 return false;
95
96 std::optional<AccessPattern> Pattern;
97 for (User *Usr : GV.users()) {
98 AccessPattern CurPattern;
99 LookupTableUse CurUse;
100 if (!analyzeLookupTableUse(CurPattern, CurUse, Usr))
101 return false;
102
103 // Make sure the access pattern is always the same
104 if (!Pattern)
105 Pattern = CurPattern;
106 else if (*Pattern != CurPattern)
107 return false;
108
109 Uses.push_back(CurUse);
110 }
111 if (!Pattern)
112 return false;
113
115 Triple TT = M.getTargetTriple();
116 // FIXME: This should be removed in the future.
117 bool ShouldDropUnnamedAddr =
118 // Drop unnamed_addr to avoid matching pattern in
119 // `handleIndirectSymViaGOTPCRel`, which generates GOTPCREL relocations
120 // not supported by the GNU linker and LLD versions below 18 on aarch64.
121 TT.isAArch64()
122 // Apple's ld64 (and ld-prime on Xcode 15.2) miscompile something on
123 // x86_64-apple-darwin. See
124 // https://github.com/rust-lang/rust/issues/140686 and
125 // https://github.com/rust-lang/rust/issues/141306.
126 || (TT.isX86() && TT.isOSDarwin());
127
128 const DataLayout &DL = M.getDataLayout();
129 APInt Offset(Pattern->Stride.getBitWidth(), 0);
130 uint64_t GVSize = GV.getGlobalSize(DL);
131 bool HasNonPoison = false;
132 for (; Offset.ult(GVSize); Offset += Pattern->Stride) {
134 Pattern->ElemType, Offset, DL);
135 if (!C)
136 return false;
137
138 if (isa<PoisonValue>(C)) {
139 Info.Ptrs.push_back(C);
140 continue;
141 }
142
143 GlobalValue *GVOp;
144 APInt GVOffset;
145
146 // If an operand is not a constant offset from a lookup table,
147 // do not generate a relative lookup table.
148 if (!IsConstantOffsetFromGlobal(C, GVOp, GVOffset, DL))
149 return false;
150
151 // If operand is mutable, do not generate a relative lookup table.
152 auto *GlobalVarOp = dyn_cast<GlobalVariable>(GVOp);
153 if (!GlobalVarOp || !GlobalVarOp->isConstant())
154 return false;
155
156 // Weak declarations have to be excluded because they may be null.
157 // Weak definitions are excluded because the assembler currently incorrectly
158 // resolves them against the local symbol, instead of emitting a relocation
159 // (https://github.com/llvm/llvm-project/issues/244540).
160 // Non-implicit dso_local is excluded because we currently do not convey to
161 // the linker that the symbol is non-preemptible, which may result in a
162 // relocation error.
163 if (GlobalVarOp->isWeakForLinker() || !GlobalVarOp->isImplicitDSOLocal())
164 return false;
165
166 // On AArch64 small code model, the text-to-data span can be up to 4GB,
167 // which exceeds 32-bit signed relative offsets. Avoid converting if the
168 // target operand requires dynamic relocations (placing it in .data.rel.ro
169 // in the data segment rather than .rodata in the text segment).
170 if (TT.isAArch64() &&
171 (!GlobalVarOp->hasInitializer() ||
172 GlobalVarOp->getInitializer()->needsDynamicRelocation()))
173 return false;
174
175 if (ShouldDropUnnamedAddr)
176 GVOps.push_back(GlobalVarOp);
177
178 HasNonPoison = true;
179 Info.Ptrs.push_back(C);
180 }
181
182 if (!HasNonPoison)
183 return false;
184
185 if (ShouldDropUnnamedAddr)
186 for (auto *GVOp : GVOps)
187 GVOp->setUnnamedAddr(GlobalValue::UnnamedAddr::None);
188
189 return true;
190}
191
193 GlobalVariable &LookupTable) {
194 Module &M = *LookupTable.getParent();
195 ArrayType *IntArrayTy =
196 ArrayType::get(Type::getInt32Ty(M.getContext()), Info.Ptrs.size());
197
198 GlobalVariable *RelLookupTable = new GlobalVariable(
199 M, IntArrayTy, LookupTable.isConstant(), LookupTable.getLinkage(),
200 nullptr, LookupTable.getName() + ".rel", &LookupTable,
201 LookupTable.getThreadLocalMode(), LookupTable.getAddressSpace(),
202 LookupTable.isExternallyInitialized());
203
204 Type *IntPtrTy = M.getDataLayout().getIntPtrType(M.getContext());
205 Type *Int32Ty = Type::getInt32Ty(M.getContext());
207
208 uint64_t Idx = 0;
209 SmallVector<Constant *, 64> RelLookupTableContents(Info.Ptrs.size());
210
211 for (Constant *Element : Info.Ptrs) {
212 if (isa<PoisonValue>(Element)) {
213 RelLookupTableContents[Idx++] = PoisonValue::get(Int32Ty);
214 continue;
215 }
216
219 Constant *RelOffset = ConstantExpr::getTrunc(Sub, Int32Ty);
220 RelLookupTableContents[Idx++] = RelOffset;
221 }
222
223 Constant *Initializer =
224 ConstantArray::get(IntArrayTy, RelLookupTableContents);
225 RelLookupTable->setInitializer(Initializer);
227 RelLookupTable->setAlignment(llvm::Align(4));
228 return RelLookupTable;
229}
230
233 GlobalVariable &LookupTable) {
234 // Generate an array that consists of relative offsets.
235 GlobalVariable *RelLookupTable =
236 createRelLookupTable(Info, LookupTable);
237
238 Module &M = *LookupTable.getParent();
239 for (const LookupTableUse &UseInfo : Uses) {
240 BasicBlock *BB = UseInfo.GEP->getParent();
241 IRBuilder<> Builder(BB);
242
243 // Place new instruction sequence before GEP.
244 Builder.SetInsertPoint(UseInfo.GEP);
245 IntegerType *IntTy = cast<IntegerType>(UseInfo.Index->getType());
246 Value *Offset = Builder.CreateShl(UseInfo.Index, ConstantInt::get(IntTy, 2),
247 "reltable.shift");
248
249 // Insert the call to load.relative intrinsic before LOAD.
250 // GEP might not be immediately followed by a LOAD, like it can be hoisted
251 // outside the loop or another instruction might be inserted them in
252 // between.
253 Builder.SetInsertPoint(UseInfo.Load);
255 &M, Intrinsic::load_relative, {UseInfo.Index->getType()});
256
257 // Create a call to load.relative intrinsic that computes the target address
258 // by adding base address (lookup table address) and relative offset.
259 Value *Result = Builder.CreateCall(
260 LoadRelIntrinsic, {RelLookupTable, Offset}, "reltable.intrinsic");
261
262 // Replace load instruction with the new generated instruction sequence.
263 UseInfo.Load->replaceAllUsesWith(Result);
264 // Remove Load and GEP instructions.
265 UseInfo.Load->eraseFromParent();
266 UseInfo.GEP->eraseFromParent();
267 }
268}
269
270// Convert lookup tables to relative lookup tables in the module.
273 for (Function &F : M) {
274 if (F.isDeclaration())
275 continue;
276
277 // Check if we have a target that supports relative lookup tables.
278 if (!GetTTI(F).shouldBuildRelLookupTables())
279 return false;
280
281 // We assume that the result is independent of the checked function.
282 break;
283 }
284
285 bool Changed = false;
286
287 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
288 LookupTableInfo Info;
290 if (!shouldConvertToRelLookupTable(Info, Uses, M, GV))
291 continue;
292
293 convertToRelLookupTable(Info, Uses, GV);
294
295 // Remove the original lookup table.
296 GV.eraseFromParent();
297
298 Changed = true;
299 }
300
301 return Changed;
302}
303
308
309 auto GetTTI = [&](Function &F) -> TargetTransformInfo & {
310 return FAM.getResult<TargetIRAnalysis>(F);
311 };
312
313 if (!convertToRelativeLookupTables(M, GetTTI))
314 return PreservedAnalyses::all();
315
318 return PA;
319}
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
FunctionAnalysisManager FAM
static bool convertToRelativeLookupTables(Module &M, function_ref< TargetTransformInfo &(Function &)> GetTTI)
static void convertToRelLookupTable(const LookupTableInfo &Info, ArrayRef< LookupTableUse > Uses, GlobalVariable &LookupTable)
static GlobalVariable * createRelLookupTable(const LookupTableInfo &Info, GlobalVariable &LookupTable)
static bool shouldConvertToRelLookupTable(LookupTableInfo &Info, SmallVectorImpl< LookupTableUse > &Uses, Module &M, GlobalVariable &GV)
static bool analyzeLookupTableUse(AccessPattern &Pattern, LookupTableUse &UseInfo, User *Usr)
This file implements relative lookup table converter that converts lookup tables to relative lookup t...
Remove Loads Into Fake Uses
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.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
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:62
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
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:64
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
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.
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:152
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
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
LLVM Value Representation.
Definition Value.h:75
iterator_range< user_iterator > users()
Definition Value.h:428
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.
@ 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.
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
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
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
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