blob: 9342a5cf406d14ab1ecae0665377e00f7be91520 [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
22#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000023#include "llvm/Constants.h"
24#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000025#include "llvm/Function.h"
26#include "llvm/Pass.h"
27#include "llvm/iMemory.h"
Chris Lattner38aec322003-09-11 16:45:55 +000028#include "llvm/Analysis/Dominators.h"
29#include "llvm/Target/TargetData.h"
30#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattner6806f562003-08-01 22:15:03 +000031#include "Support/Debug.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000032#include "Support/Statistic.h"
Chris Lattner6806f562003-08-01 22:15:03 +000033#include "Support/StringExtras.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000034
35namespace {
Misha Brukman3cfb6b12003-09-11 16:58:31 +000036 Statistic<> NumReplaced("scalarrepl", "Number of allocas broken up");
37 Statistic<> NumPromoted("scalarrepl", "Number of allocas promoted");
Chris Lattnered7b41e2003-05-27 15:45:27 +000038
39 struct SROA : public FunctionPass {
40 bool runOnFunction(Function &F);
41
Chris Lattner38aec322003-09-11 16:45:55 +000042 bool performScalarRepl(Function &F);
43 bool performPromotion(Function &F);
44
Chris Lattnera15854c2003-08-31 00:45:13 +000045 // getAnalysisUsage - This pass does not require any passes, but we know it
46 // will not alter the CFG, so say so.
47 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattner43f820d2003-10-05 21:20:13 +000048 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000049 AU.addRequired<DominanceFrontier>();
50 AU.addRequired<TargetData>();
Chris Lattnera15854c2003-08-31 00:45:13 +000051 AU.setPreservesCFG();
52 }
53
Chris Lattnered7b41e2003-05-27 15:45:27 +000054 private:
Chris Lattnerb37923f2003-05-30 19:22:14 +000055 bool isSafeElementUse(Value *Ptr);
Chris Lattner5e062a12003-05-30 04:15:41 +000056 bool isSafeUseOfAllocation(Instruction *User);
Chris Lattner546fc402003-10-29 17:55:44 +000057 bool isSafeAllocaToPromote(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +000058 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
59 };
60
61 RegisterOpt<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
62}
63
64Pass *createScalarReplAggregatesPass() { return new SROA(); }
65
66
Chris Lattnered7b41e2003-05-27 15:45:27 +000067bool SROA::runOnFunction(Function &F) {
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +000068 bool Changed = performPromotion(F);
69 while (1) {
70 bool LocalChange = performScalarRepl(F);
71 if (!LocalChange) break; // No need to repromote if no scalarrepl
72 Changed = true;
73 LocalChange = performPromotion(F);
74 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
75 }
Chris Lattner38aec322003-09-11 16:45:55 +000076
77 return Changed;
78}
79
80
81bool SROA::performPromotion(Function &F) {
82 std::vector<AllocaInst*> Allocas;
83 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner43f820d2003-10-05 21:20:13 +000084 DominatorTree &DT = getAnalysis<DominatorTree>();
85 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +000086
Chris Lattner02a3be02003-09-20 14:39:18 +000087 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +000088
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +000089 bool Changed = false;
Chris Lattner38aec322003-09-11 16:45:55 +000090
91 while (1) {
92 Allocas.clear();
93
94 // Find allocas that are safe to promote, by looking at all instructions in
95 // the entry node
96 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
97 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
98 if (isAllocaPromotable(AI, TD))
99 Allocas.push_back(AI);
100
101 if (Allocas.empty()) break;
102
Chris Lattner43f820d2003-10-05 21:20:13 +0000103 PromoteMemToReg(Allocas, DT, DF, TD);
Chris Lattner38aec322003-09-11 16:45:55 +0000104 NumPromoted += Allocas.size();
105 Changed = true;
106 }
107
108 return Changed;
109}
110
111
112// performScalarRepl - This algorithm is a simple worklist driven algorithm,
113// which runs on all of the malloc/alloca instructions in the function, removing
114// them if they are only used by getelementptr instructions.
115//
116bool SROA::performScalarRepl(Function &F) {
Chris Lattnered7b41e2003-05-27 15:45:27 +0000117 std::vector<AllocationInst*> WorkList;
118
119 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000120 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000121 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
122 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
123 WorkList.push_back(A);
124
125 // Process the worklist
126 bool Changed = false;
127 while (!WorkList.empty()) {
128 AllocationInst *AI = WorkList.back();
129 WorkList.pop_back();
130
131 // We cannot transform the allocation instruction if it is an array
Chris Lattnerd10376b2003-05-27 16:09:27 +0000132 // allocation (allocations OF arrays are ok though), and an allocation of a
133 // scalar value cannot be decomposed at all.
134 //
Chris Lattnered7b41e2003-05-27 15:45:27 +0000135 if (AI->isArrayAllocation() ||
Chris Lattnerd10376b2003-05-27 16:09:27 +0000136 (!isa<StructType>(AI->getAllocatedType()) &&
137 !isa<ArrayType>(AI->getAllocatedType()))) continue;
138
Chris Lattner5e062a12003-05-30 04:15:41 +0000139 // Check that all of the users of the allocation are capable of being
140 // transformed.
Chris Lattner546fc402003-10-29 17:55:44 +0000141 if (!isSafeAllocaToPromote(AI))
Chris Lattner5e062a12003-05-30 04:15:41 +0000142 continue;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000143
144 DEBUG(std::cerr << "Found inst to xform: " << *AI);
145 Changed = true;
146
147 std::vector<AllocaInst*> ElementAllocas;
148 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
149 ElementAllocas.reserve(ST->getNumContainedTypes());
150 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
151 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
152 AI->getName() + "." + utostr(i), AI);
153 ElementAllocas.push_back(NA);
154 WorkList.push_back(NA); // Add to worklist for recursive processing
155 }
156 } else {
Chris Lattner5e062a12003-05-30 04:15:41 +0000157 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
Chris Lattnered7b41e2003-05-27 15:45:27 +0000158 ElementAllocas.reserve(AT->getNumElements());
159 const Type *ElTy = AT->getElementType();
160 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
161 AllocaInst *NA = new AllocaInst(ElTy, 0,
162 AI->getName() + "." + utostr(i), AI);
163 ElementAllocas.push_back(NA);
164 WorkList.push_back(NA); // Add to worklist for recursive processing
165 }
166 }
167
168 // Now that we have created the alloca instructions that we want to use,
169 // expand the getelementptr instructions to use them.
170 //
171 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
172 I != E; ++I) {
173 Instruction *User = cast<Instruction>(*I);
174 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
175 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
Chris Lattnerc07736a2003-07-23 15:22:26 +0000176 uint64_t Idx = cast<ConstantInt>(GEPI->getOperand(2))->getRawValue();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000177
178 assert(Idx < ElementAllocas.size() && "Index out of range?");
179 AllocaInst *AllocaToUse = ElementAllocas[Idx];
180
181 Value *RepValue;
182 if (GEPI->getNumOperands() == 3) {
183 // Do not insert a new getelementptr instruction with zero indices,
184 // only to have it optimized out later.
185 RepValue = AllocaToUse;
186 } else {
187 // We are indexing deeply into the structure, so we still need a
188 // getelement ptr instruction to finish the indexing. This may be
189 // expanded itself once the worklist is rerun.
190 //
191 std::string OldName = GEPI->getName(); // Steal the old name...
Chris Lattner261d6862003-05-30 05:26:30 +0000192 std::vector<Value*> NewArgs;
193 NewArgs.push_back(Constant::getNullValue(Type::LongTy));
194 NewArgs.insert(NewArgs.end(), GEPI->op_begin()+3, GEPI->op_end());
Chris Lattnered7b41e2003-05-27 15:45:27 +0000195 GEPI->setName("");
196 RepValue =
Chris Lattner261d6862003-05-30 05:26:30 +0000197 new GetElementPtrInst(AllocaToUse, NewArgs, OldName, GEPI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000198 }
199
200 // Move all of the users over to the new GEP.
201 GEPI->replaceAllUsesWith(RepValue);
202 // Delete the old GEP
203 GEPI->getParent()->getInstList().erase(GEPI);
204 } else {
205 assert(0 && "Unexpected instruction type!");
206 }
207 }
208
209 // Finally, delete the Alloca instruction
210 AI->getParent()->getInstList().erase(AI);
Chris Lattnerd10376b2003-05-27 16:09:27 +0000211 NumReplaced++;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000212 }
213
214 return Changed;
215}
Chris Lattner5e062a12003-05-30 04:15:41 +0000216
217
218/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
219/// aggregate allocation.
220///
221bool SROA::isSafeUseOfAllocation(Instruction *User) {
222 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
223 // The GEP is safe to transform if it is of the form GEP <ptr>, 0, <cst>
224 if (GEPI->getNumOperands() <= 2 ||
225 GEPI->getOperand(1) != Constant::getNullValue(Type::LongTy) ||
226 !isa<Constant>(GEPI->getOperand(2)) ||
227 isa<ConstantExpr>(GEPI->getOperand(2)))
228 return false;
Chris Lattner546fc402003-10-29 17:55:44 +0000229
230 // If this is a use of an array allocation, do a bit more checking for
231 // sanity.
232 if (GEPI->getOperand(2)->getType() == Type::LongTy) {
233 const PointerType *PTy =cast<PointerType>(GEPI->getOperand(0)->getType());
234 const ArrayType *AT = cast<ArrayType>(PTy->getElementType());
235 int64_t NumElements = AT->getNumElements();
236
237 // Check to make sure that index falls within the array. If not,
238 // something funny is going on, so we won't do the optimization.
239 //
240 if (cast<ConstantSInt>(GEPI->getOperand(2))->getValue() >= NumElements ||
241 cast<ConstantSInt>(GEPI->getOperand(2))->getValue() < 0)
242 return false;
243 }
244
245 // If there are any non-simple uses of this getelementptr, make sure to
246 // reject them.
247 if (isSafeElementUse(GEPI))
248 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +0000249 }
Chris Lattner546fc402003-10-29 17:55:44 +0000250 return false;
Chris Lattner5e062a12003-05-30 04:15:41 +0000251}
252
Chris Lattnerb37923f2003-05-30 19:22:14 +0000253/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner5e062a12003-05-30 04:15:41 +0000254/// getelementptr instruction of an array aggregate allocation.
255///
Chris Lattnerb37923f2003-05-30 19:22:14 +0000256bool SROA::isSafeElementUse(Value *Ptr) {
Chris Lattner5e062a12003-05-30 04:15:41 +0000257 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
258 I != E; ++I) {
259 Instruction *User = cast<Instruction>(*I);
260 switch (User->getOpcode()) {
Chris Lattner8fce16e2003-09-12 16:02:12 +0000261 case Instruction::Load: break;
262 case Instruction::Store:
263 // Store is ok if storing INTO the pointer, not storing the pointer
264 if (User->getOperand(0) == Ptr) return false;
265 break;
Chris Lattner5e062a12003-05-30 04:15:41 +0000266 case Instruction::GetElementPtr: {
267 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
268 if (GEP->getNumOperands() > 1) {
269 if (!isa<Constant>(GEP->getOperand(1)) ||
270 !cast<Constant>(GEP->getOperand(1))->isNullValue())
271 return false; // Using pointer arithmetic to navigate the array...
Chris Lattner5e062a12003-05-30 04:15:41 +0000272 }
Chris Lattner8fce16e2003-09-12 16:02:12 +0000273 if (!isSafeElementUse(GEP)) return false;
274 break;
Chris Lattner5e062a12003-05-30 04:15:41 +0000275 }
276 default:
277 DEBUG(std::cerr << " Transformation preventing inst: " << *User);
278 return false;
279 }
280 }
281 return true; // All users look ok :)
282}
283
284
285/// isSafeStructAllocaToPromote - Check to see if the specified allocation of a
286/// structure can be broken down into elements.
287///
Chris Lattner546fc402003-10-29 17:55:44 +0000288bool SROA::isSafeAllocaToPromote(AllocationInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +0000289 // Loop over the use list of the alloca. We can only transform it if all of
290 // the users are safe to transform.
291 //
292 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattner546fc402003-10-29 17:55:44 +0000293 I != E; ++I)
Chris Lattner5e062a12003-05-30 04:15:41 +0000294 if (!isSafeUseOfAllocation(cast<Instruction>(*I))) {
295 DEBUG(std::cerr << "Cannot transform: " << *AI << " due to user: "
296 << *I);
297 return false;
298 }
299 return true;
300}