LLVM  8.0.1
ConstantMerge.cpp
Go to the documentation of this file.
1 //===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//
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 file defines the interface to a pass that merges duplicate global
11 // constants together into a single constant that is shared. This is useful
12 // because some passes (ie TraceValues) insert a lot of string constants into
13 // the program, regardless of whether or not an existing string is available.
14 //
15 // Algorithm: ConstantMerge is designed to build up a map of available constants
16 // and eliminate duplicates when it is initialized.
17 //
18 //===----------------------------------------------------------------------===//
19 
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/SmallPtrSet.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/GlobalValue.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Transforms/IPO.h"
35 #include <algorithm>
36 #include <cassert>
37 #include <utility>
38 
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "constmerge"
42 
43 STATISTIC(NumIdenticalMerged, "Number of identical global constants merged");
44 
45 /// Find values that are marked as llvm.used.
46 static void FindUsedValues(GlobalVariable *LLVMUsed,
48  if (!LLVMUsed) return;
49  ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
50 
51  for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
52  Value *Operand = Inits->getOperand(i)->stripPointerCastsNoFollowAliases();
53  GlobalValue *GV = cast<GlobalValue>(Operand);
54  UsedValues.insert(GV);
55  }
56 }
57 
58 // True if A is better than B.
59 static bool IsBetterCanonical(const GlobalVariable &A,
60  const GlobalVariable &B) {
61  if (!A.hasLocalLinkage() && B.hasLocalLinkage())
62  return true;
63 
64  if (A.hasLocalLinkage() && !B.hasLocalLinkage())
65  return false;
66 
67  return A.hasGlobalUnnamedAddr();
68 }
69 
72  GV->getAllMetadata(MDs);
73  for (const auto &V : MDs)
74  if (V.first != LLVMContext::MD_dbg)
75  return true;
76  return false;
77 }
78 
80  GlobalVariable *To) {
82  From->getDebugInfo(MDs);
83  for (auto MD : MDs)
84  To->addDebugInfo(MD);
85 }
86 
87 static unsigned getAlignment(GlobalVariable *GV) {
88  unsigned Align = GV->getAlignment();
89  if (Align)
90  return Align;
91  return GV->getParent()->getDataLayout().getPreferredAlignment(GV);
92 }
93 
94 enum class CanMerge { No, Yes };
96  if (!Old->hasGlobalUnnamedAddr() && !New->hasGlobalUnnamedAddr())
97  return CanMerge::No;
99  return CanMerge::No;
101  if (!Old->hasGlobalUnnamedAddr())
103  return CanMerge::Yes;
104 }
105 
106 static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New) {
107  Constant *NewConstant = New;
108 
109  LLVM_DEBUG(dbgs() << "Replacing global: @" << Old->getName() << " -> @"
110  << New->getName() << "\n");
111 
112  // Bump the alignment if necessary.
113  if (Old->getAlignment() || New->getAlignment())
115 
116  copyDebugLocMetadata(Old, New);
117  Old->replaceAllUsesWith(NewConstant);
118 
119  // Delete the global value from the module.
120  assert(Old->hasLocalLinkage() &&
121  "Refusing to delete an externally visible global variable.");
122  Old->eraseFromParent();
123 }
124 
125 static bool mergeConstants(Module &M) {
126  // Find all the globals that are marked "used". These cannot be merged.
128  FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
129  FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
130 
131  // Map unique constants to globals.
133 
135  SameContentReplacements;
136 
137  size_t ChangesMade = 0;
138  size_t OldChangesMade = 0;
139 
140  // Iterate constant merging while we are still making progress. Merging two
141  // constants together may allow us to merge other constants together if the
142  // second level constants have initializers which point to the globals that
143  // were just merged.
144  while (true) {
145  // Find the canonical constants others will be merged with.
146  for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
147  GVI != E; ) {
148  GlobalVariable *GV = &*GVI++;
149 
150  // If this GV is dead, remove it.
152  if (GV->use_empty() && GV->hasLocalLinkage()) {
153  GV->eraseFromParent();
154  ++ChangesMade;
155  continue;
156  }
157 
158  // Only process constants with initializers in the default address space.
159  if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
160  GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
161  // Don't touch values marked with attribute(used).
162  UsedGlobals.count(GV))
163  continue;
164 
165  // This transformation is legal for weak ODR globals in the sense it
166  // doesn't change semantics, but we really don't want to perform it
167  // anyway; it's likely to pessimize code generation, and some tools
168  // (like the Darwin linker in cases involving CFString) don't expect it.
169  if (GV->isWeakForLinker())
170  continue;
171 
172  // Don't touch globals with metadata other then !dbg.
174  continue;
175 
176  Constant *Init = GV->getInitializer();
177 
178  // Check to see if the initializer is already known.
179  GlobalVariable *&Slot = CMap[Init];
180 
181  // If this is the first constant we find or if the old one is local,
182  // replace with the current one. If the current is externally visible
183  // it cannot be replace, but can be the canonical constant we merge with.
184  bool FirstConstantFound = !Slot;
185  if (FirstConstantFound || IsBetterCanonical(*GV, *Slot)) {
186  Slot = GV;
187  LLVM_DEBUG(dbgs() << "Cmap[" << *Init << "] = " << GV->getName()
188  << (FirstConstantFound ? "\n" : " (updated)\n"));
189  }
190  }
191 
192  // Identify all globals that can be merged together, filling in the
193  // SameContentReplacements vector. We cannot do the replacement in this pass
194  // because doing so may cause initializers of other globals to be rewritten,
195  // invalidating the Constant* pointers in CMap.
196  for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
197  GVI != E; ) {
198  GlobalVariable *GV = &*GVI++;
199 
200  // Only process constants with initializers in the default address space.
201  if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
202  GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
203  // Don't touch values marked with attribute(used).
204  UsedGlobals.count(GV))
205  continue;
206 
207  // We can only replace constant with local linkage.
208  if (!GV->hasLocalLinkage())
209  continue;
210 
211  Constant *Init = GV->getInitializer();
212 
213  // Check to see if the initializer is already known.
214  auto Found = CMap.find(Init);
215  if (Found == CMap.end())
216  continue;
217 
218  GlobalVariable *Slot = Found->second;
219  if (Slot == GV)
220  continue;
221 
222  if (makeMergeable(GV, Slot) == CanMerge::No)
223  continue;
224 
225  // Make all uses of the duplicate constant use the canonical version.
226  LLVM_DEBUG(dbgs() << "Will replace: @" << GV->getName() << " -> @"
227  << Slot->getName() << "\n");
228  SameContentReplacements.push_back(std::make_pair(GV, Slot));
229  }
230 
231  // Now that we have figured out which replacements must be made, do them all
232  // now. This avoid invalidating the pointers in CMap, which are unneeded
233  // now.
234  for (unsigned i = 0, e = SameContentReplacements.size(); i != e; ++i) {
235  GlobalVariable *Old = SameContentReplacements[i].first;
236  GlobalVariable *New = SameContentReplacements[i].second;
237  replace(M, Old, New);
238  ++ChangesMade;
239  ++NumIdenticalMerged;
240  }
241 
242  if (ChangesMade == OldChangesMade)
243  break;
244  OldChangesMade = ChangesMade;
245 
246  SameContentReplacements.clear();
247  CMap.clear();
248  }
249 
250  return ChangesMade;
251 }
252 
254  if (!mergeConstants(M))
255  return PreservedAnalyses::all();
256  return PreservedAnalyses::none();
257 }
258 
259 namespace {
260 
261 struct ConstantMergeLegacyPass : public ModulePass {
262  static char ID; // Pass identification, replacement for typeid
263 
264  ConstantMergeLegacyPass() : ModulePass(ID) {
266  }
267 
268  // For this pass, process all of the globals in the module, eliminating
269  // duplicate constants.
270  bool runOnModule(Module &M) override {
271  if (skipModule(M))
272  return false;
273  return mergeConstants(M);
274  }
275 };
276 
277 } // end anonymous namespace
278 
280 
281 INITIALIZE_PASS(ConstantMergeLegacyPass, "constmerge",
282  "Merge Duplicate Global Constants", false, false)
283 
285  return new ConstantMergeLegacyPass();
286 }
unsigned getAlignment() const
Definition: GlobalObject.h:59
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
bool hasLocalLinkage() const
Definition: GlobalValue.h:436
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
This class represents lattice values for constants.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:65
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition: Module.h:387
STATISTIC(NumFunctions, "Total number of functions")
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode *>> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
Definition: Metadata.cpp:1417
void setAlignment(unsigned Align)
Definition: Globals.cpp:116
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:344
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:371
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
global_iterator global_begin()
Definition: Module.h:578
static bool IsBetterCanonical(const GlobalVariable &A, const GlobalVariable &B)
static unsigned getAlignment(GlobalVariable *GV)
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:429
static bool hasMetadataOtherThanDebugLoc(const GlobalVariable *GV)
Value * getOperand(unsigned i) const
Definition: User.h:170
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Definition: Constants.cpp:537
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:157
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:370
INITIALIZE_PASS(ConstantMergeLegacyPass, "constmerge", "Merge Duplicate Global Constants", false, false) ModulePass *llvm
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:154
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static void copyDebugLocMetadata(const GlobalVariable *From, GlobalVariable *To)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression *> &GVs) const
Fill the vector with all debug info attachements.
Definition: Metadata.cpp:1525
void eraseFromParent()
eraseFromParent - This method unlinks &#39;this&#39; from the containing module and deletes it...
Definition: Globals.cpp:359
static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New)
ModulePass * createConstantMergePass()
createConstantMergePass - This function returns a new pass that merges duplicate global constants tog...
unsigned getAddressSpace() const
Return the address space of the Pointer type.
Definition: DerivedTypes.h:495
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:382
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:160
size_t size() const
Definition: SmallVector.h:53
void initializeConstantMergeLegacyPassPass(PassRegistry &)
global_iterator global_end()
Definition: Module.h:580
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
Definition: User.h:192
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
BlockVerifier::State From
bool hasSection() const
Check if this global has a custom object file section.
Definition: GlobalObject.h:82
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:200
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
CanMerge
unsigned getPreferredAlignment(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
Definition: DataLayout.cpp:818
ConstantArray - Constant Array Declarations.
Definition: Constants.h:414
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:216
const Value * stripPointerCastsNoFollowAliases() const
Strip off pointer casts and all-zero GEPs.
Definition: Value.cpp:533
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
static bool mergeConstants(Module &M)
static void FindUsedValues(GlobalVariable *LLVMUsed, SmallPtrSetImpl< const GlobalValue *> &UsedValues)
Find values that are marked as llvm.used.
static CanMerge makeMergeable(GlobalVariable *Old, GlobalVariable *New)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:566
LLVM Value Representation.
Definition: Value.h:73
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Definition: Metadata.cpp:1521
A container for analyses that lazily runs them and caches their results.
#define LLVM_DEBUG(X)
Definition: Debug.h:123
bool use_empty() const
Definition: Value.h:323
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:274