Implement global merge optimization for global variables.
[oota-llvm.git] / lib / Transforms / Scalar / GlobalMerge.cpp
1 //===-- GlobalMerge.cpp - Internal globals merging  -----------------------===//
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 // 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 //
15 // For example, consider the code which touches several global variables at
16 // once:
17 //
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".
52 // ===---------------------------------------------------------------------===//
53
54 #include "llvm/Transforms/Scalar.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/IR/Attributes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DerivedTypes.h"
61 #include "llvm/IR/Function.h"
62 #include "llvm/IR/GlobalVariable.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/Pass.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Target/TargetLowering.h"
69 #include "llvm/Target/TargetLoweringObjectFile.h"
70 using namespace llvm;
71
72 #define DEBUG_TYPE "global-merge"
73
74 static cl::opt<bool>
75 EnableGlobalMerge("enable-global-merge", cl::NotHidden,
76                   cl::desc("Enable global merge pass"),
77                   cl::init(true));
78
79 static cl::opt<bool>
80 EnableGlobalMergeOnConst("global-merge-on-const", cl::Hidden,
81                          cl::desc("Enable global merge pass on constants"),
82                          cl::init(false));
83
84 static cl::opt<bool>
85 EnableGlobalMergeOnExternal("global-merge-on-external", cl::Hidden,
86                    cl::desc("Enable global merge pass on external linkage"),
87                    cl::init(false));
88
89 static cl::opt<bool>
90 EnableGlobalMergeAligned("global-merge-aligned", cl::Hidden,
91                    cl::desc("Set target specific alignment for global merge pass"),
92                    cl::init(false));
93
94 STATISTIC(NumMerged      , "Number of globals merged");
95 namespace {
96   class GlobalMerge : public FunctionPass {
97     const TargetMachine *TM;
98
99     bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
100                  Module &M, bool isConst, unsigned AddrSpace) const;
101
102     /// \brief Check if the given variable has been identified as must keep
103     /// \pre setMustKeepGlobalVariables must have been called on the Module that
104     ///      contains GV
105     bool isMustKeepGlobalVariable(const GlobalVariable *GV) const {
106       return MustKeepGlobalVariables.count(GV);
107     }
108
109     /// Collect every variables marked as "used" or used in a landing pad
110     /// instruction for this Module.
111     void setMustKeepGlobalVariables(Module &M);
112
113     /// Collect every variables marked as "used"
114     void collectUsedGlobalVariables(Module &M);
115
116     /// Keep track of the GlobalVariable that must not be merged away
117     SmallPtrSet<const GlobalVariable *, 16> MustKeepGlobalVariables;
118
119   public:
120     static char ID;             // Pass identification, replacement for typeid.
121     explicit GlobalMerge(const TargetMachine *TM = nullptr)
122       : FunctionPass(ID), TM(TM) {
123       initializeGlobalMergePass(*PassRegistry::getPassRegistry());
124     }
125
126     bool doInitialization(Module &M) override;
127     bool runOnFunction(Function &F) override;
128     bool doFinalization(Module &M) override;
129
130     const char *getPassName() const override {
131       return "Merge internal globals";
132     }
133
134     void getAnalysisUsage(AnalysisUsage &AU) const override {
135       AU.setPreservesCFG();
136       FunctionPass::getAnalysisUsage(AU);
137     }
138   };
139 } // end anonymous namespace
140
141 char GlobalMerge::ID = 0;
142
143 static void *initializeGlobalMergePassOnce(PassRegistry &Registry) {
144   PassInfo *PI = new PassInfo(
145       "Merge global variables",
146       "global-merge", &GlobalMerge::ID,
147       PassInfo::NormalCtor_t(callDefaultCtor<GlobalMerge>), false,
148       false, PassInfo::TargetMachineCtor_t(
149                  callTargetMachineCtor<GlobalMerge>));
150   Registry.registerPass(*PI, true);
151   return PI;
152 }
153
154 void llvm::initializeGlobalMergePass(PassRegistry &Registry) {
155   CALL_ONCE_INITIALIZATION(initializeGlobalMergePassOnce)
156 }
157
158 bool GlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
159                           Module &M, bool isConst, unsigned AddrSpace) const {
160   const TargetLowering *TLI = TM->getTargetLowering();
161   const DataLayout *DL = TLI->getDataLayout();
162
163   // FIXME: Infer the maximum possible offset depending on the actual users
164   // (these max offsets are different for the users inside Thumb or ARM
165   // functions)
166   unsigned MaxOffset = TLI->getMaximalGlobalOffset();
167
168   // FIXME: Find better heuristics
169   std::stable_sort(Globals.begin(), Globals.end(),
170                    [DL](const GlobalVariable *GV1, const GlobalVariable *GV2) {
171     Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType();
172     Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType();
173
174     return (DL->getTypeAllocSize(Ty1) < DL->getTypeAllocSize(Ty2));
175   });
176
177   Type *Int32Ty = Type::getInt32Ty(M.getContext());
178
179   assert (Globals.size() > 1);
180   
181   for (size_t i = 0, e = Globals.size(); i != e; ) {
182     size_t j = 0;
183     uint64_t MergedSize = 0;
184     std::vector<Type*> Tys;
185     std::vector<Constant*> Inits;
186
187     bool HasExternal = false;
188     GlobalVariable *TheFirstExternal = 0;
189     for (j = i; j != e; ++j) {
190       Type *Ty = Globals[j]->getType()->getElementType();
191       MergedSize += DL->getTypeAllocSize(Ty);
192       if (MergedSize > MaxOffset) {
193         break;
194       }
195       Tys.push_back(Ty);
196       Inits.push_back(Globals[j]->getInitializer());
197
198       if (Globals[j]->hasExternalLinkage() && !HasExternal) {
199         HasExternal = true;
200         TheFirstExternal = Globals[j];
201       }
202     }
203
204     // If merged variables doesn't have external linkage, we needn't to expose
205     // the symbol after merging.
206     GlobalValue::LinkageTypes Linkage = HasExternal ?
207                                           GlobalValue::ExternalLinkage :
208                                           GlobalValue::InternalLinkage ;
209
210     // If merged variables have external linkage, we use symbol name of the
211     // first variable merged as the suffix of global symbol name. This would
212     // be able to avoid the link-time naming conflict for globalm symbols.
213     Twine MergedGVName = HasExternal ?
214                            "_MergedGlobals_" + TheFirstExternal->getName() :
215                            "_MergedGlobals" ;
216
217     StructType *MergedTy = StructType::get(M.getContext(), Tys);
218     Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
219
220     GlobalVariable *MergedGV = new GlobalVariable(M, MergedTy, isConst,
221                                      Linkage, MergedInit, MergedGVName,
222                                      nullptr, GlobalVariable::NotThreadLocal,
223                                      AddrSpace);
224
225     if (EnableGlobalMergeAligned) {
226       unsigned Align = TLI->getGlobalMergeAlignment(MergedTy);
227       assert(((Align % DL->getABITypeAlignment(MergedTy)) == 0) &&
228         "Specified alignment doesn't meet natural alignment requirement.");
229       MergedGV->setAlignment(Align);
230     }
231
232     for (size_t k = i; k < j; ++k) {
233       GlobalValue::LinkageTypes Linkage = Globals[k]->getLinkage();
234       std::string Name = Globals[k]->getName();
235
236       Constant *Idx[2] = {
237         ConstantInt::get(Int32Ty, 0),
238         ConstantInt::get(Int32Ty, k-i)
239       };
240       Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(MergedGV, Idx);
241       Globals[k]->replaceAllUsesWith(GEP);
242       Globals[k]->eraseFromParent();
243
244       if (Linkage != GlobalValue::InternalLinkage) {
245         // Generate a new alias...
246         new GlobalAlias(GEP->getType(), Linkage, Name, GEP, &M);
247       }
248
249       NumMerged++;
250     }
251     i = j;
252   }
253
254   return true;
255 }
256
257 void GlobalMerge::collectUsedGlobalVariables(Module &M) {
258   // Extract global variables from llvm.used array
259   const GlobalVariable *GV = M.getGlobalVariable("llvm.used");
260   if (!GV || !GV->hasInitializer()) return;
261
262   // Should be an array of 'i8*'.
263   const ConstantArray *InitList = cast<ConstantArray>(GV->getInitializer());
264
265   for (unsigned i = 0, e = InitList->getNumOperands(); i != e; ++i)
266     if (const GlobalVariable *G =
267         dyn_cast<GlobalVariable>(InitList->getOperand(i)->stripPointerCasts()))
268       MustKeepGlobalVariables.insert(G);
269 }
270
271 void GlobalMerge::setMustKeepGlobalVariables(Module &M) {
272   collectUsedGlobalVariables(M);
273
274   for (Module::iterator IFn = M.begin(), IEndFn = M.end(); IFn != IEndFn;
275        ++IFn) {
276     for (Function::iterator IBB = IFn->begin(), IEndBB = IFn->end();
277          IBB != IEndBB; ++IBB) {
278       // Follow the invoke link to find the landing pad instruction
279       const InvokeInst *II = dyn_cast<InvokeInst>(IBB->getTerminator());
280       if (!II) continue;
281
282       const LandingPadInst *LPInst = II->getUnwindDest()->getLandingPadInst();
283       // Look for globals in the clauses of the landing pad instruction
284       for (unsigned Idx = 0, NumClauses = LPInst->getNumClauses();
285            Idx != NumClauses; ++Idx)
286         if (const GlobalVariable *GV =
287             dyn_cast<GlobalVariable>(LPInst->getClause(Idx)
288                                      ->stripPointerCasts()))
289           MustKeepGlobalVariables.insert(GV);
290     }
291   }
292 }
293
294 bool GlobalMerge::doInitialization(Module &M) {
295   if (!EnableGlobalMerge)
296     return false;
297
298   DenseMap<unsigned, SmallVector<GlobalVariable*, 16> > Globals, ConstGlobals,
299                                                         BSSGlobals;
300   const TargetLowering *TLI = TM->getTargetLowering();
301   const DataLayout *DL = TLI->getDataLayout();
302   unsigned MaxOffset = TLI->getMaximalGlobalOffset();
303   bool Changed = false;
304   setMustKeepGlobalVariables(M);
305
306   // Grab all non-const globals.
307   for (Module::global_iterator I = M.global_begin(),
308          E = M.global_end(); I != E; ++I) {
309     // Merge is safe for "normal" internal or external globals only
310     if (I->isDeclaration() || I->isThreadLocal() || I->hasSection())
311       continue;
312
313     if (!(EnableGlobalMergeOnExternal && I->hasExternalLinkage())
314           && !I->hasInternalLinkage())
315       continue;
316
317     PointerType *PT = dyn_cast<PointerType>(I->getType());
318     assert(PT && "Global variable is not a pointer!");
319
320     unsigned AddressSpace = PT->getAddressSpace();
321
322     // Ignore fancy-aligned globals for now.
323     unsigned Alignment = DL->getPreferredAlignment(I);
324     Type *Ty = I->getType()->getElementType();
325     if (Alignment > DL->getABITypeAlignment(Ty))
326       continue;
327
328     // Ignore all 'special' globals.
329     if (I->getName().startswith("llvm.") ||
330         I->getName().startswith(".llvm."))
331       continue;
332
333     // Ignore all "required" globals:
334     if (isMustKeepGlobalVariable(I))
335       continue;
336
337     if (DL->getTypeAllocSize(Ty) < MaxOffset) {
338       if (TargetLoweringObjectFile::getKindForGlobal(I, TLI->getTargetMachine())
339           .isBSSLocal())
340         BSSGlobals[AddressSpace].push_back(I);
341       else if (I->isConstant())
342         ConstGlobals[AddressSpace].push_back(I);
343       else
344         Globals[AddressSpace].push_back(I);
345     }
346   }
347
348   for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
349        I = Globals.begin(), E = Globals.end(); I != E; ++I)
350     if (I->second.size() > 1)
351       Changed |= doMerge(I->second, M, false, I->first);
352
353   for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
354        I = BSSGlobals.begin(), E = BSSGlobals.end(); I != E; ++I)
355     if (I->second.size() > 1)
356       Changed |= doMerge(I->second, M, false, I->first);
357
358   if (EnableGlobalMergeOnConst)
359     for (DenseMap<unsigned, SmallVector<GlobalVariable*, 16> >::iterator
360          I = ConstGlobals.begin(), E = ConstGlobals.end(); I != E; ++I)
361       if (I->second.size() > 1)
362         Changed |= doMerge(I->second, M, true, I->first);
363
364   return Changed;
365 }
366
367 bool GlobalMerge::runOnFunction(Function &F) {
368   return false;
369 }
370
371 bool GlobalMerge::doFinalization(Module &M) {
372   MustKeepGlobalVariables.clear();
373   return false;
374 }
375
376 Pass *llvm::createGlobalMergePass(const TargetMachine *TM) {
377   return new GlobalMerge(TM);
378 }