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