blob: 3a100647a748a686f06dbb739b640afe2b42d5b8 [file] [log] [blame]
Chris Lattnerfb41a502003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnerfb41a502003-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 Lattner5d8a12e2003-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 Lattnerfb41a502003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner79a42ac2006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnerfb41a502003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnerfb41a502003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner827cb982007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukman2b3387a2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner66e6a822007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
30#include "llvm/Pass.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000031#include "llvm/Analysis/Dominators.h"
32#include "llvm/Target/TargetData.h"
33#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Chris Lattner996795b2006-06-28 23:17:24 +000034#include "llvm/Support/Debug.h"
Chris Lattner3b0a62d2005-12-12 07:19:13 +000035#include "llvm/Support/GetElementPtrTypeIterator.h"
36#include "llvm/Support/MathExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000037#include "llvm/Support/Compiler.h"
Chris Lattnera7315132007-02-12 22:56:41 +000038#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000039#include "llvm/ADT/Statistic.h"
40#include "llvm/ADT/StringExtras.h"
Chris Lattner40d2aeb2003-12-02 17:43:55 +000041using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000042
Chris Lattner79a42ac2006-12-19 21:40:18 +000043STATISTIC(NumReplaced, "Number of allocas broken up");
44STATISTIC(NumPromoted, "Number of allocas promoted");
45STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner827cb982007-04-25 06:40:51 +000046STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnerfb41a502003-05-27 15:45:27 +000047
Chris Lattner79a42ac2006-12-19 21:40:18 +000048namespace {
Chris Lattner996795b2006-06-28 23:17:24 +000049 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000050 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +000051 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patele8ec7662007-07-09 21:19:23 +000052 if (T == -1)
Chris Lattner1f708162007-08-02 21:33:36 +000053 SRThreshold = 128;
Devang Patele8ec7662007-07-09 21:19:23 +000054 else
55 SRThreshold = T;
56 }
Devang Patel09f162c2007-05-01 21:15:47 +000057
Chris Lattnerfb41a502003-05-27 15:45:27 +000058 bool runOnFunction(Function &F);
59
Chris Lattner5d8a12e2003-09-11 16:45:55 +000060 bool performScalarRepl(Function &F);
61 bool performPromotion(Function &F);
62
Chris Lattnerc8174582003-08-31 00:45:13 +000063 // getAnalysisUsage - This pass does not require any passes, but we know it
64 // will not alter the CFG, so say so.
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelfc7fdef2007-06-07 21:57:03 +000066 AU.addRequired<DominatorTree>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000067 AU.addRequired<DominanceFrontier>();
68 AU.addRequired<TargetData>();
Chris Lattnerc8174582003-08-31 00:45:13 +000069 AU.setPreservesCFG();
70 }
71
Chris Lattnerfb41a502003-05-27 15:45:27 +000072 private:
Chris Lattner87679202007-05-30 06:11:23 +000073 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
74 /// information about the uses. All these fields are initialized to false
75 /// and set to true when something is learned.
76 struct AllocaInfo {
77 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
78 bool isUnsafe : 1;
79
80 /// needsCanon - This is set to true if there is some use of the alloca
81 /// that requires canonicalization.
82 bool needsCanon : 1;
83
84 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
85 bool isMemCpySrc : 1;
86
Zhou Sheng1ee941d2007-07-06 06:01:16 +000087 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner87679202007-05-30 06:11:23 +000088 bool isMemCpyDst : 1;
89
90 AllocaInfo()
91 : isUnsafe(false), needsCanon(false),
92 isMemCpySrc(false), isMemCpyDst(false) {}
93 };
94
Devang Patele8ec7662007-07-09 21:19:23 +000095 unsigned SRThreshold;
96
Chris Lattner87679202007-05-30 06:11:23 +000097 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
98
Chris Lattner88819122004-11-14 04:24:28 +000099 int isSafeAllocaToScalarRepl(AllocationInst *AI);
Chris Lattner87679202007-05-30 06:11:23 +0000100
101 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
102 AllocaInfo &Info);
103 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
104 AllocaInfo &Info);
105 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
106 unsigned OpNo, AllocaInfo &Info);
107 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
108 AllocaInfo &Info);
109
Chris Lattner31e5add2007-04-25 05:02:56 +0000110 void DoScalarReplacement(AllocationInst *AI,
111 std::vector<AllocationInst*> &WorkList);
Chris Lattner88819122004-11-14 04:24:28 +0000112 void CanonicalizeAllocaUsers(AllocationInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000113 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000114
Chris Lattner877a3b42007-03-19 00:16:43 +0000115 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner66e6a822007-03-05 07:52:57 +0000116 SmallVector<AllocaInst*, 32> &NewElts);
117
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000118 const Type *CanConvertToScalar(Value *V, bool &IsNotTrivial);
119 void ConvertToScalar(AllocationInst *AI, const Type *Ty);
120 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset);
Chris Lattner77205de2008-02-29 07:03:13 +0000121 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
122 unsigned Offset);
123 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
124 unsigned Offset);
Chris Lattner827cb982007-04-25 06:40:51 +0000125 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000126 };
Chris Lattnerfb41a502003-05-27 15:45:27 +0000127}
128
Dan Gohmand78c4002008-05-13 00:00:25 +0000129char SROA::ID = 0;
130static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
131
Brian Gaeke960707c2003-11-11 22:41:34 +0000132// Public interface to the ScalarReplAggregates pass
Devang Patele8ec7662007-07-09 21:19:23 +0000133FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
134 return new SROA(Threshold);
135}
Chris Lattnerfb41a502003-05-27 15:45:27 +0000136
137
Chris Lattnerfb41a502003-05-27 15:45:27 +0000138bool SROA::runOnFunction(Function &F) {
Chris Lattner9a95f2a2003-09-12 15:36:03 +0000139 bool Changed = performPromotion(F);
140 while (1) {
141 bool LocalChange = performScalarRepl(F);
142 if (!LocalChange) break; // No need to repromote if no scalarrepl
143 Changed = true;
144 LocalChange = performPromotion(F);
145 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
146 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000147
148 return Changed;
149}
150
151
152bool SROA::performPromotion(Function &F) {
153 std::vector<AllocaInst*> Allocas;
Devang Patelfc7fdef2007-06-07 21:57:03 +0000154 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattnera906bac2003-10-05 21:20:13 +0000155 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000156
Chris Lattner5dac64f2003-09-20 14:39:18 +0000157 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000158
Chris Lattner9a95f2a2003-09-12 15:36:03 +0000159 bool Changed = false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000160
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000161 while (1) {
162 Allocas.clear();
163
164 // Find allocas that are safe to promote, by looking at all instructions in
165 // the entry node
166 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
167 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel073be552007-04-25 17:15:20 +0000168 if (isAllocaPromotable(AI))
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000169 Allocas.push_back(AI);
170
171 if (Allocas.empty()) break;
172
Devang Patelfc7fdef2007-06-07 21:57:03 +0000173 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000174 NumPromoted += Allocas.size();
175 Changed = true;
176 }
177
178 return Changed;
179}
180
Chris Lattner6ff85682008-06-22 17:46:21 +0000181/// getNumSAElements - Return the number of elements in the specific struct or
182/// array.
183static uint64_t getNumSAElements(const Type *T) {
184 if (const StructType *ST = dyn_cast<StructType>(T))
185 return ST->getNumElements();
186 return cast<ArrayType>(T)->getNumElements();
187}
188
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000189// performScalarRepl - This algorithm is a simple worklist driven algorithm,
190// which runs on all of the malloc/alloca instructions in the function, removing
191// them if they are only used by getelementptr instructions.
192//
193bool SROA::performScalarRepl(Function &F) {
Chris Lattnerfb41a502003-05-27 15:45:27 +0000194 std::vector<AllocationInst*> WorkList;
195
196 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner5dac64f2003-09-20 14:39:18 +0000197 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000198 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
199 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
200 WorkList.push_back(A);
201
Chris Lattner80c94a42007-05-24 18:43:04 +0000202 const TargetData &TD = getAnalysis<TargetData>();
203
Chris Lattnerfb41a502003-05-27 15:45:27 +0000204 // Process the worklist
205 bool Changed = false;
206 while (!WorkList.empty()) {
207 AllocationInst *AI = WorkList.back();
208 WorkList.pop_back();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000209
Chris Lattnerf171af92006-12-22 23:14:42 +0000210 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
211 // with unused elements.
212 if (AI->use_empty()) {
213 AI->eraseFromParent();
214 continue;
215 }
216
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000217 // If we can turn this aggregate value (potentially with casts) into a
218 // simple scalar value that can be mem2reg'd into a register value.
219 bool IsNotTrivial = false;
220 if (const Type *ActualType = CanConvertToScalar(AI, IsNotTrivial))
Chris Lattnerdae49df2006-04-20 20:48:50 +0000221 if (IsNotTrivial && ActualType != Type::VoidTy) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000222 ConvertToScalar(AI, ActualType);
223 Changed = true;
224 continue;
225 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000226
Chris Lattner827cb982007-04-25 06:40:51 +0000227 // Check to see if we can perform the core SROA transformation. We cannot
228 // transform the allocation instruction if it is an array allocation
229 // (allocations OF arrays are ok though), and an allocation of a scalar
230 // value cannot be decomposed at all.
Chris Lattner31e5add2007-04-25 05:02:56 +0000231 if (!AI->isArrayAllocation() &&
232 (isa<StructType>(AI->getAllocatedType()) ||
Chris Lattner80c94a42007-05-24 18:43:04 +0000233 isa<ArrayType>(AI->getAllocatedType())) &&
234 AI->getAllocatedType()->isSized() &&
Chris Lattner6ff85682008-06-22 17:46:21 +0000235 // Do not promote any struct whose size is larger than "128" bytes.
236 TD.getABITypeSize(AI->getAllocatedType()) < SRThreshold &&
237 // Do not promote any struct into more than "32" separate vars.
238 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) {
Chris Lattner31e5add2007-04-25 05:02:56 +0000239 // Check that all of the users of the allocation are capable of being
240 // transformed.
241 switch (isSafeAllocaToScalarRepl(AI)) {
242 default: assert(0 && "Unexpected value!");
243 case 0: // Not safe to scalar replace.
244 break;
245 case 1: // Safe, but requires cleanup/canonicalizations first
246 CanonicalizeAllocaUsers(AI);
247 // FALL THROUGH.
248 case 3: // Safe to scalar replace.
249 DoScalarReplacement(AI, WorkList);
250 Changed = true;
Chris Lattner66e6a822007-03-05 07:52:57 +0000251 continue;
252 }
Chris Lattnerfb41a502003-05-27 15:45:27 +0000253 }
Chris Lattner827cb982007-04-25 06:40:51 +0000254
255 // Check to see if this allocation is only modified by a memcpy/memmove from
256 // a constant global. If this is the case, we can change all users to use
257 // the constant global instead. This is commonly produced by the CFE by
258 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
259 // is only subsequently read.
260 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
261 DOUT << "Found alloca equal to global: " << *AI;
262 DOUT << " memcpy = " << *TheCopy;
263 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
264 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
265 TheCopy->eraseFromParent(); // Don't mutate the global.
266 AI->eraseFromParent();
267 ++NumGlobals;
268 Changed = true;
269 continue;
270 }
Chris Lattner31e5add2007-04-25 05:02:56 +0000271
272 // Otherwise, couldn't process this.
Chris Lattnerfb41a502003-05-27 15:45:27 +0000273 }
274
275 return Changed;
276}
Chris Lattner6e5398d2003-05-30 04:15:41 +0000277
Chris Lattner31e5add2007-04-25 05:02:56 +0000278/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
279/// predicate, do SROA now.
280void SROA::DoScalarReplacement(AllocationInst *AI,
281 std::vector<AllocationInst*> &WorkList) {
Chris Lattner827cb982007-04-25 06:40:51 +0000282 DOUT << "Found inst to SROA: " << *AI;
Chris Lattner31e5add2007-04-25 05:02:56 +0000283 SmallVector<AllocaInst*, 32> ElementAllocas;
284 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
285 ElementAllocas.reserve(ST->getNumContainedTypes());
286 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
287 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
288 AI->getAlignment(),
289 AI->getName() + "." + utostr(i), AI);
290 ElementAllocas.push_back(NA);
291 WorkList.push_back(NA); // Add to worklist for recursive processing
292 }
293 } else {
294 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
295 ElementAllocas.reserve(AT->getNumElements());
296 const Type *ElTy = AT->getElementType();
297 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
298 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
299 AI->getName() + "." + utostr(i), AI);
300 ElementAllocas.push_back(NA);
301 WorkList.push_back(NA); // Add to worklist for recursive processing
302 }
303 }
304
305 // Now that we have created the alloca instructions that we want to use,
306 // expand the getelementptr instructions to use them.
307 //
308 while (!AI->use_empty()) {
309 Instruction *User = cast<Instruction>(AI->use_back());
310 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
311 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
312 BCInst->eraseFromParent();
313 continue;
314 }
315
Chris Lattner4d754bc2008-06-23 17:11:23 +0000316 // Replace:
317 // %res = load { i32, i32 }* %alloc
318 // with:
319 // %load.0 = load i32* %alloc.0
320 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
321 // %load.1 = load i32* %alloc.1
322 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman812989b2008-06-05 12:51:53 +0000323 // (Also works for arrays instead of structs)
324 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
325 Value *Insert = UndefValue::get(LI->getType());
326 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
327 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
328 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
329 }
330 LI->replaceAllUsesWith(Insert);
331 LI->eraseFromParent();
332 continue;
333 }
334
Chris Lattner4d754bc2008-06-23 17:11:23 +0000335 // Replace:
336 // store { i32, i32 } %val, { i32, i32 }* %alloc
337 // with:
338 // %val.0 = extractvalue { i32, i32 } %val, 0
339 // store i32 %val.0, i32* %alloc.0
340 // %val.1 = extractvalue { i32, i32 } %val, 1
341 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman812989b2008-06-05 12:51:53 +0000342 // (Also works for arrays instead of structs)
343 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
344 Value *Val = SI->getOperand(0);
345 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
346 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
347 new StoreInst(Extract, ElementAllocas[i], SI);
348 }
349 SI->eraseFromParent();
350 continue;
351 }
352
Chris Lattner31e5add2007-04-25 05:02:56 +0000353 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
354 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
355 unsigned Idx =
356 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
357
358 assert(Idx < ElementAllocas.size() && "Index out of range?");
359 AllocaInst *AllocaToUse = ElementAllocas[Idx];
360
361 Value *RepValue;
362 if (GEPI->getNumOperands() == 3) {
363 // Do not insert a new getelementptr instruction with zero indices, only
364 // to have it optimized out later.
365 RepValue = AllocaToUse;
366 } else {
367 // We are indexing deeply into the structure, so we still need a
368 // getelement ptr instruction to finish the indexing. This may be
369 // expanded itself once the worklist is rerun.
370 //
371 SmallVector<Value*, 8> NewArgs;
372 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty));
373 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greife9ecc682008-04-06 20:25:17 +0000374 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
375 NewArgs.end(), "", GEPI);
Chris Lattner31e5add2007-04-25 05:02:56 +0000376 RepValue->takeName(GEPI);
377 }
378
379 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattnera63dba92009-01-07 06:25:07 +0000380 if (Idx == 0 && GEPI->hasAllZeroIndices())
381 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Chris Lattner31e5add2007-04-25 05:02:56 +0000382
383 // Move all of the users over to the new GEP.
384 GEPI->replaceAllUsesWith(RepValue);
385 // Delete the old GEP
386 GEPI->eraseFromParent();
387 }
388
389 // Finally, delete the Alloca instruction
390 AI->eraseFromParent();
391 NumReplaced++;
392}
393
Chris Lattner6e5398d2003-05-30 04:15:41 +0000394
Chris Lattner88819122004-11-14 04:24:28 +0000395/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner877a3b42007-03-19 00:16:43 +0000396/// getelementptr instruction of an array aggregate allocation. isFirstElt
397/// indicates whether Ptr is known to the start of the aggregate.
Chris Lattner88819122004-11-14 04:24:28 +0000398///
Chris Lattner87679202007-05-30 06:11:23 +0000399void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
400 AllocaInfo &Info) {
Chris Lattner88819122004-11-14 04:24:28 +0000401 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
402 I != E; ++I) {
403 Instruction *User = cast<Instruction>(*I);
404 switch (User->getOpcode()) {
405 case Instruction::Load: break;
406 case Instruction::Store:
407 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattner87679202007-05-30 06:11:23 +0000408 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
Chris Lattner88819122004-11-14 04:24:28 +0000409 break;
410 case Instruction::GetElementPtr: {
411 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
Chris Lattner877a3b42007-03-19 00:16:43 +0000412 bool AreAllZeroIndices = isFirstElt;
Chris Lattner88819122004-11-14 04:24:28 +0000413 if (GEP->getNumOperands() > 1) {
Chris Lattner877a3b42007-03-19 00:16:43 +0000414 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
415 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
Chris Lattner87679202007-05-30 06:11:23 +0000416 // Using pointer arithmetic to navigate the array.
417 return MarkUnsafe(Info);
Chris Lattner877a3b42007-03-19 00:16:43 +0000418
Chris Lattnera63dba92009-01-07 06:25:07 +0000419 if (AreAllZeroIndices)
420 AreAllZeroIndices = GEP->hasAllZeroIndices();
Chris Lattner88819122004-11-14 04:24:28 +0000421 }
Chris Lattner87679202007-05-30 06:11:23 +0000422 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
423 if (Info.isUnsafe) return;
Chris Lattner88819122004-11-14 04:24:28 +0000424 break;
425 }
Chris Lattner877a3b42007-03-19 00:16:43 +0000426 case Instruction::BitCast:
Chris Lattner87679202007-05-30 06:11:23 +0000427 if (isFirstElt) {
428 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
429 if (Info.isUnsafe) return;
Chris Lattner877a3b42007-03-19 00:16:43 +0000430 break;
Chris Lattner877a3b42007-03-19 00:16:43 +0000431 }
432 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner87679202007-05-30 06:11:23 +0000433 return MarkUnsafe(Info);
434 case Instruction::Call:
435 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
436 if (isFirstElt) {
437 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
438 if (Info.isUnsafe) return;
439 break;
440 }
441 }
442 DOUT << " Transformation preventing inst: " << *User;
443 return MarkUnsafe(Info);
Chris Lattner88819122004-11-14 04:24:28 +0000444 default:
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000445 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner87679202007-05-30 06:11:23 +0000446 return MarkUnsafe(Info);
Chris Lattner88819122004-11-14 04:24:28 +0000447 }
448 }
Chris Lattner87679202007-05-30 06:11:23 +0000449 return; // All users look ok :)
Chris Lattner88819122004-11-14 04:24:28 +0000450}
451
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000452/// AllUsersAreLoads - Return true if all users of this value are loads.
453static bool AllUsersAreLoads(Value *Ptr) {
454 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
455 I != E; ++I)
456 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
457 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000458 return true;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000459}
460
Chris Lattner6e5398d2003-05-30 04:15:41 +0000461/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
462/// aggregate allocation.
463///
Chris Lattner87679202007-05-30 06:11:23 +0000464void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
465 AllocaInfo &Info) {
Chris Lattner66e6a822007-03-05 07:52:57 +0000466 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
Chris Lattner87679202007-05-30 06:11:23 +0000467 return isSafeUseOfBitCastedAllocation(C, AI, Info);
Chris Lattner52310702003-11-25 21:09:18 +0000468
Matthijs Kooijman812989b2008-06-05 12:51:53 +0000469 if (isa<LoadInst>(User))
470 return; // Loads (returning a first class aggregrate) are always rewritable
471
472 if (isa<StoreInst>(User) && User->getOperand(0) != AI)
473 return; // Store is ok if storing INTO the pointer, not storing the pointer
474
Chris Lattner87679202007-05-30 06:11:23 +0000475 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
476 if (GEPI == 0)
477 return MarkUnsafe(Info);
478
Chris Lattner52310702003-11-25 21:09:18 +0000479 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
480
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000481 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattner52310702003-11-25 21:09:18 +0000482 if (I == E ||
Chris Lattner87679202007-05-30 06:11:23 +0000483 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
484 return MarkUnsafe(Info);
485 }
Chris Lattner52310702003-11-25 21:09:18 +0000486
487 ++I;
Chris Lattner87679202007-05-30 06:11:23 +0000488 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
Chris Lattner52310702003-11-25 21:09:18 +0000489
Chris Lattner877a3b42007-03-19 00:16:43 +0000490 bool IsAllZeroIndices = true;
491
Chris Lattner3f972c92008-08-23 05:21:06 +0000492 // If the first index is a non-constant index into an array, see if we can
493 // handle it as a special case.
Chris Lattner52310702003-11-25 21:09:18 +0000494 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattner3f972c92008-08-23 05:21:06 +0000495 if (!isa<ConstantInt>(I.getOperand())) {
Chris Lattner877a3b42007-03-19 00:16:43 +0000496 IsAllZeroIndices = 0;
Chris Lattner3f972c92008-08-23 05:21:06 +0000497 uint64_t NumElements = AT->getNumElements();
Chris Lattner877a3b42007-03-19 00:16:43 +0000498
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000499 // If this is an array index and the index is not constant, we cannot
500 // promote... that is unless the array has exactly one or two elements in
501 // it, in which case we CAN promote it, but we have to canonicalize this
502 // out if this is the only problem.
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000503 if ((NumElements == 1 || NumElements == 2) &&
Chris Lattner87679202007-05-30 06:11:23 +0000504 AllUsersAreLoads(GEPI)) {
505 Info.needsCanon = true;
506 return; // Canonicalization required!
507 }
508 return MarkUnsafe(Info);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000509 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000510 }
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000511
Chris Lattner3f972c92008-08-23 05:21:06 +0000512 // Walk through the GEP type indices, checking the types that this indexes
513 // into.
514 for (; I != E; ++I) {
515 // Ignore struct elements, no extra checking needed for these.
516 if (isa<StructType>(*I))
517 continue;
518
Chris Lattner3f972c92008-08-23 05:21:06 +0000519 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
520 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000521
522 // Are all indices still zero?
Chris Lattner3f972c92008-08-23 05:21:06 +0000523 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000524
525 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
526 // This GEP indexes an array. Verify that this is an in-range constant
527 // integer. Specifically, consider A[0][i]. We cannot know that the user
528 // isn't doing invalid things like allowing i to index an out-of-range
529 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesen0a7b4f52008-11-04 20:54:03 +0000530 // of any accesses into structs where any of the components are variables.
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000531 if (IdxVal->getZExtValue() >= AT->getNumElements())
532 return MarkUnsafe(Info);
Dale Johannesen0a7b4f52008-11-04 20:54:03 +0000533 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
534 if (IdxVal->getZExtValue() >= VT->getNumElements())
535 return MarkUnsafe(Info);
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000536 }
Chris Lattner3f972c92008-08-23 05:21:06 +0000537 }
538
Chris Lattner52310702003-11-25 21:09:18 +0000539 // If there are any non-simple uses of this getelementptr, make sure to reject
540 // them.
Chris Lattner87679202007-05-30 06:11:23 +0000541 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
Chris Lattner877a3b42007-03-19 00:16:43 +0000542}
543
544/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
545/// intrinsic can be promoted by SROA. At this point, we know that the operand
546/// of the memintrinsic is a pointer to the beginning of the allocation.
Chris Lattner87679202007-05-30 06:11:23 +0000547void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
548 unsigned OpNo, AllocaInfo &Info) {
Chris Lattner877a3b42007-03-19 00:16:43 +0000549 // If not constant length, give up.
550 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattner87679202007-05-30 06:11:23 +0000551 if (!Length) return MarkUnsafe(Info);
Chris Lattner877a3b42007-03-19 00:16:43 +0000552
553 // If not the whole aggregate, give up.
554 const TargetData &TD = getAnalysis<TargetData>();
Duncan Sands399d9792007-11-04 14:43:57 +0000555 if (Length->getZExtValue() !=
556 TD.getABITypeSize(AI->getType()->getElementType()))
Chris Lattner87679202007-05-30 06:11:23 +0000557 return MarkUnsafe(Info);
Chris Lattner877a3b42007-03-19 00:16:43 +0000558
559 // We only know about memcpy/memset/memmove.
560 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI))
Chris Lattner87679202007-05-30 06:11:23 +0000561 return MarkUnsafe(Info);
562
563 // Otherwise, we can transform it. Determine whether this is a memcpy/set
564 // into or out of the aggregate.
565 if (OpNo == 1)
566 Info.isMemCpyDst = true;
567 else {
568 assert(OpNo == 2);
569 Info.isMemCpySrc = true;
570 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000571}
572
Chris Lattner66e6a822007-03-05 07:52:57 +0000573/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
574/// are
Chris Lattner87679202007-05-30 06:11:23 +0000575void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
576 AllocaInfo &Info) {
Chris Lattner66e6a822007-03-05 07:52:57 +0000577 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
578 UI != E; ++UI) {
579 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
Chris Lattner87679202007-05-30 06:11:23 +0000580 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
Chris Lattner66e6a822007-03-05 07:52:57 +0000581 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
Chris Lattner87679202007-05-30 06:11:23 +0000582 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattner66e6a822007-03-05 07:52:57 +0000583 } else {
Chris Lattner87679202007-05-30 06:11:23 +0000584 return MarkUnsafe(Info);
Chris Lattner66e6a822007-03-05 07:52:57 +0000585 }
Chris Lattner87679202007-05-30 06:11:23 +0000586 if (Info.isUnsafe) return;
Chris Lattner66e6a822007-03-05 07:52:57 +0000587 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000588}
589
Chris Lattner877a3b42007-03-19 00:16:43 +0000590/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
591/// to its first element. Transform users of the cast to use the new values
592/// instead.
593void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner66e6a822007-03-05 07:52:57 +0000594 SmallVector<AllocaInst*, 32> &NewElts) {
595 Constant *Zero = Constant::getNullValue(Type::Int32Ty);
596 const TargetData &TD = getAnalysis<TargetData>();
Chris Lattner877a3b42007-03-19 00:16:43 +0000597
598 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
599 while (UI != UE) {
600 if (BitCastInst *BCU = dyn_cast<BitCastInst>(*UI)) {
Chris Lattner66e6a822007-03-05 07:52:57 +0000601 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattner877a3b42007-03-19 00:16:43 +0000602 ++UI;
603 BCU->eraseFromParent();
Chris Lattner66e6a822007-03-05 07:52:57 +0000604 continue;
605 }
606
607 // Otherwise, must be memcpy/memmove/memset of the entire aggregate. Split
608 // into one per element.
Chris Lattner877a3b42007-03-19 00:16:43 +0000609 MemIntrinsic *MI = dyn_cast<MemIntrinsic>(*UI);
610
611 // If it's not a mem intrinsic, it must be some other user of a gep of the
612 // first pointer. Just leave these alone.
613 if (!MI) {
614 ++UI;
615 continue;
616 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000617
618 // If this is a memcpy/memmove, construct the other pointer as the
619 // appropriate type.
620 Value *OtherPtr = 0;
621 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) {
622 if (BCInst == MCI->getRawDest())
623 OtherPtr = MCI->getRawSource();
624 else {
625 assert(BCInst == MCI->getRawSource());
626 OtherPtr = MCI->getRawDest();
627 }
628 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
629 if (BCInst == MMI->getRawDest())
630 OtherPtr = MMI->getRawSource();
631 else {
632 assert(BCInst == MMI->getRawSource());
633 OtherPtr = MMI->getRawDest();
634 }
635 }
636
637 // If there is an other pointer, we want to convert it to the same pointer
638 // type as AI has, so we can GEP through it.
639 if (OtherPtr) {
640 // It is likely that OtherPtr is a bitcast, if so, remove it.
641 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
642 OtherPtr = BC->getOperand(0);
Chris Lattnera63dba92009-01-07 06:25:07 +0000643 // All zero GEPs are effectively bitcasts.
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000644 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
645 if (GEP->hasAllZeroIndices())
646 OtherPtr = GEP->getOperand(0);
647
Chris Lattner66e6a822007-03-05 07:52:57 +0000648 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
649 if (BCE->getOpcode() == Instruction::BitCast)
650 OtherPtr = BCE->getOperand(0);
651
652 // If the pointer is not the right type, insert a bitcast to the right
653 // type.
654 if (OtherPtr->getType() != AI->getType())
655 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
656 MI);
657 }
658
659 // Process each element of the aggregate.
660 Value *TheFn = MI->getOperand(0);
661 const Type *BytePtrTy = MI->getRawDest()->getType();
662 bool SROADest = MI->getRawDest() == BCInst;
663
664 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
665 // If this is a memcpy/memmove, emit a GEP of the other element address.
666 Value *OtherElt = 0;
667 if (OtherPtr) {
Chris Lattner6ff85682008-06-22 17:46:21 +0000668 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
Gabor Greife9ecc682008-04-06 20:25:17 +0000669 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner6ff85682008-06-22 17:46:21 +0000670 OtherPtr->getNameStr()+"."+utostr(i),
Gabor Greife9ecc682008-04-06 20:25:17 +0000671 MI);
Chris Lattner66e6a822007-03-05 07:52:57 +0000672 }
673
674 Value *EltPtr = NewElts[i];
Chris Lattner9f022d52007-03-08 06:36:54 +0000675 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType();
676
677 // If we got down to a scalar, insert a load or store as appropriate.
Dan Gohman7a0566b2008-05-23 00:12:03 +0000678 if (EltTy->isSingleValueType()) {
Chris Lattner9f022d52007-03-08 06:36:54 +0000679 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
680 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp",
681 MI);
682 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI);
683 continue;
684 } else {
685 assert(isa<MemSetInst>(MI));
686
687 // If the stored element is zero (common case), just store a null
688 // constant.
689 Constant *StoreVal;
690 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
691 if (CI->isZero()) {
692 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
693 } else {
Dan Gohman06c60b62007-07-16 14:29:03 +0000694 // If EltTy is a vector type, get the element type.
Chris Lattner9f022d52007-03-08 06:36:54 +0000695 const Type *ValTy = EltTy;
696 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy))
697 ValTy = VTy->getElementType();
Duncan Sands399d9792007-11-04 14:43:57 +0000698
Chris Lattner9f022d52007-03-08 06:36:54 +0000699 // Construct an integer with the right value.
Duncan Sands399d9792007-11-04 14:43:57 +0000700 unsigned EltSize = TD.getTypeSizeInBits(ValTy);
701 APInt OneVal(EltSize, CI->getZExtValue());
Chris Lattner9f022d52007-03-08 06:36:54 +0000702 APInt TotalVal(OneVal);
703 // Set each byte.
Duncan Sands399d9792007-11-04 14:43:57 +0000704 for (unsigned i = 0; 8*i < EltSize; ++i) {
Chris Lattner9f022d52007-03-08 06:36:54 +0000705 TotalVal = TotalVal.shl(8);
706 TotalVal |= OneVal;
707 }
Duncan Sands399d9792007-11-04 14:43:57 +0000708
Chris Lattner9f022d52007-03-08 06:36:54 +0000709 // Convert the integer value to the appropriate type.
710 StoreVal = ConstantInt::get(TotalVal);
711 if (isa<PointerType>(ValTy))
712 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
713 else if (ValTy->isFloatingPoint())
714 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
715 assert(StoreVal->getType() == ValTy && "Type mismatch!");
716
717 // If the requested value was a vector constant, create it.
718 if (EltTy != ValTy) {
719 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
720 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
721 StoreVal = ConstantVector::get(&Elts[0], NumElts);
722 }
723 }
724 new StoreInst(StoreVal, EltPtr, MI);
725 continue;
726 }
727 // Otherwise, if we're storing a byte variable, use a memset call for
728 // this element.
729 }
730 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000731
732 // Cast the element pointer to BytePtrTy.
733 if (EltPtr->getType() != BytePtrTy)
734 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
Chris Lattner9f022d52007-03-08 06:36:54 +0000735
736 // Cast the other pointer (if we have one) to BytePtrTy.
737 if (OtherElt && OtherElt->getType() != BytePtrTy)
738 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
739 MI);
740
Duncan Sands399d9792007-11-04 14:43:57 +0000741 unsigned EltSize = TD.getABITypeSize(EltTy);
Chris Lattner9f022d52007-03-08 06:36:54 +0000742
Chris Lattner66e6a822007-03-05 07:52:57 +0000743 // Finally, insert the meminst for this element.
744 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
745 Value *Ops[] = {
746 SROADest ? EltPtr : OtherElt, // Dest ptr
747 SROADest ? OtherElt : EltPtr, // Src ptr
748 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
749 Zero // Align
750 };
Gabor Greife9ecc682008-04-06 20:25:17 +0000751 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
Chris Lattner9f022d52007-03-08 06:36:54 +0000752 } else {
753 assert(isa<MemSetInst>(MI));
Chris Lattner66e6a822007-03-05 07:52:57 +0000754 Value *Ops[] = {
755 EltPtr, MI->getOperand(2), // Dest, Value,
756 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
757 Zero // Align
758 };
Gabor Greife9ecc682008-04-06 20:25:17 +0000759 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
Chris Lattner66e6a822007-03-05 07:52:57 +0000760 }
Chris Lattner9f022d52007-03-08 06:36:54 +0000761 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000762
763 // Finally, MI is now dead, as we've modified its actions to occur on all of
764 // the elements of the aggregate.
Chris Lattner877a3b42007-03-19 00:16:43 +0000765 ++UI;
Chris Lattner66e6a822007-03-05 07:52:57 +0000766 MI->eraseFromParent();
767 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000768}
769
Duncan Sands399d9792007-11-04 14:43:57 +0000770/// HasPadding - Return true if the specified type has any structure or
771/// alignment padding, false otherwise.
Duncan Sandsfc3c4892008-06-04 08:21:45 +0000772static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner87679202007-05-30 06:11:23 +0000773 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
774 const StructLayout *SL = TD.getStructLayout(STy);
775 unsigned PrevFieldBitOffset = 0;
776 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands399d9792007-11-04 14:43:57 +0000777 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
778
Chris Lattner87679202007-05-30 06:11:23 +0000779 // Padding in sub-elements?
Duncan Sandsfc3c4892008-06-04 08:21:45 +0000780 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner87679202007-05-30 06:11:23 +0000781 return true;
Duncan Sands399d9792007-11-04 14:43:57 +0000782
Chris Lattner87679202007-05-30 06:11:23 +0000783 // Check to see if there is any padding between this element and the
784 // previous one.
785 if (i) {
Duncan Sands399d9792007-11-04 14:43:57 +0000786 unsigned PrevFieldEnd =
Chris Lattner87679202007-05-30 06:11:23 +0000787 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
788 if (PrevFieldEnd < FieldBitOffset)
789 return true;
790 }
Duncan Sands399d9792007-11-04 14:43:57 +0000791
Chris Lattner87679202007-05-30 06:11:23 +0000792 PrevFieldBitOffset = FieldBitOffset;
793 }
Duncan Sands399d9792007-11-04 14:43:57 +0000794
Chris Lattner87679202007-05-30 06:11:23 +0000795 // Check for tail padding.
796 if (unsigned EltCount = STy->getNumElements()) {
797 unsigned PrevFieldEnd = PrevFieldBitOffset +
798 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands399d9792007-11-04 14:43:57 +0000799 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner87679202007-05-30 06:11:23 +0000800 return true;
801 }
802
803 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsfc3c4892008-06-04 08:21:45 +0000804 return HasPadding(ATy->getElementType(), TD);
Duncan Sands399d9792007-11-04 14:43:57 +0000805 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsfc3c4892008-06-04 08:21:45 +0000806 return HasPadding(VTy->getElementType(), TD);
Chris Lattner87679202007-05-30 06:11:23 +0000807 }
Duncan Sandsfc3c4892008-06-04 08:21:45 +0000808 return TD.getTypeSizeInBits(Ty) != TD.getABITypeSizeInBits(Ty);
Chris Lattner87679202007-05-30 06:11:23 +0000809}
Chris Lattner66e6a822007-03-05 07:52:57 +0000810
Chris Lattner88819122004-11-14 04:24:28 +0000811/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
812/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
813/// or 1 if safe after canonicalization has been performed.
Chris Lattner6e5398d2003-05-30 04:15:41 +0000814///
Chris Lattner88819122004-11-14 04:24:28 +0000815int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +0000816 // Loop over the use list of the alloca. We can only transform it if all of
817 // the users are safe to transform.
Chris Lattner87679202007-05-30 06:11:23 +0000818 AllocaInfo Info;
819
Chris Lattner6e5398d2003-05-30 04:15:41 +0000820 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattner88819122004-11-14 04:24:28 +0000821 I != E; ++I) {
Chris Lattner87679202007-05-30 06:11:23 +0000822 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
823 if (Info.isUnsafe) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000824 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattner88819122004-11-14 04:24:28 +0000825 return 0;
Chris Lattner6e5398d2003-05-30 04:15:41 +0000826 }
Chris Lattner88819122004-11-14 04:24:28 +0000827 }
Chris Lattner87679202007-05-30 06:11:23 +0000828
829 // Okay, we know all the users are promotable. If the aggregate is a memcpy
830 // source and destination, we have to be careful. In particular, the memcpy
831 // could be moving around elements that live in structure padding of the LLVM
832 // types, but may actually be used. In these cases, we refuse to promote the
833 // struct.
834 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Duncan Sands399d9792007-11-04 14:43:57 +0000835 HasPadding(AI->getType()->getElementType(), getAnalysis<TargetData>()))
Chris Lattner87679202007-05-30 06:11:23 +0000836 return 0;
Duncan Sands399d9792007-11-04 14:43:57 +0000837
Chris Lattner87679202007-05-30 06:11:23 +0000838 // If we require cleanup, return 1, otherwise return 3.
839 return Info.needsCanon ? 1 : 3;
Chris Lattner88819122004-11-14 04:24:28 +0000840}
841
842/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified
843/// allocation, but only if cleaned up, perform the cleanups required.
844void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000845 // At this point, we know that the end result will be SROA'd and promoted, so
846 // we can insert ugly code if required so long as sroa+mem2reg will clean it
847 // up.
848 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
849 UI != E; ) {
Chris Lattner9c62db72007-03-19 18:25:57 +0000850 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++);
851 if (!GEPI) continue;
Reid Spencer93396382004-11-15 17:29:41 +0000852 gep_type_iterator I = gep_type_begin(GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000853 ++I;
Chris Lattner88819122004-11-14 04:24:28 +0000854
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000855 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
856 uint64_t NumElements = AT->getNumElements();
Misha Brukmanb1c93172005-04-21 23:48:37 +0000857
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000858 if (!isa<ConstantInt>(I.getOperand())) {
859 if (NumElements == 1) {
Reid Spencerc635f472006-12-31 05:48:39 +0000860 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty));
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000861 } else {
862 assert(NumElements == 2 && "Unhandled case!");
863 // All users of the GEP must be loads. At each use of the GEP, insert
864 // two loads of the appropriate indexed GEP and select between them.
Reid Spencer266e42b2006-12-23 06:05:41 +0000865 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000866 Constant::getNullValue(I.getOperand()->getType()),
Reid Spencer266e42b2006-12-23 06:05:41 +0000867 "isone", GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000868 // Insert the new GEP instructions, which are properly indexed.
Chris Lattnera7315132007-02-12 22:56:41 +0000869 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Reid Spencerc635f472006-12-31 05:48:39 +0000870 Indices[1] = Constant::getNullValue(Type::Int32Ty);
Gabor Greife9ecc682008-04-06 20:25:17 +0000871 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
872 Indices.begin(),
873 Indices.end(),
874 GEPI->getName()+".0", GEPI);
Reid Spencerc635f472006-12-31 05:48:39 +0000875 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Gabor Greife9ecc682008-04-06 20:25:17 +0000876 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
877 Indices.begin(),
878 Indices.end(),
879 GEPI->getName()+".1", GEPI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000880 // Replace all loads of the variable index GEP with loads from both
881 // indexes and a select.
882 while (!GEPI->use_empty()) {
883 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
884 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
885 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
Gabor Greife9ecc682008-04-06 20:25:17 +0000886 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000887 LI->replaceAllUsesWith(R);
888 LI->eraseFromParent();
889 }
890 GEPI->eraseFromParent();
891 }
892 }
893 }
894 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000895}
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000896
897/// MergeInType - Add the 'In' type to the accumulated type so far. If the
898/// types are incompatible, return true, otherwise update Accum and return
899/// false.
Chris Lattner3323ce12006-04-14 21:42:41 +0000900///
Chris Lattner8f7b7752006-12-15 07:32:38 +0000901/// There are three cases we handle here:
902/// 1) An effectively-integer union, where the pieces are stored into as
Chris Lattner3323ce12006-04-14 21:42:41 +0000903/// smaller integers (common with byte swap and other idioms).
Chris Lattner8f7b7752006-12-15 07:32:38 +0000904/// 2) A union of vector types of the same size and potentially its elements.
905/// Here we turn element accesses into insert/extract element operations.
906/// 3) A union of scalar types, such as int/float or int/pointer. Here we
907/// merge together into integers, allowing the xform to work with #1 as
908/// well.
Chris Lattner05f82722006-10-08 23:28:04 +0000909static bool MergeInType(const Type *In, const Type *&Accum,
910 const TargetData &TD) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000911 // If this is our first type, just use it.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000912 const VectorType *PTy;
Chris Lattner3323ce12006-04-14 21:42:41 +0000913 if (Accum == Type::VoidTy || In == Accum) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000914 Accum = In;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000915 } else if (In == Type::VoidTy) {
916 // Noop.
Chris Lattner03c49532007-01-15 02:27:26 +0000917 } else if (In->isInteger() && Accum->isInteger()) { // integer union.
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000918 // Otherwise pick whichever type is larger.
Reid Spencer7a9c62b2007-01-12 07:05:14 +0000919 if (cast<IntegerType>(In)->getBitWidth() >
920 cast<IntegerType>(Accum)->getBitWidth())
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000921 Accum = In;
Chris Lattner05f82722006-10-08 23:28:04 +0000922 } else if (isa<PointerType>(In) && isa<PointerType>(Accum)) {
Chris Lattner41b44222006-10-08 23:53:04 +0000923 // Pointer unions just stay as one of the pointers.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000924 } else if (isa<VectorType>(In) || isa<VectorType>(Accum)) {
925 if ((PTy = dyn_cast<VectorType>(Accum)) &&
Chris Lattner8f7b7752006-12-15 07:32:38 +0000926 PTy->getElementType() == In) {
927 // Accum is a vector, and we are accessing an element: ok.
Reid Spencerd84d35b2007-02-15 02:26:10 +0000928 } else if ((PTy = dyn_cast<VectorType>(In)) &&
Chris Lattner8f7b7752006-12-15 07:32:38 +0000929 PTy->getElementType() == Accum) {
930 // In is a vector, and accum is an element: ok, remember In.
931 Accum = In;
Reid Spencerd84d35b2007-02-15 02:26:10 +0000932 } else if ((PTy = dyn_cast<VectorType>(In)) && isa<VectorType>(Accum) &&
933 PTy->getBitWidth() == cast<VectorType>(Accum)->getBitWidth()) {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000934 // Two vectors of the same size: keep Accum.
935 } else {
936 // Cannot insert an short into a <4 x int> or handle
937 // <2 x int> -> <4 x int>
938 return true;
939 }
Chris Lattner7c1dff92006-12-13 02:26:45 +0000940 } else {
Chris Lattner8f7b7752006-12-15 07:32:38 +0000941 // Pointer/FP/Integer unions merge together as integers.
942 switch (Accum->getTypeID()) {
943 case Type::PointerTyID: Accum = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000944 case Type::FloatTyID: Accum = Type::Int32Ty; break;
945 case Type::DoubleTyID: Accum = Type::Int64Ty; break;
Dale Johannesen1d1d0e72007-09-28 00:21:38 +0000946 case Type::X86_FP80TyID: return true;
947 case Type::FP128TyID: return true;
948 case Type::PPC_FP128TyID: return true;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000949 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000950 assert(Accum->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000951 break;
952 }
953
954 switch (In->getTypeID()) {
955 case Type::PointerTyID: In = TD.getIntPtrType(); break;
Reid Spencerc635f472006-12-31 05:48:39 +0000956 case Type::FloatTyID: In = Type::Int32Ty; break;
957 case Type::DoubleTyID: In = Type::Int64Ty; break;
Dale Johannesen1d1d0e72007-09-28 00:21:38 +0000958 case Type::X86_FP80TyID: return true;
959 case Type::FP128TyID: return true;
960 case Type::PPC_FP128TyID: return true;
Chris Lattner8f7b7752006-12-15 07:32:38 +0000961 default:
Chris Lattner03c49532007-01-15 02:27:26 +0000962 assert(In->isInteger() && "Unknown FP type!");
Chris Lattner8f7b7752006-12-15 07:32:38 +0000963 break;
964 }
965 return MergeInType(In, Accum, TD);
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000966 }
967 return false;
968}
969
Duncan Sands399d9792007-11-04 14:43:57 +0000970/// getUIntAtLeastAsBigAs - Return an unsigned integer type that is at least
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000971/// as big as the specified type. If there is no suitable type, this returns
972/// null.
Duncan Sands399d9792007-11-04 14:43:57 +0000973const Type *getUIntAtLeastAsBigAs(unsigned NumBits) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000974 if (NumBits > 64) return 0;
Reid Spencerc635f472006-12-31 05:48:39 +0000975 if (NumBits > 32) return Type::Int64Ty;
976 if (NumBits > 16) return Type::Int32Ty;
977 if (NumBits > 8) return Type::Int16Ty;
978 return Type::Int8Ty;
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000979}
980
981/// CanConvertToScalar - V is a pointer. If we can convert the pointee to a
982/// single scalar integer type, return that type. Further, if the use is not
983/// a completely trivial use that mem2reg could promote, set IsNotTrivial. If
984/// there are no uses of this pointer, return Type::VoidTy to differentiate from
985/// failure.
986///
987const Type *SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial) {
988 const Type *UsedType = Type::VoidTy; // No uses, no forced type.
989 const TargetData &TD = getAnalysis<TargetData>();
990 const PointerType *PTy = cast<PointerType>(V->getType());
991
992 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
993 Instruction *User = cast<Instruction>(*UI);
994
995 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Matthijs Kooijman812989b2008-06-05 12:51:53 +0000996 // FIXME: Loads of a first class aggregrate value could be converted to a
997 // series of loads and insertvalues
998 if (!LI->getType()->isSingleValueType())
999 return 0;
1000
Chris Lattner05f82722006-10-08 23:28:04 +00001001 if (MergeInType(LI->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001002 return 0;
1003
1004 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001005 // Storing the pointer, not into the value?
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001006 if (SI->getOperand(0) == V) return 0;
Matthijs Kooijman812989b2008-06-05 12:51:53 +00001007
1008 // FIXME: Stores of a first class aggregrate value could be converted to a
1009 // series of extractvalues and stores
1010 if (!SI->getOperand(0)->getType()->isSingleValueType())
1011 return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001012
Chris Lattner3323ce12006-04-14 21:42:41 +00001013 // NOTE: We could handle storing of FP imms into integers here!
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001014
Chris Lattner05f82722006-10-08 23:28:04 +00001015 if (MergeInType(SI->getOperand(0)->getType(), UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001016 return 0;
Chris Lattner8f7b7752006-12-15 07:32:38 +00001017 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001018 IsNotTrivial = true;
1019 const Type *SubTy = CanConvertToScalar(CI, IsNotTrivial);
Chris Lattner05f82722006-10-08 23:28:04 +00001020 if (!SubTy || MergeInType(SubTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001021 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1022 // Check to see if this is stepping over an element: GEP Ptr, int C
1023 if (GEP->getNumOperands() == 2 && isa<ConstantInt>(GEP->getOperand(1))) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001024 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Duncan Sands399d9792007-11-04 14:43:57 +00001025 unsigned ElSize = TD.getABITypeSize(PTy->getElementType());
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001026 unsigned BitOffset = Idx*ElSize*8;
1027 if (BitOffset > 64 || !isPowerOf2_32(ElSize)) return 0;
1028
1029 IsNotTrivial = true;
1030 const Type *SubElt = CanConvertToScalar(GEP, IsNotTrivial);
1031 if (SubElt == 0) return 0;
Chris Lattner03c49532007-01-15 02:27:26 +00001032 if (SubElt != Type::VoidTy && SubElt->isInteger()) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001033 const Type *NewTy =
Duncan Sands399d9792007-11-04 14:43:57 +00001034 getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(SubElt)+BitOffset);
Chris Lattner05f82722006-10-08 23:28:04 +00001035 if (NewTy == 0 || MergeInType(NewTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001036 continue;
1037 }
1038 } else if (GEP->getNumOperands() == 3 &&
1039 isa<ConstantInt>(GEP->getOperand(1)) &&
1040 isa<ConstantInt>(GEP->getOperand(2)) &&
Zhou Shengaafe4e22007-04-19 05:39:12 +00001041 cast<ConstantInt>(GEP->getOperand(1))->isZero()) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001042 // We are stepping into an element, e.g. a structure or an array:
Chris Lattnera63dba92009-01-07 06:25:07 +00001043 // GEP Ptr, i32 0, i32 Cst
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001044 const Type *AggTy = PTy->getElementType();
Reid Spencere0fc4df2006-10-20 07:07:24 +00001045 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001046
1047 if (const ArrayType *ATy = dyn_cast<ArrayType>(AggTy)) {
1048 if (Idx >= ATy->getNumElements()) return 0; // Out of range.
Reid Spencer09575ba2007-02-15 03:39:18 +00001049 } else if (const VectorType *VectorTy = dyn_cast<VectorType>(AggTy)) {
Dan Gohman06c60b62007-07-16 14:29:03 +00001050 // Getting an element of the vector.
Reid Spencer09575ba2007-02-15 03:39:18 +00001051 if (Idx >= VectorTy->getNumElements()) return 0; // Out of range.
Chris Lattner3323ce12006-04-14 21:42:41 +00001052
Reid Spencer09575ba2007-02-15 03:39:18 +00001053 // Merge in the vector type.
1054 if (MergeInType(VectorTy, UsedType, TD)) return 0;
Chris Lattner3323ce12006-04-14 21:42:41 +00001055
1056 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1057 if (SubTy == 0) return 0;
1058
Chris Lattner05f82722006-10-08 23:28:04 +00001059 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3323ce12006-04-14 21:42:41 +00001060 return 0;
1061
1062 // We'll need to change this to an insert/extract element operation.
1063 IsNotTrivial = true;
1064 continue; // Everything looks ok
1065
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001066 } else if (isa<StructType>(AggTy)) {
1067 // Structs are always ok.
1068 } else {
1069 return 0;
1070 }
Duncan Sands399d9792007-11-04 14:43:57 +00001071 const Type *NTy = getUIntAtLeastAsBigAs(TD.getABITypeSizeInBits(AggTy));
Chris Lattner05f82722006-10-08 23:28:04 +00001072 if (NTy == 0 || MergeInType(NTy, UsedType, TD)) return 0;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001073 const Type *SubTy = CanConvertToScalar(GEP, IsNotTrivial);
1074 if (SubTy == 0) return 0;
Chris Lattner05f82722006-10-08 23:28:04 +00001075 if (SubTy != Type::VoidTy && MergeInType(SubTy, UsedType, TD))
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001076 return 0;
1077 continue; // Everything looks ok
1078 }
1079 return 0;
1080 } else {
1081 // Cannot handle this!
1082 return 0;
1083 }
1084 }
1085
1086 return UsedType;
1087}
1088
1089/// ConvertToScalar - The specified alloca passes the CanConvertToScalar
1090/// predicate and is non-trivial. Convert it to something that can be trivially
1091/// promoted into a register by mem2reg.
1092void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001093 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = "
1094 << *ActualTy << "\n";
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001095 ++NumConverted;
1096
1097 BasicBlock *EntryBlock = AI->getParent();
Dan Gohmandcb291f2007-03-22 16:38:57 +00001098 assert(EntryBlock == &EntryBlock->getParent()->getEntryBlock() &&
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001099 "Not in the entry block!");
1100 EntryBlock->getInstList().remove(AI); // Take the alloca out of the program.
1101
1102 // Create and insert the alloca.
Chris Lattner3323ce12006-04-14 21:42:41 +00001103 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(),
1104 EntryBlock->begin());
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001105 ConvertUsesToScalar(AI, NewAI, 0);
1106 delete AI;
1107}
1108
1109
1110/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattner3323ce12006-04-14 21:42:41 +00001111/// directly. This happens when we are converting an "integer union" to a
1112/// single integer scalar, or when we are converting a "vector union" to a
1113/// vector with insert/extractelement instructions.
1114///
1115/// Offset is an offset from the original alloca, in bits that need to be
1116/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001117void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, unsigned Offset) {
1118 while (!Ptr->use_empty()) {
1119 Instruction *User = cast<Instruction>(Ptr->use_back());
1120
1121 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner77205de2008-02-29 07:03:13 +00001122 Value *NV = ConvertUsesOfLoadToScalar(LI, NewAI, Offset);
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001123 LI->replaceAllUsesWith(NV);
1124 LI->eraseFromParent();
1125 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1126 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1127
Chris Lattner77205de2008-02-29 07:03:13 +00001128 Value *SV = ConvertUsesOfStoreToScalar(SI, NewAI, Offset);
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001129 new StoreInst(SV, NewAI, SI);
1130 SI->eraseFromParent();
1131
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001132 } else if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb9e5b8f2008-01-30 00:39:15 +00001133 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001134 CI->eraseFromParent();
1135 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
1136 const PointerType *AggPtrTy =
1137 cast<PointerType>(GEP->getOperand(0)->getType());
1138 const TargetData &TD = getAnalysis<TargetData>();
Duncan Sands399d9792007-11-04 14:43:57 +00001139 unsigned AggSizeInBits =
1140 TD.getABITypeSizeInBits(AggPtrTy->getElementType());
1141
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001142 // Check to see if this is stepping over an element: GEP Ptr, int C
1143 unsigned NewOffset = Offset;
1144 if (GEP->getNumOperands() == 2) {
Reid Spencere0fc4df2006-10-20 07:07:24 +00001145 unsigned Idx = cast<ConstantInt>(GEP->getOperand(1))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001146 unsigned BitOffset = Idx*AggSizeInBits;
1147
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001148 NewOffset += BitOffset;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001149 } else if (GEP->getNumOperands() == 3) {
1150 // We know that operand #2 is zero.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001151 unsigned Idx = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001152 const Type *AggTy = AggPtrTy->getElementType();
1153 if (const SequentialType *SeqTy = dyn_cast<SequentialType>(AggTy)) {
Duncan Sands399d9792007-11-04 14:43:57 +00001154 unsigned ElSizeBits =
1155 TD.getABITypeSizeInBits(SeqTy->getElementType());
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001156
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001157 NewOffset += ElSizeBits*Idx;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001158 } else if (const StructType *STy = dyn_cast<StructType>(AggTy)) {
Chris Lattnerc473d8e2007-02-10 19:55:17 +00001159 unsigned EltBitOffset =
Duncan Sands399d9792007-11-04 14:43:57 +00001160 TD.getStructLayout(STy)->getElementOffsetInBits(Idx);
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001161
Chris Lattnerdaa012d2007-04-11 00:57:54 +00001162 NewOffset += EltBitOffset;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001163 } else {
1164 assert(0 && "Unsupported operation!");
1165 abort();
1166 }
1167 } else {
1168 assert(0 && "Unsupported operation!");
1169 abort();
1170 }
1171 ConvertUsesToScalar(GEP, NewAI, NewOffset);
1172 GEP->eraseFromParent();
1173 } else {
1174 assert(0 && "Unsupported operation!");
1175 abort();
1176 }
1177 }
1178}
Chris Lattner827cb982007-04-25 06:40:51 +00001179
Chris Lattner77205de2008-02-29 07:03:13 +00001180/// ConvertUsesOfLoadToScalar - Convert all of the users the specified load to
1181/// use the new alloca directly, returning the value that should replace the
1182/// load. This happens when we are converting an "integer union" to a
1183/// single integer scalar, or when we are converting a "vector union" to a
1184/// vector with insert/extractelement instructions.
1185///
1186/// Offset is an offset from the original alloca, in bits that need to be
1187/// shifted to the right. By the end of this, there should be no uses of Ptr.
1188Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI,
1189 unsigned Offset) {
1190 // The load is a bit extract from NewAI shifted right by Offset bits.
1191 Value *NV = new LoadInst(NewAI, LI->getName(), LI);
1192
1193 if (NV->getType() == LI->getType() && Offset == 0) {
1194 // We win, no conversion needed.
1195 return NV;
1196 }
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001197
1198 // If the result type of the 'union' is a pointer, then this must be ptr->ptr
1199 // cast. Anything else would result in NV being an integer.
1200 if (isa<PointerType>(NV->getType())) {
1201 assert(isa<PointerType>(LI->getType()));
1202 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1203 }
Chris Lattner77205de2008-02-29 07:03:13 +00001204
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001205 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) {
Chris Lattner77205de2008-02-29 07:03:13 +00001206 // If the result alloca is a vector type, this is either an element
1207 // access or a bitcast to another vector type.
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001208 if (isa<VectorType>(LI->getType()))
1209 return new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1210
1211 // Otherwise it must be an element access.
1212 const TargetData &TD = getAnalysis<TargetData>();
1213 unsigned Elt = 0;
1214 if (Offset) {
1215 unsigned EltSize = TD.getABITypeSizeInBits(VTy->getElementType());
1216 Elt = Offset/EltSize;
1217 Offset -= EltSize*Elt;
Chris Lattner77205de2008-02-29 07:03:13 +00001218 }
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001219 NV = new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt),
1220 "tmp", LI);
1221
1222 // If we're done, return this element.
1223 if (NV->getType() == LI->getType() && Offset == 0)
1224 return NV;
1225 }
1226
1227 const IntegerType *NTy = cast<IntegerType>(NV->getType());
1228
1229 // If this is a big-endian system and the load is narrower than the
1230 // full alloca type, we need to do a shift to get the right bits.
1231 int ShAmt = 0;
1232 const TargetData &TD = getAnalysis<TargetData>();
1233 if (TD.isBigEndian()) {
1234 // On big-endian machines, the lowest bit is stored at the bit offset
1235 // from the pointer given by getTypeStoreSizeInBits. This matters for
1236 // integers with a bitwidth that is not a multiple of 8.
1237 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
1238 TD.getTypeStoreSizeInBits(LI->getType()) - Offset;
1239 } else {
1240 ShAmt = Offset;
1241 }
1242
1243 // Note: we support negative bitwidths (with shl) which are not defined.
1244 // We do this to support (f.e.) loads off the end of a structure where
1245 // only some bits are used.
1246 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001247 NV = BinaryOperator::CreateLShr(NV,
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001248 ConstantInt::get(NV->getType(),ShAmt),
1249 LI->getName(), LI);
1250 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001251 NV = BinaryOperator::CreateShl(NV,
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001252 ConstantInt::get(NV->getType(),-ShAmt),
1253 LI->getName(), LI);
1254
1255 // Finally, unconditionally truncate the integer to the right width.
1256 unsigned LIBitWidth = TD.getTypeSizeInBits(LI->getType());
1257 if (LIBitWidth < NTy->getBitWidth())
1258 NV = new TruncInst(NV, IntegerType::get(LIBitWidth),
1259 LI->getName(), LI);
1260
1261 // If the result is an integer, this is a trunc or bitcast.
1262 if (isa<IntegerType>(LI->getType())) {
1263 // Should be done.
1264 } else if (LI->getType()->isFloatingPoint()) {
1265 // Just do a bitcast, we know the sizes match up.
Chris Lattner77205de2008-02-29 07:03:13 +00001266 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI);
1267 } else {
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001268 // Otherwise must be a pointer.
1269 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI);
Chris Lattner77205de2008-02-29 07:03:13 +00001270 }
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001271 assert(NV->getType() == LI->getType() && "Didn't convert right?");
Chris Lattner77205de2008-02-29 07:03:13 +00001272 return NV;
1273}
1274
1275
1276/// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store
1277/// pair of the new alloca directly, returning the value that should be stored
1278/// to the alloca. This happens when we are converting an "integer union" to a
1279/// single integer scalar, or when we are converting a "vector union" to a
1280/// vector with insert/extractelement instructions.
1281///
1282/// Offset is an offset from the original alloca, in bits that need to be
1283/// shifted to the right. By the end of this, there should be no uses of Ptr.
1284Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI,
1285 unsigned Offset) {
1286
1287 // Convert the stored type to the actual type, shift it left to insert
1288 // then 'or' into place.
1289 Value *SV = SI->getOperand(0);
1290 const Type *AllocaType = NewAI->getType()->getElementType();
1291 if (SV->getType() == AllocaType && Offset == 0) {
1292 // All is well.
1293 } else if (const VectorType *PTy = dyn_cast<VectorType>(AllocaType)) {
1294 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1295
1296 // If the result alloca is a vector type, this is either an element
1297 // access or a bitcast to another vector type.
1298 if (isa<VectorType>(SV->getType())) {
1299 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1300 } else {
1301 // Must be an element insertion.
1302 const TargetData &TD = getAnalysis<TargetData>();
1303 unsigned Elt = Offset/TD.getABITypeSizeInBits(PTy->getElementType());
Gabor Greife9ecc682008-04-06 20:25:17 +00001304 SV = InsertElementInst::Create(Old, SV,
1305 ConstantInt::get(Type::Int32Ty, Elt),
1306 "tmp", SI);
Chris Lattner77205de2008-02-29 07:03:13 +00001307 }
1308 } else if (isa<PointerType>(AllocaType)) {
1309 // If the alloca type is a pointer, then all the elements must be
1310 // pointers.
1311 if (SV->getType() != AllocaType)
1312 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI);
1313 } else {
1314 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI);
1315
1316 // If SV is a float, convert it to the appropriate integer type.
1317 // If it is a pointer, do the same, and also handle ptr->ptr casts
1318 // here.
1319 const TargetData &TD = getAnalysis<TargetData>();
1320 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1321 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1322 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1323 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
1324 if (SV->getType()->isFloatingPoint())
1325 SV = new BitCastInst(SV, IntegerType::get(SrcWidth),
1326 SV->getName(), SI);
1327 else if (isa<PointerType>(SV->getType()))
1328 SV = new PtrToIntInst(SV, TD.getIntPtrType(), SV->getName(), SI);
1329
1330 // Always zero extend the value if needed.
1331 if (SV->getType() != AllocaType)
1332 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI);
1333
1334 // If this is a big-endian system and the store is narrower than the
1335 // full alloca type, we need to do a shift to get the right bits.
1336 int ShAmt = 0;
1337 if (TD.isBigEndian()) {
1338 // On big-endian machines, the lowest bit is stored at the bit offset
1339 // from the pointer given by getTypeStoreSizeInBits. This matters for
1340 // integers with a bitwidth that is not a multiple of 8.
1341 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
1342 } else {
1343 ShAmt = Offset;
1344 }
1345
1346 // Note: we support negative bitwidths (with shr) which are not defined.
1347 // We do this to support (f.e.) stores off the end of a structure where
1348 // only some bits in the structure are set.
1349 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1350 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001351 SV = BinaryOperator::CreateShl(SV,
Chris Lattner77205de2008-02-29 07:03:13 +00001352 ConstantInt::get(SV->getType(), ShAmt),
1353 SV->getName(), SI);
1354 Mask <<= ShAmt;
1355 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001356 SV = BinaryOperator::CreateLShr(SV,
Chris Lattner77205de2008-02-29 07:03:13 +00001357 ConstantInt::get(SV->getType(),-ShAmt),
1358 SV->getName(), SI);
1359 Mask = Mask.lshr(ShAmt);
1360 }
1361
1362 // Mask out the bits we are about to insert from the old value, and or
1363 // in the new bits.
1364 if (SrcWidth != DestWidth) {
1365 assert(DestWidth > SrcWidth);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001366 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask),
Chris Lattner77205de2008-02-29 07:03:13 +00001367 Old->getName()+".mask", SI);
Gabor Greife1f6e4b2008-05-16 19:29:10 +00001368 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI);
Chris Lattner77205de2008-02-29 07:03:13 +00001369 }
1370 }
1371 return SV;
1372}
1373
1374
Chris Lattner827cb982007-04-25 06:40:51 +00001375
1376/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1377/// some part of a constant global variable. This intentionally only accepts
1378/// constant expressions because we don't can't rewrite arbitrary instructions.
1379static bool PointsToConstantGlobal(Value *V) {
1380 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1381 return GV->isConstant();
1382 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1383 if (CE->getOpcode() == Instruction::BitCast ||
1384 CE->getOpcode() == Instruction::GetElementPtr)
1385 return PointsToConstantGlobal(CE->getOperand(0));
1386 return false;
1387}
1388
1389/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1390/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1391/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1392/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1393/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1394/// the alloca, and if the source pointer is a pointer to a constant global, we
1395/// can optimize this.
1396static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1397 bool isOffset) {
1398 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1399 if (isa<LoadInst>(*UI)) {
1400 // Ignore loads, they are always ok.
1401 continue;
1402 }
1403 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1404 // If uses of the bitcast are ok, we are ok.
1405 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1406 return false;
1407 continue;
1408 }
1409 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1410 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1411 // doesn't, it does.
1412 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1413 isOffset || !GEP->hasAllZeroIndices()))
1414 return false;
1415 continue;
1416 }
1417
1418 // If this is isn't our memcpy/memmove, reject it as something we can't
1419 // handle.
1420 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI))
1421 return false;
1422
1423 // If we already have seen a copy, reject the second one.
1424 if (TheCopy) return false;
1425
1426 // If the pointer has been offset from the start of the alloca, we can't
1427 // safely handle this.
1428 if (isOffset) return false;
1429
1430 // If the memintrinsic isn't using the alloca as the dest, reject it.
1431 if (UI.getOperandNo() != 1) return false;
1432
1433 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1434
1435 // If the source of the memcpy/move is not a constant global, reject it.
1436 if (!PointsToConstantGlobal(MI->getOperand(2)))
1437 return false;
1438
1439 // Otherwise, the transform is safe. Remember the copy instruction.
1440 TheCopy = MI;
1441 }
1442 return true;
1443}
1444
1445/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1446/// modified by a copy from a constant global. If we can prove this, we can
1447/// replace any uses of the alloca with uses of the global directly.
1448Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1449 Instruction *TheCopy = 0;
1450 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1451 return TheCopy;
1452 return 0;
1453}