Fix bug: InstCombine/cast.ll:test11 / PR#7
[oota-llvm.git] / lib / Transforms / Scalar / ScalarReplAggregates.cpp
1 //===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
2 //
3 // This transformation implements the well known scalar replacement of
4 // aggregates transformation.  This xform breaks up alloca instructions of
5 // aggregate type (structure or array) into individual alloca instructions for
6 // each member (if possible).  Then, if possible, it transforms the individual
7 // alloca instructions into nice clean scalar SSA form.
8 //
9 // This combines a simple SRoA algorithm with the Mem2Reg algorithm because
10 // often interact, especially for C++ programs.  As such, iterating between
11 // SRoA, then Mem2Reg until we run out of things to promote works well.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Scalar.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Function.h"
19 #include "llvm/Pass.h"
20 #include "llvm/iMemory.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
24 #include "Support/Debug.h"
25 #include "Support/Statistic.h"
26 #include "Support/StringExtras.h"
27
28 namespace {
29   Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up");
30   Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted");
31
32   struct SROA : public FunctionPass {
33     bool runOnFunction(Function &F);
34
35     bool performScalarRepl(Function &F);
36     bool performPromotion(Function &F);
37
38     // getAnalysisUsage - This pass does not require any passes, but we know it
39     // will not alter the CFG, so say so.
40     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
41       AU.addRequired<DominatorTree>();
42       AU.addRequired<DominanceFrontier>();
43       AU.addRequired<TargetData>();
44       AU.setPreservesCFG();
45     }
46
47   private:
48     bool isSafeElementUse(Value *Ptr);
49     bool isSafeUseOfAllocation(Instruction *User);
50     bool isSafeStructAllocaToPromote(AllocationInst *AI);
51     bool isSafeArrayAllocaToPromote(AllocationInst *AI);
52     AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
53   };
54
55   RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
56 }
57
58 Pass *createScalarReplAggregatesPass() { return new SROA(); }
59
60
61 bool SROA::runOnFunction(Function &F) {
62   bool Changed = performPromotion(F);
63   while (1) {
64     bool LocalChange = performScalarRepl(F);
65     if (!LocalChange) break;   // No need to repromote if no scalarrepl
66     Changed = true;
67     LocalChange = performPromotion(F);
68     if (!LocalChange) break;   // No need to re-scalarrepl if no promotion
69   }
70
71   return Changed;
72 }
73
74
75 bool SROA::performPromotion(Function &F) {
76   std::vector<AllocaInst*> Allocas;
77   const TargetData &TD = getAnalysis<TargetData>();
78   DominatorTree     &DT = getAnalysis<DominatorTree>();
79   DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
80
81   BasicBlock &BB = F.getEntryBlock();  // Get the entry node for the function
82
83   bool Changed = false;
84   
85   while (1) {
86     Allocas.clear();
87
88     // Find allocas that are safe to promote, by looking at all instructions in
89     // the entry node
90     for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
91       if (AllocaInst *AI = dyn_cast<AllocaInst>(I))       // Is it an alloca?
92         if (isAllocaPromotable(AI, TD))
93           Allocas.push_back(AI);
94
95     if (Allocas.empty()) break;
96
97     PromoteMemToReg(Allocas, DT, DF, TD);
98     NumPromoted += Allocas.size();
99     Changed = true;
100   }
101
102   return Changed;
103 }
104
105
106 // performScalarRepl - This algorithm is a simple worklist driven algorithm,
107 // which runs on all of the malloc/alloca instructions in the function, removing
108 // them if they are only used by getelementptr instructions.
109 //
110 bool SROA::performScalarRepl(Function &F) {
111   std::vector<AllocationInst*> WorkList;
112
113   // Scan the entry basic block, adding any alloca's and mallocs to the worklist
114   BasicBlock &BB = F.getEntryBlock();
115   for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
116     if (AllocationInst *A = dyn_cast<AllocationInst>(I))
117       WorkList.push_back(A);
118
119   // Process the worklist
120   bool Changed = false;
121   while (!WorkList.empty()) {
122     AllocationInst *AI = WorkList.back();
123     WorkList.pop_back();
124
125     // We cannot transform the allocation instruction if it is an array
126     // allocation (allocations OF arrays are ok though), and an allocation of a
127     // scalar value cannot be decomposed at all.
128     //
129     if (AI->isArrayAllocation() ||
130         (!isa<StructType>(AI->getAllocatedType()) &&
131          !isa<ArrayType>(AI->getAllocatedType()))) continue;
132
133     // Check that all of the users of the allocation are capable of being
134     // transformed.
135     if (isa<StructType>(AI->getAllocatedType())) {
136       if (!isSafeStructAllocaToPromote(AI))
137         continue;
138     } else if (!isSafeArrayAllocaToPromote(AI))
139       continue;
140
141     DEBUG(std::cerr << "Found inst to xform: " << *AI);
142     Changed = true;
143     
144     std::vector<AllocaInst*> ElementAllocas;
145     if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
146       ElementAllocas.reserve(ST->getNumContainedTypes());
147       for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
148         AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
149                                         AI->getName() + "." + utostr(i), AI);
150         ElementAllocas.push_back(NA);
151         WorkList.push_back(NA);  // Add to worklist for recursive processing
152       }
153     } else {
154       const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
155       ElementAllocas.reserve(AT->getNumElements());
156       const Type *ElTy = AT->getElementType();
157       for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
158         AllocaInst *NA = new AllocaInst(ElTy, 0,
159                                         AI->getName() + "." + utostr(i), AI);
160         ElementAllocas.push_back(NA);
161         WorkList.push_back(NA);  // Add to worklist for recursive processing
162       }
163     }
164     
165     // Now that we have created the alloca instructions that we want to use,
166     // expand the getelementptr instructions to use them.
167     //
168     for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
169          I != E; ++I) {
170       Instruction *User = cast<Instruction>(*I);
171       if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
172         // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
173         uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue();
174         
175         assert(Idx < ElementAllocas.size() && "Index out of range?");
176         AllocaInst *AllocaToUse = ElementAllocas[Idx];
177
178         Value *RepValue;
179         if (GEPI->getNumOperands() == 3) {
180           // Do not insert a new getelementptr instruction with zero indices,
181           // only to have it optimized out later.
182           RepValue = AllocaToUse;
183         } else {
184           // We are indexing deeply into the structure, so we still need a
185           // getelement ptr instruction to finish the indexing.  This may be
186           // expanded itself once the worklist is rerun.
187           //
188           std::string OldName = GEPI->getName();  // Steal the old name...
189           std::vector<Value*> NewArgs;
190           NewArgs.push_back(Constant::getNullValue(Type::LongTy));
191           NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
192           GEPI->setName("");
193           RepValue =
194             new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
195         }
196
197         // Move all of the users over to the new GEP.
198         GEPI->replaceAllUsesWith(RepValue);
199         // Delete the old GEP
200         GEPI->getParent()->getInstList().erase(GEPI);
201       } else {
202         assert(0 && "Unexpected instruction type!");
203       }
204     }
205
206     // Finally, delete the Alloca instruction
207     AI->getParent()->getInstList().erase(AI);
208     NumReplaced++;
209   }
210
211   return Changed;
212 }
213
214
215 /// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
216 /// aggregate allocation.
217 ///
218 bool SROA::isSafeUseOfAllocation(Instruction *User) {
219   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
220     // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst>
221     if (GEPI->getNumOperands() <= 2 ||
222         GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) ||
223         !isa<Constant>(GEPI->getOperand(2)) ||
224         isa<ConstantExpr>(GEPI->getOperand(2)))
225       return false;
226   } else {
227     return false;
228   }
229   return true;
230 }
231
232 /// isSafeElementUse - Check to see if this use is an allowed use for a
233 /// getelementptr instruction of an array aggregate allocation.
234 ///
235 bool SROA::isSafeElementUse(Value *Ptr) {
236   for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
237        I != E; ++I) {
238     Instruction *User = cast<Instruction>(*I);
239     switch (User->getOpcode()) {
240     case Instruction::Load:  break;
241     case Instruction::Store:
242       // Store is ok if storing INTO the pointer, not storing the pointer
243       if (User->getOperand(0) == Ptr) return false;
244       break;
245     case Instruction::GetElementPtr: {
246       GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
247       if (GEP->getNumOperands() > 1) {
248         if (!isa<Constant>(GEP->getOperand(1)) ||
249             !cast<Constant>(GEP->getOperand(1))->isNullValue())
250           return false;  // Using pointer arithmetic to navigate the array...
251       }
252       if (!isSafeElementUse(GEP)) return false;
253       break;
254     }
255     default:
256       DEBUG(std::cerr << "  Transformation preventing inst: " << *User);
257       return false;
258     }
259   }
260   return true;  // All users look ok :)
261 }
262
263
264 /// isSafeStructAllocaToPromote - Check to see if the specified allocation of a
265 /// structure can be broken down into elements.
266 ///
267 bool SROA::isSafeStructAllocaToPromote(AllocationInst *AI) {
268   // Loop over the use list of the alloca.  We can only transform it if all of
269   // the users are safe to transform.
270   //
271   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
272        I != E; ++I) {
273     if (!isSafeUseOfAllocation(cast<Instruction>(*I))) {
274       DEBUG(std::cerr << "Cannot transform: " << *AI << "  due to user: "
275                       << *I);
276       return false;
277     }
278
279     // Pedantic check to avoid breaking broken programs...
280     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I))
281       if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI))
282         return false;
283   }
284   return true;
285 }
286
287
288 /// isSafeArrayAllocaToPromote - Check to see if the specified allocation of a
289 /// structure can be broken down into elements.
290 ///
291 bool SROA::isSafeArrayAllocaToPromote(AllocationInst *AI) {
292   const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
293   int64_t NumElements = AT->getNumElements();
294
295   // Loop over the use list of the alloca.  We can only transform it if all of
296   // the users are safe to transform.  Array allocas have extra constraints to
297   // meet though.
298   //
299   for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
300        I != E; ++I) {
301     Instruction *User = cast<Instruction>(*I);
302     if (!isSafeUseOfAllocation(User)) {
303       DEBUG(std::cerr << "Cannot transform: " << *AI << "  due to user: "
304                       << User);
305       return false;
306     }
307
308     // Check to make sure that getelementptr follow the extra rules for arrays:
309     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
310       // Check to make sure that index falls within the array.  If not,
311       // something funny is going on, so we won't do the optimization.
312       //
313       if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements)
314         return false;
315
316       // Check to make sure that the only thing that uses the resultant pointer
317       // is safe for an array access.  For example, code that looks like:
318       //   P = &A[0];  P = P + 1
319       // is legal, and should prevent promotion.
320       //
321       if (!isSafeElementUse(GEPI)) {
322         DEBUG(std::cerr << "Cannot transform: " << *AI
323                         << "  due to uses of user: " << *GEPI);
324         return false;
325       }
326     }
327   }
328   return true;
329 }
330