LLVM 17.0.0git
Go to the documentation of this file.
1//===- GlobalSplit.cpp - global variable splitter -------------------------===//
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
9// This pass uses inrange annotations on GEP indices to split globals where
10// beneficial. Clang currently attaches these annotations to references to
11// virtual table globals under the Itanium ABI for the benefit of the
12// whole-program virtual call optimization and control flow integrity passes.
19#include "llvm/IR/Constant.h"
20#include "llvm/IR/Constants.h"
21#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/Function.h"
23#include "llvm/IR/GlobalValue.h"
25#include "llvm/IR/Intrinsics.h"
26#include "llvm/IR/LLVMContext.h"
27#include "llvm/IR/Metadata.h"
28#include "llvm/IR/Module.h"
29#include "llvm/IR/Operator.h"
30#include "llvm/IR/Type.h"
31#include "llvm/IR/User.h"
33#include "llvm/Pass.h"
35#include "llvm/Transforms/IPO.h"
36#include <cstdint>
37#include <vector>
39using namespace llvm;
41static bool splitGlobal(GlobalVariable &GV) {
42 // If the address of the global is taken outside of the module, we cannot
43 // apply this transformation.
44 if (!GV.hasLocalLinkage())
45 return false;
47 // We currently only know how to split ConstantStructs.
48 auto *Init = dyn_cast_or_null<ConstantStruct>(GV.getInitializer());
49 if (!Init)
50 return false;
52 // Verify that each user of the global is an inrange getelementptr constant.
53 // From this it follows that any loads from or stores to that global must use
54 // a pointer derived from an inrange getelementptr constant, which is
55 // sufficient to allow us to apply the splitting transform.
56 for (User *U : GV.users()) {
57 if (!isa<Constant>(U))
58 return false;
60 auto *GEP = dyn_cast<GEPOperator>(U);
61 if (!GEP || !GEP->getInRangeIndex() || *GEP->getInRangeIndex() != 1 ||
62 !isa<ConstantInt>(GEP->getOperand(1)) ||
63 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
64 !isa<ConstantInt>(GEP->getOperand(2)))
65 return false;
66 }
69 GV.getMetadata(LLVMContext::MD_type, Types);
71 const DataLayout &DL = GV.getParent()->getDataLayout();
72 const StructLayout *SL = DL.getStructLayout(Init->getType());
76 std::vector<GlobalVariable *> SplitGlobals(Init->getNumOperands());
77 for (unsigned I = 0; I != Init->getNumOperands(); ++I) {
78 // Build a global representing this split piece.
79 auto *SplitGV =
80 new GlobalVariable(*GV.getParent(), Init->getOperand(I)->getType(),
82 Init->getOperand(I), GV.getName() + "." + utostr(I));
83 SplitGlobals[I] = SplitGV;
85 unsigned SplitBegin = SL->getElementOffset(I);
86 unsigned SplitEnd = (I == Init->getNumOperands() - 1)
87 ? SL->getSizeInBytes()
88 : SL->getElementOffset(I + 1);
90 // Rebuild type metadata, adjusting by the split offset.
91 // FIXME: See if we can use DW_OP_piece to preserve debug metadata here.
92 for (MDNode *Type : Types) {
93 uint64_t ByteOffset = cast<ConstantInt>(
94 cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
95 ->getZExtValue();
96 // Type metadata may be attached one byte after the end of the vtable, for
97 // classes without virtual methods in Itanium ABI. AFAIK, it is never
98 // attached to the first byte of a vtable. Subtract one to get the right
99 // slice.
100 // This is making an assumption that vtable groups are the only kinds of
101 // global variables that !type metadata can be attached to, and that they
102 // are either Itanium ABI vtable groups or contain a single vtable (i.e.
103 // Microsoft ABI vtables).
104 uint64_t AttachedTo = (ByteOffset == 0) ? ByteOffset : ByteOffset - 1;
105 if (AttachedTo < SplitBegin || AttachedTo >= SplitEnd)
106 continue;
107 SplitGV->addMetadata(
108 LLVMContext::MD_type,
110 {ConstantAsMetadata::get(
111 ConstantInt::get(Int32Ty, ByteOffset - SplitBegin)),
112 Type->getOperand(1)}));
113 }
115 if (GV.hasMetadata(LLVMContext::MD_vcall_visibility))
116 SplitGV->setVCallVisibilityMetadata(GV.getVCallVisibility());
117 }
119 for (User *U : GV.users()) {
120 auto *GEP = cast<GEPOperator>(U);
121 unsigned I = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
122 if (I >= SplitGlobals.size())
123 continue;
127 for (unsigned I = 3; I != GEP->getNumOperands(); ++I)
128 Ops.push_back(GEP->getOperand(I));
130 auto *NewGEP = ConstantExpr::getGetElementPtr(
131 SplitGlobals[I]->getInitializer()->getType(), SplitGlobals[I], Ops,
132 GEP->isInBounds());
133 GEP->replaceAllUsesWith(NewGEP);
134 }
136 // Finally, remove the original global. Any remaining uses refer to invalid
137 // elements of the global, so replace with poison.
138 if (!GV.use_empty())
140 GV.eraseFromParent();
141 return true;
144static bool splitGlobals(Module &M) {
145 // First, see if the module uses either of the llvm.type.test or
146 // llvm.type.checked.load intrinsics, which indicates that splitting globals
147 // may be beneficial.
148 Function *TypeTestFunc =
149 M.getFunction(Intrinsic::getName(Intrinsic::type_test));
150 Function *TypeCheckedLoadFunc =
151 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
152 if ((!TypeTestFunc || TypeTestFunc->use_empty()) &&
153 (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
154 return false;
156 bool Changed = false;
157 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals()))
158 Changed |= splitGlobal(GV);
159 return Changed;
163 if (!splitGlobals(M))
164 return PreservedAnalyses::all();
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static bool splitGlobals(Module &M)
static bool splitGlobal(GlobalVariable &GV)
Definition: GlobalSplit.cpp:41
Hexagon Common GEP
#define I(x, y, z)
Definition: MD5.cpp:58
This file contains the declarations for metadata subclasses.
Module.h This file contains the declarations for the Module class.
IntegerType * Int32Ty
This file defines the SmallVector class.
This file contains some functions that are useful when dealing with strings.
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:620
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, std::optional< unsigned > InRangeIndex=std::nullopt, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1232
static Constant * get(Type *Ty, uint64_t V, bool IsSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:888
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
bool hasMetadata() const
Return true if this value has any metadata attached to it.
Definition: Value.h:585
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1288
VCallVisibility getVCallVisibility() const
Definition: Metadata.cpp:1610
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
bool hasLocalLinkage() const
Definition: GlobalValue.h:523
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:652
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:290
@ PrivateLinkage
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:56
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:468
Class to represent integer types.
Definition: DerivedTypes.h:40
Metadata node.
Definition: Metadata.h:943
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1399
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:398
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1750
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:155
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:618
uint64_t getSizeInBytes() const
Definition: DataLayout.h:625
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:648
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
static IntegerType * getInt32Ty(LLVMContext &C)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:532
iterator_range< user_iterator > users()
Definition: Value.h:421
bool use_empty() const
Definition: Value.h:344
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:994
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:308
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:979
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:748