blob: 161e35a648ba58435d7decf3799f53a5977195fa [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#define DEBUG_TYPE "global-merge"
55#include "llvm/Transforms/Scalar.h"
Quentin Colombet8fc34092013-03-18 22:30:07 +000056#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000057#include "llvm/ADT/Statistic.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"
Anton Korobeynikov19edda02010-07-24 21:52:08 +000071using namespace llvm;
72
Quentin Colombet8fc34092013-03-18 22:30:07 +000073static cl::opt<bool>
Tim Northoverf804c172014-02-18 11:17:29 +000074EnableGlobalMerge("global-merge", cl::Hidden,
75 cl::desc("Enable global merge pass"),
76 cl::init(true));
77
78static cl::opt<bool>
Quentin Colombet8fc34092013-03-18 22:30:07 +000079EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
Jakub Staszak6b36db02013-07-22 21:11:30 +000080 cl::desc("Enable global merge pass on constants"),
81 cl::init(false));
Quentin Colombet8fc34092013-03-18 22:30:07 +000082
Devang Patel76c85632011-10-17 17:17:43 +000083STATISTIC(NumMerged , "Number of globals merged");
Anton Korobeynikov19edda02010-07-24 21:52:08 +000084namespace {
Devang Patel76c85632011-10-17 17:17:43 +000085 class GlobalMerge : public FunctionPass {
Bill Wendling7a639ea2013-06-19 21:07:11 +000086 const TargetMachine *TM;
Anton Korobeynikov19edda02010-07-24 21:52:08 +000087
88 bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangaa055aab2013-01-07 12:31:25 +000089 Module &M, bool isConst, unsigned AddrSpace) const;
Anton Korobeynikov19edda02010-07-24 21:52:08 +000090
Quentin Colombet8fc34092013-03-18 22:30:07 +000091 /// \brief Check if the given variable has been identified as must keep
92 /// \pre setMustKeepGlobalVariables must have been called on the Module that
93 /// contains GV
94 bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
95 return MustKeepGlobalVariables.count(GV);
96 }
97
98 /// Collect every variables marked as "used" or used in a landing pad
99 /// instruction for this Module.
100 void setMustKeepGlobalVariables(Module &M);
101
102 /// Collect every variables marked as "used"
103 void collectUsedGlobalVariables(Module &M);
104
Quentin Colombet2393cb92013-03-19 21:46:49 +0000105 /// Keep track of the GlobalVariable that must not be merged away
Quentin Colombet8fc34092013-03-18 22:30:07 +0000106 SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
107
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000108 public:
109 static char ID; // Pass identification, replacement for typeid.
Bill Wendling7a639ea2013-06-19 21:07:11 +0000110 explicit GlobalMerge(const TargetMachine *TM = 0)
111 : FunctionPass(ID), TM(TM) {
Devang Patel76c85632011-10-17 17:17:43 +0000112 initializeGlobalMergePass(*PassRegistry::getPassRegistry());
113 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000114
115 virtual bool doInitialization(Module &M);
Chris Lattnere40007a2010-09-05 21:18:45 +0000116 virtual bool runOnFunction(Function &F);
Quentin Colombet2393cb92013-03-19 21:46:49 +0000117 virtual bool doFinalization(Module &M);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000118
119 const char *getPassName() const {
120 return "Merge internal globals";
121 }
122
123 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
124 AU.setPreservesCFG();
125 FunctionPass::getAnalysisUsage(AU);
126 }
127
128 struct GlobalCmp {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000129 const DataLayout *DL;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000130
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000131 GlobalCmp(const DataLayout *DL) : DL(DL) { }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000132
Chris Lattnere40007a2010-09-05 21:18:45 +0000133 bool operator()(const GlobalVariable *GV1, const GlobalVariable *GV2) {
Chris Lattner229907c2011-07-18 04:54:35 +0000134 Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType();
135 Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType();
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000136
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000137 return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2));
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000138 }
139 };
140 };
141} // end anonymous namespace
142
Devang Patel76c85632011-10-17 17:17:43 +0000143char GlobalMerge::ID = 0;
144INITIALIZE_PASS(GlobalMerge, "global-merge",
145 "Global Merge", false, false)
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000146
Devang Patel76c85632011-10-17 17:17:43 +0000147
148bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
Silviu Barangaa055aab2013-01-07 12:31:25 +0000149 Module &M, bool isConst, unsigned AddrSpace) const {
Bill Wendling7a639ea2013-06-19 21:07:11 +0000150 const TargetLowering *TLI = TM->getTargetLowering();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000151 const DataLayout *DL = TLI->getDataLayout();
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000152
153 // FIXME: Infer the maximum possible offset depending on the actual users
154 // (these max offsets are different for the users inside Thumb or ARM
155 // functions)
156 unsigned MaxOffset = TLI->getMaximalGlobalOffset();
157
158 // FIXME: Find better heuristics
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000159 std::stable_sort(Globals.begin(), Globals.end(), GlobalCmp(DL));
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000160
Chris Lattner229907c2011-07-18 04:54:35 +0000161 Type *Int32Ty = Type::getInt32Ty(M.getContext());
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000162
163 for (size_t i = 0, e = Globals.size(); i != e; ) {
164 size_t j = 0;
165 uint64_t MergedSize = 0;
Jay Foadb804a2b2011-07-12 14:06:48 +0000166 std::vector<Type*> Tys;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000167 std::vector<Constant*> Inits;
Bob Wilson4c8ab192010-11-17 21:25:36 +0000168 for (j = i; j != e; ++j) {
Jay Foadb804a2b2011-07-12 14:06:48 +0000169 Type *Ty = Globals[j]->getType()->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000170 MergedSize += DL->getTypeAllocSize(Ty);
Bob Wilson4c8ab192010-11-17 21:25:36 +0000171 if (MergedSize > MaxOffset) {
172 break;
173 }
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000174 Tys.push_back(Ty);
175 Inits.push_back(Globals[j]->getInitializer());
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000176 }
177
Chris Lattnere40007a2010-09-05 21:18:45 +0000178 StructType *MergedTy = StructType::get(M.getContext(), Tys);
179 Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
180 GlobalVariable *MergedGV = new GlobalVariable(M, MergedTy, isConst,
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000181 GlobalValue::InternalLinkage,
Silviu Barangaa055aab2013-01-07 12:31:25 +0000182 MergedInit, "_MergedGlobals",
183 0, GlobalVariable::NotThreadLocal,
184 AddrSpace);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000185 for (size_t k = i; k < j; ++k) {
Chris Lattnere40007a2010-09-05 21:18:45 +0000186 Constant *Idx[2] = {
187 ConstantInt::get(Int32Ty, 0),
188 ConstantInt::get(Int32Ty, k-i)
189 };
Jay Foaded8db7d2011-07-21 14:31:17 +0000190 Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(MergedGV, Idx);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000191 Globals[k]->replaceAllUsesWith(GEP);
192 Globals[k]->eraseFromParent();
Devang Patel76c85632011-10-17 17:17:43 +0000193 NumMerged++;
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000194 }
195 i = j;
196 }
197
198 return true;
199}
200
Quentin Colombet8fc34092013-03-18 22:30:07 +0000201void GlobalMerge::collectUsedGlobalVariables(Module &M) {
202 // Extract global variables from llvm.used array
203 const GlobalVariable *GV = M.getGlobalVariable("llvm.used");
204 if (!GV || !GV->hasInitializer()) return;
205
206 // Should be an array of 'i8*'.
Rafael Espindola74f2e462013-04-22 14:58:02 +0000207 const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
208
Quentin Colombet8fc34092013-03-18 22:30:07 +0000209 for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
210 if (const GlobalVariable *G =
211 dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
212 MustKeepGlobalVariables.insert(G);
213}
214
215void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
Quentin Colombet8fc34092013-03-18 22:30:07 +0000216 collectUsedGlobalVariables(M);
217
218 for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
219 ++IFn) {
220 for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
221 IBB != IEndBB; ++IBB) {
222 // Follow the inwoke link to find the landing pad instruction
223 const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
224 if (!II) continue;
225
226 const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst();
227 // Look for globals in the clauses of the landing pad instruction
228 for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses();
229 Idx != NumClauses; ++Idx)
230 if (const GlobalVariable *GV =
231 dyn_cast<GlobalVariable>(LPInst->getClause(Idx)
232 ->stripPointerCasts()))
233 MustKeepGlobalVariables.insert(GV);
234 }
235 }
236}
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000237
Devang Patel76c85632011-10-17 17:17:43 +0000238bool GlobalMerge::doInitialization(Module &M) {
Tim Northoverf804c172014-02-18 11:17:29 +0000239 if (!EnableGlobalMerge)
240 return false;
241
Silviu Barangaa055aab2013-01-07 12:31:25 +0000242 DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
243 BSSGlobals;
Bill Wendling7a639ea2013-06-19 21:07:11 +0000244 const TargetLowering *TLI = TM->getTargetLowering();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000245 const DataLayout *DL = TLI->getDataLayout();
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000246 unsigned MaxOffset = TLI->getMaximalGlobalOffset();
247 bool Changed = false;
Quentin Colombet8fc34092013-03-18 22:30:07 +0000248 setMustKeepGlobalVariables(M);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000249
250 // Grab all non-const globals.
251 for (Module::global_iterator I = M.global_begin(),
252 E = M.global_end(); I != E; ++I) {
253 // Merge is safe for "normal" internal globals only
254 if (!I->hasLocalLinkage() || I->isThreadLocal() || I->hasSection())
255 continue;
256
Silviu Barangaa055aab2013-01-07 12:31:25 +0000257 PointerType *PT = dyn_cast<PointerType>(I->getType());
258 assert(PT && "Global variable is not a pointer!");
259
260 unsigned AddressSpace = PT->getAddressSpace();
261
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000262 // Ignore fancy-aligned globals for now.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000263 unsigned Alignment = DL->getPreferredAlignment(I);
Chris Lattner229907c2011-07-18 04:54:35 +0000264 Type *Ty = I->getType()->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000265 if (Alignment > DL->getABITypeAlignment(Ty))
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000266 continue;
267
Anton Korobeynikov6bcea062010-07-26 18:45:39 +0000268 // Ignore all 'special' globals.
269 if (I->getName().startswith("llvm.") ||
270 I->getName().startswith(".llvm."))
271 continue;
272
Quentin Colombet8fc34092013-03-18 22:30:07 +0000273 // Ignore all "required" globals:
Quentin Colombet8fc34092013-03-18 22:30:07 +0000274 if (isMustKeepGlobalVariable(I))
275 continue;
276
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000277 if (DL->getTypeAllocSize(Ty) < MaxOffset) {
Ahmed Charles32e983e2012-02-13 06:30:56 +0000278 if (TargetLoweringObjectFile::getKindForGlobal(I, TLI->getTargetMachine())
279 .isBSSLocal())
Silviu Barangaa055aab2013-01-07 12:31:25 +0000280 BSSGlobals[AddressSpace].push_back(I);
Bob Wilson881b45c2010-11-17 21:25:39 +0000281 else if (I->isConstant())
Silviu Barangaa055aab2013-01-07 12:31:25 +0000282 ConstGlobals[AddressSpace].push_back(I);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000283 else
Silviu Barangaa055aab2013-01-07 12:31:25 +0000284 Globals[AddressSpace].push_back(I);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000285 }
286 }
287
Silviu Barangaa055aab2013-01-07 12:31:25 +0000288 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
289 I = Globals.begin(), E = Globals.end(); I != E; ++I)
290 if (I->second.size() > 1)
291 Changed |= doMerge(I->second, M, false, I->first);
292
293 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
294 I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
295 if (I->second.size() > 1)
296 Changed |= doMerge(I->second, M, false, I->first);
Bob Wilson881b45c2010-11-17 21:25:39 +0000297
Quentin Colombet8fc34092013-03-18 22:30:07 +0000298 if (EnableGlobalMergeOnConst)
299 for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
300 I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
301 if (I->second.size() > 1)
302 Changed |= doMerge(I->second, M, true, I->first);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000303
304 return Changed;
305}
306
Devang Patel76c85632011-10-17 17:17:43 +0000307bool GlobalMerge::runOnFunction(Function &F) {
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000308 return false;
309}
310
Quentin Colombet2393cb92013-03-19 21:46:49 +0000311bool GlobalMerge::doFinalization(Module &M) {
312 MustKeepGlobalVariables.clear();
313 return false;
314}
315
Bill Wendling7a639ea2013-06-19 21:07:11 +0000316Pass *llvm::createGlobalMergePass(const TargetMachine *TM) {
317 return new GlobalMerge(TM);
Anton Korobeynikov19edda02010-07-24 21:52:08 +0000318}