LLVM 24.0.0git
ConstantMerge.cpp
Go to the documentation of this file.
1//===- ConstantMerge.cpp - Merge duplicate global constants ---------------===//
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 defines the interface to a pass that merges duplicate global
10// constants together into a single constant that is shared. This is useful
11// because some passes (ie TraceValues) insert a lot of string constants into
12// the program, regardless of whether or not an existing string is available.
13//
14// Algorithm: ConstantMerge is designed to build up a map of available constants
15// and eliminate duplicates when it is initialized.
16//
17//===----------------------------------------------------------------------===//
18
20#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/Statistic.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/GlobalValue.h"
29#include "llvm/IR/LLVMContext.h"
30#include "llvm/IR/Module.h"
32#include "llvm/Support/Debug.h"
33#include "llvm/Transforms/IPO.h"
34#include <algorithm>
35#include <cassert>
36#include <utility>
37
38using namespace llvm;
39
40#define DEBUG_TYPE "constmerge"
41
42STATISTIC(NumIdenticalMerged, "Number of identical global constants merged");
43
44/// Find values that are marked as llvm.used.
45static void FindUsedValues(GlobalVariable *LLVMUsed,
47 if (!LLVMUsed) return;
48 ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
49
50 for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
51 Value *Operand = Inits->getOperand(i)->stripPointerCasts();
52 GlobalValue *GV = cast<GlobalValue>(Operand);
53 UsedValues.insert(GV);
54 }
55}
56
57// True if A is better than B.
59 const GlobalVariable &B) {
60 if (!A.hasLocalLinkage() && B.hasLocalLinkage())
61 return true;
62
63 if (A.hasLocalLinkage() && !B.hasLocalLinkage())
64 return false;
65
66 return !A.hasComdat();
67}
68
69static void copyDebugLocMetadata(const GlobalVariable *From,
70 GlobalVariable *To) {
72 From->getDebugInfo(MDs);
73 for (auto *MD : MDs)
74 To->addDebugInfo(MD);
75}
76
78 return GV->getAlign().value_or(
80}
81
82static bool
84 const SmallPtrSetImpl<const GlobalValue *> &UsedGlobals) {
85 // Only process unnamed_addr constants with initializers in the default
86 // address space.
87 return !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
88 !GV->hasGlobalUnnamedAddr() || GV->getType()->getAddressSpace() != 0 ||
89 GV->hasSection() ||
90 // Don't touch thread-local variables.
91 GV->isThreadLocal() ||
92 // Don't touch values marked with attribute(used).
93 UsedGlobals.count(GV);
94}
95
96static bool canMerge(const GlobalVariable *Old, const GlobalVariable *New) {
97 assert(Old->hasGlobalUnnamedAddr() && New->hasGlobalUnnamedAddr());
99 return false;
100 assert(!New->hasMetadataOtherThanDebugLocAndGuid());
101
102 // Merging constants with different comdats means one group cannot in general
103 // be dropped independently without the other group now having an invalid
104 // reference to the dropped constant.
105 // If we merge into a constant that does not have comdat, we can merge even
106 // when the old constant has a comdat group because it has local linkage and
107 // is therefore not the comdat key.
108 if (Old->getComdat() != New->getComdat() && New->hasComdat())
109 return false;
110
111 return true;
112}
113
114static void replace(Module &M, GlobalVariable *Old, GlobalVariable *New) {
115 Constant *NewConstant = New;
116
117 LLVM_DEBUG(dbgs() << "Replacing global: @" << Old->getName() << " -> @"
118 << New->getName() << "\n");
119
120 // Bump the alignment if necessary.
121 if (Old->getAlign() || New->getAlign())
122 New->setAlignment(std::max(getAlign(Old), getAlign(New)));
123
124 copyDebugLocMetadata(Old, New);
125 Old->replaceAllUsesWith(NewConstant);
126
127 // Delete the global value from the module.
128 assert(Old->hasLocalLinkage() &&
129 "Refusing to delete an externally visible global variable.");
130 Old->eraseFromParent();
131}
132
133static bool mergeConstants(Module &M) {
134 // Find all the globals that are marked "used". These cannot be merged.
136 FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
137 FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
138
139 // Map unique constants to globals.
141
143 SameContentReplacements;
144
145 size_t ChangesMade = 0;
146 size_t OldChangesMade = 0;
147
148 // Iterate constant merging while we are still making progress. Merging two
149 // constants together may allow us to merge other constants together if the
150 // second level constants have initializers which point to the globals that
151 // were just merged.
152 while (true) {
153 // Find the canonical constants others will be merged with.
154 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
155 // If this GV is dead, remove it.
156 GV.removeDeadConstantUsers();
157 if (GV.use_empty() && GV.hasLocalLinkage()) {
158 GV.eraseFromParent();
159 ++ChangesMade;
160 continue;
161 }
162
163 if (isUnmergeableGlobal(&GV, UsedGlobals))
164 continue;
165
166 // This transformation is legal for weak ODR globals in the sense it
167 // doesn't change semantics, but we really don't want to perform it
168 // anyway; it's likely to pessimize code generation, and some tools
169 // (like the Darwin linker in cases involving CFString) don't expect it.
170 if (GV.isWeakForLinker())
171 continue;
172
173 // Don't touch globals with metadata other than !dbg or !guid.
174 if (GV.hasMetadataOtherThanDebugLocAndGuid())
175 continue;
176
177 Constant *Init = GV.getInitializer();
178
179 // Check to see if the initializer is already known.
180 GlobalVariable *&Slot = CMap[Init];
181
182 // If this is the first constant we find or if the old one is local,
183 // replace with the current one. If the current is externally visible
184 // it cannot be replace, but can be the canonical constant we merge with.
185 bool FirstConstantFound = !Slot;
186 if (FirstConstantFound || IsBetterCanonical(GV, *Slot)) {
187 Slot = &GV;
188 LLVM_DEBUG(dbgs() << "Cmap[" << *Init << "] = " << GV.getName()
189 << (FirstConstantFound ? "\n" : " (updated)\n"));
190 }
191 }
192
193 // Identify all globals that can be merged together, filling in the
194 // SameContentReplacements vector. We cannot do the replacement in this pass
195 // because doing so may cause initializers of other globals to be rewritten,
196 // invalidating the Constant* pointers in CMap.
197 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) {
198 if (isUnmergeableGlobal(&GV, UsedGlobals))
199 continue;
200
201 // We can only replace constant with local linkage.
202 if (!GV.hasLocalLinkage())
203 continue;
204
205 Constant *Init = GV.getInitializer();
206
207 // Check to see if the initializer is already known.
208 auto Found = CMap.find(Init);
209 if (Found == CMap.end())
210 continue;
211
212 GlobalVariable *Slot = Found->second;
213 if (Slot == &GV)
214 continue;
215
216 if (!canMerge(&GV, Slot))
217 continue;
218
219 // Make all uses of the duplicate constant use the canonical version.
220 LLVM_DEBUG(dbgs() << "Will replace: @" << GV.getName() << " -> @"
221 << Slot->getName() << "\n");
222 SameContentReplacements.push_back(std::make_pair(&GV, Slot));
223 }
224
225 // Now that we have figured out which replacements must be made, do them all
226 // now. This avoid invalidating the pointers in CMap, which are unneeded
227 // now.
228 for (const auto &[Old, New] : SameContentReplacements) {
229 replace(M, Old, New);
230 ++ChangesMade;
231 ++NumIdenticalMerged;
232 }
233
234 if (ChangesMade == OldChangesMade)
235 break;
236 OldChangesMade = ChangesMade;
237
238 SameContentReplacements.clear();
239 CMap.clear();
240 }
241
242 return ChangesMade;
243}
244
246 if (!mergeConstants(M))
247 return PreservedAnalyses::all();
248
249 // Only global variables were changed.
253 return PA;
254}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool IsBetterCanonical(const GlobalVariable &A, const GlobalVariable &B)
static void copyDebugLocMetadata(const GlobalVariable *From, GlobalVariable *To)
static bool mergeConstants(Module &M)
static Align getAlign(GlobalVariable *GV)
static bool isUnmergeableGlobal(GlobalVariable *GV, const SmallPtrSetImpl< const GlobalValue * > &UsedGlobals)
static bool canMerge(const GlobalVariable *Old, const GlobalVariable *New)
static void FindUsedValues(GlobalVariable *LLVMUsed, SmallPtrSetImpl< const GlobalValue * > &UsedValues)
Find values that are marked as llvm.used.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
Module.h This file contains the declarations for the Module class.
This file defines the SmallPtrSet class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
ConstantArray - Constant Array Declarations.
Definition Constants.h:590
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &)
This is an important base class in LLVM.
Definition Constant.h:44
LLVM_ABI Align getPreferredAlign(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
const Comdat * getComdat() const
LLVM_ABI bool hasMetadataOtherThanDebugLocAndGuid() const
Definition Globals.cpp:471
bool hasSection() const
Check if this global has a custom object file section.
bool isThreadLocal() const
If the value is "Thread Local", its value isn't shared by the threads.
bool hasLocalLinkage() const
PointerType * getType() const
Global values are always pointers.
LLVM_ABI const DataLayout & getDataLayout() const
Get the data layout of the module this global belongs to.
Definition Globals.cpp:205
bool hasGlobalUnnamedAddr() const
MaybeAlign getAlign() const
Returns the alignment of the given variable.
LLVM_ABI void getDebugInfo(SmallVectorImpl< DIGlobalVariableExpression * > &GVs) const
Fill the vector with all debug info attachements.
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
LLVM_ABI void eraseFromParent()
eraseFromParent - This method unlinks 'this' from the containing module and deletes it.
Definition Globals.cpp:609
LLVM_ABI void addDebugInfo(DIGlobalVariableExpression *GV)
Attach a DIGlobalVariableExpression.
bool hasDefinitiveInitializer() const
hasDefinitiveInitializer - Whether the global variable has an initializer, and any other instances of...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
unsigned getAddressSpace() const
Return the address space of the Pointer 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:151
PreservedAnalyses & preserve()
Mark an analysis as preserved.
Definition Analysis.h:132
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
This is an optimization pass for GlobalISel generic memory operations.
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 raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
void replace(R &&Range, const T &OldValue, const T &NewValue)
Provide wrappers to std::replace which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1926
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39