blob: 4b23ea2fbdb73326dba2efc3a3f16a35f7153318 [file] [log] [blame]
Chris Lattnerfb41a502003-05-27 15:45:27 +00001//===- 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
Chris Lattner5d8a12e2003-09-11 16:45:55 +00006// 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.
Chris Lattnerfb41a502003-05-27 15:45:27 +000012//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Scalar.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000016#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
Chris Lattnerfb41a502003-05-27 15:45:27 +000018#include "llvm/Function.h"
19#include "llvm/Pass.h"
20#include "llvm/iMemory.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000021#include "llvm/Analysis/Dominators.h"
22#include "llvm/Target/TargetData.h"
23#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000024#include "Support/Debug.h"
Chris Lattnerfb41a502003-05-27 15:45:27 +000025#include "Support/Statistic.h"
Chris Lattner8abcd562003-08-01 22:15:03 +000026#include "Support/StringExtras.h"
Chris Lattnerfb41a502003-05-27 15:45:27 +000027
28namespace {
Misha Brukman217ca0b2003-09-11 16:58:31 +000029 Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up");
30 Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted");
Chris Lattnerfb41a502003-05-27 15:45:27 +000031
32 struct SROA : public FunctionPass {
33 bool runOnFunction(Function &F);
34
Chris Lattner5d8a12e2003-09-11 16:45:55 +000035 bool performScalarRepl(Function &F);
36 bool performPromotion(Function &F);
37
Chris Lattnerc8174582003-08-31 00:45:13 +000038 // 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 {
Chris Lattnera906bac2003-10-05 21:20:13 +000041 AU.addRequired<DominatorTree>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000042 AU.addRequired<DominanceFrontier>();
43 AU.addRequired<TargetData>();
Chris Lattnerc8174582003-08-31 00:45:13 +000044 AU.setPreservesCFG();
45 }
46
Chris Lattnerfb41a502003-05-27 15:45:27 +000047 private:
Chris Lattner0078d9c2003-05-30 19:22:14 +000048 bool isSafeElementUse(Value *Ptr);
Chris Lattner6e5398d2003-05-30 04:15:41 +000049 bool isSafeUseOfAllocation(Instruction *User);
50 bool isSafeStructAllocaToPromote(AllocationInst *AI);
51 bool isSafeArrayAllocaToPromote(AllocationInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +000052 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
53 };
54
55 RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
56}
57
58Pass *createScalarReplAggregatesPass() { return new SROA(); }
59
60
Chris Lattnerfb41a502003-05-27 15:45:27 +000061bool SROA::runOnFunction(Function &F) {
Chris Lattner9a95f2a2003-09-12 15:36:03 +000062 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 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +000070
71 return Changed;
72}
73
74
75bool SROA::performPromotion(Function &F) {
76 std::vector<AllocaInst*> Allocas;
77 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattnera906bac2003-10-05 21:20:13 +000078 DominatorTree &DT = getAnalysis<DominatorTree>();
79 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000080
Chris Lattner5dac64f2003-09-20 14:39:18 +000081 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner5d8a12e2003-09-11 16:45:55 +000082
Chris Lattner9a95f2a2003-09-12 15:36:03 +000083 bool Changed = false;
Chris Lattner5d8a12e2003-09-11 16:45:55 +000084
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
Chris Lattnera906bac2003-10-05 21:20:13 +000097 PromoteMemToReg(Allocas, DT, DF, TD);
Chris Lattner5d8a12e2003-09-11 16:45:55 +000098 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//
110bool SROA::performScalarRepl(Function &F) {
Chris Lattnerfb41a502003-05-27 15:45:27 +0000111 std::vector<AllocationInst*> WorkList;
112
113 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner5dac64f2003-09-20 14:39:18 +0000114 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000115 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
Chris Lattnerc16b2102003-05-27 16:09:27 +0000126 // allocation (allocations OF arrays are ok though), and an allocation of a
127 // scalar value cannot be decomposed at all.
128 //
Chris Lattnerfb41a502003-05-27 15:45:27 +0000129 if (AI->isArrayAllocation() ||
Chris Lattnerc16b2102003-05-27 16:09:27 +0000130 (!isa<StructType>(AI->getAllocatedType()) &&
131 !isa<ArrayType>(AI->getAllocatedType()))) continue;
132
Chris Lattner6e5398d2003-05-30 04:15:41 +0000133 // 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;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000140
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 {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000154 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnerfb41a502003-05-27 15:45:27 +0000155 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>
Chris Lattner6077c312003-07-23 15:22:26 +0000173 uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000174
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...
Chris Lattner38d88c02003-05-30 05:26:30 +0000189 std::vector<Value*> NewArgs;
190 NewArgs.push_back(Constant::getNullValue(Type::LongTy));
191 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
Chris Lattnerfb41a502003-05-27 15:45:27 +0000192 GEPI->setName("");
193 RepValue =
Chris Lattner38d88c02003-05-30 05:26:30 +0000194 new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000195 }
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);
Chris Lattnerc16b2102003-05-27 16:09:27 +0000208 NumReplaced++;
Chris Lattnerfb41a502003-05-27 15:45:27 +0000209 }
210
211 return Changed;
212}
Chris Lattner6e5398d2003-05-30 04:15:41 +0000213
214
215/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
216/// aggregate allocation.
217///
218bool 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
Chris Lattner0078d9c2003-05-30 19:22:14 +0000232/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner6e5398d2003-05-30 04:15:41 +0000233/// getelementptr instruction of an array aggregate allocation.
234///
Chris Lattner0078d9c2003-05-30 19:22:14 +0000235bool SROA::isSafeElementUse(Value *Ptr) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000236 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()) {
Chris Lattner7fdde922003-09-12 16:02:12 +0000240 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;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000245 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...
Chris Lattner6e5398d2003-05-30 04:15:41 +0000251 }
Chris Lattner7fdde922003-09-12 16:02:12 +0000252 if (!isSafeElementUse(GEP)) return false;
253 break;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000254 }
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///
267bool 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();
Chris Lattnerd847be02003-05-30 18:09:57 +0000272 I != E; ++I) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000273 if (!isSafeUseOfAllocation(cast<Instruction>(*I))) {
274 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
275 << *I);
276 return false;
277 }
Chris Lattnerd847be02003-05-30 18:09:57 +0000278
279 // Pedantic check to avoid breaking broken programs...
280 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*I))
Chris Lattner0078d9c2003-05-30 19:22:14 +0000281 if (GEPI->getNumOperands() == 3 && !isSafeElementUse(GEPI))
Chris Lattnerd847be02003-05-30 18:09:57 +0000282 return false;
283 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000284 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///
291bool 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 //
Chris Lattner0078d9c2003-05-30 19:22:14 +0000321 if (!isSafeElementUse(GEPI)) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000322 DEBUG(std::cerr << "Cannot transform: " << *AI
323 << " due to uses of user: " << *GEPI);
324 return false;
325 }
326 }
327 }
328 return true;
329}
330