blob: 1ca0e9185bced30d890b2bcc28a7151298100224 [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner372dda82007-03-05 07:52:57 +000031#include "llvm/Pass.h"
Chris Lattner38aec322003-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 Patel4afc90d2009-02-10 07:00:59 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner95255282006-06-28 23:17:24 +000036#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000039#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000040#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000041#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000042#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumReplaced, "Number of allocas broken up");
47STATISTIC(NumPromoted, "Number of allocas promoted");
48STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000049STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000050
Chris Lattner0e5f4992006-12-19 21:40:18 +000051namespace {
Chris Lattnerc4472072010-04-15 23:50:26 +000052 struct ConvertToScalarInfo;
53
Chris Lattner3e8b6632009-09-02 06:11:42 +000054 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000055 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000056 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000057 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000058 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000059 else
60 SRThreshold = T;
61 }
Devang Patel794fd752007-05-01 21:15:47 +000062
Chris Lattnered7b41e2003-05-27 15:45:27 +000063 bool runOnFunction(Function &F);
64
Chris Lattner38aec322003-09-11 16:45:55 +000065 bool performScalarRepl(Function &F);
66 bool performPromotion(Function &F);
67
Chris Lattnera15854c2003-08-31 00:45:13 +000068 // getAnalysisUsage - This pass does not require any passes, but we know it
69 // will not alter the CFG, so say so.
70 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000071 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000072 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000073 AU.setPreservesCFG();
74 }
75
Chris Lattnered7b41e2003-05-27 15:45:27 +000076 private:
Chris Lattner56c38522009-01-07 06:34:28 +000077 TargetData *TD;
78
Bob Wilsonb742def2009-12-18 20:14:40 +000079 /// DeadInsts - Keep track of instructions we have made dead, so that
80 /// we can remove them after we are done working.
81 SmallVector<Value*, 32> DeadInsts;
82
Chris Lattner39a1c042007-05-30 06:11:23 +000083 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
84 /// information about the uses. All these fields are initialized to false
85 /// and set to true when something is learned.
86 struct AllocaInfo {
87 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
88 bool isUnsafe : 1;
89
Chris Lattner39a1c042007-05-30 06:11:23 +000090 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
91 bool isMemCpySrc : 1;
92
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000093 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000094 bool isMemCpyDst : 1;
95
96 AllocaInfo()
Victor Hernandez6c146ee2010-01-21 23:05:53 +000097 : isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false) {}
Chris Lattner39a1c042007-05-30 06:11:23 +000098 };
99
Devang Patelff366852007-07-09 21:19:23 +0000100 unsigned SRThreshold;
101
Chris Lattner39a1c042007-05-30 06:11:23 +0000102 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
103
Victor Hernandez6c146ee2010-01-21 23:05:53 +0000104 bool isSafeAllocaToScalarRepl(AllocaInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000105
Bob Wilsonb742def2009-12-18 20:14:40 +0000106 void isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000107 AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000108 void isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t &Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000109 AllocaInfo &Info);
110 void isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
111 const Type *MemOpType, bool isStore, AllocaInfo &Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000112 bool TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size);
Bob Wilsone88728d2009-12-19 06:53:17 +0000113 uint64_t FindElementAndOffset(const Type *&T, uint64_t &Offset,
114 const Type *&IdxTy);
Chris Lattner39a1c042007-05-30 06:11:23 +0000115
Victor Hernandez7b929da2009-10-23 21:09:37 +0000116 void DoScalarReplacement(AllocaInst *AI,
117 std::vector<AllocaInst*> &WorkList);
Bob Wilsonb742def2009-12-18 20:14:40 +0000118 void DeleteDeadInstructions();
Victor Hernandez7b929da2009-10-23 21:09:37 +0000119 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocaInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000120
Bob Wilsonb742def2009-12-18 20:14:40 +0000121 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
122 SmallVector<AllocaInst*, 32> &NewElts);
123 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
124 SmallVector<AllocaInst*, 32> &NewElts);
125 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
126 SmallVector<AllocaInst*, 32> &NewElts);
127 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000128 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000129 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000130 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000131 SmallVector<AllocaInst*, 32> &NewElts);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000132 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000133 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000134
Chris Lattner31d80102010-04-15 21:59:20 +0000135 static MemTransferInst *isOnlyCopiedFromConstantGlobal(AllocaInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000136 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000137}
138
Dan Gohman844731a2008-05-13 00:00:25 +0000139char SROA::ID = 0;
140static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
141
Brian Gaeked0fde302003-11-11 22:41:34 +0000142// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000143FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
144 return new SROA(Threshold);
145}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000146
147
Chris Lattnered7b41e2003-05-27 15:45:27 +0000148bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000149 TD = getAnalysisIfAvailable<TargetData>();
150
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000151 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000152
153 // FIXME: ScalarRepl currently depends on TargetData more than it
154 // theoretically needs to. It should be refactored in order to support
155 // target-independent IR. Until this is done, just skip the actual
156 // scalar-replacement portion of this pass.
157 if (!TD) return Changed;
158
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000159 while (1) {
160 bool LocalChange = performScalarRepl(F);
161 if (!LocalChange) break; // No need to repromote if no scalarrepl
162 Changed = true;
163 LocalChange = performPromotion(F);
164 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
165 }
Chris Lattner38aec322003-09-11 16:45:55 +0000166
167 return Changed;
168}
169
170
171bool SROA::performPromotion(Function &F) {
172 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000173 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000174 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000175
Chris Lattner02a3be02003-09-20 14:39:18 +0000176 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000177
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000178 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000179
Chris Lattner38aec322003-09-11 16:45:55 +0000180 while (1) {
181 Allocas.clear();
182
183 // Find allocas that are safe to promote, by looking at all instructions in
184 // the entry node
185 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
186 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000187 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000188 Allocas.push_back(AI);
189
190 if (Allocas.empty()) break;
191
Nick Lewyckyce2c51b2009-11-23 03:50:44 +0000192 PromoteMemToReg(Allocas, DT, DF);
Chris Lattner38aec322003-09-11 16:45:55 +0000193 NumPromoted += Allocas.size();
194 Changed = true;
195 }
196
197 return Changed;
198}
199
Bob Wilson3992feb2010-02-03 17:23:56 +0000200/// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
201/// SROA. It must be a struct or array type with a small number of elements.
202static bool ShouldAttemptScalarRepl(AllocaInst *AI) {
203 const Type *T = AI->getAllocatedType();
204 // Do not promote any struct into more than 32 separate vars.
Chris Lattner963a97f2008-06-22 17:46:21 +0000205 if (const StructType *ST = dyn_cast<StructType>(T))
Bob Wilson3992feb2010-02-03 17:23:56 +0000206 return ST->getNumElements() <= 32;
207 // Arrays are much less likely to be safe for SROA; only consider
208 // them if they are very small.
209 if (const ArrayType *AT = dyn_cast<ArrayType>(T))
210 return AT->getNumElements() <= 8;
211 return false;
Chris Lattner963a97f2008-06-22 17:46:21 +0000212}
213
Chris Lattnerc4472072010-04-15 23:50:26 +0000214namespace {
Chris Lattner593375d2010-04-16 00:20:00 +0000215/// ConvertToScalarInfo - This struct is used by CanConvertToScalar
Chris Lattnerc4472072010-04-15 23:50:26 +0000216struct ConvertToScalarInfo {
217 /// AllocaSize - The size of the alloca being considered.
218 unsigned AllocaSize;
Chris Lattner593375d2010-04-16 00:20:00 +0000219 const TargetData &TD;
Chris Lattnerc4472072010-04-15 23:50:26 +0000220
221 bool IsNotTrivial;
222 const Type *VectorTy;
223 bool HadAVector;
224
Chris Lattner593375d2010-04-16 00:20:00 +0000225 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td)
226 : AllocaSize(Size), TD(td) {
Chris Lattnerc4472072010-04-15 23:50:26 +0000227 IsNotTrivial = false;
228 VectorTy = 0;
229 HadAVector = false;
230 }
231
232 bool shouldConvertToVector() const {
233 return VectorTy && VectorTy->isVectorTy() && HadAVector;
234 }
Chris Lattner593375d2010-04-16 00:20:00 +0000235
236 AllocaInst *TryConvert(AllocaInst *AI) {
237 // If we can't convert this scalar, or if mem2reg can trivially do it, bail
238 // out.
239 if (!CanConvertToScalar(AI, 0) || !IsNotTrivial)
240 // FIXME: In the trivial case, just use mem2reg.
241 return 0;
242
243 // If we were able to find a vector type that can handle this with
244 // insert/extract elements, and if there was at least one use that had
245 // a vector type, promote this to a vector. We don't want to promote
246 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
247 // we just get a lot of insert/extracts. If at least one vector is
248 // involved, then we probably really do have a union of vector/array.
249 const Type *NewTy;
250 if (shouldConvertToVector()) {
251 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
252 << *VectorTy << '\n');
253 NewTy = VectorTy; // Use the vector type.
254 } else {
255 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
256 // Create and insert the integer alloca.
257 NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
258 }
259 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
260 ConvertUsesToScalar(AI, NewAI, 0);
261 return NewAI;
262 }
263
264 bool CanConvertToScalar(Value *V, uint64_t Offset);
265 void MergeInType(const Type *In, uint64_t Offset);
266 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
267
268 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
269 uint64_t Offset, IRBuilder<> &Builder);
270 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
271 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattnerc4472072010-04-15 23:50:26 +0000272};
273} // end anonymous namespace.
274
275
276
Chris Lattner38aec322003-09-11 16:45:55 +0000277// performScalarRepl - This algorithm is a simple worklist driven algorithm,
278// which runs on all of the malloc/alloca instructions in the function, removing
279// them if they are only used by getelementptr instructions.
280//
281bool SROA::performScalarRepl(Function &F) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000282 std::vector<AllocaInst*> WorkList;
Chris Lattnered7b41e2003-05-27 15:45:27 +0000283
Chris Lattner31d80102010-04-15 21:59:20 +0000284 // Scan the entry basic block, adding allocas to the worklist.
Chris Lattner02a3be02003-09-20 14:39:18 +0000285 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000286 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
Victor Hernandez7b929da2009-10-23 21:09:37 +0000287 if (AllocaInst *A = dyn_cast<AllocaInst>(I))
Chris Lattnered7b41e2003-05-27 15:45:27 +0000288 WorkList.push_back(A);
289
290 // Process the worklist
291 bool Changed = false;
292 while (!WorkList.empty()) {
Victor Hernandez7b929da2009-10-23 21:09:37 +0000293 AllocaInst *AI = WorkList.back();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000294 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000295
Chris Lattneradd2bd72006-12-22 23:14:42 +0000296 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
297 // with unused elements.
298 if (AI->use_empty()) {
299 AI->eraseFromParent();
Chris Lattnerc4472072010-04-15 23:50:26 +0000300 Changed = true;
Chris Lattneradd2bd72006-12-22 23:14:42 +0000301 continue;
302 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000303
304 // If this alloca is impossible for us to promote, reject it early.
305 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
306 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000307
308 // Check to see if this allocation is only modified by a memcpy/memmove from
309 // a constant global. If this is the case, we can change all users to use
310 // the constant global instead. This is commonly produced by the CFE by
311 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
312 // is only subsequently read.
Chris Lattner31d80102010-04-15 21:59:20 +0000313 if (MemTransferInst *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
David Greene504c7d82010-01-05 01:27:09 +0000314 DEBUG(dbgs() << "Found alloca equal to global: " << *AI << '\n');
315 DEBUG(dbgs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner31d80102010-04-15 21:59:20 +0000316 Constant *TheSrc = cast<Constant>(TheCopy->getSource());
Owen Andersonbaf3c402009-07-29 18:55:55 +0000317 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000318 TheCopy->eraseFromParent(); // Don't mutate the global.
319 AI->eraseFromParent();
320 ++NumGlobals;
321 Changed = true;
322 continue;
323 }
Chris Lattner15c82772009-02-02 20:44:45 +0000324
Chris Lattner7809ecd2009-02-03 01:30:09 +0000325 // Check to see if we can perform the core SROA transformation. We cannot
326 // transform the allocation instruction if it is an array allocation
327 // (allocations OF arrays are ok though), and an allocation of a scalar
328 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000329 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000330
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000331 // Do not promote [0 x %struct].
332 if (AllocaSize == 0) continue;
Chris Lattner31d80102010-04-15 21:59:20 +0000333
334 // Do not promote any struct whose size is too big.
335 if (AllocaSize > SRThreshold) continue;
336
Bob Wilson3992feb2010-02-03 17:23:56 +0000337 // If the alloca looks like a good candidate for scalar replacement, and if
338 // all its users can be transformed, then split up the aggregate into its
339 // separate elements.
340 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
341 DoScalarReplacement(AI, WorkList);
342 Changed = true;
343 continue;
344 }
345
Chris Lattner6e733d32009-01-28 20:16:43 +0000346 // If we can turn this aggregate value (potentially with casts) into a
347 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000348 // IsNotTrivial tracks whether this is something that mem2reg could have
349 // promoted itself. If so, we don't want to transform it needlessly. Note
350 // that we can't just check based on the type: the alloca may be of an i32
351 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner593375d2010-04-16 00:20:00 +0000352 if (AllocaInst *NewAI =
353 ConvertToScalarInfo((unsigned)AllocaSize, *TD).TryConvert(AI)) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000354 NewAI->takeName(AI);
355 AI->eraseFromParent();
356 ++NumConverted;
357 Changed = true;
358 continue;
Chris Lattner593375d2010-04-16 00:20:00 +0000359 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000360
Chris Lattner7809ecd2009-02-03 01:30:09 +0000361 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000362 }
363
364 return Changed;
365}
Chris Lattner5e062a12003-05-30 04:15:41 +0000366
Chris Lattnera10b29b2007-04-25 05:02:56 +0000367/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
368/// predicate, do SROA now.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000369void SROA::DoScalarReplacement(AllocaInst *AI,
370 std::vector<AllocaInst*> &WorkList) {
David Greene504c7d82010-01-05 01:27:09 +0000371 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000372 SmallVector<AllocaInst*, 32> ElementAllocas;
373 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
374 ElementAllocas.reserve(ST->getNumContainedTypes());
375 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000376 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000377 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000378 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000379 ElementAllocas.push_back(NA);
380 WorkList.push_back(NA); // Add to worklist for recursive processing
381 }
382 } else {
383 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
384 ElementAllocas.reserve(AT->getNumElements());
385 const Type *ElTy = AT->getElementType();
386 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000387 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000388 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000389 ElementAllocas.push_back(NA);
390 WorkList.push_back(NA); // Add to worklist for recursive processing
391 }
392 }
393
Bob Wilsonb742def2009-12-18 20:14:40 +0000394 // Now that we have created the new alloca instructions, rewrite all the
395 // uses of the old alloca.
396 RewriteForScalarRepl(AI, AI, 0, ElementAllocas);
Chris Lattnera59adc42009-12-14 05:11:02 +0000397
Bob Wilsonb742def2009-12-18 20:14:40 +0000398 // Now erase any instructions that were made dead while rewriting the alloca.
399 DeleteDeadInstructions();
Bob Wilson39c88a62009-12-17 18:34:24 +0000400 AI->eraseFromParent();
Bob Wilsonb742def2009-12-18 20:14:40 +0000401
Chris Lattnera10b29b2007-04-25 05:02:56 +0000402 NumReplaced++;
403}
Chris Lattnera59adc42009-12-14 05:11:02 +0000404
Bob Wilsonb742def2009-12-18 20:14:40 +0000405/// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
406/// recursively including all their operands that become trivially dead.
407void SROA::DeleteDeadInstructions() {
408 while (!DeadInsts.empty()) {
409 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
Chris Lattnera59adc42009-12-14 05:11:02 +0000410
Bob Wilsonb742def2009-12-18 20:14:40 +0000411 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
412 if (Instruction *U = dyn_cast<Instruction>(*OI)) {
413 // Zero out the operand and see if it becomes trivially dead.
414 // (But, don't add allocas to the dead instruction list -- they are
415 // already on the worklist and will be deleted separately.)
416 *OI = 0;
417 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
418 DeadInsts.push_back(U);
Chris Lattnera59adc42009-12-14 05:11:02 +0000419 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000420
421 I->eraseFromParent();
Chris Lattnera59adc42009-12-14 05:11:02 +0000422 }
Chris Lattnera59adc42009-12-14 05:11:02 +0000423}
Bob Wilsonb742def2009-12-18 20:14:40 +0000424
Bob Wilsonb742def2009-12-18 20:14:40 +0000425/// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
426/// performing scalar replacement of alloca AI. The results are flagged in
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000427/// the Info parameter. Offset indicates the position within AI that is
428/// referenced by this instruction.
Bob Wilsonb742def2009-12-18 20:14:40 +0000429void SROA::isSafeForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000430 AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000431 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
432 Instruction *User = cast<Instruction>(*UI);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000433
Bob Wilsonb742def2009-12-18 20:14:40 +0000434 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000435 isSafeForScalarRepl(BC, AI, Offset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000436 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000437 uint64_t GEPOffset = Offset;
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000438 isSafeGEP(GEPI, AI, GEPOffset, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000439 if (!Info.isUnsafe)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000440 isSafeForScalarRepl(GEPI, AI, GEPOffset, Info);
Gabor Greif2ff961f2010-04-15 20:51:13 +0000441 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000442 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
443 if (Length)
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000444 isSafeMemAccess(AI, Offset, Length->getZExtValue(), 0,
Gabor Greif2ff961f2010-04-15 20:51:13 +0000445 UI.getOperandNo() == 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000446 else
447 MarkUnsafe(Info);
448 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
449 if (!LI->isVolatile()) {
450 const Type *LIType = LI->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000451 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(LIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000452 LIType, false, Info);
453 } else
454 MarkUnsafe(Info);
455 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
456 // Store is ok if storing INTO the pointer, not storing the pointer
457 if (!SI->isVolatile() && SI->getOperand(0) != I) {
458 const Type *SIType = SI->getOperand(0)->getType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000459 isSafeMemAccess(AI, Offset, TD->getTypeAllocSize(SIType),
Bob Wilsonb742def2009-12-18 20:14:40 +0000460 SIType, true, Info);
461 } else
462 MarkUnsafe(Info);
Bob Wilsonb742def2009-12-18 20:14:40 +0000463 } else {
464 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
465 MarkUnsafe(Info);
466 }
467 if (Info.isUnsafe) return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000468 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000469}
Bob Wilson39c88a62009-12-17 18:34:24 +0000470
Bob Wilsonb742def2009-12-18 20:14:40 +0000471/// isSafeGEP - Check if a GEP instruction can be handled for scalar
472/// replacement. It is safe when all the indices are constant, in-bounds
473/// references, and when the resulting offset corresponds to an element within
474/// the alloca type. The results are flagged in the Info parameter. Upon
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000475/// return, Offset is adjusted as specified by the GEP indices.
Bob Wilsonb742def2009-12-18 20:14:40 +0000476void SROA::isSafeGEP(GetElementPtrInst *GEPI, AllocaInst *AI,
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000477 uint64_t &Offset, AllocaInfo &Info) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000478 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
479 if (GEPIt == E)
480 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000481
Chris Lattner88e6dc82008-08-23 05:21:06 +0000482 // Walk through the GEP type indices, checking the types that this indexes
483 // into.
Bob Wilsonb742def2009-12-18 20:14:40 +0000484 for (; GEPIt != E; ++GEPIt) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000485 // Ignore struct elements, no extra checking needed for these.
Duncan Sands1df98592010-02-16 11:11:14 +0000486 if ((*GEPIt)->isStructTy())
Chris Lattner88e6dc82008-08-23 05:21:06 +0000487 continue;
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000488
Bob Wilsonb742def2009-12-18 20:14:40 +0000489 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
490 if (!IdxVal)
491 return MarkUnsafe(Info);
Chris Lattner88e6dc82008-08-23 05:21:06 +0000492 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000493
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000494 // Compute the offset due to this GEP and check if the alloca has a
495 // component element at that offset.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000496 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
497 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
498 &Indices[0], Indices.size());
Bob Wilsonb742def2009-12-18 20:14:40 +0000499 if (!TypeHasComponent(AI->getAllocatedType(), Offset, 0))
500 MarkUnsafe(Info);
Chris Lattner5e062a12003-05-30 04:15:41 +0000501}
502
Bob Wilsonb742def2009-12-18 20:14:40 +0000503/// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
504/// alloca or has an offset and size that corresponds to a component element
505/// within it. The offset checked here may have been formed from a GEP with a
506/// pointer bitcasted to a different type.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000507void SROA::isSafeMemAccess(AllocaInst *AI, uint64_t Offset, uint64_t MemSize,
Bob Wilsonb742def2009-12-18 20:14:40 +0000508 const Type *MemOpType, bool isStore,
509 AllocaInfo &Info) {
510 // Check if this is a load/store of the entire alloca.
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000511 if (Offset == 0 && MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000512 bool UsesAggregateType = (MemOpType == AI->getAllocatedType());
513 // This is safe for MemIntrinsics (where MemOpType is 0), integer types
514 // (which are essentially the same as the MemIntrinsics, especially with
515 // regard to copying padding between elements), or references using the
516 // aggregate type of the alloca.
Duncan Sands1df98592010-02-16 11:11:14 +0000517 if (!MemOpType || MemOpType->isIntegerTy() || UsesAggregateType) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000518 if (!UsesAggregateType) {
519 if (isStore)
520 Info.isMemCpyDst = true;
521 else
522 Info.isMemCpySrc = true;
523 }
524 return;
525 }
526 }
527 // Check if the offset/size correspond to a component within the alloca type.
528 const Type *T = AI->getAllocatedType();
Bob Wilson3c3af5d2009-12-21 18:39:47 +0000529 if (TypeHasComponent(T, Offset, MemSize))
Bob Wilsonb742def2009-12-18 20:14:40 +0000530 return;
531
532 return MarkUnsafe(Info);
533}
534
535/// TypeHasComponent - Return true if T has a component type with the
536/// specified offset and size. If Size is zero, do not check the size.
537bool SROA::TypeHasComponent(const Type *T, uint64_t Offset, uint64_t Size) {
538 const Type *EltTy;
539 uint64_t EltSize;
540 if (const StructType *ST = dyn_cast<StructType>(T)) {
541 const StructLayout *Layout = TD->getStructLayout(ST);
542 unsigned EltIdx = Layout->getElementContainingOffset(Offset);
543 EltTy = ST->getContainedType(EltIdx);
544 EltSize = TD->getTypeAllocSize(EltTy);
545 Offset -= Layout->getElementOffset(EltIdx);
546 } else if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
547 EltTy = AT->getElementType();
548 EltSize = TD->getTypeAllocSize(EltTy);
Bob Wilsonf27a4cd2009-12-22 06:57:14 +0000549 if (Offset >= AT->getNumElements() * EltSize)
550 return false;
Bob Wilsonb742def2009-12-18 20:14:40 +0000551 Offset %= EltSize;
552 } else {
553 return false;
554 }
555 if (Offset == 0 && (Size == 0 || EltSize == Size))
556 return true;
557 // Check if the component spans multiple elements.
558 if (Offset + Size > EltSize)
559 return false;
560 return TypeHasComponent(EltTy, Offset, Size);
561}
562
563/// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite
564/// the instruction I, which references it, to use the separate elements.
565/// Offset indicates the position within AI that is referenced by this
566/// instruction.
567void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset,
568 SmallVector<AllocaInst*, 32> &NewElts) {
569 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) {
570 Instruction *User = cast<Instruction>(*UI);
571
572 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
573 RewriteBitCast(BC, AI, Offset, NewElts);
574 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
575 RewriteGEP(GEPI, AI, Offset, NewElts);
576 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
577 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
578 uint64_t MemSize = Length->getZExtValue();
579 if (Offset == 0 &&
580 MemSize == TD->getTypeAllocSize(AI->getAllocatedType()))
581 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts);
Bob Wilsone88728d2009-12-19 06:53:17 +0000582 // Otherwise the intrinsic can only touch a single element and the
583 // address operand will be updated, so nothing else needs to be done.
Bob Wilsonb742def2009-12-18 20:14:40 +0000584 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
585 const Type *LIType = LI->getType();
586 if (LIType == AI->getAllocatedType()) {
587 // Replace:
588 // %res = load { i32, i32 }* %alloc
589 // with:
590 // %load.0 = load i32* %alloc.0
591 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
592 // %load.1 = load i32* %alloc.1
593 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
594 // (Also works for arrays instead of structs)
595 Value *Insert = UndefValue::get(LIType);
596 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
597 Value *Load = new LoadInst(NewElts[i], "load", LI);
598 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
599 }
600 LI->replaceAllUsesWith(Insert);
601 DeadInsts.push_back(LI);
Duncan Sands1df98592010-02-16 11:11:14 +0000602 } else if (LIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +0000603 TD->getTypeAllocSize(LIType) ==
604 TD->getTypeAllocSize(AI->getAllocatedType())) {
605 // If this is a load of the entire alloca to an integer, rewrite it.
606 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
607 }
608 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
609 Value *Val = SI->getOperand(0);
610 const Type *SIType = Val->getType();
611 if (SIType == AI->getAllocatedType()) {
612 // Replace:
613 // store { i32, i32 } %val, { i32, i32 }* %alloc
614 // with:
615 // %val.0 = extractvalue { i32, i32 } %val, 0
616 // store i32 %val.0, i32* %alloc.0
617 // %val.1 = extractvalue { i32, i32 } %val, 1
618 // store i32 %val.1, i32* %alloc.1
619 // (Also works for arrays instead of structs)
620 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
621 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
622 new StoreInst(Extract, NewElts[i], SI);
623 }
624 DeadInsts.push_back(SI);
Duncan Sands1df98592010-02-16 11:11:14 +0000625 } else if (SIType->isIntegerTy() &&
Bob Wilsonb742def2009-12-18 20:14:40 +0000626 TD->getTypeAllocSize(SIType) ==
627 TD->getTypeAllocSize(AI->getAllocatedType())) {
628 // If this is a store of the entire alloca from an integer, rewrite it.
629 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
630 }
631 }
Bob Wilson39c88a62009-12-17 18:34:24 +0000632 }
633}
634
Bob Wilsonb742def2009-12-18 20:14:40 +0000635/// RewriteBitCast - Update a bitcast reference to the alloca being replaced
636/// and recursively continue updating all of its uses.
637void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset,
638 SmallVector<AllocaInst*, 32> &NewElts) {
639 RewriteForScalarRepl(BC, AI, Offset, NewElts);
640 if (BC->getOperand(0) != AI)
641 return;
Bob Wilson39c88a62009-12-17 18:34:24 +0000642
Bob Wilsonb742def2009-12-18 20:14:40 +0000643 // The bitcast references the original alloca. Replace its uses with
644 // references to the first new element alloca.
645 Instruction *Val = NewElts[0];
646 if (Val->getType() != BC->getDestTy()) {
647 Val = new BitCastInst(Val, BC->getDestTy(), "", BC);
648 Val->takeName(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000649 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000650 BC->replaceAllUsesWith(Val);
651 DeadInsts.push_back(BC);
Daniel Dunbarfca55c82009-12-16 10:56:17 +0000652}
653
Bob Wilsonb742def2009-12-18 20:14:40 +0000654/// FindElementAndOffset - Return the index of the element containing Offset
655/// within the specified type, which must be either a struct or an array.
656/// Sets T to the type of the element and Offset to the offset within that
Bob Wilsone88728d2009-12-19 06:53:17 +0000657/// element. IdxTy is set to the type of the index result to be used in a
658/// GEP instruction.
659uint64_t SROA::FindElementAndOffset(const Type *&T, uint64_t &Offset,
660 const Type *&IdxTy) {
661 uint64_t Idx = 0;
Bob Wilsonb742def2009-12-18 20:14:40 +0000662 if (const StructType *ST = dyn_cast<StructType>(T)) {
663 const StructLayout *Layout = TD->getStructLayout(ST);
664 Idx = Layout->getElementContainingOffset(Offset);
665 T = ST->getContainedType(Idx);
666 Offset -= Layout->getElementOffset(Idx);
Bob Wilsone88728d2009-12-19 06:53:17 +0000667 IdxTy = Type::getInt32Ty(T->getContext());
668 return Idx;
Chris Lattnera59adc42009-12-14 05:11:02 +0000669 }
Bob Wilsone88728d2009-12-19 06:53:17 +0000670 const ArrayType *AT = cast<ArrayType>(T);
671 T = AT->getElementType();
672 uint64_t EltSize = TD->getTypeAllocSize(T);
673 Idx = Offset / EltSize;
674 Offset -= Idx * EltSize;
675 IdxTy = Type::getInt64Ty(T->getContext());
Bob Wilsonb742def2009-12-18 20:14:40 +0000676 return Idx;
677}
678
679/// RewriteGEP - Check if this GEP instruction moves the pointer across
680/// elements of the alloca that are being split apart, and if so, rewrite
681/// the GEP to be relative to the new element.
682void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset,
683 SmallVector<AllocaInst*, 32> &NewElts) {
684 uint64_t OldOffset = Offset;
685 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
686 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(),
687 &Indices[0], Indices.size());
688
689 RewriteForScalarRepl(GEPI, AI, Offset, NewElts);
690
691 const Type *T = AI->getAllocatedType();
Bob Wilsone88728d2009-12-19 06:53:17 +0000692 const Type *IdxTy;
693 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000694 if (GEPI->getOperand(0) == AI)
Bob Wilsone88728d2009-12-19 06:53:17 +0000695 OldIdx = ~0ULL; // Force the GEP to be rewritten.
Bob Wilsonb742def2009-12-18 20:14:40 +0000696
697 T = AI->getAllocatedType();
698 uint64_t EltOffset = Offset;
Bob Wilsone88728d2009-12-19 06:53:17 +0000699 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy);
Bob Wilsonb742def2009-12-18 20:14:40 +0000700
701 // If this GEP does not move the pointer across elements of the alloca
702 // being split, then it does not needs to be rewritten.
703 if (Idx == OldIdx)
704 return;
705
706 const Type *i32Ty = Type::getInt32Ty(AI->getContext());
707 SmallVector<Value*, 8> NewArgs;
708 NewArgs.push_back(Constant::getNullValue(i32Ty));
709 while (EltOffset != 0) {
Bob Wilsone88728d2009-12-19 06:53:17 +0000710 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy);
711 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx));
Bob Wilsonb742def2009-12-18 20:14:40 +0000712 }
713 Instruction *Val = NewElts[Idx];
714 if (NewArgs.size() > 1) {
715 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs.begin(),
716 NewArgs.end(), "", GEPI);
717 Val->takeName(GEPI);
718 }
719 if (Val->getType() != GEPI->getType())
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000720 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI);
Bob Wilsonb742def2009-12-18 20:14:40 +0000721 GEPI->replaceAllUsesWith(Val);
722 DeadInsts.push_back(GEPI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000723}
724
725/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
726/// Rewrite it to copy or set the elements of the scalarized memory.
Bob Wilsonb742def2009-12-18 20:14:40 +0000727void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst,
Victor Hernandez7b929da2009-10-23 21:09:37 +0000728 AllocaInst *AI,
Chris Lattnerd93afec2009-01-07 07:18:45 +0000729 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000730 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000731 // appropriate type. The "Other" pointer is the pointer that goes to memory
732 // that doesn't have anything to do with the alloca that we are promoting. For
733 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000734 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +0000735 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000736 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000737 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
Bob Wilsonb742def2009-12-18 20:14:40 +0000738 if (Inst == MTI->getRawDest())
Chris Lattner3ce5e882009-03-08 03:37:16 +0000739 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000740 else {
Bob Wilsonb742def2009-12-18 20:14:40 +0000741 assert(Inst == MTI->getRawSource());
Chris Lattner3ce5e882009-03-08 03:37:16 +0000742 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000743 }
744 }
Bob Wilson78c50b82009-12-08 18:22:03 +0000745
Chris Lattnerd93afec2009-01-07 07:18:45 +0000746 // If there is an other pointer, we want to convert it to the same pointer
747 // type as AI has, so we can GEP through it safely.
748 if (OtherPtr) {
Bob Wilsonb742def2009-12-18 20:14:40 +0000749
750 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
751 // optimization, but it's also required to detect the corner case where
752 // both pointer operands are referencing the same memory, and where
753 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
754 // function is only called for mem intrinsics that access the whole
755 // aggregate, so non-zero GEPs are not an issue here.)
756 while (1) {
757 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) {
758 OtherPtr = BC->getOperand(0);
759 continue;
760 }
761 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) {
762 // All zero GEPs are effectively bitcasts.
763 if (GEP->hasAllZeroIndices()) {
764 OtherPtr = GEP->getOperand(0);
765 continue;
766 }
767 }
768 break;
769 }
Bob Wilsona756b1d2010-01-19 04:32:48 +0000770 // Copying the alloca to itself is a no-op: just delete it.
771 if (OtherPtr == AI || OtherPtr == NewElts[0]) {
772 // This code will run twice for a no-op memcpy -- once for each operand.
773 // Put only one reference to MI on the DeadInsts list.
774 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(),
775 E = DeadInsts.end(); I != E; ++I)
776 if (*I == MI) return;
777 DeadInsts.push_back(MI);
Bob Wilsonb742def2009-12-18 20:14:40 +0000778 return;
Bob Wilsona756b1d2010-01-19 04:32:48 +0000779 }
Chris Lattner372dda82007-03-05 07:52:57 +0000780
Chris Lattnerd93afec2009-01-07 07:18:45 +0000781 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
782 if (BCE->getOpcode() == Instruction::BitCast)
783 OtherPtr = BCE->getOperand(0);
784
785 // If the pointer is not the right type, insert a bitcast to the right
786 // type.
787 if (OtherPtr->getType() != AI->getType())
788 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
789 MI);
790 }
791
792 // Process each element of the aggregate.
Gabor Greif2ff961f2010-04-15 20:51:13 +0000793 Value *TheFn = MI->getCalledValue();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000794 const Type *BytePtrTy = MI->getRawDest()->getType();
Bob Wilsonb742def2009-12-18 20:14:40 +0000795 bool SROADest = MI->getRawDest() == Inst;
Chris Lattnerd93afec2009-01-07 07:18:45 +0000796
Owen Anderson1d0be152009-08-13 21:58:54 +0000797 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +0000798
799 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
800 // If this is a memcpy/memmove, emit a GEP of the other element address.
801 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000802 unsigned OtherEltAlign = MemAlignment;
803
Bob Wilsona756b1d2010-01-19 04:32:48 +0000804 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000805 Value *Idx[2] = { Zero,
806 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Bob Wilsonb742def2009-12-18 20:14:40 +0000807 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, Idx + 2,
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000808 OtherPtr->getName()+"."+Twine(i),
Bob Wilsonb742def2009-12-18 20:14:40 +0000809 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000810 uint64_t EltOffset;
811 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
812 if (const StructType *ST =
813 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
814 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
815 } else {
816 const Type *EltTy =
817 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000818 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000819 }
820
821 // The alignment of the other pointer is the guaranteed alignment of the
822 // element, which is affected by both the known alignment of the whole
823 // mem intrinsic and the alignment of the element. If the alignment of
824 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
825 // known alignment is just 4 bytes.
826 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000827 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000828
829 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000830 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000831
832 // If we got down to a scalar, insert a load or store as appropriate.
833 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000834 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000835 if (SROADest) {
836 // From Other to Alloca.
837 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
838 new StoreInst(Elt, EltPtr, MI);
839 } else {
840 // From Alloca to Other.
841 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
842 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
843 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000844 continue;
845 }
846 assert(isa<MemSetInst>(MI));
847
848 // If the stored element is zero (common case), just store a null
849 // constant.
850 Constant *StoreVal;
Gabor Greif2ff961f2010-04-15 20:51:13 +0000851 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(1))) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000852 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000853 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000854 } else {
855 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000856 const Type *ValTy = EltTy->getScalarType();
857
Chris Lattnerd93afec2009-01-07 07:18:45 +0000858 // Construct an integer with the right value.
859 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
860 APInt OneVal(EltSize, CI->getZExtValue());
861 APInt TotalVal(OneVal);
862 // Set each byte.
863 for (unsigned i = 0; 8*i < EltSize; ++i) {
864 TotalVal = TotalVal.shl(8);
865 TotalVal |= OneVal;
866 }
867
868 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +0000869 StoreVal = ConstantInt::get(Context, TotalVal);
Duncan Sands1df98592010-02-16 11:11:14 +0000870 if (ValTy->isPointerTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000871 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000872 else if (ValTy->isFloatingPointTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000873 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000874 assert(StoreVal->getType() == ValTy && "Type mismatch!");
875
876 // If the requested value was a vector constant, create it.
877 if (EltTy != ValTy) {
878 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
879 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000880 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000881 }
882 }
883 new StoreInst(StoreVal, EltPtr, MI);
884 continue;
885 }
886 // Otherwise, if we're storing a byte variable, use a memset call for
887 // this element.
888 }
889
890 // Cast the element pointer to BytePtrTy.
891 if (EltPtr->getType() != BytePtrTy)
Benjamin Kramer2d64ca02010-01-27 19:46:52 +0000892 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getName(), MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000893
894 // Cast the other pointer (if we have one) to BytePtrTy.
Mon P Wang20adc9d2010-04-04 03:10:48 +0000895 if (OtherElt && OtherElt->getType() != BytePtrTy) {
896 // Preserve address space of OtherElt
897 const PointerType* OtherPTy = cast<PointerType>(OtherElt->getType());
898 const PointerType* PTy = cast<PointerType>(BytePtrTy);
899 if (OtherPTy->getElementType() != PTy->getElementType()) {
900 Type *NewOtherPTy = PointerType::get(PTy->getElementType(),
901 OtherPTy->getAddressSpace());
902 OtherElt = new BitCastInst(OtherElt, NewOtherPTy,
903 OtherElt->getNameStr(), MI);
904 }
905 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000906
Duncan Sands777d2302009-05-09 07:06:46 +0000907 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000908
909 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000910 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000911 Value *Ops[] = {
912 SROADest ? EltPtr : OtherElt, // Dest ptr
913 SROADest ? OtherElt : EltPtr, // Src ptr
Gabor Greif2ff961f2010-04-15 20:51:13 +0000914 ConstantInt::get(MI->getOperand(2)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +0000915 // Align
Mon P Wang20adc9d2010-04-04 03:10:48 +0000916 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign),
917 MI->getVolatileCst()
Chris Lattnerd93afec2009-01-07 07:18:45 +0000918 };
Mon P Wang20adc9d2010-04-04 03:10:48 +0000919 // In case we fold the address space overloaded memcpy of A to B
920 // with memcpy of B to C, change the function to be a memcpy of A to C.
921 const Type *Tys[] = { Ops[0]->getType(), Ops[1]->getType(),
922 Ops[2]->getType() };
923 Module *M = MI->getParent()->getParent()->getParent();
924 TheFn = Intrinsic::getDeclaration(M, MI->getIntrinsicID(), Tys, 3);
925 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000926 } else {
927 assert(isa<MemSetInst>(MI));
928 Value *Ops[] = {
Gabor Greif2ff961f2010-04-15 20:51:13 +0000929 EltPtr, MI->getOperand(1), // Dest, Value,
930 ConstantInt::get(MI->getOperand(2)->getType(), EltSize), // Size
Mon P Wang20adc9d2010-04-04 03:10:48 +0000931 Zero, // Align
932 ConstantInt::get(Type::getInt1Ty(MI->getContext()), 0) // isVolatile
Chris Lattnerd93afec2009-01-07 07:18:45 +0000933 };
Mon P Wang20adc9d2010-04-04 03:10:48 +0000934 const Type *Tys[] = { Ops[0]->getType(), Ops[2]->getType() };
935 Module *M = MI->getParent()->getParent()->getParent();
936 TheFn = Intrinsic::getDeclaration(M, Intrinsic::memset, Tys, 2);
937 CallInst::Create(TheFn, Ops, Ops + 5, "", MI);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000938 }
Chris Lattner372dda82007-03-05 07:52:57 +0000939 }
Bob Wilsonb742def2009-12-18 20:14:40 +0000940 DeadInsts.push_back(MI);
Chris Lattner372dda82007-03-05 07:52:57 +0000941}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000942
Bob Wilson39fdd692009-12-04 21:57:37 +0000943/// RewriteStoreUserOfWholeAlloca - We found a store of an integer that
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000944/// overwrites the entire allocation. Extract out the pieces of the stored
945/// integer and store them individually.
Victor Hernandez7b929da2009-10-23 21:09:37 +0000946void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI,
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000947 SmallVector<AllocaInst*, 32> &NewElts){
948 // Extract each element out of the integer according to its structure offset
949 // and store the element value to the individual alloca.
950 Value *SrcVal = SI->getOperand(0);
Bob Wilsonb742def2009-12-18 20:14:40 +0000951 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +0000952 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000953
Eli Friedman41b33f42009-06-01 09:14:32 +0000954 // Handle tail padding by extending the operand
955 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000956 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000957 IntegerType::get(SI->getContext(), AllocaSizeBits),
958 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000959
David Greene504c7d82010-01-05 01:27:09 +0000960 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
Nick Lewycky59136252009-09-15 07:08:25 +0000961 << '\n');
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000962
963 // There are two forms here: AI could be an array or struct. Both cases
964 // have different ways to compute the element offset.
965 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
966 const StructLayout *Layout = TD->getStructLayout(EltSTy);
967
968 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
969 // Get the number of bits to shift SrcVal to get the value.
970 const Type *FieldTy = EltSTy->getElementType(i);
971 uint64_t Shift = Layout->getElementOffsetInBits(i);
972
973 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000974 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000975
976 Value *EltVal = SrcVal;
977 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000978 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000979 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
980 "sroa.store.elt", SI);
981 }
982
983 // Truncate down to an integer of the right size.
984 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000985
986 // Ignore zero sized fields like {}, they obviously contain no data.
987 if (FieldSizeBits == 0) continue;
988
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000989 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000990 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000991 IntegerType::get(SI->getContext(), FieldSizeBits),
992 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000993 Value *DestField = NewElts[i];
994 if (EltVal->getType() == FieldTy) {
995 // Storing to an integer field of this size, just do it.
Duncan Sands1df98592010-02-16 11:11:14 +0000996 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000997 // Bitcast to the right element type (for fp/vector values).
998 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
999 } else {
1000 // Otherwise, bitcast the dest pointer (for aggregates).
1001 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001002 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001003 "", SI);
1004 }
1005 new StoreInst(EltVal, DestField, SI);
1006 }
1007
1008 } else {
1009 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
1010 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001011 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001012 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
1013
1014 uint64_t Shift;
1015
1016 if (TD->isBigEndian())
1017 Shift = AllocaSizeBits-ElementOffset;
1018 else
1019 Shift = 0;
1020
1021 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +00001022 // Ignore zero sized fields like {}, they obviously contain no data.
1023 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001024
1025 Value *EltVal = SrcVal;
1026 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001027 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001028 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
1029 "sroa.store.elt", SI);
1030 }
1031
1032 // Truncate down to an integer of the right size.
1033 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001034 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001035 IntegerType::get(SI->getContext(),
1036 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001037 Value *DestField = NewElts[i];
1038 if (EltVal->getType() == ArrayEltTy) {
1039 // Storing to an integer field of this size, just do it.
Duncan Sandsb0bc6c32010-02-15 16:12:20 +00001040 } else if (ArrayEltTy->isFloatingPointTy() ||
Duncan Sands1df98592010-02-16 11:11:14 +00001041 ArrayEltTy->isVectorTy()) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001042 // Bitcast to the right element type (for fp/vector values).
1043 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1044 } else {
1045 // Otherwise, bitcast the dest pointer (for aggregates).
1046 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001047 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001048 "", SI);
1049 }
1050 new StoreInst(EltVal, DestField, SI);
1051
1052 if (TD->isBigEndian())
1053 Shift -= ElementOffset;
1054 else
1055 Shift += ElementOffset;
1056 }
1057 }
1058
Bob Wilsonb742def2009-12-18 20:14:40 +00001059 DeadInsts.push_back(SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001060}
1061
Bob Wilson39fdd692009-12-04 21:57:37 +00001062/// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001063/// an integer. Load the individual pieces to form the aggregate value.
Victor Hernandez7b929da2009-10-23 21:09:37 +00001064void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI,
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001065 SmallVector<AllocaInst*, 32> &NewElts) {
1066 // Extract each element out of the NewElts according to its structure offset
1067 // and form the result value.
Bob Wilsonb742def2009-12-18 20:14:40 +00001068 const Type *AllocaEltTy = AI->getAllocatedType();
Duncan Sands777d2302009-05-09 07:06:46 +00001069 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001070
David Greene504c7d82010-01-05 01:27:09 +00001071 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
Nick Lewycky59136252009-09-15 07:08:25 +00001072 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001073
1074 // There are two forms here: AI could be an array or struct. Both cases
1075 // have different ways to compute the element offset.
1076 const StructLayout *Layout = 0;
1077 uint64_t ArrayEltBitOffset = 0;
1078 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1079 Layout = TD->getStructLayout(EltSTy);
1080 } else {
1081 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001082 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001083 }
Owen Andersone922c022009-07-22 00:24:57 +00001084
Owen Andersone922c022009-07-22 00:24:57 +00001085 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001086 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001087
1088 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1089 // Load the value from the alloca. If the NewElt is an aggregate, cast
1090 // the pointer to an integer of the same size before doing the load.
1091 Value *SrcField = NewElts[i];
1092 const Type *FieldTy =
1093 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001094 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1095
1096 // Ignore zero sized fields like {}, they obviously contain no data.
1097 if (FieldSizeBits == 0) continue;
1098
Owen Anderson1d0be152009-08-13 21:58:54 +00001099 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1100 FieldSizeBits);
Duncan Sands1df98592010-02-16 11:11:14 +00001101 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() &&
1102 !FieldTy->isVectorTy())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001103 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001104 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001105 "", LI);
1106 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1107
1108 // If SrcField is a fp or vector of the right size but that isn't an
1109 // integer type, bitcast to an integer so we can shift it.
1110 if (SrcField->getType() != FieldIntTy)
1111 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1112
1113 // Zero extend the field to be the same size as the final alloca so that
1114 // we can shift and insert it.
1115 if (SrcField->getType() != ResultVal->getType())
1116 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1117
1118 // Determine the number of bits to shift SrcField.
1119 uint64_t Shift;
1120 if (Layout) // Struct case.
1121 Shift = Layout->getElementOffsetInBits(i);
1122 else // Array case.
1123 Shift = i*ArrayEltBitOffset;
1124
1125 if (TD->isBigEndian())
1126 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1127
1128 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001129 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001130 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1131 }
1132
1133 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1134 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001135
1136 // Handle tail padding by truncating the result
1137 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1138 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1139
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001140 LI->replaceAllUsesWith(ResultVal);
Bob Wilsonb742def2009-12-18 20:14:40 +00001141 DeadInsts.push_back(LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001142}
1143
Duncan Sands3cb36502007-11-04 14:43:57 +00001144/// HasPadding - Return true if the specified type has any structure or
1145/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001146static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001147 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1148 const StructLayout *SL = TD.getStructLayout(STy);
1149 unsigned PrevFieldBitOffset = 0;
1150 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001151 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1152
Chris Lattner39a1c042007-05-30 06:11:23 +00001153 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001154 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001155 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001156
Chris Lattner39a1c042007-05-30 06:11:23 +00001157 // Check to see if there is any padding between this element and the
1158 // previous one.
1159 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001160 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001161 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1162 if (PrevFieldEnd < FieldBitOffset)
1163 return true;
1164 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001165
Chris Lattner39a1c042007-05-30 06:11:23 +00001166 PrevFieldBitOffset = FieldBitOffset;
1167 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001168
Chris Lattner39a1c042007-05-30 06:11:23 +00001169 // Check for tail padding.
1170 if (unsigned EltCount = STy->getNumElements()) {
1171 unsigned PrevFieldEnd = PrevFieldBitOffset +
1172 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001173 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001174 return true;
1175 }
1176
1177 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001178 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001179 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001180 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001181 }
Duncan Sands777d2302009-05-09 07:06:46 +00001182 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001183}
Chris Lattner372dda82007-03-05 07:52:57 +00001184
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001185/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1186/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1187/// or 1 if safe after canonicalization has been performed.
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001188bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001189 // Loop over the use list of the alloca. We can only transform it if all of
1190 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001191 AllocaInfo Info;
1192
Bob Wilson3c3af5d2009-12-21 18:39:47 +00001193 isSafeForScalarRepl(AI, AI, 0, Info);
Bob Wilsonb742def2009-12-18 20:14:40 +00001194 if (Info.isUnsafe) {
David Greene504c7d82010-01-05 01:27:09 +00001195 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001196 return false;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001197 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001198
1199 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1200 // source and destination, we have to be careful. In particular, the memcpy
1201 // could be moving around elements that live in structure padding of the LLVM
1202 // types, but may actually be used. In these cases, we refuse to promote the
1203 // struct.
1204 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Bob Wilsonb742def2009-12-18 20:14:40 +00001205 HasPadding(AI->getAllocatedType(), *TD))
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001206 return false;
Duncan Sands3cb36502007-11-04 14:43:57 +00001207
Victor Hernandez6c146ee2010-01-21 23:05:53 +00001208 return true;
Chris Lattner5e062a12003-05-30 04:15:41 +00001209}
Chris Lattnera1888942005-12-12 07:19:13 +00001210
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001211/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1212/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001213///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001214/// There are two cases we handle here:
1215/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001216/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001217/// This promotes a <4 x float> with a store of float to the third element
1218/// into a <4 x float> that uses insert element.
1219/// 2) A fully general blob of memory, which we turn into some (potentially
1220/// large) integer type with extract and insert operations where the loads
1221/// and stores would mutate the memory.
Chris Lattner593375d2010-04-16 00:20:00 +00001222void ConvertToScalarInfo::MergeInType(const Type *In, uint64_t Offset) {
Chris Lattnerc4472072010-04-15 23:50:26 +00001223 // Remember if we saw a vector type.
Chris Lattner593375d2010-04-16 00:20:00 +00001224 HadAVector |= In->isVectorTy();
Chris Lattnerc4472072010-04-15 23:50:26 +00001225
Chris Lattner593375d2010-04-16 00:20:00 +00001226 if (VectorTy && VectorTy->isVoidTy())
Chris Lattnerc4472072010-04-15 23:50:26 +00001227 return;
1228
Chris Lattner7809ecd2009-02-03 01:30:09 +00001229 // If this could be contributing to a vector, analyze it.
Chris Lattner996d7a92009-02-02 18:02:59 +00001230
Chris Lattnerc4472072010-04-15 23:50:26 +00001231 // If the In type is a vector that is the same size as the alloca, see if it
1232 // matches the existing VecTy.
1233 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
Chris Lattner593375d2010-04-16 00:20:00 +00001234 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
Chris Lattnerc4472072010-04-15 23:50:26 +00001235 // If we're storing/loading a vector of the right size, allow it as a
1236 // vector. If this the first vector we see, remember the type so that
1237 // we know the element size.
Chris Lattner593375d2010-04-16 00:20:00 +00001238 if (VectorTy == 0)
1239 VectorTy = VInTy;
Chris Lattnerc4472072010-04-15 23:50:26 +00001240 return;
1241 }
1242 } else if (In->isFloatTy() || In->isDoubleTy() ||
1243 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 &&
1244 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1245 // If we're accessing something that could be an element of a vector, see
1246 // if the implied vector agrees with what we already have and if Offset is
1247 // compatible with it.
1248 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
Chris Lattner593375d2010-04-16 00:20:00 +00001249 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 &&
1250 (VectorTy == 0 ||
1251 cast<VectorType>(VectorTy)->getElementType()
Chris Lattnerc4472072010-04-15 23:50:26 +00001252 ->getPrimitiveSizeInBits()/8 == EltSize)) {
Chris Lattner593375d2010-04-16 00:20:00 +00001253 if (VectorTy == 0)
1254 VectorTy = VectorType::get(In, AllocaSize/EltSize);
Chris Lattnerc4472072010-04-15 23:50:26 +00001255 return;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001256 }
1257 }
1258
Chris Lattner7809ecd2009-02-03 01:30:09 +00001259 // Otherwise, we have a case that we can't handle with an optimized vector
1260 // form. We can still turn this into a large integer.
Chris Lattner593375d2010-04-16 00:20:00 +00001261 VectorTy = Type::getVoidTy(In->getContext());
Chris Lattnera1888942005-12-12 07:19:13 +00001262}
1263
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001264/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Bob Wilsonefc58e72009-12-09 18:05:27 +00001265/// its accesses to a single vector type, return true and set VecTy to
Chris Lattner7809ecd2009-02-03 01:30:09 +00001266/// the new type. If we could convert the alloca into a single promotable
1267/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1268/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1269/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001270///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001271/// If we see at least one access to the value that is as a vector type, set the
1272/// SawVec flag.
Chris Lattner593375d2010-04-16 00:20:00 +00001273bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001274 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1275 Instruction *User = cast<Instruction>(*UI);
1276
1277 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001278 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001279 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001280 return false;
Chris Lattner593375d2010-04-16 00:20:00 +00001281 MergeInType(LI->getType(), Offset);
Chris Lattnercf321862009-01-07 06:39:58 +00001282 continue;
1283 }
1284
1285 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001286 // Storing the pointer, not into the value?
Chris Lattnerc4472072010-04-15 23:50:26 +00001287 if (SI->getOperand(0) == V || SI->isVolatile()) return false;
Chris Lattner593375d2010-04-16 00:20:00 +00001288 MergeInType(SI->getOperand(0)->getType(), Offset);
Chris Lattnercf321862009-01-07 06:39:58 +00001289 continue;
1290 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001291
1292 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner593375d2010-04-16 00:20:00 +00001293 if (!CanConvertToScalar(BCI, Offset))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001294 return false;
Chris Lattner593375d2010-04-16 00:20:00 +00001295 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001296 continue;
1297 }
1298
1299 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001300 // If this is a GEP with a variable indices, we can't handle it.
1301 if (!GEP->hasAllConstantIndices())
1302 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001303
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001304 // Compute the offset that this GEP adds to the pointer.
1305 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Chris Lattner593375d2010-04-16 00:20:00 +00001306 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
1307 &Indices[0], Indices.size());
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001308 // See if all uses can be converted.
Chris Lattner593375d2010-04-16 00:20:00 +00001309 if (!CanConvertToScalar(GEP, Offset+GEPOffset))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001310 return false;
Chris Lattner593375d2010-04-16 00:20:00 +00001311 IsNotTrivial = true;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001312 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001313 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001314
Chris Lattner3d730f72009-02-03 02:01:43 +00001315 // If this is a constant sized memset of a constant value (e.g. 0) we can
1316 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001317 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1318 // Store of constant value and constant size.
1319 if (isa<ConstantInt>(MSI->getValue()) &&
1320 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner593375d2010-04-16 00:20:00 +00001321 IsNotTrivial = true;
Chris Lattner3ce5e882009-03-08 03:37:16 +00001322 continue;
1323 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001324 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001325
1326 // If this is a memcpy or memmove into or out of the whole allocation, we
1327 // can handle it like a load or store of the scalar type.
1328 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1329 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
Chris Lattner593375d2010-04-16 00:20:00 +00001330 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1331 IsNotTrivial = true;
Chris Lattnerc5704872009-03-08 04:04:21 +00001332 continue;
1333 }
1334 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001335
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001336 // Otherwise, we cannot handle this!
1337 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001338 }
1339
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001340 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001341}
1342
Chris Lattnera1888942005-12-12 07:19:13 +00001343/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001344/// directly. This happens when we are converting an "integer union" to a
1345/// single integer scalar, or when we are converting a "vector union" to a
1346/// vector with insert/extractelement instructions.
1347///
1348/// Offset is an offset from the original alloca, in bits that need to be
1349/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner593375d2010-04-16 00:20:00 +00001350void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI,
1351 uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001352 while (!Ptr->use_empty()) {
1353 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001354
Chris Lattnercf321862009-01-07 06:39:58 +00001355 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001356 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001357 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001358 continue;
1359 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001360
Chris Lattnercf321862009-01-07 06:39:58 +00001361 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001362 // Compute the offset that this GEP adds to the pointer.
1363 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
Chris Lattner593375d2010-04-16 00:20:00 +00001364 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(),
1365 &Indices[0], Indices.size());
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001366 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001367 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001368 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001369 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001370
Chris Lattner9bc67da2009-02-03 19:45:44 +00001371 IRBuilder<> Builder(User->getParent(), User);
1372
1373 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001374 // The load is a bit extract from NewAI shifted right by Offset bits.
1375 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1376 Value *NewLoadVal
1377 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1378 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001379 LI->eraseFromParent();
1380 continue;
1381 }
1382
1383 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1384 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Chris Lattneraadadb32009-12-22 19:33:28 +00001385 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Chris Lattner9bc67da2009-02-03 19:45:44 +00001386 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1387 Builder);
1388 Builder.CreateStore(New, NewAI);
1389 SI->eraseFromParent();
Chris Lattneraadadb32009-12-22 19:33:28 +00001390
1391 // If the load we just inserted is now dead, then the inserted store
1392 // overwrote the entire thing.
1393 if (Old->use_empty())
1394 Old->eraseFromParent();
Chris Lattner9bc67da2009-02-03 19:45:44 +00001395 continue;
1396 }
1397
Chris Lattner3d730f72009-02-03 02:01:43 +00001398 // If this is a constant sized memset of a constant value (e.g. 0) we can
1399 // transform it into a store of the expanded constant value.
1400 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1401 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1402 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001403 if (NumBytes != 0) {
1404 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1405
1406 // Compute the value replicated the right number of times.
1407 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001408
Chris Lattner33e24ad2009-04-21 16:52:12 +00001409 // Splat the value if non-zero.
1410 if (Val)
1411 for (unsigned i = 1; i != NumBytes; ++i)
1412 APVal |= APVal << 8;
Benjamin Kramere6f32942009-11-29 21:17:48 +00001413
Chris Lattneraadadb32009-12-22 19:33:28 +00001414 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in");
Owen Andersone922c022009-07-22 00:24:57 +00001415 Value *New = ConvertScalar_InsertValue(
Owen Andersoneed707b2009-07-24 23:12:02 +00001416 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001417 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001418 Builder.CreateStore(New, NewAI);
Chris Lattneraadadb32009-12-22 19:33:28 +00001419
1420 // If the load we just inserted is now dead, then the memset overwrote
1421 // the entire thing.
1422 if (Old->use_empty())
1423 Old->eraseFromParent();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001424 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001425 MSI->eraseFromParent();
1426 continue;
1427 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001428
1429 // If this is a memcpy or memmove into or out of the whole allocation, we
1430 // can handle it like a load or store of the scalar type.
1431 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1432 assert(Offset == 0 && "must be store to start of alloca");
1433
1434 // If the source and destination are both to the same alloca, then this is
1435 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1436 // as appropriate.
Bob Wilson03274292010-01-25 18:26:54 +00001437 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject(0));
Chris Lattnerc5704872009-03-08 04:04:21 +00001438
Bob Wilson03274292010-01-25 18:26:54 +00001439 if (MTI->getSource()->getUnderlyingObject(0) != OrigAI) {
Chris Lattnerc5704872009-03-08 04:04:21 +00001440 // Dest must be OrigAI, change this to be a load from the original
1441 // pointer (bitcasted), then a store to our new alloca.
1442 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1443 Value *SrcPtr = MTI->getSource();
1444 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1445
1446 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1447 SrcVal->setAlignment(MTI->getAlignment());
1448 Builder.CreateStore(SrcVal, NewAI);
Bob Wilson03274292010-01-25 18:26:54 +00001449 } else if (MTI->getDest()->getUnderlyingObject(0) != OrigAI) {
Chris Lattnerc5704872009-03-08 04:04:21 +00001450 // Src must be OrigAI, change this to be a load from NewAI then a store
1451 // through the original dest pointer (bitcasted).
1452 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1453 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1454
1455 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1456 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1457 NewStore->setAlignment(MTI->getAlignment());
1458 } else {
1459 // Noop transfer. Src == Dst
1460 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001461
1462 MTI->eraseFromParent();
1463 continue;
1464 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001465
Torok Edwinc23197a2009-07-14 16:55:14 +00001466 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001467 }
1468}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001469
Chris Lattner6e011152009-02-03 21:01:03 +00001470/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1471/// or vector value FromVal, extracting the bits from the offset specified by
1472/// Offset. This returns the value, which is of type ToType.
1473///
1474/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001475/// integer scalar, or when we are converting a "vector union" to a vector with
1476/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001477///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001478/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001479/// shifted to the right.
Chris Lattner593375d2010-04-16 00:20:00 +00001480Value *ConvertToScalarInfo::
1481ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1482 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001483 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001484 if (FromVal->getType() == ToType && Offset == 0)
1485 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001486
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001487 // If the result alloca is a vector type, this is either an element
1488 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001489 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
Duncan Sands1df98592010-02-16 11:11:14 +00001490 if (ToType->isVectorTy())
Chris Lattner6e011152009-02-03 21:01:03 +00001491 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001492
1493 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001494 unsigned Elt = 0;
1495 if (Offset) {
Chris Lattner593375d2010-04-16 00:20:00 +00001496 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001497 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001498 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001499 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001500 // Return the element extracted out of it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001501 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1502 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001503 if (V->getType() != ToType)
1504 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001505 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001506 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001507
1508 // If ToType is a first class aggregate, extract out each of the pieces and
1509 // use insertvalue's to form the FCA.
1510 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
Chris Lattner593375d2010-04-16 00:20:00 +00001511 const StructLayout &Layout = *TD.getStructLayout(ST);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001512 Value *Res = UndefValue::get(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001513 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1514 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001515 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001516 Builder);
1517 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1518 }
1519 return Res;
1520 }
1521
1522 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Chris Lattner593375d2010-04-16 00:20:00 +00001523 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001524 Value *Res = UndefValue::get(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001525 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1526 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1527 Offset+i*EltSize, Builder);
1528 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1529 }
1530 return Res;
1531 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001532
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001533 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001534 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001535
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001536 // If this is a big-endian system and the load is narrower than the
1537 // full alloca type, we need to do a shift to get the right bits.
1538 int ShAmt = 0;
Chris Lattner593375d2010-04-16 00:20:00 +00001539 if (TD.isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001540 // On big-endian machines, the lowest bit is stored at the bit offset
1541 // from the pointer given by getTypeStoreSizeInBits. This matters for
1542 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner593375d2010-04-16 00:20:00 +00001543 ShAmt = TD.getTypeStoreSizeInBits(NTy) -
1544 TD.getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001545 } else {
1546 ShAmt = Offset;
1547 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001548
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001549 // Note: we support negative bitwidths (with shl) which are not defined.
1550 // We do this to support (f.e.) loads off the end of a structure where
1551 // only some bits are used.
1552 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001553 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001554 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001555 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001556 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001557 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001558 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001559 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001560
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001561 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner593375d2010-04-16 00:20:00 +00001562 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001563 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001564 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001565 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1566 LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001567 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001568 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001569 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1570 LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001571
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001572 // If the result is an integer, this is a trunc or bitcast.
Duncan Sands1df98592010-02-16 11:11:14 +00001573 if (ToType->isIntegerTy()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001574 // Should be done.
Duncan Sands1df98592010-02-16 11:11:14 +00001575 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001576 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001577 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001578 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001579 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001580 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001581 }
Chris Lattner6e011152009-02-03 21:01:03 +00001582 assert(FromVal->getType() == ToType && "Didn't convert right?");
1583 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001584}
1585
Chris Lattner9b872db2009-02-03 19:30:11 +00001586/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1587/// or vector value "Old" at the offset specified by Offset.
1588///
1589/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001590/// single integer scalar, or when we are converting a "vector union" to a
1591/// vector with insert/extractelement instructions.
1592///
1593/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001594/// shifted to the right.
Chris Lattner593375d2010-04-16 00:20:00 +00001595Value *ConvertToScalarInfo::
1596ConvertScalar_InsertValue(Value *SV, Value *Old,
1597 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner800de312008-02-29 07:03:13 +00001598 // Convert the stored type to the actual type, shift it left to insert
1599 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001600 const Type *AllocaType = Old->getType();
Owen Andersone922c022009-07-22 00:24:57 +00001601 LLVMContext &Context = Old->getContext();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001602
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001603 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Chris Lattner593375d2010-04-16 00:20:00 +00001604 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy);
1605 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001606
1607 // Changing the whole vector with memset or with an access of a different
1608 // vector type?
1609 if (ValSize == VecSize)
1610 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1611
Chris Lattner593375d2010-04-16 00:20:00 +00001612 uint64_t EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001613
1614 // Must be an element insertion.
1615 unsigned Elt = Offset/EltSize;
1616
1617 if (SV->getType() != VTy->getElementType())
1618 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1619
1620 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001621 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001622 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001623 return SV;
1624 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001625
1626 // If SV is a first-class aggregate value, insert each value recursively.
1627 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
Chris Lattner593375d2010-04-16 00:20:00 +00001628 const StructLayout &Layout = *TD.getStructLayout(ST);
Chris Lattner9b872db2009-02-03 19:30:11 +00001629 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001630 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001631 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001632 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001633 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001634 }
1635 return Old;
1636 }
1637
1638 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Chris Lattner593375d2010-04-16 00:20:00 +00001639 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001640 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001641 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1642 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001643 }
1644 return Old;
1645 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001646
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001647 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001648 // If it is a pointer, do the same.
Chris Lattner593375d2010-04-16 00:20:00 +00001649 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType());
1650 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType);
1651 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType());
1652 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType);
Duncan Sands1df98592010-02-16 11:11:14 +00001653 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy())
Owen Anderson1d0be152009-08-13 21:58:54 +00001654 SV = Builder.CreateBitCast(SV,
1655 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Duncan Sands1df98592010-02-16 11:11:14 +00001656 else if (SV->getType()->isPointerTy())
Chris Lattner593375d2010-04-16 00:20:00 +00001657 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext()), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001658
Chris Lattner7809ecd2009-02-03 01:30:09 +00001659 // Zero extend or truncate the value if needed.
1660 if (SV->getType() != AllocaType) {
1661 if (SV->getType()->getPrimitiveSizeInBits() <
1662 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001663 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001664 else {
1665 // Truncation may be needed if storing more than the alloca can hold
1666 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001667 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001668 SrcWidth = DestWidth;
1669 SrcStoreWidth = DestStoreWidth;
1670 }
1671 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001672
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001673 // If this is a big-endian system and the store is narrower than the
1674 // full alloca type, we need to do a shift to get the right bits.
1675 int ShAmt = 0;
Chris Lattner593375d2010-04-16 00:20:00 +00001676 if (TD.isBigEndian()) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001677 // On big-endian machines, the lowest bit is stored at the bit offset
1678 // from the pointer given by getTypeStoreSizeInBits. This matters for
1679 // integers with a bitwidth that is not a multiple of 8.
1680 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001681 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001682 ShAmt = Offset;
1683 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001684
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001685 // Note: we support negative bitwidths (with shr) which are not defined.
1686 // We do this to support (f.e.) stores off the end of a structure where
1687 // only some bits in the structure are set.
1688 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1689 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001690 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001691 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001692 Mask <<= ShAmt;
1693 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001694 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001695 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001696 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001697 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001698
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001699 // Mask out the bits we are about to insert from the old value, and or
1700 // in the new bits.
1701 if (SrcWidth != DestWidth) {
1702 assert(DestWidth > SrcWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +00001703 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001704 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001705 }
1706 return SV;
1707}
1708
1709
Chris Lattner79b3bd32007-04-25 06:40:51 +00001710
1711/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1712/// some part of a constant global variable. This intentionally only accepts
1713/// constant expressions because we don't can't rewrite arbitrary instructions.
1714static bool PointsToConstantGlobal(Value *V) {
1715 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1716 return GV->isConstant();
1717 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1718 if (CE->getOpcode() == Instruction::BitCast ||
1719 CE->getOpcode() == Instruction::GetElementPtr)
1720 return PointsToConstantGlobal(CE->getOperand(0));
1721 return false;
1722}
1723
1724/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1725/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1726/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1727/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1728/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1729/// the alloca, and if the source pointer is a pointer to a constant global, we
1730/// can optimize this.
Chris Lattner31d80102010-04-15 21:59:20 +00001731static bool isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Chris Lattner79b3bd32007-04-25 06:40:51 +00001732 bool isOffset) {
1733 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Gabor Greif8a8a4352010-04-06 19:32:30 +00001734 User *U = cast<Instruction>(*UI);
1735
1736 if (LoadInst *LI = dyn_cast<LoadInst>(U))
Chris Lattner6e733d32009-01-28 20:16:43 +00001737 // Ignore non-volatile loads, they are always ok.
1738 if (!LI->isVolatile())
1739 continue;
1740
Gabor Greif8a8a4352010-04-06 19:32:30 +00001741 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001742 // If uses of the bitcast are ok, we are ok.
1743 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1744 return false;
1745 continue;
1746 }
Gabor Greif8a8a4352010-04-06 19:32:30 +00001747 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
Chris Lattner79b3bd32007-04-25 06:40:51 +00001748 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1749 // doesn't, it does.
1750 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1751 isOffset || !GEP->hasAllZeroIndices()))
1752 return false;
1753 continue;
1754 }
1755
1756 // If this is isn't our memcpy/memmove, reject it as something we can't
1757 // handle.
Chris Lattner31d80102010-04-15 21:59:20 +00001758 MemTransferInst *MI = dyn_cast<MemTransferInst>(U);
1759 if (MI == 0)
Chris Lattner79b3bd32007-04-25 06:40:51 +00001760 return false;
1761
1762 // If we already have seen a copy, reject the second one.
1763 if (TheCopy) return false;
1764
1765 // If the pointer has been offset from the start of the alloca, we can't
1766 // safely handle this.
1767 if (isOffset) return false;
1768
1769 // If the memintrinsic isn't using the alloca as the dest, reject it.
Gabor Greif2ff961f2010-04-15 20:51:13 +00001770 if (UI.getOperandNo() != 0) return false;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001771
Chris Lattner79b3bd32007-04-25 06:40:51 +00001772 // If the source of the memcpy/move is not a constant global, reject it.
Chris Lattner31d80102010-04-15 21:59:20 +00001773 if (!PointsToConstantGlobal(MI->getSource()))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001774 return false;
1775
1776 // Otherwise, the transform is safe. Remember the copy instruction.
1777 TheCopy = MI;
1778 }
1779 return true;
1780}
1781
1782/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1783/// modified by a copy from a constant global. If we can prove this, we can
1784/// replace any uses of the alloca with uses of the global directly.
Chris Lattner31d80102010-04-15 21:59:20 +00001785MemTransferInst *SROA::isOnlyCopiedFromConstantGlobal(AllocaInst *AI) {
1786 MemTransferInst *TheCopy = 0;
Chris Lattner79b3bd32007-04-25 06:40:51 +00001787 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1788 return TheCopy;
1789 return 0;
1790}