LLVM  6.0.0svn
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"
23 #include "llvm/ADT/SmallPtrSet.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/Module.h"
29 #include "llvm/IR/Operator.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Transforms/IPO.h"
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "constmerge"
35 
36 STATISTIC(NumMerged, "Number of global constants merged");
37 
38 /// Find values that are marked as llvm.used.
39 static void FindUsedValues(GlobalVariable *LLVMUsed,
41  if (!LLVMUsed) return;
42  ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
43 
44  for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
45  Value *Operand = Inits->getOperand(i)->stripPointerCastsNoFollowAliases();
46  GlobalValue *GV = cast<GlobalValue>(Operand);
47  UsedValues.insert(GV);
48  }
49 }
50 
51 // True if A is better than B.
52 static bool IsBetterCanonical(const GlobalVariable &A,
53  const GlobalVariable &B) {
54  if (!A.hasLocalLinkage() && B.hasLocalLinkage())
55  return true;
56 
57  if (A.hasLocalLinkage() && !B.hasLocalLinkage())
58  return false;
59 
60  return A.hasGlobalUnnamedAddr();
61 }
62 
65  GV->getAllMetadata(MDs);
66  for (const auto &V : MDs)
67  if (V.first != LLVMContext::MD_dbg)
68  return true;
69  return false;
70 }
71 
72 static void copyDebugLocMetadata(const GlobalVariable *From,
73  GlobalVariable *To) {
75  From->getDebugInfo(MDs);
76  for (auto MD : MDs)
77  To->addDebugInfo(MD);
78 }
79 
80 static unsigned getAlignment(GlobalVariable *GV) {
81  unsigned Align = GV->getAlignment();
82  if (Align)
83  return Align;
84  return GV->getParent()->getDataLayout().getPreferredAlignment(GV);
85 }
86 
87 static bool mergeConstants(Module &M) {
88  // Find all the globals that are marked "used". These cannot be merged.
90  FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
91  FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
92 
93  // Map unique constants to globals.
95 
96  // Replacements - This vector contains a list of replacements to perform.
98 
99  bool MadeChange = false;
100 
101  // Iterate constant merging while we are still making progress. Merging two
102  // constants together may allow us to merge other constants together if the
103  // second level constants have initializers which point to the globals that
104  // were just merged.
105  while (1) {
106 
107  // First: Find the canonical constants others will be merged with.
108  for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
109  GVI != E; ) {
110  GlobalVariable *GV = &*GVI++;
111 
112  // If this GV is dead, remove it.
114  if (GV->use_empty() && GV->hasLocalLinkage()) {
115  GV->eraseFromParent();
116  continue;
117  }
118 
119  // Only process constants with initializers in the default address space.
120  if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
121  GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
122  // Don't touch values marked with attribute(used).
123  UsedGlobals.count(GV))
124  continue;
125 
126  // This transformation is legal for weak ODR globals in the sense it
127  // doesn't change semantics, but we really don't want to perform it
128  // anyway; it's likely to pessimize code generation, and some tools
129  // (like the Darwin linker in cases involving CFString) don't expect it.
130  if (GV->isWeakForLinker())
131  continue;
132 
133  // Don't touch globals with metadata other then !dbg.
135  continue;
136 
137  Constant *Init = GV->getInitializer();
138 
139  // Check to see if the initializer is already known.
140  GlobalVariable *&Slot = CMap[Init];
141 
142  // If this is the first constant we find or if the old one is local,
143  // replace with the current one. If the current is externally visible
144  // it cannot be replace, but can be the canonical constant we merge with.
145  if (!Slot || IsBetterCanonical(*GV, *Slot))
146  Slot = GV;
147  }
148 
149  // Second: identify all globals that can be merged together, filling in
150  // the Replacements vector. We cannot do the replacement in this pass
151  // because doing so may cause initializers of other globals to be rewritten,
152  // invalidating the Constant* pointers in CMap.
153  for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
154  GVI != E; ) {
155  GlobalVariable *GV = &*GVI++;
156 
157  // Only process constants with initializers in the default address space.
158  if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
159  GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
160  // Don't touch values marked with attribute(used).
161  UsedGlobals.count(GV))
162  continue;
163 
164  // We can only replace constant with local linkage.
165  if (!GV->hasLocalLinkage())
166  continue;
167 
168  Constant *Init = GV->getInitializer();
169 
170  // Check to see if the initializer is already known.
171  GlobalVariable *Slot = CMap[Init];
172 
173  if (!Slot || Slot == GV)
174  continue;
175 
176  if (!Slot->hasGlobalUnnamedAddr() && !GV->hasGlobalUnnamedAddr())
177  continue;
178 
180  continue;
181 
182  if (!GV->hasGlobalUnnamedAddr())
184 
185  // Make all uses of the duplicate constant use the canonical version.
186  Replacements.push_back(std::make_pair(GV, Slot));
187  }
188 
189  if (Replacements.empty())
190  return MadeChange;
191  CMap.clear();
192 
193  // Now that we have figured out which replacements must be made, do them all
194  // now. This avoid invalidating the pointers in CMap, which are unneeded
195  // now.
196  for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
197  // Bump the alignment if necessary.
198  if (Replacements[i].first->getAlignment() ||
199  Replacements[i].second->getAlignment()) {
200  Replacements[i].second->setAlignment(
201  std::max(getAlignment(Replacements[i].first),
202  getAlignment(Replacements[i].second)));
203  }
204 
205  copyDebugLocMetadata(Replacements[i].first, Replacements[i].second);
206 
207  // Eliminate any uses of the dead global.
208  Replacements[i].first->replaceAllUsesWith(Replacements[i].second);
209 
210  // Delete the global value from the module.
211  assert(Replacements[i].first->hasLocalLinkage() &&
212  "Refusing to delete an externally visible global variable.");
213  Replacements[i].first->eraseFromParent();
214  }
215 
216  NumMerged += Replacements.size();
217  Replacements.clear();
218  }
219 }
220 
222  if (!mergeConstants(M))
223  return PreservedAnalyses::all();
224  return PreservedAnalyses::none();
225 }
226 
227 namespace {
228 struct ConstantMergeLegacyPass : public ModulePass {
229  static char ID; // Pass identification, replacement for typeid
230  ConstantMergeLegacyPass() : ModulePass(ID) {
232  }
233 
234  // For this pass, process all of the globals in the module, eliminating
235  // duplicate constants.
236  bool runOnModule(Module &M) {
237  if (skipModule(M))
238  return false;
239  return mergeConstants(M);
240  }
241 };
242 }
243 
245 INITIALIZE_PASS(ConstantMergeLegacyPass, "constmerge",
246  "Merge Duplicate Global Constants", false, false)
247 
249  return new ConstantMergeLegacyPass();
250 }
unsigned getAlignment() const
Definition: GlobalObject.h:59
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
bool hasLocalLinkage() const
Definition: GlobalValue.h:416
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.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
unsigned second
GlobalVariable * getGlobalVariable(StringRef Name) const
Look up the specified global variable in the module symbol table.
Definition: Module.h:368
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:1404
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Definition: SmallPtrSet.h:345
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
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:555
static bool IsBetterCanonical(const GlobalVariable &A, const GlobalVariable &B)
static unsigned getAlignment(GlobalVariable *GV)
static bool hasMetadataOtherThanDebugLoc(const GlobalVariable *GV)
Value * getOperand(unsigned i) const
Definition: User.h:154
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
Definition: Constants.cpp:475
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
static bool isWeakForLinker(LinkageTypes Linkage)
Whether the definition of this global may be replaced at link time.
Definition: GlobalValue.h:350
INITIALIZE_PASS(ConstantMergeLegacyPass, "constmerge", "Merge Duplicate Global Constants", false, false) ModulePass *llvm
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
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)
#define A
Definition: LargeTest.cpp:12
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:372
void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression *> &GVs) const
Fill the vector with all debug info attachements.
Definition: Metadata.cpp:1515
void eraseFromParent()
eraseFromParent - This method unlinks &#39;this&#39; from the containing module and deletes it...
Definition: Globals.cpp:335
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:383
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
void initializeConstantMergeLegacyPassPass(PassRegistry &)
unsigned first
global_iterator global_end()
Definition: Module.h:557
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
Definition: User.h:176
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:423
#define E
Definition: LargeTest.cpp:27
#define B
Definition: LargeTest.cpp:24
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:864
Module.h This file contains the declarations for the Module class.
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:187
unsigned getPreferredAlignment(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
Definition: DataLayout.cpp:760
ConstantArray - Constant Array Declarations.
Definition: Constants.h:405
PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
void setUnnamedAddr(UnnamedAddr Val)
Definition: GlobalValue.h:203
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:61
const Value * stripPointerCastsNoFollowAliases() const
Strip off pointer casts and all-zero GEPs.
Definition: Value.cpp:531
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:235
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
static bool mergeConstants(Module &M)
static void FindUsedValues(GlobalVariable *LLVMUsed, SmallPtrSetImpl< const GlobalValue *> &UsedValues)
Find values that are marked as llvm.used.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:545
LLVM Value Representation.
Definition: Value.h:73
void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
Definition: Metadata.cpp:1511
A container for analyses that lazily runs them and caches their results.
bool use_empty() const
Definition: Value.h:322
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:260