blob: a182943c784fab0c6ea7eea65e5c6923148267f5 [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"
Owen Anderson340288c2009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner66e6a822007-03-05 07:52:57 +000031#include "llvm/Pass.h"
Chris Lattner5d8a12e2003-09-11 16:45:55 +000032#include "llvm/Analysis/Dominators.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patelcaf44852009-02-10 07:00:59 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner996795b2006-06-28 23:17:24 +000036#include "llvm/Support/Debug.h"
Torok Edwinccb29cd2009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattner3b0a62d2005-12-12 07:19:13 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerc1fb96d2009-02-03 19:41:50 +000039#include "llvm/Support/IRBuilder.h"
Chris Lattner3b0a62d2005-12-12 07:19:13 +000040#include "llvm/Support/MathExtras.h"
Chris Lattner3d27be12006-08-27 12:54:02 +000041#include "llvm/Support/Compiler.h"
Chris Lattnera7315132007-02-12 22:56:41 +000042#include "llvm/ADT/SmallVector.h"
Reid Spencer7c16caa2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
44#include "llvm/ADT/StringExtras.h"
Chris Lattner40d2aeb2003-12-02 17:43:55 +000045using namespace llvm;
Brian Gaeke960707c2003-11-11 22:41:34 +000046
Chris Lattner79a42ac2006-12-19 21:40:18 +000047STATISTIC(NumReplaced, "Number of allocas broken up");
48STATISTIC(NumPromoted, "Number of allocas promoted");
49STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner827cb982007-04-25 06:40:51 +000050STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnerfb41a502003-05-27 15:45:27 +000051
Chris Lattner79a42ac2006-12-19 21:40:18 +000052namespace {
Chris Lattner996795b2006-06-28 23:17:24 +000053 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
Nick Lewyckye7da2d62007-05-06 13:37:16 +000054 static char ID; // Pass identification, replacement for typeid
Dan Gohmana79db302008-09-04 17:05:41 +000055 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patele8ec7662007-07-09 21:19:23 +000056 if (T == -1)
Chris Lattner1f708162007-08-02 21:33:36 +000057 SRThreshold = 128;
Devang Patele8ec7662007-07-09 21:19:23 +000058 else
59 SRThreshold = T;
60 }
Devang Patel09f162c2007-05-01 21:15:47 +000061
Chris Lattnerfb41a502003-05-27 15:45:27 +000062 bool runOnFunction(Function &F);
63
Chris Lattner5d8a12e2003-09-11 16:45:55 +000064 bool performScalarRepl(Function &F);
65 bool performPromotion(Function &F);
66
Chris Lattnerc8174582003-08-31 00:45:13 +000067 // getAnalysisUsage - This pass does not require any passes, but we know it
68 // will not alter the CFG, so say so.
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patelfc7fdef2007-06-07 21:57:03 +000070 AU.addRequired<DominatorTree>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +000071 AU.addRequired<DominanceFrontier>();
72 AU.addRequired<TargetData>();
Chris Lattnerc8174582003-08-31 00:45:13 +000073 AU.setPreservesCFG();
74 }
75
Chris Lattnerfb41a502003-05-27 15:45:27 +000076 private:
Chris Lattner938b54f2009-01-07 06:34:28 +000077 TargetData *TD;
78
Chris Lattner87679202007-05-30 06:11:23 +000079 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
80 /// information about the uses. All these fields are initialized to false
81 /// and set to true when something is learned.
82 struct AllocaInfo {
83 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
84 bool isUnsafe : 1;
85
Devang Patelcaf44852009-02-10 07:00:59 +000086 /// needsCleanup - This is set to true if there is some use of the alloca
87 /// that requires cleanup.
88 bool needsCleanup : 1;
Chris Lattner87679202007-05-30 06:11:23 +000089
90 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
91 bool isMemCpySrc : 1;
92
Zhou Sheng1ee941d2007-07-06 06:01:16 +000093 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner87679202007-05-30 06:11:23 +000094 bool isMemCpyDst : 1;
95
96 AllocaInfo()
Devang Patelcaf44852009-02-10 07:00:59 +000097 : isUnsafe(false), needsCleanup(false),
Chris Lattner87679202007-05-30 06:11:23 +000098 isMemCpySrc(false), isMemCpyDst(false) {}
99 };
100
Devang Patele8ec7662007-07-09 21:19:23 +0000101 unsigned SRThreshold;
102
Chris Lattner87679202007-05-30 06:11:23 +0000103 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
104
Chris Lattner88819122004-11-14 04:24:28 +0000105 int isSafeAllocaToScalarRepl(AllocationInst *AI);
Chris Lattner87679202007-05-30 06:11:23 +0000106
107 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
108 AllocaInfo &Info);
109 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
110 AllocaInfo &Info);
111 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
112 unsigned OpNo, AllocaInfo &Info);
113 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
114 AllocaInfo &Info);
115
Chris Lattner31e5add2007-04-25 05:02:56 +0000116 void DoScalarReplacement(AllocationInst *AI,
117 std::vector<AllocationInst*> &WorkList);
Devang Patelcaf44852009-02-10 07:00:59 +0000118 void CleanupGEP(GetElementPtrInst *GEP);
119 void CleanupAllocaUsers(AllocationInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000120 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000121
Chris Lattner877a3b42007-03-19 00:16:43 +0000122 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner66e6a822007-03-05 07:52:57 +0000123 SmallVector<AllocaInst*, 32> &NewElts);
124
Chris Lattner9a2de652009-01-07 07:18:45 +0000125 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
126 AllocationInst *AI,
127 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000128 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
129 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerc518dfd2009-01-08 05:42:05 +0000130 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
Chris Lattnerdf179872009-01-28 20:16:43 +0000131 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner9a2de652009-01-07 07:18:45 +0000132
Chris Lattner09b65ab2009-02-03 01:30:09 +0000133 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner73eff2e2009-02-03 18:15:05 +0000134 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattnerec99c462009-01-31 02:28:54 +0000135 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattnerf5df53c2009-02-03 21:01:03 +0000136 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner576baa42009-02-03 19:45:44 +0000137 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner18f56c22009-02-03 19:30:11 +0000138 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattnerc1fb96d2009-02-03 19:41:50 +0000139 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner827cb982007-04-25 06:40:51 +0000140 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
Chris Lattnerfb41a502003-05-27 15:45:27 +0000141 };
Chris Lattnerfb41a502003-05-27 15:45:27 +0000142}
143
Dan Gohmand78c4002008-05-13 00:00:25 +0000144char SROA::ID = 0;
145static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
146
Brian Gaeke960707c2003-11-11 22:41:34 +0000147// Public interface to the ScalarReplAggregates pass
Devang Patele8ec7662007-07-09 21:19:23 +0000148FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
149 return new SROA(Threshold);
150}
Chris Lattnerfb41a502003-05-27 15:45:27 +0000151
152
Chris Lattnerfb41a502003-05-27 15:45:27 +0000153bool SROA::runOnFunction(Function &F) {
Chris Lattner938b54f2009-01-07 06:34:28 +0000154 TD = &getAnalysis<TargetData>();
155
Chris Lattner9a95f2a2003-09-12 15:36:03 +0000156 bool Changed = performPromotion(F);
157 while (1) {
158 bool LocalChange = performScalarRepl(F);
159 if (!LocalChange) break; // No need to repromote if no scalarrepl
160 Changed = true;
161 LocalChange = performPromotion(F);
162 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
163 }
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000164
165 return Changed;
166}
167
168
169bool SROA::performPromotion(Function &F) {
170 std::vector<AllocaInst*> Allocas;
Devang Patelfc7fdef2007-06-07 21:57:03 +0000171 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattnera906bac2003-10-05 21:20:13 +0000172 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000173
Chris Lattner5dac64f2003-09-20 14:39:18 +0000174 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000175
Chris Lattner9a95f2a2003-09-12 15:36:03 +0000176 bool Changed = false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000177
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000178 while (1) {
179 Allocas.clear();
180
181 // Find allocas that are safe to promote, by looking at all instructions in
182 // the entry node
183 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
184 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel073be552007-04-25 17:15:20 +0000185 if (isAllocaPromotable(AI))
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000186 Allocas.push_back(AI);
187
188 if (Allocas.empty()) break;
189
Owen Anderson47db9412009-07-22 00:24:57 +0000190 PromoteMemToReg(Allocas, DT, DF, F.getContext());
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000191 NumPromoted += Allocas.size();
192 Changed = true;
193 }
194
195 return Changed;
196}
197
Chris Lattner6ff85682008-06-22 17:46:21 +0000198/// getNumSAElements - Return the number of elements in the specific struct or
199/// array.
200static uint64_t getNumSAElements(const Type *T) {
201 if (const StructType *ST = dyn_cast<StructType>(T))
202 return ST->getNumElements();
203 return cast<ArrayType>(T)->getNumElements();
204}
205
Chris Lattner5d8a12e2003-09-11 16:45:55 +0000206// performScalarRepl - This algorithm is a simple worklist driven algorithm,
207// which runs on all of the malloc/alloca instructions in the function, removing
208// them if they are only used by getelementptr instructions.
209//
210bool SROA::performScalarRepl(Function &F) {
Chris Lattnerfb41a502003-05-27 15:45:27 +0000211 std::vector<AllocationInst*> WorkList;
212
213 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner5dac64f2003-09-20 14:39:18 +0000214 BasicBlock &BB = F.getEntryBlock();
Chris Lattnerfb41a502003-05-27 15:45:27 +0000215 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
216 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
217 WorkList.push_back(A);
218
219 // Process the worklist
220 bool Changed = false;
221 while (!WorkList.empty()) {
222 AllocationInst *AI = WorkList.back();
223 WorkList.pop_back();
Chris Lattner3b0a62d2005-12-12 07:19:13 +0000224
Chris Lattnerf171af92006-12-22 23:14:42 +0000225 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
226 // with unused elements.
227 if (AI->use_empty()) {
228 AI->eraseFromParent();
229 continue;
230 }
Chris Lattner09b65ab2009-02-03 01:30:09 +0000231
232 // If this alloca is impossible for us to promote, reject it early.
233 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
234 continue;
Chris Lattner827cb982007-04-25 06:40:51 +0000235
236 // Check to see if this allocation is only modified by a memcpy/memmove from
237 // a constant global. If this is the case, we can change all users to use
238 // the constant global instead. This is commonly produced by the CFE by
239 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
240 // is only subsequently read.
241 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
242 DOUT << "Found alloca equal to global: " << *AI;
243 DOUT << " memcpy = " << *TheCopy;
244 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Anderson340288c2009-07-03 19:42:02 +0000245 AI->replaceAllUsesWith(
Owen Anderson47db9412009-07-22 00:24:57 +0000246 F.getContext().getConstantExprBitCast(TheSrc, AI->getType()));
Chris Lattner827cb982007-04-25 06:40:51 +0000247 TheCopy->eraseFromParent(); // Don't mutate the global.
248 AI->eraseFromParent();
249 ++NumGlobals;
250 Changed = true;
251 continue;
252 }
Chris Lattner43cecd72009-02-02 20:44:45 +0000253
Chris Lattner09b65ab2009-02-03 01:30:09 +0000254 // Check to see if we can perform the core SROA transformation. We cannot
255 // transform the allocation instruction if it is an array allocation
256 // (allocations OF arrays are ok though), and an allocation of a scalar
257 // value cannot be decomposed at all.
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000258 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling3e44bf32009-03-03 12:12:58 +0000259
260 // Do not promote any struct whose size is too big.
Bill Wendlinga68fc7a2009-03-03 19:18:49 +0000261 if (AllocaSize > SRThreshold) continue;
Bill Wendling38eae042009-03-01 03:55:12 +0000262
Chris Lattner09b65ab2009-02-03 01:30:09 +0000263 if ((isa<StructType>(AI->getAllocatedType()) ||
264 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner09b65ab2009-02-03 01:30:09 +0000265 // Do not promote any struct into more than "32" separate vars.
Evan Cheng5fd4fc72009-03-06 00:56:43 +0000266 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner09b65ab2009-02-03 01:30:09 +0000267 // Check that all of the users of the allocation are capable of being
268 // transformed.
269 switch (isSafeAllocaToScalarRepl(AI)) {
Torok Edwinfbcc6632009-07-14 16:55:14 +0000270 default: llvm_unreachable("Unexpected value!");
Chris Lattner09b65ab2009-02-03 01:30:09 +0000271 case 0: // Not safe to scalar replace.
272 break;
273 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patelcaf44852009-02-10 07:00:59 +0000274 CleanupAllocaUsers(AI);
Chris Lattner09b65ab2009-02-03 01:30:09 +0000275 // FALL THROUGH.
276 case 3: // Safe to scalar replace.
277 DoScalarReplacement(AI, WorkList);
278 Changed = true;
279 continue;
280 }
281 }
Chris Lattnerdf179872009-01-28 20:16:43 +0000282
283 // If we can turn this aggregate value (potentially with casts) into a
284 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattnerec99c462009-01-31 02:28:54 +0000285 // IsNotTrivial tracks whether this is something that mem2reg could have
286 // promoted itself. If so, we don't want to transform it needlessly. Note
287 // that we can't just check based on the type: the alloca may be of an i32
288 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattnerdf179872009-01-28 20:16:43 +0000289 bool IsNotTrivial = false;
Chris Lattner09b65ab2009-02-03 01:30:09 +0000290 const Type *VectorTy = 0;
Chris Lattner73eff2e2009-02-03 18:15:05 +0000291 bool HadAVector = false;
292 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattnerb5b0c872009-03-04 19:22:30 +0000293 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner09b65ab2009-02-03 01:30:09 +0000294 AllocaInst *NewAI;
Chris Lattner73eff2e2009-02-03 18:15:05 +0000295 // If we were able to find a vector type that can handle this with
296 // insert/extract elements, and if there was at least one use that had
297 // a vector type, promote this to a vector. We don't want to promote
298 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
299 // we just get a lot of insert/extracts. If at least one vector is
300 // involved, then we probably really do have a union of vector/array.
301 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Chris Lattner09b65ab2009-02-03 01:30:09 +0000302 DOUT << "CONVERT TO VECTOR: " << *AI << " TYPE = " << *VectorTy <<"\n";
Chris Lattner43cecd72009-02-02 20:44:45 +0000303
Chris Lattner09b65ab2009-02-03 01:30:09 +0000304 // Create and insert the vector alloca.
Owen Anderson4fdeba92009-07-15 23:53:25 +0000305 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner43cecd72009-02-02 20:44:45 +0000306 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner09b65ab2009-02-03 01:30:09 +0000307 } else {
308 DOUT << "CONVERT TO SCALAR INTEGER: " << *AI << "\n";
309
310 // Create and insert the integer alloca.
Owen Anderson47db9412009-07-22 00:24:57 +0000311 const Type *NewTy = F.getContext().getIntegerType(AllocaSize*8);
Owen Anderson4fdeba92009-07-15 23:53:25 +0000312 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattner09b65ab2009-02-03 01:30:09 +0000313 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattnerdf179872009-01-28 20:16:43 +0000314 }
Chris Lattner09b65ab2009-02-03 01:30:09 +0000315 NewAI->takeName(AI);
316 AI->eraseFromParent();
317 ++NumConverted;
318 Changed = true;
319 continue;
320 }
Chris Lattnerdf179872009-01-28 20:16:43 +0000321
Chris Lattner09b65ab2009-02-03 01:30:09 +0000322 // Otherwise, couldn't process this alloca.
Chris Lattnerfb41a502003-05-27 15:45:27 +0000323 }
324
325 return Changed;
326}
Chris Lattner6e5398d2003-05-30 04:15:41 +0000327
Chris Lattner31e5add2007-04-25 05:02:56 +0000328/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
329/// predicate, do SROA now.
330void SROA::DoScalarReplacement(AllocationInst *AI,
331 std::vector<AllocationInst*> &WorkList) {
Chris Lattner827cb982007-04-25 06:40:51 +0000332 DOUT << "Found inst to SROA: " << *AI;
Chris Lattner31e5add2007-04-25 05:02:56 +0000333 SmallVector<AllocaInst*, 32> ElementAllocas;
Owen Anderson47db9412009-07-22 00:24:57 +0000334 LLVMContext &Context = AI->getContext();
Chris Lattner31e5add2007-04-25 05:02:56 +0000335 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
336 ElementAllocas.reserve(ST->getNumContainedTypes());
337 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson4fdeba92009-07-15 23:53:25 +0000338 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattner31e5add2007-04-25 05:02:56 +0000339 AI->getAlignment(),
340 AI->getName() + "." + utostr(i), AI);
341 ElementAllocas.push_back(NA);
342 WorkList.push_back(NA); // Add to worklist for recursive processing
343 }
344 } else {
345 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
346 ElementAllocas.reserve(AT->getNumElements());
347 const Type *ElTy = AT->getElementType();
348 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson4fdeba92009-07-15 23:53:25 +0000349 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Chris Lattner31e5add2007-04-25 05:02:56 +0000350 AI->getName() + "." + utostr(i), AI);
351 ElementAllocas.push_back(NA);
352 WorkList.push_back(NA); // Add to worklist for recursive processing
353 }
354 }
355
356 // Now that we have created the alloca instructions that we want to use,
357 // expand the getelementptr instructions to use them.
358 //
359 while (!AI->use_empty()) {
360 Instruction *User = cast<Instruction>(AI->use_back());
361 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
362 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
363 BCInst->eraseFromParent();
364 continue;
365 }
366
Chris Lattner4d754bc2008-06-23 17:11:23 +0000367 // Replace:
368 // %res = load { i32, i32 }* %alloc
369 // with:
370 // %load.0 = load i32* %alloc.0
371 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
372 // %load.1 = load i32* %alloc.1
373 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman812989b2008-06-05 12:51:53 +0000374 // (Also works for arrays instead of structs)
375 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson47db9412009-07-22 00:24:57 +0000376 Value *Insert = Context.getUndef(LI->getType());
Matthijs Kooijman812989b2008-06-05 12:51:53 +0000377 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
378 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
379 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
380 }
381 LI->replaceAllUsesWith(Insert);
382 LI->eraseFromParent();
383 continue;
384 }
385
Chris Lattner4d754bc2008-06-23 17:11:23 +0000386 // Replace:
387 // store { i32, i32 } %val, { i32, i32 }* %alloc
388 // with:
389 // %val.0 = extractvalue { i32, i32 } %val, 0
390 // store i32 %val.0, i32* %alloc.0
391 // %val.1 = extractvalue { i32, i32 } %val, 1
392 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman812989b2008-06-05 12:51:53 +0000393 // (Also works for arrays instead of structs)
394 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
395 Value *Val = SI->getOperand(0);
396 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
397 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
398 new StoreInst(Extract, ElementAllocas[i], SI);
399 }
400 SI->eraseFromParent();
401 continue;
402 }
403
Chris Lattner31e5add2007-04-25 05:02:56 +0000404 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
405 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
406 unsigned Idx =
407 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
408
409 assert(Idx < ElementAllocas.size() && "Index out of range?");
410 AllocaInst *AllocaToUse = ElementAllocas[Idx];
411
412 Value *RepValue;
413 if (GEPI->getNumOperands() == 3) {
414 // Do not insert a new getelementptr instruction with zero indices, only
415 // to have it optimized out later.
416 RepValue = AllocaToUse;
417 } else {
418 // We are indexing deeply into the structure, so we still need a
419 // getelement ptr instruction to finish the indexing. This may be
420 // expanded itself once the worklist is rerun.
421 //
422 SmallVector<Value*, 8> NewArgs;
Owen Anderson47db9412009-07-22 00:24:57 +0000423 NewArgs.push_back(Context.getNullValue(Type::Int32Ty));
Chris Lattner31e5add2007-04-25 05:02:56 +0000424 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greife9ecc682008-04-06 20:25:17 +0000425 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
426 NewArgs.end(), "", GEPI);
Chris Lattner31e5add2007-04-25 05:02:56 +0000427 RepValue->takeName(GEPI);
428 }
429
430 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattnera63dba92009-01-07 06:25:07 +0000431 if (Idx == 0 && GEPI->hasAllZeroIndices())
432 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Chris Lattner31e5add2007-04-25 05:02:56 +0000433
434 // Move all of the users over to the new GEP.
435 GEPI->replaceAllUsesWith(RepValue);
436 // Delete the old GEP
437 GEPI->eraseFromParent();
438 }
439
440 // Finally, delete the Alloca instruction
441 AI->eraseFromParent();
442 NumReplaced++;
443}
444
Chris Lattner6e5398d2003-05-30 04:15:41 +0000445
Chris Lattner88819122004-11-14 04:24:28 +0000446/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner877a3b42007-03-19 00:16:43 +0000447/// getelementptr instruction of an array aggregate allocation. isFirstElt
448/// indicates whether Ptr is known to the start of the aggregate.
Chris Lattner88819122004-11-14 04:24:28 +0000449///
Chris Lattner87679202007-05-30 06:11:23 +0000450void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
451 AllocaInfo &Info) {
Chris Lattner88819122004-11-14 04:24:28 +0000452 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
453 I != E; ++I) {
454 Instruction *User = cast<Instruction>(*I);
455 switch (User->getOpcode()) {
456 case Instruction::Load: break;
457 case Instruction::Store:
458 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattner87679202007-05-30 06:11:23 +0000459 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
Chris Lattner88819122004-11-14 04:24:28 +0000460 break;
461 case Instruction::GetElementPtr: {
462 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
Chris Lattner877a3b42007-03-19 00:16:43 +0000463 bool AreAllZeroIndices = isFirstElt;
Chris Lattner88819122004-11-14 04:24:28 +0000464 if (GEP->getNumOperands() > 1) {
Chris Lattner877a3b42007-03-19 00:16:43 +0000465 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
466 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
Chris Lattner87679202007-05-30 06:11:23 +0000467 // Using pointer arithmetic to navigate the array.
468 return MarkUnsafe(Info);
Chris Lattner877a3b42007-03-19 00:16:43 +0000469
Chris Lattnera63dba92009-01-07 06:25:07 +0000470 if (AreAllZeroIndices)
471 AreAllZeroIndices = GEP->hasAllZeroIndices();
Chris Lattner88819122004-11-14 04:24:28 +0000472 }
Chris Lattner87679202007-05-30 06:11:23 +0000473 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
474 if (Info.isUnsafe) return;
Chris Lattner88819122004-11-14 04:24:28 +0000475 break;
476 }
Chris Lattner877a3b42007-03-19 00:16:43 +0000477 case Instruction::BitCast:
Chris Lattner87679202007-05-30 06:11:23 +0000478 if (isFirstElt) {
479 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
480 if (Info.isUnsafe) return;
Chris Lattner877a3b42007-03-19 00:16:43 +0000481 break;
Chris Lattner877a3b42007-03-19 00:16:43 +0000482 }
483 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner87679202007-05-30 06:11:23 +0000484 return MarkUnsafe(Info);
485 case Instruction::Call:
486 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
487 if (isFirstElt) {
488 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
489 if (Info.isUnsafe) return;
490 break;
491 }
492 }
493 DOUT << " Transformation preventing inst: " << *User;
494 return MarkUnsafe(Info);
Chris Lattner88819122004-11-14 04:24:28 +0000495 default:
Bill Wendling5dbf43c2006-11-26 09:46:52 +0000496 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner87679202007-05-30 06:11:23 +0000497 return MarkUnsafe(Info);
Chris Lattner88819122004-11-14 04:24:28 +0000498 }
499 }
Chris Lattner87679202007-05-30 06:11:23 +0000500 return; // All users look ok :)
Chris Lattner88819122004-11-14 04:24:28 +0000501}
502
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000503/// AllUsersAreLoads - Return true if all users of this value are loads.
504static bool AllUsersAreLoads(Value *Ptr) {
505 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
506 I != E; ++I)
507 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
508 return false;
Misha Brukmanb1c93172005-04-21 23:48:37 +0000509 return true;
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000510}
511
Chris Lattner6e5398d2003-05-30 04:15:41 +0000512/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
513/// aggregate allocation.
514///
Chris Lattner87679202007-05-30 06:11:23 +0000515void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
516 AllocaInfo &Info) {
Owen Anderson47db9412009-07-22 00:24:57 +0000517 LLVMContext &Context = User->getContext();
Chris Lattner66e6a822007-03-05 07:52:57 +0000518 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
Chris Lattner87679202007-05-30 06:11:23 +0000519 return isSafeUseOfBitCastedAllocation(C, AI, Info);
Chris Lattner52310702003-11-25 21:09:18 +0000520
Chris Lattnerdf179872009-01-28 20:16:43 +0000521 if (LoadInst *LI = dyn_cast<LoadInst>(User))
522 if (!LI->isVolatile())
523 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman812989b2008-06-05 12:51:53 +0000524
Chris Lattnerdf179872009-01-28 20:16:43 +0000525 if (StoreInst *SI = dyn_cast<StoreInst>(User))
526 if (!SI->isVolatile() && SI->getOperand(0) != AI)
527 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman812989b2008-06-05 12:51:53 +0000528
Chris Lattner87679202007-05-30 06:11:23 +0000529 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
530 if (GEPI == 0)
531 return MarkUnsafe(Info);
532
Chris Lattner52310702003-11-25 21:09:18 +0000533 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
534
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000535 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattner52310702003-11-25 21:09:18 +0000536 if (I == E ||
Owen Anderson47db9412009-07-22 00:24:57 +0000537 I.getOperand() != Context.getNullValue(I.getOperand()->getType())) {
Chris Lattner87679202007-05-30 06:11:23 +0000538 return MarkUnsafe(Info);
539 }
Chris Lattner52310702003-11-25 21:09:18 +0000540
541 ++I;
Chris Lattner87679202007-05-30 06:11:23 +0000542 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
Chris Lattner52310702003-11-25 21:09:18 +0000543
Chris Lattner877a3b42007-03-19 00:16:43 +0000544 bool IsAllZeroIndices = true;
545
Chris Lattner3f972c92008-08-23 05:21:06 +0000546 // If the first index is a non-constant index into an array, see if we can
547 // handle it as a special case.
Chris Lattner52310702003-11-25 21:09:18 +0000548 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattner3f972c92008-08-23 05:21:06 +0000549 if (!isa<ConstantInt>(I.getOperand())) {
Chris Lattner877a3b42007-03-19 00:16:43 +0000550 IsAllZeroIndices = 0;
Chris Lattner3f972c92008-08-23 05:21:06 +0000551 uint64_t NumElements = AT->getNumElements();
Chris Lattner877a3b42007-03-19 00:16:43 +0000552
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000553 // If this is an array index and the index is not constant, we cannot
554 // promote... that is unless the array has exactly one or two elements in
555 // it, in which case we CAN promote it, but we have to canonicalize this
556 // out if this is the only problem.
Chris Lattnerfc34f8b2006-03-08 01:05:29 +0000557 if ((NumElements == 1 || NumElements == 2) &&
Chris Lattner87679202007-05-30 06:11:23 +0000558 AllUsersAreLoads(GEPI)) {
Devang Patelcaf44852009-02-10 07:00:59 +0000559 Info.needsCleanup = true;
Chris Lattner87679202007-05-30 06:11:23 +0000560 return; // Canonicalization required!
561 }
562 return MarkUnsafe(Info);
Chris Lattnerfe3f4e62004-11-14 05:00:19 +0000563 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000564 }
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000565
Chris Lattner3f972c92008-08-23 05:21:06 +0000566 // Walk through the GEP type indices, checking the types that this indexes
567 // into.
568 for (; I != E; ++I) {
569 // Ignore struct elements, no extra checking needed for these.
570 if (isa<StructType>(*I))
571 continue;
572
Chris Lattner3f972c92008-08-23 05:21:06 +0000573 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
574 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000575
576 // Are all indices still zero?
Chris Lattner3f972c92008-08-23 05:21:06 +0000577 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000578
579 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
580 // This GEP indexes an array. Verify that this is an in-range constant
581 // integer. Specifically, consider A[0][i]. We cannot know that the user
582 // isn't doing invalid things like allowing i to index an out-of-range
583 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesen0a7b4f52008-11-04 20:54:03 +0000584 // of any accesses into structs where any of the components are variables.
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000585 if (IdxVal->getZExtValue() >= AT->getNumElements())
586 return MarkUnsafe(Info);
Dale Johannesen0a7b4f52008-11-04 20:54:03 +0000587 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
588 if (IdxVal->getZExtValue() >= VT->getNumElements())
589 return MarkUnsafe(Info);
Matthijs Kooijmancbe5e162008-10-06 16:23:31 +0000590 }
Chris Lattner3f972c92008-08-23 05:21:06 +0000591 }
592
Chris Lattner52310702003-11-25 21:09:18 +0000593 // If there are any non-simple uses of this getelementptr, make sure to reject
594 // them.
Chris Lattner87679202007-05-30 06:11:23 +0000595 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
Chris Lattner877a3b42007-03-19 00:16:43 +0000596}
597
598/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
599/// intrinsic can be promoted by SROA. At this point, we know that the operand
600/// of the memintrinsic is a pointer to the beginning of the allocation.
Chris Lattner87679202007-05-30 06:11:23 +0000601void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
602 unsigned OpNo, AllocaInfo &Info) {
Chris Lattner877a3b42007-03-19 00:16:43 +0000603 // If not constant length, give up.
604 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattner87679202007-05-30 06:11:23 +0000605 if (!Length) return MarkUnsafe(Info);
Chris Lattner877a3b42007-03-19 00:16:43 +0000606
607 // If not the whole aggregate, give up.
Duncan Sands399d9792007-11-04 14:43:57 +0000608 if (Length->getZExtValue() !=
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000609 TD->getTypeAllocSize(AI->getType()->getElementType()))
Chris Lattner87679202007-05-30 06:11:23 +0000610 return MarkUnsafe(Info);
Chris Lattner877a3b42007-03-19 00:16:43 +0000611
612 // We only know about memcpy/memset/memmove.
Chris Lattner334268a2009-03-08 03:37:16 +0000613 if (!isa<MemIntrinsic>(MI))
Chris Lattner87679202007-05-30 06:11:23 +0000614 return MarkUnsafe(Info);
615
616 // Otherwise, we can transform it. Determine whether this is a memcpy/set
617 // into or out of the aggregate.
618 if (OpNo == 1)
619 Info.isMemCpyDst = true;
620 else {
621 assert(OpNo == 2);
622 Info.isMemCpySrc = true;
623 }
Chris Lattner6e5398d2003-05-30 04:15:41 +0000624}
625
Chris Lattner66e6a822007-03-05 07:52:57 +0000626/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
627/// are
Chris Lattner87679202007-05-30 06:11:23 +0000628void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
629 AllocaInfo &Info) {
Chris Lattner66e6a822007-03-05 07:52:57 +0000630 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
631 UI != E; ++UI) {
632 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
Chris Lattner87679202007-05-30 06:11:23 +0000633 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
Chris Lattner66e6a822007-03-05 07:52:57 +0000634 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
Chris Lattner87679202007-05-30 06:11:23 +0000635 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000636 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattnerdf179872009-01-28 20:16:43 +0000637 if (SI->isVolatile())
638 return MarkUnsafe(Info);
639
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000640 // If storing the entire alloca in one chunk through a bitcasted pointer
641 // to integer, we can transform it. This happens (for example) when you
642 // cast a {i32,i32}* to i64* and store through it. This is similar to the
643 // memcpy case and occurs in various "byval" cases and emulated memcpys.
644 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000645 TD->getTypeAllocSize(SI->getOperand(0)->getType()) ==
646 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000647 Info.isMemCpyDst = true;
648 continue;
649 }
650 return MarkUnsafe(Info);
Chris Lattnerc518dfd2009-01-08 05:42:05 +0000651 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattnerdf179872009-01-28 20:16:43 +0000652 if (LI->isVolatile())
653 return MarkUnsafe(Info);
654
Chris Lattnerc518dfd2009-01-08 05:42:05 +0000655 // If loading the entire alloca in one chunk through a bitcasted pointer
656 // to integer, we can transform it. This happens (for example) when you
657 // cast a {i32,i32}* to i64* and load through it. This is similar to the
658 // memcpy case and occurs in various "byval" cases and emulated memcpys.
659 if (isa<IntegerType>(LI->getType()) &&
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000660 TD->getTypeAllocSize(LI->getType()) ==
661 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattnerc518dfd2009-01-08 05:42:05 +0000662 Info.isMemCpySrc = true;
663 continue;
664 }
665 return MarkUnsafe(Info);
Devang Patelcaf44852009-02-10 07:00:59 +0000666 } else if (isa<DbgInfoIntrinsic>(UI)) {
667 // If one user is DbgInfoIntrinsic then check if all users are
668 // DbgInfoIntrinsics.
669 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
670 Info.needsCleanup = true;
671 return;
672 }
673 else
674 MarkUnsafe(Info);
675 }
676 else {
Chris Lattner87679202007-05-30 06:11:23 +0000677 return MarkUnsafe(Info);
Chris Lattner66e6a822007-03-05 07:52:57 +0000678 }
Chris Lattner87679202007-05-30 06:11:23 +0000679 if (Info.isUnsafe) return;
Chris Lattner66e6a822007-03-05 07:52:57 +0000680 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000681}
682
Chris Lattner877a3b42007-03-19 00:16:43 +0000683/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
684/// to its first element. Transform users of the cast to use the new values
685/// instead.
686void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner66e6a822007-03-05 07:52:57 +0000687 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner877a3b42007-03-19 00:16:43 +0000688 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
689 while (UI != UE) {
Chris Lattner9a2de652009-01-07 07:18:45 +0000690 Instruction *User = cast<Instruction>(*UI++);
691 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Chris Lattner66e6a822007-03-05 07:52:57 +0000692 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000693 if (BCU->use_empty()) BCU->eraseFromParent();
Chris Lattner66e6a822007-03-05 07:52:57 +0000694 continue;
695 }
696
Chris Lattner9a2de652009-01-07 07:18:45 +0000697 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
698 // This must be memcpy/memmove/memset of the entire aggregate.
699 // Split into one per element.
700 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Chris Lattner877a3b42007-03-19 00:16:43 +0000701 continue;
702 }
Chris Lattner9a2de652009-01-07 07:18:45 +0000703
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000704 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattnerc518dfd2009-01-08 05:42:05 +0000705 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000706 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
707 continue;
708 }
Chris Lattnerc518dfd2009-01-08 05:42:05 +0000709
710 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
711 // If this is a load of the entire alloca to an integer, rewrite it.
712 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
713 continue;
714 }
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000715
716 // Otherwise it must be some other user of a gep of the first pointer. Just
717 // leave these alone.
Chris Lattner9a2de652009-01-07 07:18:45 +0000718 continue;
Chris Lattnerc518dfd2009-01-08 05:42:05 +0000719 }
Chris Lattner9a2de652009-01-07 07:18:45 +0000720}
721
722/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
723/// Rewrite it to copy or set the elements of the scalarized memory.
724void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
725 AllocationInst *AI,
726 SmallVector<AllocaInst*, 32> &NewElts) {
727
728 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattnera41bb402009-03-04 19:23:25 +0000729 // appropriate type. The "Other" pointer is the pointer that goes to memory
730 // that doesn't have anything to do with the alloca that we are promoting. For
731 // memset, this Value* stays null.
Chris Lattner9a2de652009-01-07 07:18:45 +0000732 Value *OtherPtr = 0;
Owen Anderson47db9412009-07-22 00:24:57 +0000733 LLVMContext &Context = MI->getContext();
Chris Lattnerdc35e5b2009-03-08 03:59:00 +0000734 unsigned MemAlignment = MI->getAlignment();
Chris Lattner334268a2009-03-08 03:37:16 +0000735 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
736 if (BCInst == MTI->getRawDest())
737 OtherPtr = MTI->getRawSource();
Chris Lattner9a2de652009-01-07 07:18:45 +0000738 else {
Chris Lattner334268a2009-03-08 03:37:16 +0000739 assert(BCInst == MTI->getRawSource());
740 OtherPtr = MTI->getRawDest();
Chris Lattner9a2de652009-01-07 07:18:45 +0000741 }
742 }
743
744 // If there is an other pointer, we want to convert it to the same pointer
745 // type as AI has, so we can GEP through it safely.
746 if (OtherPtr) {
747 // It is likely that OtherPtr is a bitcast, if so, remove it.
748 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
749 OtherPtr = BC->getOperand(0);
750 // All zero GEPs are effectively bitcasts.
751 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
752 if (GEP->hasAllZeroIndices())
753 OtherPtr = GEP->getOperand(0);
Chris Lattner66e6a822007-03-05 07:52:57 +0000754
Chris Lattner9a2de652009-01-07 07:18:45 +0000755 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
756 if (BCE->getOpcode() == Instruction::BitCast)
757 OtherPtr = BCE->getOperand(0);
758
759 // If the pointer is not the right type, insert a bitcast to the right
760 // type.
761 if (OtherPtr->getType() != AI->getType())
762 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
763 MI);
764 }
765
766 // Process each element of the aggregate.
767 Value *TheFn = MI->getOperand(0);
768 const Type *BytePtrTy = MI->getRawDest()->getType();
769 bool SROADest = MI->getRawDest() == BCInst;
770
Owen Anderson47db9412009-07-22 00:24:57 +0000771 Constant *Zero = Context.getNullValue(Type::Int32Ty);
Chris Lattner9a2de652009-01-07 07:18:45 +0000772
773 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
774 // If this is a memcpy/memmove, emit a GEP of the other element address.
775 Value *OtherElt = 0;
Chris Lattner5c204c92009-03-04 19:20:50 +0000776 unsigned OtherEltAlign = MemAlignment;
777
Chris Lattner66e6a822007-03-05 07:52:57 +0000778 if (OtherPtr) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000779 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) };
Chris Lattner9a2de652009-01-07 07:18:45 +0000780 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner6ff85682008-06-22 17:46:21 +0000781 OtherPtr->getNameStr()+"."+utostr(i),
Chris Lattner9a2de652009-01-07 07:18:45 +0000782 MI);
Chris Lattner5c204c92009-03-04 19:20:50 +0000783 uint64_t EltOffset;
784 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
785 if (const StructType *ST =
786 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
787 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
788 } else {
789 const Type *EltTy =
790 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000791 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner5c204c92009-03-04 19:20:50 +0000792 }
793
794 // The alignment of the other pointer is the guaranteed alignment of the
795 // element, which is affected by both the known alignment of the whole
796 // mem intrinsic and the alignment of the element. If the alignment of
797 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
798 // known alignment is just 4 bytes.
799 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattner9f022d52007-03-08 06:36:54 +0000800 }
Chris Lattner9a2de652009-01-07 07:18:45 +0000801
802 Value *EltPtr = NewElts[i];
Chris Lattner5c204c92009-03-04 19:20:50 +0000803 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattner9a2de652009-01-07 07:18:45 +0000804
805 // If we got down to a scalar, insert a load or store as appropriate.
806 if (EltTy->isSingleValueType()) {
Chris Lattner334268a2009-03-08 03:37:16 +0000807 if (isa<MemTransferInst>(MI)) {
Chris Lattner5c204c92009-03-04 19:20:50 +0000808 if (SROADest) {
809 // From Other to Alloca.
810 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
811 new StoreInst(Elt, EltPtr, MI);
812 } else {
813 // From Alloca to Other.
814 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
815 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
816 }
Chris Lattner9a2de652009-01-07 07:18:45 +0000817 continue;
818 }
819 assert(isa<MemSetInst>(MI));
820
821 // If the stored element is zero (common case), just store a null
822 // constant.
823 Constant *StoreVal;
824 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
825 if (CI->isZero()) {
Owen Anderson47db9412009-07-22 00:24:57 +0000826 StoreVal = Context.getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattner9a2de652009-01-07 07:18:45 +0000827 } else {
828 // If EltTy is a vector type, get the element type.
Dan Gohmanadfd42a2009-06-16 00:20:26 +0000829 const Type *ValTy = EltTy->getScalarType();
830
Chris Lattner9a2de652009-01-07 07:18:45 +0000831 // Construct an integer with the right value.
832 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
833 APInt OneVal(EltSize, CI->getZExtValue());
834 APInt TotalVal(OneVal);
835 // Set each byte.
836 for (unsigned i = 0; 8*i < EltSize; ++i) {
837 TotalVal = TotalVal.shl(8);
838 TotalVal |= OneVal;
839 }
840
841 // Convert the integer value to the appropriate type.
Owen Andersonedb4a702009-07-24 23:12:02 +0000842 StoreVal = ConstantInt::get(Context, TotalVal);
Chris Lattner9a2de652009-01-07 07:18:45 +0000843 if (isa<PointerType>(ValTy))
Owen Anderson47db9412009-07-22 00:24:57 +0000844 StoreVal = Context.getConstantExprIntToPtr(StoreVal, ValTy);
Chris Lattner9a2de652009-01-07 07:18:45 +0000845 else if (ValTy->isFloatingPoint())
Owen Anderson47db9412009-07-22 00:24:57 +0000846 StoreVal = Context.getConstantExprBitCast(StoreVal, ValTy);
Chris Lattner9a2de652009-01-07 07:18:45 +0000847 assert(StoreVal->getType() == ValTy && "Type mismatch!");
848
849 // If the requested value was a vector constant, create it.
850 if (EltTy != ValTy) {
851 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
852 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Anderson47db9412009-07-22 00:24:57 +0000853 StoreVal = Context.getConstantVector(&Elts[0], NumElts);
Chris Lattner9a2de652009-01-07 07:18:45 +0000854 }
855 }
856 new StoreInst(StoreVal, EltPtr, MI);
857 continue;
858 }
859 // Otherwise, if we're storing a byte variable, use a memset call for
860 // this element.
861 }
862
863 // Cast the element pointer to BytePtrTy.
864 if (EltPtr->getType() != BytePtrTy)
865 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
866
867 // Cast the other pointer (if we have one) to BytePtrTy.
868 if (OtherElt && OtherElt->getType() != BytePtrTy)
869 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
870 MI);
871
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000872 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattner9a2de652009-01-07 07:18:45 +0000873
874 // Finally, insert the meminst for this element.
Chris Lattner334268a2009-03-08 03:37:16 +0000875 if (isa<MemTransferInst>(MI)) {
Chris Lattner9a2de652009-01-07 07:18:45 +0000876 Value *Ops[] = {
877 SROADest ? EltPtr : OtherElt, // Dest ptr
878 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersonedb4a702009-07-24 23:12:02 +0000879 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
880 ConstantInt::get(Type::Int32Ty, OtherEltAlign) // Align
Chris Lattner9a2de652009-01-07 07:18:45 +0000881 };
882 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
883 } else {
884 assert(isa<MemSetInst>(MI));
885 Value *Ops[] = {
886 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersonedb4a702009-07-24 23:12:02 +0000887 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattner9a2de652009-01-07 07:18:45 +0000888 Zero // Align
889 };
890 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
891 }
Chris Lattner66e6a822007-03-05 07:52:57 +0000892 }
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000893 MI->eraseFromParent();
Chris Lattner66e6a822007-03-05 07:52:57 +0000894}
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000895
896/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
897/// overwrites the entire allocation. Extract out the pieces of the stored
898/// integer and store them individually.
899void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
900 AllocationInst *AI,
901 SmallVector<AllocaInst*, 32> &NewElts){
902 // Extract each element out of the integer according to its structure offset
903 // and store the element value to the individual alloca.
Owen Anderson47db9412009-07-22 00:24:57 +0000904 LLVMContext &Context = SI->getContext();
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000905 Value *SrcVal = SI->getOperand(0);
906 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000907 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner9a2de652009-01-07 07:18:45 +0000908
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000909 // If this isn't a store of an integer to the whole alloca, it may be a store
910 // to the first element. Just ignore the store in this case and normal SROA
Eli Friedmanee94e3c2009-06-01 09:14:32 +0000911 // will handle it.
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000912 if (!isa<IntegerType>(SrcVal->getType()) ||
Eli Friedmanee94e3c2009-06-01 09:14:32 +0000913 TD->getTypeAllocSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000914 return;
Eli Friedmanee94e3c2009-06-01 09:14:32 +0000915 // Handle tail padding by extending the operand
916 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Anderson340288c2009-07-03 19:42:02 +0000917 SrcVal = new ZExtInst(SrcVal,
Owen Anderson47db9412009-07-22 00:24:57 +0000918 Context.getIntegerType(AllocaSizeBits), "", SI);
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000919
920 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
921
922 // There are two forms here: AI could be an array or struct. Both cases
923 // have different ways to compute the element offset.
924 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
925 const StructLayout *Layout = TD->getStructLayout(EltSTy);
926
927 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
928 // Get the number of bits to shift SrcVal to get the value.
929 const Type *FieldTy = EltSTy->getElementType(i);
930 uint64_t Shift = Layout->getElementOffsetInBits(i);
931
932 if (TD->isBigEndian())
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000933 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000934
935 Value *EltVal = SrcVal;
936 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000937 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000938 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
939 "sroa.store.elt", SI);
940 }
941
942 // Truncate down to an integer of the right size.
943 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattnerae0e8572009-01-09 18:18:43 +0000944
945 // Ignore zero sized fields like {}, they obviously contain no data.
946 if (FieldSizeBits == 0) continue;
947
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000948 if (FieldSizeBits != AllocaSizeBits)
Owen Anderson340288c2009-07-03 19:42:02 +0000949 EltVal = new TruncInst(EltVal,
Owen Anderson47db9412009-07-22 00:24:57 +0000950 Context.getIntegerType(FieldSizeBits), "", SI);
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000951 Value *DestField = NewElts[i];
952 if (EltVal->getType() == FieldTy) {
953 // Storing to an integer field of this size, just do it.
954 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
955 // Bitcast to the right element type (for fp/vector values).
956 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
957 } else {
958 // Otherwise, bitcast the dest pointer (for aggregates).
959 DestField = new BitCastInst(DestField,
Owen Anderson47db9412009-07-22 00:24:57 +0000960 Context.getPointerTypeUnqual(EltVal->getType()),
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000961 "", SI);
962 }
963 new StoreInst(EltVal, DestField, SI);
964 }
965
966 } else {
967 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
968 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +0000969 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000970 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
971
972 uint64_t Shift;
973
974 if (TD->isBigEndian())
975 Shift = AllocaSizeBits-ElementOffset;
976 else
977 Shift = 0;
978
979 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattnerae0e8572009-01-09 18:18:43 +0000980 // Ignore zero sized fields like {}, they obviously contain no data.
981 if (ElementSizeBits == 0) continue;
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000982
983 Value *EltVal = SrcVal;
984 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000985 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000986 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
987 "sroa.store.elt", SI);
988 }
989
990 // Truncate down to an integer of the right size.
991 if (ElementSizeBits != AllocaSizeBits)
Owen Anderson340288c2009-07-03 19:42:02 +0000992 EltVal = new TruncInst(EltVal,
Owen Anderson47db9412009-07-22 00:24:57 +0000993 Context.getIntegerType(ElementSizeBits),"",SI);
Chris Lattnerf2b8c822009-01-07 08:11:13 +0000994 Value *DestField = NewElts[i];
995 if (EltVal->getType() == ArrayEltTy) {
996 // Storing to an integer field of this size, just do it.
997 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
998 // Bitcast to the right element type (for fp/vector values).
999 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1000 } else {
1001 // Otherwise, bitcast the dest pointer (for aggregates).
1002 DestField = new BitCastInst(DestField,
Owen Anderson47db9412009-07-22 00:24:57 +00001003 Context.getPointerTypeUnqual(EltVal->getType()),
Chris Lattnerf2b8c822009-01-07 08:11:13 +00001004 "", SI);
1005 }
1006 new StoreInst(EltVal, DestField, SI);
1007
1008 if (TD->isBigEndian())
1009 Shift -= ElementOffset;
1010 else
1011 Shift += ElementOffset;
1012 }
1013 }
1014
1015 SI->eraseFromParent();
1016}
1017
Chris Lattnerc518dfd2009-01-08 05:42:05 +00001018/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
1019/// an integer. Load the individual pieces to form the aggregate value.
1020void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
1021 SmallVector<AllocaInst*, 32> &NewElts) {
1022 // Extract each element out of the NewElts according to its structure offset
1023 // and form the result value.
1024 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001025 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00001026
1027 // If this isn't a load of the whole alloca to an integer, it may be a load
1028 // of the first element. Just ignore the load in this case and normal SROA
Eli Friedmanee94e3c2009-06-01 09:14:32 +00001029 // will handle it.
Chris Lattnerc518dfd2009-01-08 05:42:05 +00001030 if (!isa<IntegerType>(LI->getType()) ||
Eli Friedmanee94e3c2009-06-01 09:14:32 +00001031 TD->getTypeAllocSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattnerc518dfd2009-01-08 05:42:05 +00001032 return;
1033
1034 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
1035
1036 // There are two forms here: AI could be an array or struct. Both cases
1037 // have different ways to compute the element offset.
1038 const StructLayout *Layout = 0;
1039 uint64_t ArrayEltBitOffset = 0;
1040 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1041 Layout = TD->getStructLayout(EltSTy);
1042 } else {
1043 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001044 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00001045 }
Owen Anderson47db9412009-07-22 00:24:57 +00001046
1047 LLVMContext &Context = LI->getContext();
1048
1049 Value *ResultVal =
1050 Context.getNullValue(Context.getIntegerType(AllocaSizeBits));
Chris Lattnerc518dfd2009-01-08 05:42:05 +00001051
1052 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1053 // Load the value from the alloca. If the NewElt is an aggregate, cast
1054 // the pointer to an integer of the same size before doing the load.
1055 Value *SrcField = NewElts[i];
1056 const Type *FieldTy =
1057 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattnerae0e8572009-01-09 18:18:43 +00001058 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1059
1060 // Ignore zero sized fields like {}, they obviously contain no data.
1061 if (FieldSizeBits == 0) continue;
1062
Owen Anderson47db9412009-07-22 00:24:57 +00001063 const IntegerType *FieldIntTy = Context.getIntegerType(FieldSizeBits);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00001064 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1065 !isa<VectorType>(FieldTy))
Owen Anderson340288c2009-07-03 19:42:02 +00001066 SrcField = new BitCastInst(SrcField,
Owen Anderson47db9412009-07-22 00:24:57 +00001067 Context.getPointerTypeUnqual(FieldIntTy),
Chris Lattnerc518dfd2009-01-08 05:42:05 +00001068 "", LI);
1069 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1070
1071 // If SrcField is a fp or vector of the right size but that isn't an
1072 // integer type, bitcast to an integer so we can shift it.
1073 if (SrcField->getType() != FieldIntTy)
1074 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1075
1076 // Zero extend the field to be the same size as the final alloca so that
1077 // we can shift and insert it.
1078 if (SrcField->getType() != ResultVal->getType())
1079 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1080
1081 // Determine the number of bits to shift SrcField.
1082 uint64_t Shift;
1083 if (Layout) // Struct case.
1084 Shift = Layout->getElementOffsetInBits(i);
1085 else // Array case.
1086 Shift = i*ArrayEltBitOffset;
1087
1088 if (TD->isBigEndian())
1089 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1090
1091 if (Shift) {
Owen Andersonedb4a702009-07-24 23:12:02 +00001092 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattnerc518dfd2009-01-08 05:42:05 +00001093 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1094 }
1095
1096 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1097 }
Eli Friedmanee94e3c2009-06-01 09:14:32 +00001098
1099 // Handle tail padding by truncating the result
1100 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1101 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1102
Chris Lattnerc518dfd2009-01-08 05:42:05 +00001103 LI->replaceAllUsesWith(ResultVal);
1104 LI->eraseFromParent();
1105}
1106
Chris Lattner66e6a822007-03-05 07:52:57 +00001107
Duncan Sands399d9792007-11-04 14:43:57 +00001108/// HasPadding - Return true if the specified type has any structure or
1109/// alignment padding, false otherwise.
Duncan Sandsfc3c4892008-06-04 08:21:45 +00001110static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner87679202007-05-30 06:11:23 +00001111 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1112 const StructLayout *SL = TD.getStructLayout(STy);
1113 unsigned PrevFieldBitOffset = 0;
1114 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands399d9792007-11-04 14:43:57 +00001115 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1116
Chris Lattner87679202007-05-30 06:11:23 +00001117 // Padding in sub-elements?
Duncan Sandsfc3c4892008-06-04 08:21:45 +00001118 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner87679202007-05-30 06:11:23 +00001119 return true;
Duncan Sands399d9792007-11-04 14:43:57 +00001120
Chris Lattner87679202007-05-30 06:11:23 +00001121 // Check to see if there is any padding between this element and the
1122 // previous one.
1123 if (i) {
Duncan Sands399d9792007-11-04 14:43:57 +00001124 unsigned PrevFieldEnd =
Chris Lattner87679202007-05-30 06:11:23 +00001125 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1126 if (PrevFieldEnd < FieldBitOffset)
1127 return true;
1128 }
Duncan Sands399d9792007-11-04 14:43:57 +00001129
Chris Lattner87679202007-05-30 06:11:23 +00001130 PrevFieldBitOffset = FieldBitOffset;
1131 }
Duncan Sands399d9792007-11-04 14:43:57 +00001132
Chris Lattner87679202007-05-30 06:11:23 +00001133 // Check for tail padding.
1134 if (unsigned EltCount = STy->getNumElements()) {
1135 unsigned PrevFieldEnd = PrevFieldBitOffset +
1136 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands399d9792007-11-04 14:43:57 +00001137 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner87679202007-05-30 06:11:23 +00001138 return true;
1139 }
1140
1141 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsfc3c4892008-06-04 08:21:45 +00001142 return HasPadding(ATy->getElementType(), TD);
Duncan Sands399d9792007-11-04 14:43:57 +00001143 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsfc3c4892008-06-04 08:21:45 +00001144 return HasPadding(VTy->getElementType(), TD);
Chris Lattner87679202007-05-30 06:11:23 +00001145 }
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001146 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner87679202007-05-30 06:11:23 +00001147}
Chris Lattner66e6a822007-03-05 07:52:57 +00001148
Chris Lattner88819122004-11-14 04:24:28 +00001149/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1150/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1151/// or 1 if safe after canonicalization has been performed.
Chris Lattner6e5398d2003-05-30 04:15:41 +00001152///
Chris Lattner88819122004-11-14 04:24:28 +00001153int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner6e5398d2003-05-30 04:15:41 +00001154 // Loop over the use list of the alloca. We can only transform it if all of
1155 // the users are safe to transform.
Chris Lattner87679202007-05-30 06:11:23 +00001156 AllocaInfo Info;
1157
Chris Lattner6e5398d2003-05-30 04:15:41 +00001158 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattner88819122004-11-14 04:24:28 +00001159 I != E; ++I) {
Chris Lattner87679202007-05-30 06:11:23 +00001160 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1161 if (Info.isUnsafe) {
Bill Wendling5dbf43c2006-11-26 09:46:52 +00001162 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattner88819122004-11-14 04:24:28 +00001163 return 0;
Chris Lattner6e5398d2003-05-30 04:15:41 +00001164 }
Chris Lattner88819122004-11-14 04:24:28 +00001165 }
Chris Lattner87679202007-05-30 06:11:23 +00001166
1167 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1168 // source and destination, we have to be careful. In particular, the memcpy
1169 // could be moving around elements that live in structure padding of the LLVM
1170 // types, but may actually be used. In these cases, we refuse to promote the
1171 // struct.
1172 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner938b54f2009-01-07 06:34:28 +00001173 HasPadding(AI->getType()->getElementType(), *TD))
Chris Lattner87679202007-05-30 06:11:23 +00001174 return 0;
Duncan Sands399d9792007-11-04 14:43:57 +00001175
Chris Lattner87679202007-05-30 06:11:23 +00001176 // If we require cleanup, return 1, otherwise return 3.
Devang Patelcaf44852009-02-10 07:00:59 +00001177 return Info.needsCleanup ? 1 : 3;
Chris Lattner88819122004-11-14 04:24:28 +00001178}
1179
Devang Patelcaf44852009-02-10 07:00:59 +00001180/// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1181/// is canonicalized here.
1182void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1183 gep_type_iterator I = gep_type_begin(GEPI);
1184 ++I;
1185
Devang Patelda1a6322009-02-10 19:28:07 +00001186 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1187 if (!AT)
1188 return;
1189
1190 uint64_t NumElements = AT->getNumElements();
1191
1192 if (isa<ConstantInt>(I.getOperand()))
1193 return;
1194
Owen Anderson47db9412009-07-22 00:24:57 +00001195 LLVMContext &Context = GEPI->getContext();
1196
Devang Patelda1a6322009-02-10 19:28:07 +00001197 if (NumElements == 1) {
Owen Anderson47db9412009-07-22 00:24:57 +00001198 GEPI->setOperand(2, Context.getNullValue(Type::Int32Ty));
Devang Patelda1a6322009-02-10 19:28:07 +00001199 return;
1200 }
Devang Patelcaf44852009-02-10 07:00:59 +00001201
Devang Patelda1a6322009-02-10 19:28:07 +00001202 assert(NumElements == 2 && "Unhandled case!");
1203 // All users of the GEP must be loads. At each use of the GEP, insert
1204 // two loads of the appropriate indexed GEP and select between them.
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001205 Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(),
Owen Anderson47db9412009-07-22 00:24:57 +00001206 Context.getNullValue(I.getOperand()->getType()),
Owen Anderson1e5f00e2009-07-09 23:48:35 +00001207 "isone");
Devang Patelda1a6322009-02-10 19:28:07 +00001208 // Insert the new GEP instructions, which are properly indexed.
1209 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Owen Anderson47db9412009-07-22 00:24:57 +00001210 Indices[1] = Context.getNullValue(Type::Int32Ty);
Devang Patelda1a6322009-02-10 19:28:07 +00001211 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1212 Indices.begin(),
1213 Indices.end(),
1214 GEPI->getName()+".0", GEPI);
Owen Andersonedb4a702009-07-24 23:12:02 +00001215 Indices[1] = ConstantInt::get(Type::Int32Ty, 1);
Devang Patelda1a6322009-02-10 19:28:07 +00001216 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1217 Indices.begin(),
1218 Indices.end(),
1219 GEPI->getName()+".1", GEPI);
1220 // Replace all loads of the variable index GEP with loads from both
1221 // indexes and a select.
1222 while (!GEPI->use_empty()) {
1223 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1224 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1225 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1226 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1227 LI->replaceAllUsesWith(R);
1228 LI->eraseFromParent();
Devang Patelcaf44852009-02-10 07:00:59 +00001229 }
Devang Patelda1a6322009-02-10 19:28:07 +00001230 GEPI->eraseFromParent();
Devang Patelcaf44852009-02-10 07:00:59 +00001231}
1232
Devang Patelda1a6322009-02-10 19:28:07 +00001233
Devang Patelcaf44852009-02-10 07:00:59 +00001234/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Chris Lattner88819122004-11-14 04:24:28 +00001235/// allocation, but only if cleaned up, perform the cleanups required.
Devang Patelcaf44852009-02-10 07:00:59 +00001236void SROA::CleanupAllocaUsers(AllocationInst *AI) {
Chris Lattnerfe3f4e62004-11-14 05:00:19 +00001237 // At this point, we know that the end result will be SROA'd and promoted, so
1238 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1239 // up.
1240 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1241 UI != E; ) {
Devang Patelcaf44852009-02-10 07:00:59 +00001242 User *U = *UI++;
1243 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1244 CleanupGEP(GEPI);
Jay Foade57ba2e2009-06-06 17:49:35 +00001245 else {
1246 Instruction *I = cast<Instruction>(U);
Devang Patelcaf44852009-02-10 07:00:59 +00001247 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
Zhou Sheng4e2af3c2009-03-18 12:48:48 +00001248 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
Devang Patelcaf44852009-02-10 07:00:59 +00001249 // Safe to remove debug info uses.
1250 while (!DbgInUses.empty()) {
1251 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1252 DI->eraseFromParent();
Chris Lattnerfe3f4e62004-11-14 05:00:19 +00001253 }
Devang Patelcaf44852009-02-10 07:00:59 +00001254 I->eraseFromParent();
Chris Lattnerfe3f4e62004-11-14 05:00:19 +00001255 }
1256 }
1257 }
Chris Lattner6e5398d2003-05-30 04:15:41 +00001258}
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001259
Chris Lattnerec99c462009-01-31 02:28:54 +00001260/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1261/// the offset specified by Offset (which is specified in bytes).
Chris Lattner3323ce12006-04-14 21:42:41 +00001262///
Chris Lattnerec99c462009-01-31 02:28:54 +00001263/// There are two cases we handle here:
1264/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattner8f7b7752006-12-15 07:32:38 +00001265/// Here we turn element accesses into insert/extract element operations.
Chris Lattnerec99c462009-01-31 02:28:54 +00001266/// This promotes a <4 x float> with a store of float to the third element
1267/// into a <4 x float> that uses insert element.
1268/// 2) A fully general blob of memory, which we turn into some (potentially
1269/// large) integer type with extract and insert operations where the loads
1270/// and stores would mutate the memory.
Chris Lattner09b65ab2009-02-03 01:30:09 +00001271static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Anderson340288c2009-07-03 19:42:02 +00001272 unsigned AllocaSize, const TargetData &TD,
Owen Anderson47db9412009-07-22 00:24:57 +00001273 LLVMContext &Context) {
Chris Lattner09b65ab2009-02-03 01:30:09 +00001274 // If this could be contributing to a vector, analyze it.
1275 if (VecTy != Type::VoidTy) { // either null or a vector type.
Chris Lattner18eba4f2009-02-02 18:02:59 +00001276
Chris Lattner09b65ab2009-02-03 01:30:09 +00001277 // If the In type is a vector that is the same size as the alloca, see if it
1278 // matches the existing VecTy.
1279 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1280 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1281 // If we're storing/loading a vector of the right size, allow it as a
1282 // vector. If this the first vector we see, remember the type so that
1283 // we know the element size.
1284 if (VecTy == 0)
1285 VecTy = VInTy;
1286 return;
1287 }
1288 } else if (In == Type::FloatTy || In == Type::DoubleTy ||
1289 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1290 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1291 // If we're accessing something that could be an element of a vector, see
1292 // if the implied vector agrees with what we already have and if Offset is
1293 // compatible with it.
1294 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1295 if (Offset % EltSize == 0 &&
1296 AllocaSize % EltSize == 0 &&
1297 (VecTy == 0 ||
1298 cast<VectorType>(VecTy)->getElementType()
1299 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1300 if (VecTy == 0)
Owen Anderson47db9412009-07-22 00:24:57 +00001301 VecTy = In->getContext().getVectorType(In, AllocaSize/EltSize);
Chris Lattner09b65ab2009-02-03 01:30:09 +00001302 return;
1303 }
Chris Lattnerec99c462009-01-31 02:28:54 +00001304 }
1305 }
1306
Chris Lattner09b65ab2009-02-03 01:30:09 +00001307 // Otherwise, we have a case that we can't handle with an optimized vector
1308 // form. We can still turn this into a large integer.
1309 VecTy = Type::VoidTy;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001310}
1311
Chris Lattnerec99c462009-01-31 02:28:54 +00001312/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Chris Lattner09b65ab2009-02-03 01:30:09 +00001313/// its accesses to use a to single vector type, return true, and set VecTy to
1314/// the new type. If we could convert the alloca into a single promotable
1315/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1316/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1317/// is the current offset from the base of the alloca being analyzed.
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001318///
Chris Lattner73eff2e2009-02-03 18:15:05 +00001319/// If we see at least one access to the value that is as a vector type, set the
1320/// SawVec flag.
1321///
1322bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1323 bool &SawVec, uint64_t Offset,
Chris Lattner09b65ab2009-02-03 01:30:09 +00001324 unsigned AllocaSize) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001325 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1326 Instruction *User = cast<Instruction>(*UI);
1327
1328 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerec99c462009-01-31 02:28:54 +00001329 // Don't break volatile loads.
Chris Lattnerdf179872009-01-28 20:16:43 +00001330 if (LI->isVolatile())
Chris Lattnerec99c462009-01-31 02:28:54 +00001331 return false;
Owen Anderson47db9412009-07-22 00:24:57 +00001332 MergeInType(LI->getType(), Offset, VecTy,
1333 AllocaSize, *TD, V->getContext());
Chris Lattner73eff2e2009-02-03 18:15:05 +00001334 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnerdb561142009-01-07 06:39:58 +00001335 continue;
1336 }
1337
1338 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer2eadb532007-01-21 00:29:26 +00001339 // Storing the pointer, not into the value?
Chris Lattnerdf179872009-01-28 20:16:43 +00001340 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Anderson340288c2009-07-03 19:42:02 +00001341 MergeInType(SI->getOperand(0)->getType(), Offset,
Owen Anderson47db9412009-07-22 00:24:57 +00001342 VecTy, AllocaSize, *TD, V->getContext());
Chris Lattner73eff2e2009-02-03 18:15:05 +00001343 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnerdb561142009-01-07 06:39:58 +00001344 continue;
1345 }
Chris Lattnerec99c462009-01-31 02:28:54 +00001346
1347 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner73eff2e2009-02-03 18:15:05 +00001348 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1349 AllocaSize))
Chris Lattnerec99c462009-01-31 02:28:54 +00001350 return false;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001351 IsNotTrivial = true;
Chris Lattnerdb561142009-01-07 06:39:58 +00001352 continue;
1353 }
1354
1355 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattnerec99c462009-01-31 02:28:54 +00001356 // If this is a GEP with a variable indices, we can't handle it.
1357 if (!GEP->hasAllConstantIndices())
1358 return false;
Chris Lattnerdb561142009-01-07 06:39:58 +00001359
Chris Lattnerec99c462009-01-31 02:28:54 +00001360 // Compute the offset that this GEP adds to the pointer.
1361 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1362 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1363 &Indices[0], Indices.size());
1364 // See if all uses can be converted.
Chris Lattner73eff2e2009-02-03 18:15:05 +00001365 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner09b65ab2009-02-03 01:30:09 +00001366 AllocaSize))
Chris Lattnerec99c462009-01-31 02:28:54 +00001367 return false;
1368 IsNotTrivial = true;
1369 continue;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001370 }
Chris Lattner334268a2009-03-08 03:37:16 +00001371
Chris Lattner6aa6b1f2009-02-03 02:01:43 +00001372 // If this is a constant sized memset of a constant value (e.g. 0) we can
1373 // handle it.
Chris Lattner334268a2009-03-08 03:37:16 +00001374 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1375 // Store of constant value and constant size.
1376 if (isa<ConstantInt>(MSI->getValue()) &&
1377 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner334268a2009-03-08 03:37:16 +00001378 IsNotTrivial = true;
1379 continue;
1380 }
Chris Lattner6aa6b1f2009-02-03 02:01:43 +00001381 }
Chris Lattnerc0097572009-03-08 04:04:21 +00001382
1383 // If this is a memcpy or memmove into or out of the whole allocation, we
1384 // can handle it like a load or store of the scalar type.
1385 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1386 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1387 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1388 IsNotTrivial = true;
1389 continue;
1390 }
1391 }
Chris Lattnerdc35e5b2009-03-08 03:59:00 +00001392
Devang Patel25b62512009-03-06 07:03:54 +00001393 // Ignore dbg intrinsic.
1394 if (isa<DbgInfoIntrinsic>(User))
1395 continue;
1396
Chris Lattnerec99c462009-01-31 02:28:54 +00001397 // Otherwise, we cannot handle this!
1398 return false;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001399 }
1400
Chris Lattnerec99c462009-01-31 02:28:54 +00001401 return true;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001402}
1403
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001404
1405/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattner3323ce12006-04-14 21:42:41 +00001406/// directly. This happens when we are converting an "integer union" to a
1407/// single integer scalar, or when we are converting a "vector union" to a
1408/// vector with insert/extractelement instructions.
1409///
1410/// Offset is an offset from the original alloca, in bits that need to be
1411/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattnerec99c462009-01-31 02:28:54 +00001412void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001413 while (!Ptr->use_empty()) {
1414 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands6f361ff2009-02-02 10:06:20 +00001415
Chris Lattnerdb561142009-01-07 06:39:58 +00001416 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb9e5b8f2008-01-30 00:39:15 +00001417 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001418 CI->eraseFromParent();
Chris Lattnerdb561142009-01-07 06:39:58 +00001419 continue;
1420 }
Duncan Sands6f361ff2009-02-02 10:06:20 +00001421
Chris Lattnerdb561142009-01-07 06:39:58 +00001422 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattnerec99c462009-01-31 02:28:54 +00001423 // Compute the offset that this GEP adds to the pointer.
1424 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1425 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1426 &Indices[0], Indices.size());
1427 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001428 GEP->eraseFromParent();
Chris Lattnerdb561142009-01-07 06:39:58 +00001429 continue;
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001430 }
Chris Lattner6aa6b1f2009-02-03 02:01:43 +00001431
Chris Lattner576baa42009-02-03 19:45:44 +00001432 IRBuilder<> Builder(User->getParent(), User);
1433
1434 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001435 // The load is a bit extract from NewAI shifted right by Offset bits.
1436 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1437 Value *NewLoadVal
1438 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1439 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner576baa42009-02-03 19:45:44 +00001440 LI->eraseFromParent();
1441 continue;
1442 }
1443
1444 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1445 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Daniel Dunbar4975db62009-07-25 04:41:11 +00001446 // FIXME: Remove once builder has Twine API.
1447 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").str().c_str());
Chris Lattner576baa42009-02-03 19:45:44 +00001448 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1449 Builder);
1450 Builder.CreateStore(New, NewAI);
1451 SI->eraseFromParent();
1452 continue;
1453 }
1454
Chris Lattner6aa6b1f2009-02-03 02:01:43 +00001455 // If this is a constant sized memset of a constant value (e.g. 0) we can
1456 // transform it into a store of the expanded constant value.
1457 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1458 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1459 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner69223bb2009-04-21 16:52:12 +00001460 if (NumBytes != 0) {
1461 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1462
1463 // Compute the value replicated the right number of times.
1464 APInt APVal(NumBytes*8, Val);
Chris Lattner6aa6b1f2009-02-03 02:01:43 +00001465
Chris Lattner69223bb2009-04-21 16:52:12 +00001466 // Splat the value if non-zero.
1467 if (Val)
1468 for (unsigned i = 1; i != NumBytes; ++i)
1469 APVal |= APVal << 8;
1470
Daniel Dunbar4975db62009-07-25 04:41:11 +00001471 // FIXME: Remove once builder has Twine API.
1472 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").str().c_str());
Owen Anderson47db9412009-07-22 00:24:57 +00001473 Value *New = ConvertScalar_InsertValue(
Owen Andersonedb4a702009-07-24 23:12:02 +00001474 ConstantInt::get(User->getContext(), APVal),
Owen Anderson340288c2009-07-03 19:42:02 +00001475 Old, Offset, Builder);
Chris Lattner69223bb2009-04-21 16:52:12 +00001476 Builder.CreateStore(New, NewAI);
1477 }
Chris Lattner6aa6b1f2009-02-03 02:01:43 +00001478 MSI->eraseFromParent();
1479 continue;
1480 }
Chris Lattnerc0097572009-03-08 04:04:21 +00001481
1482 // If this is a memcpy or memmove into or out of the whole allocation, we
1483 // can handle it like a load or store of the scalar type.
1484 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1485 assert(Offset == 0 && "must be store to start of alloca");
1486
1487 // If the source and destination are both to the same alloca, then this is
1488 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1489 // as appropriate.
1490 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1491
1492 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1493 // Dest must be OrigAI, change this to be a load from the original
1494 // pointer (bitcasted), then a store to our new alloca.
1495 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1496 Value *SrcPtr = MTI->getSource();
1497 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1498
1499 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1500 SrcVal->setAlignment(MTI->getAlignment());
1501 Builder.CreateStore(SrcVal, NewAI);
1502 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1503 // Src must be OrigAI, change this to be a load from NewAI then a store
1504 // through the original dest pointer (bitcasted).
1505 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1506 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1507
1508 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1509 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1510 NewStore->setAlignment(MTI->getAlignment());
1511 } else {
1512 // Noop transfer. Src == Dst
1513 }
1514
1515
1516 MTI->eraseFromParent();
1517 continue;
1518 }
Chris Lattnerdc35e5b2009-03-08 03:59:00 +00001519
Devang Patel25b62512009-03-06 07:03:54 +00001520 // If user is a dbg info intrinsic then it is safe to remove it.
1521 if (isa<DbgInfoIntrinsic>(User)) {
1522 User->eraseFromParent();
1523 continue;
1524 }
1525
Torok Edwinfbcc6632009-07-14 16:55:14 +00001526 llvm_unreachable("Unsupported operation!");
Chris Lattner3b0a62d2005-12-12 07:19:13 +00001527 }
1528}
Chris Lattner827cb982007-04-25 06:40:51 +00001529
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001530/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1531/// or vector value FromVal, extracting the bits from the offset specified by
1532/// Offset. This returns the value, which is of type ToType.
1533///
1534/// This happens when we are converting an "integer union" to a single
Duncan Sands6f361ff2009-02-02 10:06:20 +00001535/// integer scalar, or when we are converting a "vector union" to a vector with
1536/// insert/extractelement instructions.
Chris Lattner77205de2008-02-29 07:03:13 +00001537///
Duncan Sands6f361ff2009-02-02 10:06:20 +00001538/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001539/// shifted to the right.
1540Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1541 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattnerec99c462009-01-31 02:28:54 +00001542 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001543 if (FromVal->getType() == ToType && Offset == 0)
1544 return FromVal;
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001545
Owen Anderson47db9412009-07-22 00:24:57 +00001546 LLVMContext &Context = FromVal->getContext();
1547
Chris Lattnerec99c462009-01-31 02:28:54 +00001548 // If the result alloca is a vector type, this is either an element
1549 // access or a bitcast to another vector type of the same size.
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001550 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1551 if (isa<VectorType>(ToType))
1552 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001553
1554 // Otherwise it must be an element access.
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001555 unsigned Elt = 0;
1556 if (Offset) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001557 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001558 Elt = Offset/EltSize;
Chris Lattnerec99c462009-01-31 02:28:54 +00001559 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner77205de2008-02-29 07:03:13 +00001560 }
Chris Lattnerec99c462009-01-31 02:28:54 +00001561 // Return the element extracted out of it.
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001562 Value *V = Builder.CreateExtractElement(FromVal,
Owen Andersonedb4a702009-07-24 23:12:02 +00001563 ConstantInt::get(Type::Int32Ty,Elt),
Chris Lattner576baa42009-02-03 19:45:44 +00001564 "tmp");
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001565 if (V->getType() != ToType)
1566 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner09b65ab2009-02-03 01:30:09 +00001567 return V;
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001568 }
Chris Lattneref37dc82009-02-03 21:08:45 +00001569
1570 // If ToType is a first class aggregate, extract out each of the pieces and
1571 // use insertvalue's to form the FCA.
1572 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1573 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Anderson47db9412009-07-22 00:24:57 +00001574 Value *Res = Context.getUndef(ST);
Chris Lattneref37dc82009-02-03 21:08:45 +00001575 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1576 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnerbbbb7432009-02-06 04:34:07 +00001577 Offset+Layout.getElementOffsetInBits(i),
Chris Lattneref37dc82009-02-03 21:08:45 +00001578 Builder);
1579 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1580 }
1581 return Res;
1582 }
1583
1584 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001585 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson47db9412009-07-22 00:24:57 +00001586 Value *Res = Context.getUndef(AT);
Chris Lattneref37dc82009-02-03 21:08:45 +00001587 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1588 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1589 Offset+i*EltSize, Builder);
1590 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1591 }
1592 return Res;
1593 }
Duncan Sands6f361ff2009-02-02 10:06:20 +00001594
Chris Lattnerec99c462009-01-31 02:28:54 +00001595 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001596 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands6f361ff2009-02-02 10:06:20 +00001597
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001598 // If this is a big-endian system and the load is narrower than the
1599 // full alloca type, we need to do a shift to get the right bits.
1600 int ShAmt = 0;
Chris Lattner938b54f2009-01-07 06:34:28 +00001601 if (TD->isBigEndian()) {
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001602 // On big-endian machines, the lowest bit is stored at the bit offset
1603 // from the pointer given by getTypeStoreSizeInBits. This matters for
1604 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner938b54f2009-01-07 06:34:28 +00001605 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001606 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001607 } else {
1608 ShAmt = Offset;
1609 }
Duncan Sands6f361ff2009-02-02 10:06:20 +00001610
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001611 // Note: we support negative bitwidths (with shl) which are not defined.
1612 // We do this to support (f.e.) loads off the end of a structure where
1613 // only some bits are used.
1614 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Anderson340288c2009-07-03 19:42:02 +00001615 FromVal = Builder.CreateLShr(FromVal,
Owen Andersonedb4a702009-07-24 23:12:02 +00001616 ConstantInt::get(FromVal->getType(),
Chris Lattneref37dc82009-02-03 21:08:45 +00001617 ShAmt), "tmp");
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001618 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Anderson340288c2009-07-03 19:42:02 +00001619 FromVal = Builder.CreateShl(FromVal,
Owen Andersonedb4a702009-07-24 23:12:02 +00001620 ConstantInt::get(FromVal->getType(),
Chris Lattneref37dc82009-02-03 21:08:45 +00001621 -ShAmt), "tmp");
Duncan Sands6f361ff2009-02-02 10:06:20 +00001622
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001623 // Finally, unconditionally truncate the integer to the right width.
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001624 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001625 if (LIBitWidth < NTy->getBitWidth())
Owen Anderson340288c2009-07-03 19:42:02 +00001626 FromVal =
Owen Anderson47db9412009-07-22 00:24:57 +00001627 Builder.CreateTrunc(FromVal, Context.getIntegerType(LIBitWidth), "tmp");
Chris Lattner80810b42009-02-03 07:08:57 +00001628 else if (LIBitWidth > NTy->getBitWidth())
Owen Anderson340288c2009-07-03 19:42:02 +00001629 FromVal =
Owen Anderson47db9412009-07-22 00:24:57 +00001630 Builder.CreateZExt(FromVal, Context.getIntegerType(LIBitWidth), "tmp");
Duncan Sands6f361ff2009-02-02 10:06:20 +00001631
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001632 // If the result is an integer, this is a trunc or bitcast.
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001633 if (isa<IntegerType>(ToType)) {
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001634 // Should be done.
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001635 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001636 // Just do a bitcast, we know the sizes match up.
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001637 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner77205de2008-02-29 07:03:13 +00001638 } else {
Chris Lattnerc966ceb2008-02-29 07:12:06 +00001639 // Otherwise must be a pointer.
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001640 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner77205de2008-02-29 07:03:13 +00001641 }
Chris Lattnerf5df53c2009-02-03 21:01:03 +00001642 assert(FromVal->getType() == ToType && "Didn't convert right?");
1643 return FromVal;
Chris Lattner77205de2008-02-29 07:03:13 +00001644}
1645
1646
Chris Lattner18f56c22009-02-03 19:30:11 +00001647/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1648/// or vector value "Old" at the offset specified by Offset.
1649///
1650/// This happens when we are converting an "integer union" to a
Chris Lattner77205de2008-02-29 07:03:13 +00001651/// single integer scalar, or when we are converting a "vector union" to a
1652/// vector with insert/extractelement instructions.
1653///
1654/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner18f56c22009-02-03 19:30:11 +00001655/// shifted to the right.
1656Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattnerc1fb96d2009-02-03 19:41:50 +00001657 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands6f361ff2009-02-02 10:06:20 +00001658
Chris Lattner77205de2008-02-29 07:03:13 +00001659 // Convert the stored type to the actual type, shift it left to insert
1660 // then 'or' into place.
Chris Lattner18f56c22009-02-03 19:30:11 +00001661 const Type *AllocaType = Old->getType();
Owen Anderson47db9412009-07-22 00:24:57 +00001662 LLVMContext &Context = Old->getContext();
Duncan Sands6f361ff2009-02-02 10:06:20 +00001663
Chris Lattnerec99c462009-01-31 02:28:54 +00001664 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001665 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1666 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner21a84f32009-03-08 04:17:04 +00001667
1668 // Changing the whole vector with memset or with an access of a different
1669 // vector type?
1670 if (ValSize == VecSize)
1671 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1672
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001673 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner21a84f32009-03-08 04:17:04 +00001674
1675 // Must be an element insertion.
1676 unsigned Elt = Offset/EltSize;
1677
1678 if (SV->getType() != VTy->getElementType())
1679 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1680
1681 SV = Builder.CreateInsertElement(Old, SV,
Owen Andersonedb4a702009-07-24 23:12:02 +00001682 ConstantInt::get(Type::Int32Ty, Elt),
Chris Lattner21a84f32009-03-08 04:17:04 +00001683 "tmp");
Chris Lattnerec99c462009-01-31 02:28:54 +00001684 return SV;
1685 }
Chris Lattner18f56c22009-02-03 19:30:11 +00001686
1687 // If SV is a first-class aggregate value, insert each value recursively.
1688 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1689 const StructLayout &Layout = *TD->getStructLayout(ST);
1690 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattnerc1fb96d2009-02-03 19:41:50 +00001691 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner18f56c22009-02-03 19:30:11 +00001692 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnerbbbb7432009-02-06 04:34:07 +00001693 Offset+Layout.getElementOffsetInBits(i),
Chris Lattnerc1fb96d2009-02-03 19:41:50 +00001694 Builder);
Chris Lattner18f56c22009-02-03 19:30:11 +00001695 }
1696 return Old;
1697 }
1698
1699 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sandsaf9eaa82009-05-09 07:06:46 +00001700 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner18f56c22009-02-03 19:30:11 +00001701 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattnerc1fb96d2009-02-03 19:41:50 +00001702 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1703 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner18f56c22009-02-03 19:30:11 +00001704 }
1705 return Old;
1706 }
Duncan Sands6f361ff2009-02-02 10:06:20 +00001707
Chris Lattnerec99c462009-01-31 02:28:54 +00001708 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner18f56c22009-02-03 19:30:11 +00001709 // If it is a pointer, do the same.
Chris Lattnerec99c462009-01-31 02:28:54 +00001710 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1711 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1712 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1713 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1714 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Anderson47db9412009-07-22 00:24:57 +00001715 SV = Builder.CreateBitCast(SV, Context.getIntegerType(SrcWidth), "tmp");
Chris Lattnerec99c462009-01-31 02:28:54 +00001716 else if (isa<PointerType>(SV->getType()))
Chris Lattnerc1fb96d2009-02-03 19:41:50 +00001717 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(), "tmp");
Duncan Sands6f361ff2009-02-02 10:06:20 +00001718
Chris Lattner09b65ab2009-02-03 01:30:09 +00001719 // Zero extend or truncate the value if needed.
1720 if (SV->getType() != AllocaType) {
1721 if (SV->getType()->getPrimitiveSizeInBits() <
1722 AllocaType->getPrimitiveSizeInBits())
Chris Lattnerc1fb96d2009-02-03 19:41:50 +00001723 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner09b65ab2009-02-03 01:30:09 +00001724 else {
1725 // Truncation may be needed if storing more than the alloca can hold
1726 // (undefined behavior).
Chris Lattnerc1fb96d2009-02-03 19:41:50 +00001727 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner09b65ab2009-02-03 01:30:09 +00001728 SrcWidth = DestWidth;
1729 SrcStoreWidth = DestStoreWidth;
1730 }
1731 }
Duncan Sands6f361ff2009-02-02 10:06:20 +00001732
Chris Lattnerec99c462009-01-31 02:28:54 +00001733 // If this is a big-endian system and the store is narrower than the
1734 // full alloca type, we need to do a shift to get the right bits.
1735 int ShAmt = 0;
1736 if (TD->isBigEndian()) {
1737 // On big-endian machines, the lowest bit is stored at the bit offset
1738 // from the pointer given by getTypeStoreSizeInBits. This matters for
1739 // integers with a bitwidth that is not a multiple of 8.
1740 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner77205de2008-02-29 07:03:13 +00001741 } else {
Chris Lattnerec99c462009-01-31 02:28:54 +00001742 ShAmt = Offset;
1743 }
Duncan Sands6f361ff2009-02-02 10:06:20 +00001744
Chris Lattnerec99c462009-01-31 02:28:54 +00001745 // Note: we support negative bitwidths (with shr) which are not defined.
1746 // We do this to support (f.e.) stores off the end of a structure where
1747 // only some bits in the structure are set.
1748 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1749 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersonedb4a702009-07-24 23:12:02 +00001750 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Anderson340288c2009-07-03 19:42:02 +00001751 ShAmt), "tmp");
Chris Lattnerec99c462009-01-31 02:28:54 +00001752 Mask <<= ShAmt;
1753 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersonedb4a702009-07-24 23:12:02 +00001754 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Anderson340288c2009-07-03 19:42:02 +00001755 -ShAmt), "tmp");
Duncan Sands33d6e972009-02-02 09:53:14 +00001756 Mask = Mask.lshr(-ShAmt);
Chris Lattnerec99c462009-01-31 02:28:54 +00001757 }
Duncan Sands6f361ff2009-02-02 10:06:20 +00001758
Chris Lattnerec99c462009-01-31 02:28:54 +00001759 // Mask out the bits we are about to insert from the old value, and or
1760 // in the new bits.
1761 if (SrcWidth != DestWidth) {
1762 assert(DestWidth > SrcWidth);
Owen Andersonedb4a702009-07-24 23:12:02 +00001763 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattnerc1fb96d2009-02-03 19:41:50 +00001764 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner77205de2008-02-29 07:03:13 +00001765 }
1766 return SV;
1767}
1768
1769
Chris Lattner827cb982007-04-25 06:40:51 +00001770
1771/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1772/// some part of a constant global variable. This intentionally only accepts
1773/// constant expressions because we don't can't rewrite arbitrary instructions.
1774static bool PointsToConstantGlobal(Value *V) {
1775 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1776 return GV->isConstant();
1777 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1778 if (CE->getOpcode() == Instruction::BitCast ||
1779 CE->getOpcode() == Instruction::GetElementPtr)
1780 return PointsToConstantGlobal(CE->getOperand(0));
1781 return false;
1782}
1783
1784/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1785/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1786/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1787/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1788/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1789/// the alloca, and if the source pointer is a pointer to a constant global, we
1790/// can optimize this.
1791static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1792 bool isOffset) {
1793 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattnerdf179872009-01-28 20:16:43 +00001794 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1795 // Ignore non-volatile loads, they are always ok.
1796 if (!LI->isVolatile())
1797 continue;
1798
Chris Lattner827cb982007-04-25 06:40:51 +00001799 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1800 // If uses of the bitcast are ok, we are ok.
1801 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1802 return false;
1803 continue;
1804 }
1805 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1806 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1807 // doesn't, it does.
1808 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1809 isOffset || !GEP->hasAllZeroIndices()))
1810 return false;
1811 continue;
1812 }
1813
1814 // If this is isn't our memcpy/memmove, reject it as something we can't
1815 // handle.
Chris Lattner334268a2009-03-08 03:37:16 +00001816 if (!isa<MemTransferInst>(*UI))
Chris Lattner827cb982007-04-25 06:40:51 +00001817 return false;
1818
1819 // If we already have seen a copy, reject the second one.
1820 if (TheCopy) return false;
1821
1822 // If the pointer has been offset from the start of the alloca, we can't
1823 // safely handle this.
1824 if (isOffset) return false;
1825
1826 // If the memintrinsic isn't using the alloca as the dest, reject it.
1827 if (UI.getOperandNo() != 1) return false;
1828
1829 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1830
1831 // If the source of the memcpy/move is not a constant global, reject it.
1832 if (!PointsToConstantGlobal(MI->getOperand(2)))
1833 return false;
1834
1835 // Otherwise, the transform is safe. Remember the copy instruction.
1836 TheCopy = MI;
1837 }
1838 return true;
1839}
1840
1841/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1842/// modified by a copy from a constant global. If we can prove this, we can
1843/// replace any uses of the alloca with uses of the global directly.
1844Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1845 Instruction *TheCopy = 0;
1846 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1847 return TheCopy;
1848 return 0;
1849}