LLVM  5.0.0
GlobalSplit.cpp
Go to the documentation of this file.
1 //===- GlobalSplit.cpp - global variable splitter -------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass uses inrange annotations on GEP indices to split globals where
11 // beneficial. Clang currently attaches these annotations to references to
12 // virtual table globals under the Itanium ABI for the benefit of the
13 // whole-program virtual call optimization and control flow integrity passes.
14 //
15 //===----------------------------------------------------------------------===//
16 
18 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/GlobalVariable.h"
21 #include "llvm/IR/Intrinsics.h"
22 #include "llvm/IR/Module.h"
23 #include "llvm/IR/Operator.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Transforms/IPO.h"
26 
27 #include <set>
28 
29 using namespace llvm;
30 
31 namespace {
32 
33 bool splitGlobal(GlobalVariable &GV) {
34  // If the address of the global is taken outside of the module, we cannot
35  // apply this transformation.
36  if (!GV.hasLocalLinkage())
37  return false;
38 
39  // We currently only know how to split ConstantStructs.
40  auto *Init = dyn_cast_or_null<ConstantStruct>(GV.getInitializer());
41  if (!Init)
42  return false;
43 
44  // Verify that each user of the global is an inrange getelementptr constant.
45  // From this it follows that any loads from or stores to that global must use
46  // a pointer derived from an inrange getelementptr constant, which is
47  // sufficient to allow us to apply the splitting transform.
48  for (User *U : GV.users()) {
49  if (!isa<Constant>(U))
50  return false;
51 
52  auto *GEP = dyn_cast<GEPOperator>(U);
53  if (!GEP || !GEP->getInRangeIndex() || *GEP->getInRangeIndex() != 1 ||
54  !isa<ConstantInt>(GEP->getOperand(1)) ||
55  !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
56  !isa<ConstantInt>(GEP->getOperand(2)))
57  return false;
58  }
59 
62 
63  const DataLayout &DL = GV.getParent()->getDataLayout();
64  const StructLayout *SL = DL.getStructLayout(Init->getType());
65 
67 
68  std::vector<GlobalVariable *> SplitGlobals(Init->getNumOperands());
69  for (unsigned I = 0; I != Init->getNumOperands(); ++I) {
70  // Build a global representing this split piece.
71  auto *SplitGV =
72  new GlobalVariable(*GV.getParent(), Init->getOperand(I)->getType(),
74  Init->getOperand(I), GV.getName() + "." + utostr(I));
75  SplitGlobals[I] = SplitGV;
76 
77  unsigned SplitBegin = SL->getElementOffset(I);
78  unsigned SplitEnd = (I == Init->getNumOperands() - 1)
79  ? SL->getSizeInBytes()
80  : SL->getElementOffset(I + 1);
81 
82  // Rebuild type metadata, adjusting by the split offset.
83  // FIXME: See if we can use DW_OP_piece to preserve debug metadata here.
84  for (MDNode *Type : Types) {
85  uint64_t ByteOffset = cast<ConstantInt>(
86  cast<ConstantAsMetadata>(Type->getOperand(0))->getValue())
87  ->getZExtValue();
88  // Type metadata may be attached one byte after the end of the vtable, for
89  // classes without virtual methods in Itanium ABI. AFAIK, it is never
90  // attached to the first byte of a vtable. Subtract one to get the right
91  // slice.
92  // This is making an assumption that vtable groups are the only kinds of
93  // global variables that !type metadata can be attached to, and that they
94  // are either Itanium ABI vtable groups or contain a single vtable (i.e.
95  // Microsoft ABI vtables).
96  uint64_t AttachedTo = (ByteOffset == 0) ? ByteOffset : ByteOffset - 1;
97  if (AttachedTo < SplitBegin || AttachedTo >= SplitEnd)
98  continue;
99  SplitGV->addMetadata(
101  *MDNode::get(GV.getContext(),
103  ConstantInt::get(Int32Ty, ByteOffset - SplitBegin)),
104  Type->getOperand(1)}));
105  }
106  }
107 
108  for (User *U : GV.users()) {
109  auto *GEP = cast<GEPOperator>(U);
110  unsigned I = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
111  if (I >= SplitGlobals.size())
112  continue;
113 
115  Ops.push_back(ConstantInt::get(Int32Ty, 0));
116  for (unsigned I = 3; I != GEP->getNumOperands(); ++I)
117  Ops.push_back(GEP->getOperand(I));
118 
119  auto *NewGEP = ConstantExpr::getGetElementPtr(
120  SplitGlobals[I]->getInitializer()->getType(), SplitGlobals[I], Ops,
121  GEP->isInBounds());
122  GEP->replaceAllUsesWith(NewGEP);
123  }
124 
125  // Finally, remove the original global. Any remaining uses refer to invalid
126  // elements of the global, so replace with undef.
127  if (!GV.use_empty())
129  GV.eraseFromParent();
130  return true;
131 }
132 
133 bool splitGlobals(Module &M) {
134  // First, see if the module uses either of the llvm.type.test or
135  // llvm.type.checked.load intrinsics, which indicates that splitting globals
136  // may be beneficial.
137  Function *TypeTestFunc =
138  M.getFunction(Intrinsic::getName(Intrinsic::type_test));
139  Function *TypeCheckedLoadFunc =
140  M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load));
141  if ((!TypeTestFunc || TypeTestFunc->use_empty()) &&
142  (!TypeCheckedLoadFunc || TypeCheckedLoadFunc->use_empty()))
143  return false;
144 
145  bool Changed = false;
146  for (auto I = M.global_begin(); I != M.global_end();) {
147  GlobalVariable &GV = *I;
148  ++I;
149  Changed |= splitGlobal(GV);
150  }
151  return Changed;
152 }
153 
154 struct GlobalSplit : public ModulePass {
155  static char ID;
156  GlobalSplit() : ModulePass(ID) {
158  }
159  bool runOnModule(Module &M) {
160  if (skipModule(M))
161  return false;
162 
163  return splitGlobals(M);
164  }
165 };
166 
167 }
168 
169 INITIALIZE_PASS(GlobalSplit, "globalsplit", "Global splitter", false, false)
170 char GlobalSplit::ID = 0;
171 
173  return new GlobalSplit;
174 }
175 
177  if (!splitGlobals(M))
178  return PreservedAnalyses::all();
179  return PreservedAnalyses::none();
180 }
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:109
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
DataLayout DL
static Constant * getGetElementPtr(Type *Ty, Constant *C, ArrayRef< Constant * > IdxList, bool InBounds=false, Optional< unsigned > InRangeIndex=None, Type *OnlyIfReducedTy=nullptr)
Getelementptr form.
Definition: Constants.h:1115
void initializeGlobalSplitPass(PassRegistry &)
Like Internal, but omit from symbol table.
Definition: GlobalValue.h:57
Metadata node.
Definition: Metadata.h:862
Hexagon Common GEP
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:218
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition: DataLayout.h:493
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Definition: Function.cpp:591
const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
Definition: DataLayout.cpp:562
global_iterator global_begin()
Definition: Module.h:555
static std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:160
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:428
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:408
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
Definition: Module.cpp:172
uint64_t getElementOffset(unsigned Idx) const
Definition: DataLayout.h:515
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
This file contains the declarations for the subclasses of Constant, which represent the different fla...
void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it...
Definition: Globals.cpp:335
Class to represent integer types.
Definition: DerivedTypes.h:40
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
Definition: Constants.cpp:1320
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:697
static wasm::ValType getType(const TargetRegisterClass *RC)
ModulePass * createGlobalSplitPass()
This pass splits globals into pieces for the benefit of whole-program devirtualization and control-fl...
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition: PassSupport.h:34
global_iterator global_end()
Definition: Module.h:557
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
Module.h This file contains the declarations for the Module class.
uint64_t getSizeInBytes() const
Definition: DataLayout.h:501
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:560
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
iterator_range< user_iterator > users()
Definition: Value.h:395
MDNode * getMetadata(unsigned KindID) const
Get the current metadata attachments for the given kind, if any.
Definition: Metadata.cpp:1431
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1164
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
Definition: Lint.cpp:529
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:260
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.cpp:361
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:235
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
bool hasLocalLinkage() const
Definition: GlobalValue.h:416
bool use_empty() const
Definition: Value.h:322
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:545
A container for analyses that lazily runs them and caches their results.
IntegerType * Int32Ty