blob: 79de17567f764624c79d33deac9fab307614bdf4 [file] [log] [blame]
Devang Patel76c85632011-10-17 17:17:43 +00001//===-- GlobalMerge.cpp - Internal globals merging -----------------------===//
Anton Korobeynikov19edda02010-07-24 21:52:08 +00002//
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// This pass merges globals with internal linkage into one. This way all the
10// globals which were merged into a biggest one can be addressed using offsets
11// from the same base pointer (no need for separate base pointer for each of the
12// global). Such a transformation can significantly reduce the register pressure
13// when many globals are involved.
14//
Nadav Rotem465834c2012-07-24 10:51:42 +000015// For example, consider the code which touches several global variables at
Eric Christopherbf86fd32010-09-28 04:18:29 +000016// once:
Anton Korobeynikov19edda02010-07-24 21:52:08 +000017//
18// static int foo[N], bar[N], baz[N];
19//
20// for (i = 0; i < N; ++i) {
21// foo[i] = bar[i] * baz[i];
22// }
23//
24// On ARM the addresses of 3 arrays should be kept in the registers, thus
25// this code has quite large register pressure (loop body):
26//
27// ldr r1, [r5], #4
28// ldr r2, [r6], #4
29// mul r1, r2, r1
30// str r1, [r0], #4
31//
32// Pass converts the code to something like:
33//
34// static struct {
35// int foo[N];
36// int bar[N];
37// int baz[N];
38// } merged;
39//
40// for (i = 0; i < N; ++i) {
41// merged.foo[i] = merged.bar[i] * merged.baz[i];
42// }
43//
44// and in ARM code this becomes:
45//
46// ldr r0, [r5, #40]
47// ldr r1, [r5, #80]
48// mul r0, r1, r0
49// str r0, [r5], #4
50//
51// note that we saved 2 registers here almostly "for free".
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +000052//
53// However, merging globals can have tradeoffs:
54// - it confuses debuggers, tools, and users
55// - it makes linker optimizations less useful (order files, LOHs, ...)
56// - it forces usage of indexed addressing (which isn't necessarily "free")
57// - it can increase register pressure when the uses are disparate enough.
58//
59// We use heuristics to discover the best global grouping we can (cf cl::opts).
Eric Christopherbf86fd32010-09-28 04:18:29 +000060// ===---------------------------------------------------------------------===//
Anton Korobeynikov19edda02010-07-24 21:52:08 +000061
Devang Patel76c85632011-10-17 17:17:43 +000062#include "llvm/Transforms/Scalar.h"
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +000063#include "llvm/ADT/DenseMap.h"
64#include "llvm/ADT/SmallBitVector.h"
Quentin Colombet8fc34092013-03-18 22:30:07 +000065#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000066#include "llvm/ADT/Statistic.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000067#include "llvm/CodeGen/Passes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000068#include "llvm/IR/Attributes.h"
69#include "llvm/IR/Constants.h"
70#include "llvm/IR/DataLayout.h"
71#include "llvm/IR/DerivedTypes.h"
72#include "llvm/IR/Function.h"
73#include "llvm/IR/GlobalVariable.h"
74#include "llvm/IR/Instructions.h"
75#include "llvm/IR/Intrinsics.h"
76#include "llvm/IR/Module.h"
Anton Korobeynikov19edda02010-07-24 21:52:08 +000077#include "llvm/Pass.h"
Quentin Colombet8fc34092013-03-18 22:30:07 +000078#include "llvm/Support/CommandLine.h"
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +000079#include "llvm/Support/Debug.h"
80#include "llvm/Support/raw_ostream.h"
Anton Korobeynikov19edda02010-07-24 21:52:08 +000081#include "llvm/Target/TargetLowering.h"
Bob Wilson881b45c2010-11-17 21:25:39 +000082#include "llvm/Target/TargetLoweringObjectFile.h"
Eric Christopherd9134482014-08-04 21:25:23 +000083#include "llvm/Target/TargetSubtargetInfo.h"
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +000084#include <algorithm>
Anton Korobeynikov19edda02010-07-24 21:52:08 +000085using namespace llvm;
86
Chandler Carruth964daaa2014-04-22 02:55:47 +000087#define DEBUG_TYPE "global-merge"
88
Ahmed Bougachab96444e2015-04-11 00:06:36 +000089// FIXME: This is only useful as a last-resort way to disable the pass.
Quentin Colombet8fc34092013-03-18 22:30:07 +000090static cl::opt<bool>
Jiangning Liu3e5b8552014-06-11 06:35:26 +000091EnableGlobalMerge("enable-global-merge", cl::Hidden,
Ahmed Bougachab96444e2015-04-11 00:06:36 +000092 cl::desc("Enable the global merge pass"),
Tim Northoverf804c172014-02-18 11:17:29 +000093 cl::init(true));
94
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +000095static cl::opt<bool> GlobalMergeGroupByUse(
96 "global-merge-group-by-use", cl::Hidden,
97 cl::desc("Improve global merge pass to look at uses"), cl::init(true));
98
99static cl::opt<bool> GlobalMergeIgnoreSingleUse(
100 "global-merge-ignore-single-use", cl::Hidden,
101 cl::desc("Improve global merge pass to ignore globals only used alone"),
102 cl::init(true));
103
Tim Northoverf804c172014-02-18 11:17:29 +0000104static cl::opt<bool>
Quentin Colombet8fc34092013-03-18 22:30:07 +0000105EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
Jakub Staszak6b36db02013-07-22 21:11:30 +0000106 cl::desc("Enable global merge pass on constants"),
107 cl::init(false));
Quentin Colombet8fc34092013-03-18 22:30:07 +0000108
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000109// FIXME: this could be a transitional option, and we probably need to remove
110// it if only we are sure this optimization could always benefit all targets.
111static cl::opt<bool>
112EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden,
113 cl::desc("Enable global merge pass on external linkage"),
114 cl::init(false));
115
Eric Christophered47b222015-02-23 19:28:45 +0000116STATISTIC(NumMerged, "Number of globals merged");
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000117namespace {
Devang Patel76c85632011-10-17 17:17:43 +0000118 class GlobalMerge : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000119 const TargetMachine *TM;
Eric Christophered47b222015-02-23 19:28:45 +0000120 const DataLayout *DL;
121 // FIXME: Infer the maximum possible offset depending on the actual users
122 // (these max offsets are different for the users inside Thumb or ARM
123 // functions), see the code that passes in the offset in the ARM backend
124 // for more information.
125 unsigned MaxOffset;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000126
127 bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangaa055aab2013-01-07 12:31:25 +0000128 Module &M, bool isConst, unsigned AddrSpace) const;
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000129 /// \brief Merge everything in \p Globals for which the corresponding bit
130 /// in \p GlobalSet is set.
131 bool doMerge(SmallVectorImpl<GlobalVariable *> &Globals,
132 const BitVector &GlobalSet, Module &M, bool isConst,
133 unsigned AddrSpace) const;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000134
Quentin Colombet8fc34092013-03-18 22:30:07 +0000135 /// \brief Check if the given variable has been identified as must keep
136 /// \pre setMustKeepGlobalVariables must have been called on the Module that
137 /// contains GV
138 bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
139 return MustKeepGlobalVariables.count(GV);
140 }
141
142 /// Collect every variables marked as "used" or used in a landing pad
143 /// instruction for this Module.
144 void setMustKeepGlobalVariables(Module &M);
145
146 /// Collect every variables marked as "used"
147 void collectUsedGlobalVariables(Module &M);
148
Quentin Colombet2393cb92013-03-19 21:46:49 +0000149 /// Keep track of the GlobalVariable that must not be merged away
Quentin Colombet8fc34092013-03-18 22:30:07 +0000150 SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
151
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000152 public:
153 static char ID; // Pass identification, replacement for typeid.
Eric Christophered47b222015-02-23 19:28:45 +0000154 explicit GlobalMerge(const TargetMachine *TM = nullptr,
155 unsigned MaximalOffset = 0)
156 : FunctionPass(ID), TM(TM), DL(TM->getDataLayout()),
157 MaxOffset(MaximalOffset) {
Devang Patel76c85632011-10-17 17:17:43 +0000158 initializeGlobalMergePass(*PassRegistry::getPassRegistry());
159 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000160
Craig Topper3e4c6972014-03-05 09:10:37 +0000161 bool doInitialization(Module &M) override;
162 bool runOnFunction(Function &F) override;
163 bool doFinalization(Module &M) override;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000164
Craig Topper3e4c6972014-03-05 09:10:37 +0000165 const char *getPassName() const override {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000166 return "Merge internal globals";
167 }
168
Craig Topper3e4c6972014-03-05 09:10:37 +0000169 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000170 AU.setPreservesCFG();
171 FunctionPass::getAnalysisUsage(AU);
172 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000173 };
174} // end anonymous namespace
175
Devang Patel76c85632011-10-17 17:17:43 +0000176char GlobalMerge::ID = 0;
Eric Christophered47b222015-02-23 19:28:45 +0000177INITIALIZE_PASS_BEGIN(GlobalMerge, "global-merge", "Merge global variables",
178 false, false)
179INITIALIZE_PASS_END(GlobalMerge, "global-merge", "Merge global variables",
180 false, false)
Devang Patel76c85632011-10-17 17:17:43 +0000181
182bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangaa055aab2013-01-07 12:31:25 +0000183 Module &M, bool isConst, unsigned AddrSpace) const {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000184 // FIXME: Find better heuristics
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000185 std::stable_sort(Globals.begin(), Globals.end(),
Eric Christophered47b222015-02-23 19:28:45 +0000186 [this](const GlobalVariable *GV1, const GlobalVariable *GV2) {
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000187 Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType();
188 Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType();
189
190 return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2));
191 });
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000192
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000193 // If we want to just blindly group all globals together, do so.
194 if (!GlobalMergeGroupByUse) {
195 BitVector AllGlobals(Globals.size());
196 AllGlobals.set();
197 return doMerge(Globals, AllGlobals, M, isConst, AddrSpace);
198 }
199
200 // If we want to be smarter, look at all uses of each global, to try to
201 // discover all sets of globals used together, and how many times each of
202 // these sets occured.
203 //
204 // Keep this reasonably efficient, by having an append-only list of all sets
205 // discovered so far (UsedGlobalSet), and mapping each "together-ness" unit of
206 // code (currently, a Function) to the set of globals seen so far that are
207 // used together in that unit (GlobalUsesByFunction).
208 //
209 // When we look at the Nth global, we now that any new set is either:
210 // - the singleton set {N}, containing this global only, or
211 // - the union of {N} and a previously-discovered set, containing some
212 // combination of the previous N-1 globals.
213 // Using that knowledge, when looking at the Nth global, we can keep:
214 // - a reference to the singleton set {N} (CurGVOnlySetIdx)
215 // - a list mapping each previous set to its union with {N} (EncounteredUGS),
216 // if it actually occurs.
217
218 // We keep track of the sets of globals used together "close enough".
219 struct UsedGlobalSet {
220 UsedGlobalSet(size_t Size) : Globals(Size), UsageCount(1) {}
221 BitVector Globals;
222 unsigned UsageCount;
223 };
224
225 // Each set is unique in UsedGlobalSets.
226 std::vector<UsedGlobalSet> UsedGlobalSets;
227
228 // Avoid repeating the create-global-set pattern.
229 auto CreateGlobalSet = [&]() -> UsedGlobalSet & {
230 UsedGlobalSets.emplace_back(Globals.size());
231 return UsedGlobalSets.back();
232 };
233
234 // The first set is the empty set.
235 CreateGlobalSet().UsageCount = 0;
236
237 // We define "close enough" to be "in the same function".
238 // FIXME: Grouping uses by function is way too aggressive, so we should have
239 // a better metric for distance between uses.
240 // The obvious alternative would be to group by BasicBlock, but that's in
241 // turn too conservative..
242 // Anything in between wouldn't be trivial to compute, so just stick with
243 // per-function grouping.
244
245 // The value type is an index into UsedGlobalSets.
246 // The default (0) conveniently points to the empty set.
247 DenseMap<Function *, size_t /*UsedGlobalSetIdx*/> GlobalUsesByFunction;
248
249 // Now, look at each merge-eligible global in turn.
250
251 // Keep track of the sets we already encountered to which we added the
252 // current global.
253 // Each element matches the same-index element in UsedGlobalSets.
254 // This lets us efficiently tell whether a set has already been expanded to
255 // include the current global.
256 std::vector<size_t> EncounteredUGS;
257
258 for (size_t GI = 0, GE = Globals.size(); GI != GE; ++GI) {
259 GlobalVariable *GV = Globals[GI];
260
261 // Reset the encountered sets for this global...
262 std::fill(EncounteredUGS.begin(), EncounteredUGS.end(), 0);
263 // ...and grow it in case we created new sets for the previous global.
264 EncounteredUGS.resize(UsedGlobalSets.size());
265
266 // We might need to create a set that only consists of the current global.
267 // Keep track of its index into UsedGlobalSets.
268 size_t CurGVOnlySetIdx = 0;
269
270 // For each global, look at all its Uses.
271 for (auto &U : GV->uses()) {
272 // This Use might be a ConstantExpr. We're interested in Instruction
273 // users, so look through ConstantExpr...
274 Use *UI, *UE;
275 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U.getUser())) {
276 UI = &*CE->use_begin();
277 UE = nullptr;
278 } else if (isa<Instruction>(U.getUser())) {
279 UI = &U;
280 UE = UI->getNext();
281 } else {
282 continue;
283 }
284
285 // ...to iterate on all the instruction users of the global.
286 // Note that we iterate on Uses and not on Users to be able to getNext().
287 for (; UI != UE; UI = UI->getNext()) {
288 Instruction *I = dyn_cast<Instruction>(UI->getUser());
289 if (!I)
290 continue;
291
292 Function *ParentFn = I->getParent()->getParent();
293 size_t UGSIdx = GlobalUsesByFunction[ParentFn];
294
295 // If this is the first global the basic block uses, map it to the set
296 // consisting of this global only.
297 if (!UGSIdx) {
298 // If that set doesn't exist yet, create it.
299 if (!CurGVOnlySetIdx) {
300 CurGVOnlySetIdx = UsedGlobalSets.size();
301 CreateGlobalSet().Globals.set(GI);
302 } else {
303 ++UsedGlobalSets[CurGVOnlySetIdx].UsageCount;
304 }
305
306 GlobalUsesByFunction[ParentFn] = CurGVOnlySetIdx;
307 continue;
308 }
309
310 // If we already encountered this BB, just increment the counter.
311 if (UsedGlobalSets[UGSIdx].Globals.test(GI)) {
312 ++UsedGlobalSets[UGSIdx].UsageCount;
313 continue;
314 }
315
316 // If not, the previous set wasn't actually used in this function.
317 --UsedGlobalSets[UGSIdx].UsageCount;
318
319 // If we already expanded the previous set to include this global, just
320 // reuse that expanded set.
321 if (size_t ExpandedIdx = EncounteredUGS[UGSIdx]) {
322 ++UsedGlobalSets[ExpandedIdx].UsageCount;
323 GlobalUsesByFunction[ParentFn] = ExpandedIdx;
324 continue;
325 }
326
327 // If not, create a new set consisting of the union of the previous set
328 // and this global. Mark it as encountered, so we can reuse it later.
329 GlobalUsesByFunction[ParentFn] = EncounteredUGS[UGSIdx] =
330 UsedGlobalSets.size();
331
332 UsedGlobalSet &NewUGS = CreateGlobalSet();
333 NewUGS.Globals.set(GI);
334 NewUGS.Globals |= UsedGlobalSets[UGSIdx].Globals;
335 }
336 }
337 }
338
339 // Now we found a bunch of sets of globals used together. We accumulated
340 // the number of times we encountered the sets (i.e., the number of blocks
341 // that use that exact set of globals).
342 //
343 // Multiply that by the size of the set to give us a crude profitability
344 // metric.
345 std::sort(UsedGlobalSets.begin(), UsedGlobalSets.end(),
346 [](const UsedGlobalSet &UGS1, const UsedGlobalSet &UGS2) {
347 return UGS1.Globals.count() * UGS1.UsageCount <
348 UGS2.Globals.count() * UGS2.UsageCount;
349 });
350
351 // We can choose to merge all globals together, but ignore globals never used
352 // with another global. This catches the obviously non-profitable cases of
353 // having a single global, but is aggressive enough for any other case.
354 if (GlobalMergeIgnoreSingleUse) {
355 BitVector AllGlobals(Globals.size());
356 for (size_t i = 0, e = UsedGlobalSets.size(); i != e; ++i) {
357 const UsedGlobalSet &UGS = UsedGlobalSets[e - i - 1];
358 if (UGS.UsageCount == 0)
359 continue;
360 if (UGS.Globals.count() > 1)
361 AllGlobals |= UGS.Globals;
362 }
363 return doMerge(Globals, AllGlobals, M, isConst, AddrSpace);
364 }
365
366 // Starting from the sets with the best (=biggest) profitability, find a
367 // good combination.
368 // The ideal (and expensive) solution can only be found by trying all
369 // combinations, looking for the one with the best profitability.
370 // Don't be smart about it, and just pick the first compatible combination,
371 // starting with the sets with the best profitability.
372 BitVector PickedGlobals(Globals.size());
373 bool Changed = false;
374
375 for (size_t i = 0, e = UsedGlobalSets.size(); i != e; ++i) {
376 const UsedGlobalSet &UGS = UsedGlobalSets[e - i - 1];
377 if (UGS.UsageCount == 0)
378 continue;
379 if (PickedGlobals.anyCommon(UGS.Globals))
380 continue;
381 PickedGlobals |= UGS.Globals;
382 // If the set only contains one global, there's no point in merging.
383 // Ignore the global for inclusion in other sets though, so keep it in
384 // PickedGlobals.
385 if (UGS.Globals.count() < 2)
386 continue;
387 Changed |= doMerge(Globals, UGS.Globals, M, isConst, AddrSpace);
388 }
389
390 return Changed;
391}
392
393bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable *> &Globals,
394 const BitVector &GlobalSet, Module &M, bool isConst,
395 unsigned AddrSpace) const {
396
Chris Lattner229907c2011-07-18 04:54:35 +0000397 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000398
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000399 assert(Globals.size() > 1);
400
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000401 DEBUG(dbgs() << " Trying to merge set, starts with #"
402 << GlobalSet.find_first() << "\n");
403
404 ssize_t i = GlobalSet.find_first();
405 while (i != -1) {
406 ssize_t j = 0;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000407 uint64_t MergedSize = 0;
Jay Foadb804a2b2011-07-12 14:06:48 +0000408 std::vector<Type*> Tys;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000409 std::vector<Constant*> Inits;
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000410
411 bool HasExternal = false;
412 GlobalVariable *TheFirstExternal = 0;
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000413 for (j = i; j != -1; j = GlobalSet.find_next(j)) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000414 Type *Ty = Globals[j]->getType()->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000415 MergedSize += DL->getTypeAllocSize(Ty);
Bob Wilson4c8ab192010-11-17 21:25:36 +0000416 if (MergedSize > MaxOffset) {
417 break;
418 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000419 Tys.push_back(Ty);
420 Inits.push_back(Globals[j]->getInitializer());
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000421
422 if (Globals[j]->hasExternalLinkage() && !HasExternal) {
423 HasExternal = true;
424 TheFirstExternal = Globals[j];
425 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000426 }
427
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000428 // If merged variables doesn't have external linkage, we needn't to expose
429 // the symbol after merging.
430 GlobalValue::LinkageTypes Linkage = HasExternal
431 ? GlobalValue::ExternalLinkage
432 : GlobalValue::InternalLinkage;
433
Chris Lattnere40007a2010-09-05 21:18:45 +0000434 StructType *MergedTy = StructType::get(M.getContext(), Tys);
435 Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000436
Benjamin Kramercccdadc2014-07-08 14:55:06 +0000437 // If merged variables have external linkage, we use symbol name of the
438 // first variable merged as the suffix of global symbol name. This would
439 // be able to avoid the link-time naming conflict for globalm symbols.
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000440 GlobalVariable *MergedGV = new GlobalVariable(
Benjamin Kramercccdadc2014-07-08 14:55:06 +0000441 M, MergedTy, isConst, Linkage, MergedInit,
442 HasExternal ? "_MergedGlobals_" + TheFirstExternal->getName()
443 : "_MergedGlobals",
444 nullptr, GlobalVariable::NotThreadLocal, AddrSpace);
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000445
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000446 for (ssize_t k = i, idx = 0; k != j; k = GlobalSet.find_next(k)) {
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000447 GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage();
448 std::string Name = Globals[k]->getName();
449
Chris Lattnere40007a2010-09-05 21:18:45 +0000450 Constant *Idx[2] = {
451 ConstantInt::get(Int32Ty, 0),
Ahmed Bougacha279e3ee2015-04-18 01:21:58 +0000452 ConstantInt::get(Int32Ty, idx++)
Chris Lattnere40007a2010-09-05 21:18:45 +0000453 };
David Blaikie4a2e73b2015-04-02 18:55:32 +0000454 Constant *GEP =
455 ConstantExpr::getInBoundsGetElementPtr(MergedTy, MergedGV, Idx);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000456 Globals[k]->replaceAllUsesWith(GEP);
457 Globals[k]->eraseFromParent();
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000458
459 if (Linkage != GlobalValue::InternalLinkage) {
460 // Generate a new alias...
461 auto *PTy = cast<PointerType>(GEP->getType());
David Blaikief64246b2015-04-29 21:22:39 +0000462 GlobalAlias::create(PTy, Linkage, Name, GEP, &M);
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000463 }
464
Devang Patel76c85632011-10-17 17:17:43 +0000465 NumMerged++;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000466 }
467 i = j;
468 }
469
470 return true;
471}
472
Quentin Colombet8fc34092013-03-18 22:30:07 +0000473void GlobalMerge::collectUsedGlobalVariables(Module &M) {
474 // Extract global variables from llvm.used array
475 const GlobalVariable *GV = M.getGlobalVariable("llvm.used");
476 if (!GV || !GV->hasInitializer()) return;
477
478 // Should be an array of 'i8*'.
Rafael Espindola74f2e462013-04-22 14:58:02 +0000479 const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
480
Quentin Colombet8fc34092013-03-18 22:30:07 +0000481 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
482 if (const GlobalVariable *G =
483 dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
484 MustKeepGlobalVariables.insert(G);
485}
486
487void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
Quentin Colombet8fc34092013-03-18 22:30:07 +0000488 collectUsedGlobalVariables(M);
489
490 for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
491 ++IFn) {
492 for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
493 IBB != IEndBB; ++IBB) {
Mark Seaborn07e74862014-03-13 00:04:17 +0000494 // Follow the invoke link to find the landing pad instruction
Quentin Colombet8fc34092013-03-18 22:30:07 +0000495 const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
496 if (!II) continue;
497
498 const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst();
499 // Look for globals in the clauses of the landing pad instruction
500 for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses();
501 Idx != NumClauses; ++Idx)
502 if (const GlobalVariable *GV =
503 dyn_cast<GlobalVariable>(LPInst->getClause(Idx)
504 ->stripPointerCasts()))
505 MustKeepGlobalVariables.insert(GV);
506 }
507 }
508}
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000509
Devang Patel76c85632011-10-17 17:17:43 +0000510bool GlobalMerge::doInitialization(Module &M) {
Tim Northoverf804c172014-02-18 11:17:29 +0000511 if (!EnableGlobalMerge)
512 return false;
513
Silviu Barangaa055aab2013-01-07 12:31:25 +0000514 DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
515 BSSGlobals;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000516 bool Changed = false;
Quentin Colombet8fc34092013-03-18 22:30:07 +0000517 setMustKeepGlobalVariables(M);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000518
519 // Grab all non-const globals.
520 for (Module::global_iterator I = M.global_begin(),
521 E = M.global_end(); I != E; ++I) {
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000522 // Merge is safe for "normal" internal or external globals only
523 if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
524 continue;
525
526 if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) &&
527 !I->hasInternalLinkage())
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000528 continue;
529
Silviu Barangaa055aab2013-01-07 12:31:25 +0000530 PointerType *PT = dyn_cast<PointerType>(I->getType());
531 assert(PT && "Global variable is not a pointer!");
532
533 unsigned AddressSpace = PT->getAddressSpace();
534
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000535 // Ignore fancy-aligned globals for now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000536 unsigned Alignment = DL->getPreferredAlignment(I);
Chris Lattner229907c2011-07-18 04:54:35 +0000537 Type *Ty = I->getType()->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000538 if (Alignment > DL->getABITypeAlignment(Ty))
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000539 continue;
540
Anton Korobeynikov6bcea062010-07-26 18:45:39 +0000541 // Ignore all 'special' globals.
542 if (I->getName().startswith("llvm.") ||
543 I->getName().startswith(".llvm."))
544 continue;
545
Quentin Colombet8fc34092013-03-18 22:30:07 +0000546 // Ignore all "required" globals:
Quentin Colombet8fc34092013-03-18 22:30:07 +0000547 if (isMustKeepGlobalVariable(I))
548 continue;
549
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000550 if (DL->getTypeAllocSize(Ty) < MaxOffset) {
Eric Christopher2af33752014-06-10 20:39:39 +0000551 if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
Silviu Barangaa055aab2013-01-07 12:31:25 +0000552 BSSGlobals[AddressSpace].push_back(I);
Bob Wilson881b45c2010-11-17 21:25:39 +0000553 else if (I->isConstant())
Silviu Barangaa055aab2013-01-07 12:31:25 +0000554 ConstGlobals[AddressSpace].push_back(I);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000555 else
Silviu Barangaa055aab2013-01-07 12:31:25 +0000556 Globals[AddressSpace].push_back(I);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000557 }
558 }
559
Silviu Barangaa055aab2013-01-07 12:31:25 +0000560 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
561 I = Globals.begin(), E = Globals.end(); I != E; ++I)
562 if (I->second.size() > 1)
563 Changed |= doMerge(I->second, M, false, I->first);
564
565 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
566 I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
567 if (I->second.size() > 1)
568 Changed |= doMerge(I->second, M, false, I->first);
Bob Wilson881b45c2010-11-17 21:25:39 +0000569
Quentin Colombet8fc34092013-03-18 22:30:07 +0000570 if (EnableGlobalMergeOnConst)
571 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
572 I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
573 if (I->second.size() > 1)
574 Changed |= doMerge(I->second, M, true, I->first);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000575
576 return Changed;
577}
578
Devang Patel76c85632011-10-17 17:17:43 +0000579bool GlobalMerge::runOnFunction(Function &F) {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000580 return false;
581}
582
Quentin Colombet2393cb92013-03-19 21:46:49 +0000583bool GlobalMerge::doFinalization(Module &M) {
584 MustKeepGlobalVariables.clear();
585 return false;
586}
587
Eric Christophered47b222015-02-23 19:28:45 +0000588Pass *llvm::createGlobalMergePass(const TargetMachine *TM, unsigned Offset) {
589 return new GlobalMerge(TM, Offset);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000590}