Rewrite TargetMaterializeConstant.
[oota-llvm.git] / lib / Target / ARM / ARMGlobalMerge.cpp
1 //===-- ARMGlobalMerge.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 once:
16 //
17 // static int foo[N], bar[N], baz[N];
18 //
19 // for (i = 0; i < N; ++i) {
20 //    foo[i] = bar[i] * baz[i];
21 // }
22 //
23 //  On ARM the addresses of 3 arrays should be kept in the registers, thus
24 //  this code has quite large register pressure (loop body):
25 //
26 //  ldr     r1, [r5], #4
27 //  ldr     r2, [r6], #4
28 //  mul     r1, r2, r1
29 //  str     r1, [r0], #4
30 //
31 //  Pass converts the code to something like:
32 //
33 //  static struct {
34 //    int foo[N];
35 //    int bar[N];
36 //    int baz[N];
37 //  } merged;
38 //
39 //  for (i = 0; i < N; ++i) {
40 //    merged.foo[i] = merged.bar[i] * merged.baz[i];
41 //  }
42 //
43 //  and in ARM code this becomes:
44 //
45 //  ldr     r0, [r5, #40]
46 //  ldr     r1, [r5, #80]
47 //  mul     r0, r1, r0
48 //  str     r0, [r5], #4
49 //
50 //  note that we saved 2 registers here almostly "for free".
51 // ===----------------------------------------------------------------------===//
52
53 #define DEBUG_TYPE "arm-global-merge"
54 #include "ARM.h"
55 #include "llvm/CodeGen/Passes.h"
56 #include "llvm/Attributes.h"
57 #include "llvm/Constants.h"
58 #include "llvm/DerivedTypes.h"
59 #include "llvm/Function.h"
60 #include "llvm/GlobalVariable.h"
61 #include "llvm/Instructions.h"
62 #include "llvm/Intrinsics.h"
63 #include "llvm/Module.h"
64 #include "llvm/Pass.h"
65 #include "llvm/Target/TargetData.h"
66 #include "llvm/Target/TargetLowering.h"
67 using namespace llvm;
68
69 namespace {
70   class ARMGlobalMerge : public FunctionPass {
71     /// TLI - Keep a pointer of a TargetLowering to consult for determining
72     /// target type sizes.
73     const TargetLowering *TLI;
74
75     bool doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
76                  Module &M, bool) const;
77
78   public:
79     static char ID;             // Pass identification, replacement for typeid.
80     explicit ARMGlobalMerge(const TargetLowering *tli)
81       : FunctionPass(ID), TLI(tli) {}
82
83     virtual bool doInitialization(Module &M);
84     virtual bool runOnFunction(Function &F);
85
86     const char *getPassName() const {
87       return "Merge internal globals";
88     }
89
90     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
91       AU.setPreservesCFG();
92       FunctionPass::getAnalysisUsage(AU);
93     }
94
95     struct GlobalCmp {
96       const TargetData *TD;
97
98       GlobalCmp(const TargetData *td) : TD(td) { }
99
100       bool operator()(const GlobalVariable *GV1, const GlobalVariable *GV2) {
101         const Type *Ty1 = cast<PointerType>(GV1->getType())->getElementType();
102         const Type *Ty2 = cast<PointerType>(GV2->getType())->getElementType();
103
104         return (TD->getTypeAllocSize(Ty1) < TD->getTypeAllocSize(Ty2));
105       }
106     };
107   };
108 } // end anonymous namespace
109
110 char ARMGlobalMerge::ID = 0;
111
112 bool ARMGlobalMerge::doMerge(SmallVectorImpl<GlobalVariable*> &Globals,
113                              Module &M, bool isConst) const {
114   const TargetData *TD = TLI->getTargetData();
115
116   // FIXME: Infer the maximum possible offset depending on the actual users
117   // (these max offsets are different for the users inside Thumb or ARM
118   // functions)
119   unsigned MaxOffset = TLI->getMaximalGlobalOffset();
120
121   // FIXME: Find better heuristics
122   std::stable_sort(Globals.begin(), Globals.end(), GlobalCmp(TD));
123
124   const Type *Int32Ty = Type::getInt32Ty(M.getContext());
125
126   for (size_t i = 0, e = Globals.size(); i != e; ) {
127     size_t j = 0;
128     uint64_t MergedSize = 0;
129     std::vector<const Type*> Tys;
130     std::vector<Constant*> Inits;
131     for (j = i; MergedSize < MaxOffset && j != e; ++j) {
132       const Type *Ty = Globals[j]->getType()->getElementType();
133       Tys.push_back(Ty);
134       Inits.push_back(Globals[j]->getInitializer());
135       MergedSize += TD->getTypeAllocSize(Ty);
136     }
137
138     StructType *MergedTy = StructType::get(M.getContext(), Tys);
139     Constant *MergedInit = ConstantStruct::get(MergedTy, Inits);
140     GlobalVariable *MergedGV = new GlobalVariable(M, MergedTy, isConst,
141                                                   GlobalValue::InternalLinkage,
142                                                   MergedInit, "merged");
143     for (size_t k = i; k < j; ++k) {
144       Constant *Idx[2] = {
145         ConstantInt::get(Int32Ty, 0),
146         ConstantInt::get(Int32Ty, k-i)
147       };
148       Constant *GEP = ConstantExpr::getInBoundsGetElementPtr(MergedGV, Idx, 2);
149       Globals[k]->replaceAllUsesWith(GEP);
150       Globals[k]->eraseFromParent();
151     }
152     i = j;
153   }
154
155   return true;
156 }
157
158
159 bool ARMGlobalMerge::doInitialization(Module &M) {
160   SmallVector<GlobalVariable*, 16> Globals, ConstGlobals;
161   const TargetData *TD = TLI->getTargetData();
162   unsigned MaxOffset = TLI->getMaximalGlobalOffset();
163   bool Changed = false;
164
165   // Grab all non-const globals.
166   for (Module::global_iterator I = M.global_begin(),
167          E = M.global_end(); I != E; ++I) {
168     // Merge is safe for "normal" internal globals only
169     if (!I->hasLocalLinkage() || I->isThreadLocal() || I->hasSection())
170       continue;
171
172     // Ignore fancy-aligned globals for now.
173     if (I->getAlignment() != 0)
174       continue;
175
176     // Ignore all 'special' globals.
177     if (I->getName().startswith("llvm.") ||
178         I->getName().startswith(".llvm."))
179       continue;
180
181     if (TD->getTypeAllocSize(I->getType()) < MaxOffset) {
182       if (I->isConstant())
183         ConstGlobals.push_back(I);
184       else
185         Globals.push_back(I);
186     }
187   }
188
189   if (Globals.size() > 1)
190     Changed |= doMerge(Globals, M, false);
191   // FIXME: This currently breaks the EH processing due to way how the 
192   // typeinfo detection works. We might want to detect the TIs and ignore 
193   // them in the future.
194   
195   // if (ConstGlobals.size() > 1)
196   //  Changed |= doMerge(ConstGlobals, M, true);
197
198   return Changed;
199 }
200
201 bool ARMGlobalMerge::runOnFunction(Function &F) {
202   return false;
203 }
204
205 FunctionPass *llvm::createARMGlobalMergePass(const TargetLowering *tli) {
206   return new ARMGlobalMerge(tli);
207 }