blob: 2157bcbe7d4a4b7fc7fbe5c05a98069c0c2834aa [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".
Eric Christopherbf86fd32010-09-28 04:18:29 +000052// ===---------------------------------------------------------------------===//
Anton Korobeynikov19edda02010-07-24 21:52:08 +000053
Devang Patel76c85632011-10-17 17:17:43 +000054#include "llvm/Transforms/Scalar.h"
Quentin Colombet8fc34092013-03-18 22:30:07 +000055#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000056#include "llvm/ADT/Statistic.h"
Chandler Carruthd9903882015-01-14 11:23:27 +000057#include "llvm/CodeGen/Passes.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000058#include "llvm/IR/Attributes.h"
59#include "llvm/IR/Constants.h"
60#include "llvm/IR/DataLayout.h"
61#include "llvm/IR/DerivedTypes.h"
62#include "llvm/IR/Function.h"
63#include "llvm/IR/GlobalVariable.h"
64#include "llvm/IR/Instructions.h"
65#include "llvm/IR/Intrinsics.h"
66#include "llvm/IR/Module.h"
Anton Korobeynikov19edda02010-07-24 21:52:08 +000067#include "llvm/Pass.h"
Quentin Colombet8fc34092013-03-18 22:30:07 +000068#include "llvm/Support/CommandLine.h"
Anton Korobeynikov19edda02010-07-24 21:52:08 +000069#include "llvm/Target/TargetLowering.h"
Bob Wilson881b45c2010-11-17 21:25:39 +000070#include "llvm/Target/TargetLoweringObjectFile.h"
Eric Christopherd9134482014-08-04 21:25:23 +000071#include "llvm/Target/TargetSubtargetInfo.h"
Anton Korobeynikov19edda02010-07-24 21:52:08 +000072using namespace llvm;
73
Chandler Carruth964daaa2014-04-22 02:55:47 +000074#define DEBUG_TYPE "global-merge"
75
Ahmed Bougachab96444e2015-04-11 00:06:36 +000076// FIXME: This is only useful as a last-resort way to disable the pass.
Quentin Colombet8fc34092013-03-18 22:30:07 +000077static cl::opt<bool>
Jiangning Liu3e5b8552014-06-11 06:35:26 +000078EnableGlobalMerge("enable-global-merge", cl::Hidden,
Ahmed Bougachab96444e2015-04-11 00:06:36 +000079 cl::desc("Enable the global merge pass"),
Tim Northoverf804c172014-02-18 11:17:29 +000080 cl::init(true));
81
82static cl::opt<bool>
Quentin Colombet8fc34092013-03-18 22:30:07 +000083EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
Jakub Staszak6b36db02013-07-22 21:11:30 +000084 cl::desc("Enable global merge pass on constants"),
85 cl::init(false));
Quentin Colombet8fc34092013-03-18 22:30:07 +000086
Jiangning Liub2ae37f2014-06-11 06:44:53 +000087// FIXME: this could be a transitional option, and we probably need to remove
88// it if only we are sure this optimization could always benefit all targets.
89static cl::opt<bool>
90EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden,
91 cl::desc("Enable global merge pass on external linkage"),
92 cl::init(false));
93
Eric Christophered47b222015-02-23 19:28:45 +000094STATISTIC(NumMerged, "Number of globals merged");
Anton Korobeynikov19edda02010-07-24 21:52:08 +000095namespace {
Devang Patel76c85632011-10-17 17:17:43 +000096 class GlobalMerge : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +000097 const TargetMachine *TM;
Eric Christophered47b222015-02-23 19:28:45 +000098 const DataLayout *DL;
99 // FIXME: Infer the maximum possible offset depending on the actual users
100 // (these max offsets are different for the users inside Thumb or ARM
101 // functions), see the code that passes in the offset in the ARM backend
102 // for more information.
103 unsigned MaxOffset;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000104
105 bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangaa055aab2013-01-07 12:31:25 +0000106 Module &M, bool isConst, unsigned AddrSpace) const;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000107
Quentin Colombet8fc34092013-03-18 22:30:07 +0000108 /// \brief Check if the given variable has been identified as must keep
109 /// \pre setMustKeepGlobalVariables must have been called on the Module that
110 /// contains GV
111 bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
112 return MustKeepGlobalVariables.count(GV);
113 }
114
115 /// Collect every variables marked as "used" or used in a landing pad
116 /// instruction for this Module.
117 void setMustKeepGlobalVariables(Module &M);
118
119 /// Collect every variables marked as "used"
120 void collectUsedGlobalVariables(Module &M);
121
Quentin Colombet2393cb92013-03-19 21:46:49 +0000122 /// Keep track of the GlobalVariable that must not be merged away
Quentin Colombet8fc34092013-03-18 22:30:07 +0000123 SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
124
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000125 public:
126 static char ID; // Pass identification, replacement for typeid.
Eric Christophered47b222015-02-23 19:28:45 +0000127 explicit GlobalMerge(const TargetMachine *TM = nullptr,
128 unsigned MaximalOffset = 0)
129 : FunctionPass(ID), TM(TM), DL(TM->getDataLayout()),
130 MaxOffset(MaximalOffset) {
Devang Patel76c85632011-10-17 17:17:43 +0000131 initializeGlobalMergePass(*PassRegistry::getPassRegistry());
132 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000133
Craig Topper3e4c6972014-03-05 09:10:37 +0000134 bool doInitialization(Module &M) override;
135 bool runOnFunction(Function &F) override;
136 bool doFinalization(Module &M) override;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000137
Craig Topper3e4c6972014-03-05 09:10:37 +0000138 const char *getPassName() const override {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000139 return "Merge internal globals";
140 }
141
Craig Topper3e4c6972014-03-05 09:10:37 +0000142 void getAnalysisUsage(AnalysisUsage &AU) const override {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000143 AU.setPreservesCFG();
144 FunctionPass::getAnalysisUsage(AU);
145 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000146 };
147} // end anonymous namespace
148
Devang Patel76c85632011-10-17 17:17:43 +0000149char GlobalMerge::ID = 0;
Eric Christophered47b222015-02-23 19:28:45 +0000150INITIALIZE_PASS_BEGIN(GlobalMerge, "global-merge", "Merge global variables",
151 false, false)
152INITIALIZE_PASS_END(GlobalMerge, "global-merge", "Merge global variables",
153 false, false)
Devang Patel76c85632011-10-17 17:17:43 +0000154
155bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangaa055aab2013-01-07 12:31:25 +0000156 Module &M, bool isConst, unsigned AddrSpace) const {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000157 // FIXME: Find better heuristics
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000158 std::stable_sort(Globals.begin(), Globals.end(),
Eric Christophered47b222015-02-23 19:28:45 +0000159 [this](const GlobalVariable *GV1, const GlobalVariable *GV2) {
Benjamin Kramer3a377bc2014-03-01 11:47:00 +0000160 Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType();
161 Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType();
162
163 return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2));
164 });
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000165
Chris Lattner229907c2011-07-18 04:54:35 +0000166 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000167
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000168 assert(Globals.size() > 1);
169
170 // FIXME: This simple solution merges globals all together as maximum as
171 // possible. However, with this solution it would be hard to remove dead
172 // global symbols at link-time. An alternative solution could be checking
173 // global symbols references function by function, and make the symbols
174 // being referred in the same function merged and we would probably need
175 // to introduce heuristic algorithm to solve the merge conflict from
176 // different functions.
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000177 for (size_t i = 0, e = Globals.size(); i != e; ) {
178 size_t j = 0;
179 uint64_t MergedSize = 0;
Jay Foadb804a2b2011-07-12 14:06:48 +0000180 std::vector<Type*> Tys;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000181 std::vector<Constant*> Inits;
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000182
183 bool HasExternal = false;
184 GlobalVariable *TheFirstExternal = 0;
Bob Wilson4c8ab192010-11-17 21:25:36 +0000185 for (j = i; j != e; ++j) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000186 Type *Ty = Globals[j]->getType()->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000187 MergedSize += DL->getTypeAllocSize(Ty);
Bob Wilson4c8ab192010-11-17 21:25:36 +0000188 if (MergedSize > MaxOffset) {
189 break;
190 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000191 Tys.push_back(Ty);
192 Inits.push_back(Globals[j]->getInitializer());
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000193
194 if (Globals[j]->hasExternalLinkage() && !HasExternal) {
195 HasExternal = true;
196 TheFirstExternal = Globals[j];
197 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000198 }
199
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000200 // If merged variables doesn't have external linkage, we needn't to expose
201 // the symbol after merging.
202 GlobalValue::LinkageTypes Linkage = HasExternal
203 ? GlobalValue::ExternalLinkage
204 : GlobalValue::InternalLinkage;
205
Chris Lattnere40007a2010-09-05 21:18:45 +0000206 StructType *MergedTy = StructType::get(M.getContext(), Tys);
207 Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000208
Benjamin Kramercccdadc2014-07-08 14:55:06 +0000209 // If merged variables have external linkage, we use symbol name of the
210 // first variable merged as the suffix of global symbol name. This would
211 // be able to avoid the link-time naming conflict for globalm symbols.
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000212 GlobalVariable *MergedGV = new GlobalVariable(
Benjamin Kramercccdadc2014-07-08 14:55:06 +0000213 M, MergedTy, isConst, Linkage, MergedInit,
214 HasExternal ? "_MergedGlobals_" + TheFirstExternal->getName()
215 : "_MergedGlobals",
216 nullptr, GlobalVariable::NotThreadLocal, AddrSpace);
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000217
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000218 for (size_t k = i; k < j; ++k) {
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000219 GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage();
220 std::string Name = Globals[k]->getName();
221
Chris Lattnere40007a2010-09-05 21:18:45 +0000222 Constant *Idx[2] = {
223 ConstantInt::get(Int32Ty, 0),
224 ConstantInt::get(Int32Ty, k-i)
225 };
David Blaikie4a2e73b2015-04-02 18:55:32 +0000226 Constant *GEP =
227 ConstantExpr::getInBoundsGetElementPtr(MergedTy, MergedGV, Idx);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000228 Globals[k]->replaceAllUsesWith(GEP);
229 Globals[k]->eraseFromParent();
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000230
231 if (Linkage != GlobalValue::InternalLinkage) {
232 // Generate a new alias...
233 auto *PTy = cast<PointerType>(GEP->getType());
234 GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(),
235 Linkage, Name, GEP, &M);
236 }
237
Devang Patel76c85632011-10-17 17:17:43 +0000238 NumMerged++;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000239 }
240 i = j;
241 }
242
243 return true;
244}
245
Quentin Colombet8fc34092013-03-18 22:30:07 +0000246void GlobalMerge::collectUsedGlobalVariables(Module &M) {
247 // Extract global variables from llvm.used array
248 const GlobalVariable *GV = M.getGlobalVariable("llvm.used");
249 if (!GV || !GV->hasInitializer()) return;
250
251 // Should be an array of 'i8*'.
Rafael Espindola74f2e462013-04-22 14:58:02 +0000252 const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
253
Quentin Colombet8fc34092013-03-18 22:30:07 +0000254 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
255 if (const GlobalVariable *G =
256 dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
257 MustKeepGlobalVariables.insert(G);
258}
259
260void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
Quentin Colombet8fc34092013-03-18 22:30:07 +0000261 collectUsedGlobalVariables(M);
262
263 for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
264 ++IFn) {
265 for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
266 IBB != IEndBB; ++IBB) {
Mark Seaborn07e74862014-03-13 00:04:17 +0000267 // Follow the invoke link to find the landing pad instruction
Quentin Colombet8fc34092013-03-18 22:30:07 +0000268 const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
269 if (!II) continue;
270
271 const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst();
272 // Look for globals in the clauses of the landing pad instruction
273 for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses();
274 Idx != NumClauses; ++Idx)
275 if (const GlobalVariable *GV =
276 dyn_cast<GlobalVariable>(LPInst->getClause(Idx)
277 ->stripPointerCasts()))
278 MustKeepGlobalVariables.insert(GV);
279 }
280 }
281}
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000282
Devang Patel76c85632011-10-17 17:17:43 +0000283bool GlobalMerge::doInitialization(Module &M) {
Tim Northoverf804c172014-02-18 11:17:29 +0000284 if (!EnableGlobalMerge)
285 return false;
286
Silviu Barangaa055aab2013-01-07 12:31:25 +0000287 DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
288 BSSGlobals;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000289 bool Changed = false;
Quentin Colombet8fc34092013-03-18 22:30:07 +0000290 setMustKeepGlobalVariables(M);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000291
292 // Grab all non-const globals.
293 for (Module::global_iterator I = M.global_begin(),
294 E = M.global_end(); I != E; ++I) {
Jiangning Liub2ae37f2014-06-11 06:44:53 +0000295 // Merge is safe for "normal" internal or external globals only
296 if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
297 continue;
298
299 if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage()) &&
300 !I->hasInternalLinkage())
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000301 continue;
302
Silviu Barangaa055aab2013-01-07 12:31:25 +0000303 PointerType *PT = dyn_cast<PointerType>(I->getType());
304 assert(PT && "Global variable is not a pointer!");
305
306 unsigned AddressSpace = PT->getAddressSpace();
307
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000308 // Ignore fancy-aligned globals for now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000309 unsigned Alignment = DL->getPreferredAlignment(I);
Chris Lattner229907c2011-07-18 04:54:35 +0000310 Type *Ty = I->getType()->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000311 if (Alignment > DL->getABITypeAlignment(Ty))
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000312 continue;
313
Anton Korobeynikov6bcea062010-07-26 18:45:39 +0000314 // Ignore all 'special' globals.
315 if (I->getName().startswith("llvm.") ||
316 I->getName().startswith(".llvm."))
317 continue;
318
Quentin Colombet8fc34092013-03-18 22:30:07 +0000319 // Ignore all "required" globals:
Quentin Colombet8fc34092013-03-18 22:30:07 +0000320 if (isMustKeepGlobalVariable(I))
321 continue;
322
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000323 if (DL->getTypeAllocSize(Ty) < MaxOffset) {
Eric Christopher2af33752014-06-10 20:39:39 +0000324 if (TargetLoweringObjectFile::getKindForGlobal(I, *TM).isBSSLocal())
Silviu Barangaa055aab2013-01-07 12:31:25 +0000325 BSSGlobals[AddressSpace].push_back(I);
Bob Wilson881b45c2010-11-17 21:25:39 +0000326 else if (I->isConstant())
Silviu Barangaa055aab2013-01-07 12:31:25 +0000327 ConstGlobals[AddressSpace].push_back(I);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000328 else
Silviu Barangaa055aab2013-01-07 12:31:25 +0000329 Globals[AddressSpace].push_back(I);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000330 }
331 }
332
Silviu Barangaa055aab2013-01-07 12:31:25 +0000333 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
334 I = Globals.begin(), E = Globals.end(); I != E; ++I)
335 if (I->second.size() > 1)
336 Changed |= doMerge(I->second, M, false, I->first);
337
338 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
339 I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
340 if (I->second.size() > 1)
341 Changed |= doMerge(I->second, M, false, I->first);
Bob Wilson881b45c2010-11-17 21:25:39 +0000342
Quentin Colombet8fc34092013-03-18 22:30:07 +0000343 if (EnableGlobalMergeOnConst)
344 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
345 I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
346 if (I->second.size() > 1)
347 Changed |= doMerge(I->second, M, true, I->first);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000348
349 return Changed;
350}
351
Devang Patel76c85632011-10-17 17:17:43 +0000352bool GlobalMerge::runOnFunction(Function &F) {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000353 return false;
354}
355
Quentin Colombet2393cb92013-03-19 21:46:49 +0000356bool GlobalMerge::doFinalization(Module &M) {
357 MustKeepGlobalVariables.clear();
358 return false;
359}
360
Eric Christophered47b222015-02-23 19:28:45 +0000361Pass *llvm::createGlobalMergePass(const TargetMachine *TM, unsigned Offset) {
362 return new GlobalMerge(TM, Offset);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000363}