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 
20 #include "llvm/Transforms/IPO.h"
21 #include "llvm/ADT/DenseMap.h"
22 #include "llvm/ADT/PointerIntPair.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 using namespace llvm;
32 
33 #define DEBUG_TYPE "constmerge"
34 
35 STATISTIC(NumMerged, "Number of global constants merged");
36 
37 namespace {
38   struct ConstantMerge : public ModulePass {
39     static char ID; // Pass identification, replacement for typeid
40     ConstantMerge() : ModulePass(ID) {
41       initializeConstantMergePass(*PassRegistry::getPassRegistry());
42     }
43 
44     // For this pass, process all of the globals in the module, eliminating
45     // duplicate constants.
46     bool runOnModule(Module &M) override;
47 
48     // Return the alignment of the global, including converting the default
49     // alignment to a concrete value.
50     unsigned getAlignment(GlobalVariable *GV) const;
51 
52   };
53 }
54 
55 char ConstantMerge::ID = 0;
56 INITIALIZE_PASS(ConstantMerge, "constmerge",
57                 "Merge Duplicate Global Constants", false, false)
58 
59 ModulePass *llvm::createConstantMergePass() { return new ConstantMerge(); }
60 
61 
62 
63 /// Find values that are marked as llvm.used.
64 static void FindUsedValues(GlobalVariable *LLVMUsed,
65                            SmallPtrSetImpl<const GlobalValue*> &UsedValues) {
66   if (!LLVMUsed) return;
67   ConstantArray *Inits = cast<ConstantArray>(LLVMUsed->getInitializer());
68 
69   for (unsigned i = 0, e = Inits->getNumOperands(); i != e; ++i) {
70     Value *Operand = Inits->getOperand(i)->stripPointerCastsNoFollowAliases();
71     GlobalValue *GV = cast<GlobalValue>(Operand);
72     UsedValues.insert(GV);
73   }
74 }
75 
76 // True if A is better than B.
77 static bool IsBetterCanonical(const GlobalVariable &A,
78                               const GlobalVariable &B) {
79   if (!A.hasLocalLinkage() && B.hasLocalLinkage())
80     return true;
81 
82   if (A.hasLocalLinkage() && !B.hasLocalLinkage())
83     return false;
84 
85   return A.hasUnnamedAddr();
86 }
87 
88 unsigned ConstantMerge::getAlignment(GlobalVariable *GV) const {
89   unsigned Align = GV->getAlignment();
90   if (Align)
91     return Align;
92   return GV->getParent()->getDataLayout().getPreferredAlignment(GV);
93 }
94 
95 bool ConstantMerge::runOnModule(Module &M) {
96   if (skipModule(M))
97     return false;
98 
99   // Find all the globals that are marked "used".  These cannot be merged.
100   SmallPtrSet<const GlobalValue*, 8> UsedGlobals;
101   FindUsedValues(M.getGlobalVariable("llvm.used"), UsedGlobals);
102   FindUsedValues(M.getGlobalVariable("llvm.compiler.used"), UsedGlobals);
103 
104   // Map unique constants to globals.
105   DenseMap<Constant *, GlobalVariable *> CMap;
106 
107   // Replacements - This vector contains a list of replacements to perform.
108   SmallVector<std::pair<GlobalVariable*, GlobalVariable*>, 32> Replacements;
109 
110   bool MadeChange = false;
111 
112   // Iterate constant merging while we are still making progress.  Merging two
113   // constants together may allow us to merge other constants together if the
114   // second level constants have initializers which point to the globals that
115   // were just merged.
116   while (1) {
117 
118     // First: Find the canonical constants others will be merged with.
119     for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
120          GVI != E; ) {
121       GlobalVariable *GV = &*GVI++;
122 
123       // If this GV is dead, remove it.
124       GV->removeDeadConstantUsers();
125       if (GV->use_empty() && GV->hasLocalLinkage()) {
126         GV->eraseFromParent();
127         continue;
128       }
129 
130       // Only process constants with initializers in the default address space.
131       if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
132           GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
133           // Don't touch values marked with attribute(used).
134           UsedGlobals.count(GV))
135         continue;
136 
137       // This transformation is legal for weak ODR globals in the sense it
138       // doesn't change semantics, but we really don't want to perform it
139       // anyway; it's likely to pessimize code generation, and some tools
140       // (like the Darwin linker in cases involving CFString) don't expect it.
141       if (GV->isWeakForLinker())
142         continue;
143 
144       Constant *Init = GV->getInitializer();
145 
146       // Check to see if the initializer is already known.
147       GlobalVariable *&Slot = CMap[Init];
148 
149       // If this is the first constant we find or if the old one is local,
150       // replace with the current one. If the current is externally visible
151       // it cannot be replace, but can be the canonical constant we merge with.
152       if (!Slot || IsBetterCanonical(*GV, *Slot))
153         Slot = GV;
154     }
155 
156     // Second: identify all globals that can be merged together, filling in
157     // the Replacements vector.  We cannot do the replacement in this pass
158     // because doing so may cause initializers of other globals to be rewritten,
159     // invalidating the Constant* pointers in CMap.
160     for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
161          GVI != E; ) {
162       GlobalVariable *GV = &*GVI++;
163 
164       // Only process constants with initializers in the default address space.
165       if (!GV->isConstant() || !GV->hasDefinitiveInitializer() ||
166           GV->getType()->getAddressSpace() != 0 || GV->hasSection() ||
167           // Don't touch values marked with attribute(used).
168           UsedGlobals.count(GV))
169         continue;
170 
171       // We can only replace constant with local linkage.
172       if (!GV->hasLocalLinkage())
173         continue;
174 
175       Constant *Init = GV->getInitializer();
176 
177       // Check to see if the initializer is already known.
178       GlobalVariable *Slot = CMap[Init];
179 
180       if (!Slot || Slot == GV)
181         continue;
182 
183       if (!Slot->hasUnnamedAddr() && !GV->hasUnnamedAddr())
184         continue;
185 
186       if (!GV->hasUnnamedAddr())
187         Slot->setUnnamedAddr(false);
188 
189       // Make all uses of the duplicate constant use the canonical version.
190       Replacements.push_back(std::make_pair(GV, Slot));
191     }
192 
193     if (Replacements.empty())
194       return MadeChange;
195     CMap.clear();
196 
197     // Now that we have figured out which replacements must be made, do them all
198     // now.  This avoid invalidating the pointers in CMap, which are unneeded
199     // now.
200     for (unsigned i = 0, e = Replacements.size(); i != e; ++i) {
201       // Bump the alignment if necessary.
202       if (Replacements[i].first->getAlignment() ||
203           Replacements[i].second->getAlignment()) {
204         Replacements[i].second->setAlignment(
205             std::max(getAlignment(Replacements[i].first),
206                      getAlignment(Replacements[i].second)));
207       }
208 
209       // Eliminate any uses of the dead global.
210       Replacements[i].first->replaceAllUsesWith(Replacements[i].second);
211 
212       // Delete the global value from the module.
213       assert(Replacements[i].first->hasLocalLinkage() &&
214              "Refusing to delete an externally visible global variable.");
215       Replacements[i].first->eraseFromParent();
216     }
217 
218     NumMerged += Replacements.size();
219     Replacements.clear();
220   }
221 }
222