blob: 4812370c9bb60eb343302f0f01feb1ef8befed2b [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 Lattnera4f0b3a2006-08-27 12:54:02 +000041#include "llvm/Support/Compiler.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000042#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000043#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000044#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000045using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000046
Chris Lattner0e5f4992006-12-19 21:40:18 +000047STATISTIC(NumReplaced, "Number of allocas broken up");
48STATISTIC(NumPromoted, "Number of allocas promoted");
49STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000050STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000051
Chris Lattner0e5f4992006-12-19 21:40:18 +000052namespace {
Chris Lattner95255282006-06-28 23:17:24 +000053 struct VISIBILITY_HIDDEN SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000054 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000055 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000056 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000057 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000058 else
59 SRThreshold = T;
60 }
Devang Patel794fd752007-05-01 21:15:47 +000061
Chris Lattnered7b41e2003-05-27 15:45:27 +000062 bool runOnFunction(Function &F);
63
Chris Lattner38aec322003-09-11 16:45:55 +000064 bool performScalarRepl(Function &F);
65 bool performPromotion(Function &F);
66
Chris Lattnera15854c2003-08-31 00:45:13 +000067 // getAnalysisUsage - This pass does not require any passes, but we know it
68 // will not alter the CFG, so say so.
69 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000070 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000071 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000072 AU.setPreservesCFG();
73 }
74
Chris Lattnered7b41e2003-05-27 15:45:27 +000075 private:
Chris Lattner56c38522009-01-07 06:34:28 +000076 TargetData *TD;
77
Chris Lattner39a1c042007-05-30 06:11:23 +000078 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
79 /// information about the uses. All these fields are initialized to false
80 /// and set to true when something is learned.
81 struct AllocaInfo {
82 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
83 bool isUnsafe : 1;
84
Devang Patel4afc90d2009-02-10 07:00:59 +000085 /// needsCleanup - This is set to true if there is some use of the alloca
86 /// that requires cleanup.
87 bool needsCleanup : 1;
Chris Lattner39a1c042007-05-30 06:11:23 +000088
89 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
90 bool isMemCpySrc : 1;
91
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000092 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000093 bool isMemCpyDst : 1;
94
95 AllocaInfo()
Devang Patel4afc90d2009-02-10 07:00:59 +000096 : isUnsafe(false), needsCleanup(false),
Chris Lattner39a1c042007-05-30 06:11:23 +000097 isMemCpySrc(false), isMemCpyDst(false) {}
98 };
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
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000104 int isSafeAllocaToScalarRepl(AllocationInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000105
106 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
107 AllocaInfo &Info);
108 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
109 AllocaInfo &Info);
110 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
111 unsigned OpNo, AllocaInfo &Info);
112 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
113 AllocaInfo &Info);
114
Chris Lattnera10b29b2007-04-25 05:02:56 +0000115 void DoScalarReplacement(AllocationInst *AI,
116 std::vector<AllocationInst*> &WorkList);
Devang Patel4afc90d2009-02-10 07:00:59 +0000117 void CleanupGEP(GetElementPtrInst *GEP);
118 void CleanupAllocaUsers(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000119 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000120
Chris Lattner8bf99112007-03-19 00:16:43 +0000121 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000122 SmallVector<AllocaInst*, 32> &NewElts);
123
Chris Lattnerd93afec2009-01-07 07:18:45 +0000124 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
125 AllocationInst *AI,
126 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000127 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
128 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000129 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000130 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000131
Chris Lattner7809ecd2009-02-03 01:30:09 +0000132 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner1a3257b2009-02-03 18:15:05 +0000133 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000134 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000135 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000136 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000137 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000138 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner79b3bd32007-04-25 06:40:51 +0000139 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000140 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000141}
142
Dan Gohman844731a2008-05-13 00:00:25 +0000143char SROA::ID = 0;
144static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
145
Brian Gaeked0fde302003-11-11 22:41:34 +0000146// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000147FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
148 return new SROA(Threshold);
149}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000150
151
Chris Lattnered7b41e2003-05-27 15:45:27 +0000152bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000153 TD = getAnalysisIfAvailable<TargetData>();
154
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000155 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000156
157 // FIXME: ScalarRepl currently depends on TargetData more than it
158 // theoretically needs to. It should be refactored in order to support
159 // target-independent IR. Until this is done, just skip the actual
160 // scalar-replacement portion of this pass.
161 if (!TD) return Changed;
162
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000163 while (1) {
164 bool LocalChange = performScalarRepl(F);
165 if (!LocalChange) break; // No need to repromote if no scalarrepl
166 Changed = true;
167 LocalChange = performPromotion(F);
168 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
169 }
Chris Lattner38aec322003-09-11 16:45:55 +0000170
171 return Changed;
172}
173
174
175bool SROA::performPromotion(Function &F) {
176 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000177 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000178 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000179
Chris Lattner02a3be02003-09-20 14:39:18 +0000180 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000181
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000182 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000183
Chris Lattner38aec322003-09-11 16:45:55 +0000184 while (1) {
185 Allocas.clear();
186
187 // Find allocas that are safe to promote, by looking at all instructions in
188 // the entry node
189 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
190 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000191 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000192 Allocas.push_back(AI);
193
194 if (Allocas.empty()) break;
195
Owen Andersone922c022009-07-22 00:24:57 +0000196 PromoteMemToReg(Allocas, DT, DF, F.getContext());
Chris Lattner38aec322003-09-11 16:45:55 +0000197 NumPromoted += Allocas.size();
198 Changed = true;
199 }
200
201 return Changed;
202}
203
Chris Lattner963a97f2008-06-22 17:46:21 +0000204/// getNumSAElements - Return the number of elements in the specific struct or
205/// array.
206static uint64_t getNumSAElements(const Type *T) {
207 if (const StructType *ST = dyn_cast<StructType>(T))
208 return ST->getNumElements();
209 return cast<ArrayType>(T)->getNumElements();
210}
211
Chris Lattner38aec322003-09-11 16:45:55 +0000212// performScalarRepl - This algorithm is a simple worklist driven algorithm,
213// which runs on all of the malloc/alloca instructions in the function, removing
214// them if they are only used by getelementptr instructions.
215//
216bool SROA::performScalarRepl(Function &F) {
Chris Lattnered7b41e2003-05-27 15:45:27 +0000217 std::vector<AllocationInst*> WorkList;
218
219 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000220 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000221 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
222 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
223 WorkList.push_back(A);
224
225 // Process the worklist
226 bool Changed = false;
227 while (!WorkList.empty()) {
228 AllocationInst *AI = WorkList.back();
229 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000230
Chris Lattneradd2bd72006-12-22 23:14:42 +0000231 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
232 // with unused elements.
233 if (AI->use_empty()) {
234 AI->eraseFromParent();
235 continue;
236 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000237
238 // If this alloca is impossible for us to promote, reject it early.
239 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
240 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000241
242 // Check to see if this allocation is only modified by a memcpy/memmove from
243 // a constant global. If this is the case, we can change all users to use
244 // the constant global instead. This is commonly produced by the CFE by
245 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
246 // is only subsequently read.
247 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000248 DEBUG(errs() << "Found alloca equal to global: " << *AI);
249 DEBUG(errs() << " memcpy = " << *TheCopy);
Chris Lattner79b3bd32007-04-25 06:40:51 +0000250 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000251 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000252 TheCopy->eraseFromParent(); // Don't mutate the global.
253 AI->eraseFromParent();
254 ++NumGlobals;
255 Changed = true;
256 continue;
257 }
Chris Lattner15c82772009-02-02 20:44:45 +0000258
Chris Lattner7809ecd2009-02-03 01:30:09 +0000259 // Check to see if we can perform the core SROA transformation. We cannot
260 // transform the allocation instruction if it is an array allocation
261 // (allocations OF arrays are ok though), and an allocation of a scalar
262 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000263 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000264
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000265 // Do not promote [0 x %struct].
266 if (AllocaSize == 0) continue;
267
Bill Wendling5a377cb2009-03-03 12:12:58 +0000268 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000269 if (AllocaSize > SRThreshold) continue;
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000270
Chris Lattner7809ecd2009-02-03 01:30:09 +0000271 if ((isa<StructType>(AI->getAllocatedType()) ||
272 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner7809ecd2009-02-03 01:30:09 +0000273 // Do not promote any struct into more than "32" separate vars.
Evan Cheng67fca632009-03-06 00:56:43 +0000274 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000275 // Check that all of the users of the allocation are capable of being
276 // transformed.
277 switch (isSafeAllocaToScalarRepl(AI)) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000278 default: llvm_unreachable("Unexpected value!");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000279 case 0: // Not safe to scalar replace.
280 break;
281 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel4afc90d2009-02-10 07:00:59 +0000282 CleanupAllocaUsers(AI);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000283 // FALL THROUGH.
284 case 3: // Safe to scalar replace.
285 DoScalarReplacement(AI, WorkList);
286 Changed = true;
287 continue;
288 }
289 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000290
291 // If we can turn this aggregate value (potentially with casts) into a
292 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000293 // IsNotTrivial tracks whether this is something that mem2reg could have
294 // promoted itself. If so, we don't want to transform it needlessly. Note
295 // that we can't just check based on the type: the alloca may be of an i32
296 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000297 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000298 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000299 bool HadAVector = false;
300 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000301 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000302 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000303 // If we were able to find a vector type that can handle this with
304 // insert/extract elements, and if there was at least one use that had
305 // a vector type, promote this to a vector. We don't want to promote
306 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
307 // we just get a lot of insert/extracts. If at least one vector is
308 // involved, then we probably really do have a union of vector/array.
309 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000310 DEBUG(errs() << "CONVERT TO VECTOR: " << *AI << " TYPE = "
311 << *VectorTy << '\n');
Chris Lattner15c82772009-02-02 20:44:45 +0000312
Chris Lattner7809ecd2009-02-03 01:30:09 +0000313 // Create and insert the vector alloca.
Owen Anderson50dead02009-07-15 23:53:25 +0000314 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000315 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000316 } else {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000317 DEBUG(errs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000318
319 // Create and insert the integer alloca.
Owen Anderson1d0be152009-08-13 21:58:54 +0000320 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
Owen Anderson50dead02009-07-15 23:53:25 +0000321 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattner7809ecd2009-02-03 01:30:09 +0000322 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000323 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000324 NewAI->takeName(AI);
325 AI->eraseFromParent();
326 ++NumConverted;
327 Changed = true;
328 continue;
329 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000330
Chris Lattner7809ecd2009-02-03 01:30:09 +0000331 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000332 }
333
334 return Changed;
335}
Chris Lattner5e062a12003-05-30 04:15:41 +0000336
Chris Lattnera10b29b2007-04-25 05:02:56 +0000337/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
338/// predicate, do SROA now.
339void SROA::DoScalarReplacement(AllocationInst *AI,
340 std::vector<AllocationInst*> &WorkList) {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000341 DEBUG(errs() << "Found inst to SROA: " << *AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000342 SmallVector<AllocaInst*, 32> ElementAllocas;
343 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
344 ElementAllocas.reserve(ST->getNumContainedTypes());
345 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000346 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000347 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000348 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000349 ElementAllocas.push_back(NA);
350 WorkList.push_back(NA); // Add to worklist for recursive processing
351 }
352 } else {
353 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
354 ElementAllocas.reserve(AT->getNumElements());
355 const Type *ElTy = AT->getElementType();
356 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000357 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000358 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000359 ElementAllocas.push_back(NA);
360 WorkList.push_back(NA); // Add to worklist for recursive processing
361 }
362 }
363
364 // Now that we have created the alloca instructions that we want to use,
365 // expand the getelementptr instructions to use them.
366 //
367 while (!AI->use_empty()) {
368 Instruction *User = cast<Instruction>(AI->use_back());
369 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
370 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
371 BCInst->eraseFromParent();
372 continue;
373 }
374
Chris Lattner2a6a6452008-06-23 17:11:23 +0000375 // Replace:
376 // %res = load { i32, i32 }* %alloc
377 // with:
378 // %load.0 = load i32* %alloc.0
379 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
380 // %load.1 = load i32* %alloc.1
381 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000382 // (Also works for arrays instead of structs)
383 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000384 Value *Insert = UndefValue::get(LI->getType());
Matthijs Kooijman02518142008-06-05 12:51:53 +0000385 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
386 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
387 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
388 }
389 LI->replaceAllUsesWith(Insert);
390 LI->eraseFromParent();
391 continue;
392 }
393
Chris Lattner2a6a6452008-06-23 17:11:23 +0000394 // Replace:
395 // store { i32, i32 } %val, { i32, i32 }* %alloc
396 // with:
397 // %val.0 = extractvalue { i32, i32 } %val, 0
398 // store i32 %val.0, i32* %alloc.0
399 // %val.1 = extractvalue { i32, i32 } %val, 1
400 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000401 // (Also works for arrays instead of structs)
402 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
403 Value *Val = SI->getOperand(0);
404 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
405 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
406 new StoreInst(Extract, ElementAllocas[i], SI);
407 }
408 SI->eraseFromParent();
409 continue;
410 }
411
Chris Lattnera10b29b2007-04-25 05:02:56 +0000412 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
413 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
414 unsigned Idx =
415 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
416
417 assert(Idx < ElementAllocas.size() && "Index out of range?");
418 AllocaInst *AllocaToUse = ElementAllocas[Idx];
419
420 Value *RepValue;
421 if (GEPI->getNumOperands() == 3) {
422 // Do not insert a new getelementptr instruction with zero indices, only
423 // to have it optimized out later.
424 RepValue = AllocaToUse;
425 } else {
426 // We are indexing deeply into the structure, so we still need a
427 // getelement ptr instruction to finish the indexing. This may be
428 // expanded itself once the worklist is rerun.
429 //
430 SmallVector<Value*, 8> NewArgs;
Owen Anderson1d0be152009-08-13 21:58:54 +0000431 NewArgs.push_back(Constant::getNullValue(
432 Type::getInt32Ty(AI->getContext())));
Chris Lattnera10b29b2007-04-25 05:02:56 +0000433 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +0000434 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
435 NewArgs.end(), "", GEPI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000436 RepValue->takeName(GEPI);
437 }
438
439 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000440 if (Idx == 0 && GEPI->hasAllZeroIndices())
441 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000442
443 // Move all of the users over to the new GEP.
444 GEPI->replaceAllUsesWith(RepValue);
445 // Delete the old GEP
446 GEPI->eraseFromParent();
447 }
448
449 // Finally, delete the Alloca instruction
450 AI->eraseFromParent();
451 NumReplaced++;
452}
453
Chris Lattner5e062a12003-05-30 04:15:41 +0000454
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000455/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner8bf99112007-03-19 00:16:43 +0000456/// getelementptr instruction of an array aggregate allocation. isFirstElt
457/// indicates whether Ptr is known to the start of the aggregate.
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000458///
Chris Lattner39a1c042007-05-30 06:11:23 +0000459void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
460 AllocaInfo &Info) {
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000461 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
462 I != E; ++I) {
463 Instruction *User = cast<Instruction>(*I);
464 switch (User->getOpcode()) {
465 case Instruction::Load: break;
466 case Instruction::Store:
467 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattner39a1c042007-05-30 06:11:23 +0000468 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000469 break;
470 case Instruction::GetElementPtr: {
471 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
Chris Lattner8bf99112007-03-19 00:16:43 +0000472 bool AreAllZeroIndices = isFirstElt;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000473 if (GEP->getNumOperands() > 1) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000474 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
475 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
Chris Lattner39a1c042007-05-30 06:11:23 +0000476 // Using pointer arithmetic to navigate the array.
477 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000478
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000479 if (AreAllZeroIndices)
480 AreAllZeroIndices = GEP->hasAllZeroIndices();
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000481 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000482 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
483 if (Info.isUnsafe) return;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000484 break;
485 }
Chris Lattner8bf99112007-03-19 00:16:43 +0000486 case Instruction::BitCast:
Chris Lattner39a1c042007-05-30 06:11:23 +0000487 if (isFirstElt) {
488 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
489 if (Info.isUnsafe) return;
Chris Lattner8bf99112007-03-19 00:16:43 +0000490 break;
Chris Lattner8bf99112007-03-19 00:16:43 +0000491 }
Chris Lattnerbdff5482009-08-23 04:37:46 +0000492 DEBUG(errs() << " Transformation preventing inst: " << *User);
Chris Lattner39a1c042007-05-30 06:11:23 +0000493 return MarkUnsafe(Info);
494 case Instruction::Call:
495 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
496 if (isFirstElt) {
497 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
498 if (Info.isUnsafe) return;
499 break;
500 }
501 }
Chris Lattnerbdff5482009-08-23 04:37:46 +0000502 DEBUG(errs() << " Transformation preventing inst: " << *User);
Chris Lattner39a1c042007-05-30 06:11:23 +0000503 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000504 default:
Chris Lattnerbdff5482009-08-23 04:37:46 +0000505 DEBUG(errs() << " Transformation preventing inst: " << *User);
Chris Lattner39a1c042007-05-30 06:11:23 +0000506 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000507 }
508 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000509 return; // All users look ok :)
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000510}
511
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000512/// AllUsersAreLoads - Return true if all users of this value are loads.
513static bool AllUsersAreLoads(Value *Ptr) {
514 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
515 I != E; ++I)
516 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
517 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000518 return true;
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000519}
520
Chris Lattner5e062a12003-05-30 04:15:41 +0000521/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
522/// aggregate allocation.
523///
Chris Lattner39a1c042007-05-30 06:11:23 +0000524void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
525 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000526 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
Chris Lattner39a1c042007-05-30 06:11:23 +0000527 return isSafeUseOfBitCastedAllocation(C, AI, Info);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000528
Chris Lattner6e733d32009-01-28 20:16:43 +0000529 if (LoadInst *LI = dyn_cast<LoadInst>(User))
530 if (!LI->isVolatile())
531 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman02518142008-06-05 12:51:53 +0000532
Chris Lattner6e733d32009-01-28 20:16:43 +0000533 if (StoreInst *SI = dyn_cast<StoreInst>(User))
534 if (!SI->isVolatile() && SI->getOperand(0) != AI)
535 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman02518142008-06-05 12:51:53 +0000536
Chris Lattner39a1c042007-05-30 06:11:23 +0000537 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
538 if (GEPI == 0)
539 return MarkUnsafe(Info);
540
Chris Lattnerbe883a22003-11-25 21:09:18 +0000541 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
542
Chris Lattner25de4862006-03-08 01:05:29 +0000543 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattnerbe883a22003-11-25 21:09:18 +0000544 if (I == E ||
Owen Andersona7235ea2009-07-31 20:28:14 +0000545 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000546 return MarkUnsafe(Info);
547 }
Chris Lattnerbe883a22003-11-25 21:09:18 +0000548
549 ++I;
Chris Lattner39a1c042007-05-30 06:11:23 +0000550 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
Chris Lattnerbe883a22003-11-25 21:09:18 +0000551
Chris Lattner8bf99112007-03-19 00:16:43 +0000552 bool IsAllZeroIndices = true;
553
Chris Lattner88e6dc82008-08-23 05:21:06 +0000554 // If the first index is a non-constant index into an array, see if we can
555 // handle it as a special case.
Chris Lattnerbe883a22003-11-25 21:09:18 +0000556 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000557 if (!isa<ConstantInt>(I.getOperand())) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000558 IsAllZeroIndices = 0;
Chris Lattner88e6dc82008-08-23 05:21:06 +0000559 uint64_t NumElements = AT->getNumElements();
Chris Lattner8bf99112007-03-19 00:16:43 +0000560
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000561 // If this is an array index and the index is not constant, we cannot
562 // promote... that is unless the array has exactly one or two elements in
563 // it, in which case we CAN promote it, but we have to canonicalize this
564 // out if this is the only problem.
Chris Lattner25de4862006-03-08 01:05:29 +0000565 if ((NumElements == 1 || NumElements == 2) &&
Chris Lattner39a1c042007-05-30 06:11:23 +0000566 AllUsersAreLoads(GEPI)) {
Devang Patel4afc90d2009-02-10 07:00:59 +0000567 Info.needsCleanup = true;
Chris Lattner39a1c042007-05-30 06:11:23 +0000568 return; // Canonicalization required!
569 }
570 return MarkUnsafe(Info);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000571 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000572 }
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000573
Chris Lattner88e6dc82008-08-23 05:21:06 +0000574 // Walk through the GEP type indices, checking the types that this indexes
575 // into.
576 for (; I != E; ++I) {
577 // Ignore struct elements, no extra checking needed for these.
578 if (isa<StructType>(*I))
579 continue;
580
Chris Lattner88e6dc82008-08-23 05:21:06 +0000581 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
582 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000583
584 // Are all indices still zero?
Chris Lattner88e6dc82008-08-23 05:21:06 +0000585 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000586
587 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
588 // This GEP indexes an array. Verify that this is an in-range constant
589 // integer. Specifically, consider A[0][i]. We cannot know that the user
590 // isn't doing invalid things like allowing i to index an out-of-range
591 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000592 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000593 if (IdxVal->getZExtValue() >= AT->getNumElements())
594 return MarkUnsafe(Info);
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000595 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
596 if (IdxVal->getZExtValue() >= VT->getNumElements())
597 return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000598 }
Chris Lattner88e6dc82008-08-23 05:21:06 +0000599 }
600
Chris Lattnerbe883a22003-11-25 21:09:18 +0000601 // If there are any non-simple uses of this getelementptr, make sure to reject
602 // them.
Chris Lattner39a1c042007-05-30 06:11:23 +0000603 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000604}
605
606/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
607/// intrinsic can be promoted by SROA. At this point, we know that the operand
608/// of the memintrinsic is a pointer to the beginning of the allocation.
Chris Lattner39a1c042007-05-30 06:11:23 +0000609void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
610 unsigned OpNo, AllocaInfo &Info) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000611 // If not constant length, give up.
612 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattner39a1c042007-05-30 06:11:23 +0000613 if (!Length) return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000614
615 // If not the whole aggregate, give up.
Duncan Sands3cb36502007-11-04 14:43:57 +0000616 if (Length->getZExtValue() !=
Duncan Sands777d2302009-05-09 07:06:46 +0000617 TD->getTypeAllocSize(AI->getType()->getElementType()))
Chris Lattner39a1c042007-05-30 06:11:23 +0000618 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000619
620 // We only know about memcpy/memset/memmove.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000621 if (!isa<MemIntrinsic>(MI))
Chris Lattner39a1c042007-05-30 06:11:23 +0000622 return MarkUnsafe(Info);
623
624 // Otherwise, we can transform it. Determine whether this is a memcpy/set
625 // into or out of the aggregate.
626 if (OpNo == 1)
627 Info.isMemCpyDst = true;
628 else {
629 assert(OpNo == 2);
630 Info.isMemCpySrc = true;
631 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000632}
633
Chris Lattner372dda82007-03-05 07:52:57 +0000634/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
635/// are
Chris Lattner39a1c042007-05-30 06:11:23 +0000636void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
637 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000638 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
639 UI != E; ++UI) {
640 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000641 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000642 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000643 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000644 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000645 if (SI->isVolatile())
646 return MarkUnsafe(Info);
647
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000648 // If storing the entire alloca in one chunk through a bitcasted pointer
649 // to integer, we can transform it. This happens (for example) when you
650 // cast a {i32,i32}* to i64* and store through it. This is similar to the
651 // memcpy case and occurs in various "byval" cases and emulated memcpys.
652 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000653 TD->getTypeAllocSize(SI->getOperand(0)->getType()) ==
654 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000655 Info.isMemCpyDst = true;
656 continue;
657 }
658 return MarkUnsafe(Info);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000659 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000660 if (LI->isVolatile())
661 return MarkUnsafe(Info);
662
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000663 // If loading the entire alloca in one chunk through a bitcasted pointer
664 // to integer, we can transform it. This happens (for example) when you
665 // cast a {i32,i32}* to i64* and load through it. This is similar to the
666 // memcpy case and occurs in various "byval" cases and emulated memcpys.
667 if (isa<IntegerType>(LI->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000668 TD->getTypeAllocSize(LI->getType()) ==
669 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000670 Info.isMemCpySrc = true;
671 continue;
672 }
673 return MarkUnsafe(Info);
Devang Patel4afc90d2009-02-10 07:00:59 +0000674 } else if (isa<DbgInfoIntrinsic>(UI)) {
675 // If one user is DbgInfoIntrinsic then check if all users are
676 // DbgInfoIntrinsics.
677 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
678 Info.needsCleanup = true;
679 return;
680 }
681 else
682 MarkUnsafe(Info);
683 }
684 else {
Chris Lattner39a1c042007-05-30 06:11:23 +0000685 return MarkUnsafe(Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000686 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000687 if (Info.isUnsafe) return;
Chris Lattner372dda82007-03-05 07:52:57 +0000688 }
Chris Lattner372dda82007-03-05 07:52:57 +0000689}
690
Chris Lattner8bf99112007-03-19 00:16:43 +0000691/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
692/// to its first element. Transform users of the cast to use the new values
693/// instead.
694void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000695 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000696 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
697 while (UI != UE) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000698 Instruction *User = cast<Instruction>(*UI++);
699 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Chris Lattner372dda82007-03-05 07:52:57 +0000700 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000701 if (BCU->use_empty()) BCU->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000702 continue;
703 }
704
Chris Lattnerd93afec2009-01-07 07:18:45 +0000705 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
706 // This must be memcpy/memmove/memset of the entire aggregate.
707 // Split into one per element.
708 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Chris Lattner8bf99112007-03-19 00:16:43 +0000709 continue;
710 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000711
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000712 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000713 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000714 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
715 continue;
716 }
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000717
718 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
719 // If this is a load of the entire alloca to an integer, rewrite it.
720 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
721 continue;
722 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000723
724 // Otherwise it must be some other user of a gep of the first pointer. Just
725 // leave these alone.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000726 continue;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000727 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000728}
729
730/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
731/// Rewrite it to copy or set the elements of the scalarized memory.
732void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
733 AllocationInst *AI,
734 SmallVector<AllocaInst*, 32> &NewElts) {
735
736 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000737 // appropriate type. The "Other" pointer is the pointer that goes to memory
738 // that doesn't have anything to do with the alloca that we are promoting. For
739 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000740 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +0000741 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000742 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000743 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
744 if (BCInst == MTI->getRawDest())
745 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000746 else {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000747 assert(BCInst == MTI->getRawSource());
748 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000749 }
750 }
751
752 // If there is an other pointer, we want to convert it to the same pointer
753 // type as AI has, so we can GEP through it safely.
754 if (OtherPtr) {
755 // It is likely that OtherPtr is a bitcast, if so, remove it.
756 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
757 OtherPtr = BC->getOperand(0);
758 // All zero GEPs are effectively bitcasts.
759 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
760 if (GEP->hasAllZeroIndices())
761 OtherPtr = GEP->getOperand(0);
Chris Lattner372dda82007-03-05 07:52:57 +0000762
Chris Lattnerd93afec2009-01-07 07:18:45 +0000763 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
764 if (BCE->getOpcode() == Instruction::BitCast)
765 OtherPtr = BCE->getOperand(0);
766
767 // If the pointer is not the right type, insert a bitcast to the right
768 // type.
769 if (OtherPtr->getType() != AI->getType())
770 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
771 MI);
772 }
773
774 // Process each element of the aggregate.
775 Value *TheFn = MI->getOperand(0);
776 const Type *BytePtrTy = MI->getRawDest()->getType();
777 bool SROADest = MI->getRawDest() == BCInst;
778
Owen Anderson1d0be152009-08-13 21:58:54 +0000779 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +0000780
781 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
782 // If this is a memcpy/memmove, emit a GEP of the other element address.
783 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000784 unsigned OtherEltAlign = MemAlignment;
785
Chris Lattner372dda82007-03-05 07:52:57 +0000786 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000787 Value *Idx[2] = { Zero,
788 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Chris Lattnerd93afec2009-01-07 07:18:45 +0000789 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000790 OtherPtr->getNameStr()+"."+Twine(i),
Chris Lattnerd93afec2009-01-07 07:18:45 +0000791 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000792 uint64_t EltOffset;
793 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
794 if (const StructType *ST =
795 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
796 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
797 } else {
798 const Type *EltTy =
799 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000800 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000801 }
802
803 // The alignment of the other pointer is the guaranteed alignment of the
804 // element, which is affected by both the known alignment of the whole
805 // mem intrinsic and the alignment of the element. If the alignment of
806 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
807 // known alignment is just 4 bytes.
808 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000809 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000810
811 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000812 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000813
814 // If we got down to a scalar, insert a load or store as appropriate.
815 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000816 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000817 if (SROADest) {
818 // From Other to Alloca.
819 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
820 new StoreInst(Elt, EltPtr, MI);
821 } else {
822 // From Alloca to Other.
823 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
824 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
825 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000826 continue;
827 }
828 assert(isa<MemSetInst>(MI));
829
830 // If the stored element is zero (common case), just store a null
831 // constant.
832 Constant *StoreVal;
833 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
834 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000835 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000836 } else {
837 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000838 const Type *ValTy = EltTy->getScalarType();
839
Chris Lattnerd93afec2009-01-07 07:18:45 +0000840 // Construct an integer with the right value.
841 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
842 APInt OneVal(EltSize, CI->getZExtValue());
843 APInt TotalVal(OneVal);
844 // Set each byte.
845 for (unsigned i = 0; 8*i < EltSize; ++i) {
846 TotalVal = TotalVal.shl(8);
847 TotalVal |= OneVal;
848 }
849
850 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +0000851 StoreVal = ConstantInt::get(Context, TotalVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000852 if (isa<PointerType>(ValTy))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000853 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000854 else if (ValTy->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000855 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000856 assert(StoreVal->getType() == ValTy && "Type mismatch!");
857
858 // If the requested value was a vector constant, create it.
859 if (EltTy != ValTy) {
860 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
861 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000862 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000863 }
864 }
865 new StoreInst(StoreVal, EltPtr, MI);
866 continue;
867 }
868 // Otherwise, if we're storing a byte variable, use a memset call for
869 // this element.
870 }
871
872 // Cast the element pointer to BytePtrTy.
873 if (EltPtr->getType() != BytePtrTy)
874 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
875
876 // Cast the other pointer (if we have one) to BytePtrTy.
877 if (OtherElt && OtherElt->getType() != BytePtrTy)
878 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
879 MI);
880
Duncan Sands777d2302009-05-09 07:06:46 +0000881 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000882
883 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000884 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000885 Value *Ops[] = {
886 SROADest ? EltPtr : OtherElt, // Dest ptr
887 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersoneed707b2009-07-24 23:12:02 +0000888 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +0000889 // Align
890 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
Chris Lattnerd93afec2009-01-07 07:18:45 +0000891 };
892 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
893 } else {
894 assert(isa<MemSetInst>(MI));
895 Value *Ops[] = {
896 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersoneed707b2009-07-24 23:12:02 +0000897 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000898 Zero // Align
899 };
900 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
901 }
Chris Lattner372dda82007-03-05 07:52:57 +0000902 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000903 MI->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000904}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000905
906/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
907/// overwrites the entire allocation. Extract out the pieces of the stored
908/// integer and store them individually.
909void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
910 AllocationInst *AI,
911 SmallVector<AllocaInst*, 32> &NewElts){
912 // Extract each element out of the integer according to its structure offset
913 // and store the element value to the individual alloca.
914 Value *SrcVal = SI->getOperand(0);
915 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000916 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000917
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000918 // If this isn't a store of an integer to the whole alloca, it may be a store
919 // to the first element. Just ignore the store in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +0000920 // will handle it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000921 if (!isa<IntegerType>(SrcVal->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +0000922 TD->getTypeAllocSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000923 return;
Eli Friedman41b33f42009-06-01 09:14:32 +0000924 // Handle tail padding by extending the operand
925 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000926 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000927 IntegerType::get(SI->getContext(), AllocaSizeBits),
928 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000929
Chris Lattnerbdff5482009-08-23 04:37:46 +0000930 DEBUG(errs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000931
932 // There are two forms here: AI could be an array or struct. Both cases
933 // have different ways to compute the element offset.
934 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
935 const StructLayout *Layout = TD->getStructLayout(EltSTy);
936
937 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
938 // Get the number of bits to shift SrcVal to get the value.
939 const Type *FieldTy = EltSTy->getElementType(i);
940 uint64_t Shift = Layout->getElementOffsetInBits(i);
941
942 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000943 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000944
945 Value *EltVal = SrcVal;
946 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000947 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000948 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
949 "sroa.store.elt", SI);
950 }
951
952 // Truncate down to an integer of the right size.
953 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000954
955 // Ignore zero sized fields like {}, they obviously contain no data.
956 if (FieldSizeBits == 0) continue;
957
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000958 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000959 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000960 IntegerType::get(SI->getContext(), FieldSizeBits),
961 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000962 Value *DestField = NewElts[i];
963 if (EltVal->getType() == FieldTy) {
964 // Storing to an integer field of this size, just do it.
965 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
966 // Bitcast to the right element type (for fp/vector values).
967 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
968 } else {
969 // Otherwise, bitcast the dest pointer (for aggregates).
970 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +0000971 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000972 "", SI);
973 }
974 new StoreInst(EltVal, DestField, SI);
975 }
976
977 } else {
978 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
979 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000980 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000981 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
982
983 uint64_t Shift;
984
985 if (TD->isBigEndian())
986 Shift = AllocaSizeBits-ElementOffset;
987 else
988 Shift = 0;
989
990 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +0000991 // Ignore zero sized fields like {}, they obviously contain no data.
992 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000993
994 Value *EltVal = SrcVal;
995 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +0000996 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000997 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
998 "sroa.store.elt", SI);
999 }
1000
1001 // Truncate down to an integer of the right size.
1002 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001003 EltVal = new TruncInst(EltVal,
Owen Anderson1d0be152009-08-13 21:58:54 +00001004 IntegerType::get(SI->getContext(),
1005 ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001006 Value *DestField = NewElts[i];
1007 if (EltVal->getType() == ArrayEltTy) {
1008 // Storing to an integer field of this size, just do it.
1009 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
1010 // Bitcast to the right element type (for fp/vector values).
1011 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
1012 } else {
1013 // Otherwise, bitcast the dest pointer (for aggregates).
1014 DestField = new BitCastInst(DestField,
Owen Andersondebcb012009-07-29 22:17:13 +00001015 PointerType::getUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +00001016 "", SI);
1017 }
1018 new StoreInst(EltVal, DestField, SI);
1019
1020 if (TD->isBigEndian())
1021 Shift -= ElementOffset;
1022 else
1023 Shift += ElementOffset;
1024 }
1025 }
1026
1027 SI->eraseFromParent();
1028}
1029
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001030/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
1031/// an integer. Load the individual pieces to form the aggregate value.
1032void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
1033 SmallVector<AllocaInst*, 32> &NewElts) {
1034 // Extract each element out of the NewElts according to its structure offset
1035 // and form the result value.
1036 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001037 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001038
1039 // If this isn't a load of the whole alloca to an integer, it may be a load
1040 // of the first element. Just ignore the load in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +00001041 // will handle it.
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001042 if (!isa<IntegerType>(LI->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +00001043 TD->getTypeAllocSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001044 return;
1045
Chris Lattnerbdff5482009-08-23 04:37:46 +00001046 DEBUG(errs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001047
1048 // There are two forms here: AI could be an array or struct. Both cases
1049 // have different ways to compute the element offset.
1050 const StructLayout *Layout = 0;
1051 uint64_t ArrayEltBitOffset = 0;
1052 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1053 Layout = TD->getStructLayout(EltSTy);
1054 } else {
1055 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001056 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001057 }
Owen Andersone922c022009-07-22 00:24:57 +00001058
Owen Andersone922c022009-07-22 00:24:57 +00001059 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001060 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001061
1062 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1063 // Load the value from the alloca. If the NewElt is an aggregate, cast
1064 // the pointer to an integer of the same size before doing the load.
1065 Value *SrcField = NewElts[i];
1066 const Type *FieldTy =
1067 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001068 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1069
1070 // Ignore zero sized fields like {}, they obviously contain no data.
1071 if (FieldSizeBits == 0) continue;
1072
Owen Anderson1d0be152009-08-13 21:58:54 +00001073 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1074 FieldSizeBits);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001075 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1076 !isa<VectorType>(FieldTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001077 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001078 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001079 "", LI);
1080 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1081
1082 // If SrcField is a fp or vector of the right size but that isn't an
1083 // integer type, bitcast to an integer so we can shift it.
1084 if (SrcField->getType() != FieldIntTy)
1085 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1086
1087 // Zero extend the field to be the same size as the final alloca so that
1088 // we can shift and insert it.
1089 if (SrcField->getType() != ResultVal->getType())
1090 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1091
1092 // Determine the number of bits to shift SrcField.
1093 uint64_t Shift;
1094 if (Layout) // Struct case.
1095 Shift = Layout->getElementOffsetInBits(i);
1096 else // Array case.
1097 Shift = i*ArrayEltBitOffset;
1098
1099 if (TD->isBigEndian())
1100 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1101
1102 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001103 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001104 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1105 }
1106
1107 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1108 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001109
1110 // Handle tail padding by truncating the result
1111 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1112 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1113
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001114 LI->replaceAllUsesWith(ResultVal);
1115 LI->eraseFromParent();
1116}
1117
Chris Lattner372dda82007-03-05 07:52:57 +00001118
Duncan Sands3cb36502007-11-04 14:43:57 +00001119/// HasPadding - Return true if the specified type has any structure or
1120/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001121static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001122 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1123 const StructLayout *SL = TD.getStructLayout(STy);
1124 unsigned PrevFieldBitOffset = 0;
1125 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001126 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1127
Chris Lattner39a1c042007-05-30 06:11:23 +00001128 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001129 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001130 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001131
Chris Lattner39a1c042007-05-30 06:11:23 +00001132 // Check to see if there is any padding between this element and the
1133 // previous one.
1134 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001135 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001136 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1137 if (PrevFieldEnd < FieldBitOffset)
1138 return true;
1139 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001140
Chris Lattner39a1c042007-05-30 06:11:23 +00001141 PrevFieldBitOffset = FieldBitOffset;
1142 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001143
Chris Lattner39a1c042007-05-30 06:11:23 +00001144 // Check for tail padding.
1145 if (unsigned EltCount = STy->getNumElements()) {
1146 unsigned PrevFieldEnd = PrevFieldBitOffset +
1147 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001148 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001149 return true;
1150 }
1151
1152 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001153 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001154 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001155 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001156 }
Duncan Sands777d2302009-05-09 07:06:46 +00001157 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001158}
Chris Lattner372dda82007-03-05 07:52:57 +00001159
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001160/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1161/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1162/// or 1 if safe after canonicalization has been performed.
Chris Lattner5e062a12003-05-30 04:15:41 +00001163///
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001164int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001165 // Loop over the use list of the alloca. We can only transform it if all of
1166 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001167 AllocaInfo Info;
1168
Chris Lattner5e062a12003-05-30 04:15:41 +00001169 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001170 I != E; ++I) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001171 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1172 if (Info.isUnsafe) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00001173 DEBUG(errs() << "Cannot transform: " << *AI << " due to user: " << **I);
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001174 return 0;
Chris Lattner5e062a12003-05-30 04:15:41 +00001175 }
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001176 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001177
1178 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1179 // source and destination, we have to be careful. In particular, the memcpy
1180 // could be moving around elements that live in structure padding of the LLVM
1181 // types, but may actually be used. In these cases, we refuse to promote the
1182 // struct.
1183 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner56c38522009-01-07 06:34:28 +00001184 HasPadding(AI->getType()->getElementType(), *TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001185 return 0;
Duncan Sands3cb36502007-11-04 14:43:57 +00001186
Chris Lattner39a1c042007-05-30 06:11:23 +00001187 // If we require cleanup, return 1, otherwise return 3.
Devang Patel4afc90d2009-02-10 07:00:59 +00001188 return Info.needsCleanup ? 1 : 3;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001189}
1190
Devang Patel4afc90d2009-02-10 07:00:59 +00001191/// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1192/// is canonicalized here.
1193void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1194 gep_type_iterator I = gep_type_begin(GEPI);
1195 ++I;
1196
Devang Patel7afe8fa2009-02-10 19:28:07 +00001197 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1198 if (!AT)
1199 return;
1200
1201 uint64_t NumElements = AT->getNumElements();
1202
1203 if (isa<ConstantInt>(I.getOperand()))
1204 return;
1205
1206 if (NumElements == 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001207 GEPI->setOperand(2,
1208 Constant::getNullValue(Type::getInt32Ty(GEPI->getContext())));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001209 return;
1210 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001211
Devang Patel7afe8fa2009-02-10 19:28:07 +00001212 assert(NumElements == 2 && "Unhandled case!");
1213 // All users of the GEP must be loads. At each use of the GEP, insert
1214 // two loads of the appropriate indexed GEP and select between them.
Owen Anderson333c4002009-07-09 23:48:35 +00001215 Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(),
Owen Andersona7235ea2009-07-31 20:28:14 +00001216 Constant::getNullValue(I.getOperand()->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001217 "isone");
Devang Patel7afe8fa2009-02-10 19:28:07 +00001218 // Insert the new GEP instructions, which are properly indexed.
1219 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Owen Anderson1d0be152009-08-13 21:58:54 +00001220 Indices[1] = Constant::getNullValue(Type::getInt32Ty(GEPI->getContext()));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001221 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1222 Indices.begin(),
1223 Indices.end(),
1224 GEPI->getName()+".0", GEPI);
Owen Anderson1d0be152009-08-13 21:58:54 +00001225 Indices[1] = ConstantInt::get(Type::getInt32Ty(GEPI->getContext()), 1);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001226 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1227 Indices.begin(),
1228 Indices.end(),
1229 GEPI->getName()+".1", GEPI);
1230 // Replace all loads of the variable index GEP with loads from both
1231 // indexes and a select.
1232 while (!GEPI->use_empty()) {
1233 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1234 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1235 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1236 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1237 LI->replaceAllUsesWith(R);
1238 LI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001239 }
Devang Patel7afe8fa2009-02-10 19:28:07 +00001240 GEPI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001241}
1242
Devang Patel7afe8fa2009-02-10 19:28:07 +00001243
Devang Patel4afc90d2009-02-10 07:00:59 +00001244/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001245/// allocation, but only if cleaned up, perform the cleanups required.
Devang Patel4afc90d2009-02-10 07:00:59 +00001246void SROA::CleanupAllocaUsers(AllocationInst *AI) {
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001247 // At this point, we know that the end result will be SROA'd and promoted, so
1248 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1249 // up.
1250 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1251 UI != E; ) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001252 User *U = *UI++;
1253 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1254 CleanupGEP(GEPI);
Jay Foad0906b1b2009-06-06 17:49:35 +00001255 else {
1256 Instruction *I = cast<Instruction>(U);
Devang Patel4afc90d2009-02-10 07:00:59 +00001257 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
Zhou Shengb0c41992009-03-18 12:48:48 +00001258 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001259 // Safe to remove debug info uses.
1260 while (!DbgInUses.empty()) {
1261 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1262 DI->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001263 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001264 I->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001265 }
1266 }
1267 }
Chris Lattner5e062a12003-05-30 04:15:41 +00001268}
Chris Lattnera1888942005-12-12 07:19:13 +00001269
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001270/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1271/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001272///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001273/// There are two cases we handle here:
1274/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001275/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001276/// This promotes a <4 x float> with a store of float to the third element
1277/// into a <4 x float> that uses insert element.
1278/// 2) A fully general blob of memory, which we turn into some (potentially
1279/// large) integer type with extract and insert operations where the loads
1280/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001281static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001282 unsigned AllocaSize, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +00001283 LLVMContext &Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001284 // If this could be contributing to a vector, analyze it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001285 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001286
Chris Lattner7809ecd2009-02-03 01:30:09 +00001287 // If the In type is a vector that is the same size as the alloca, see if it
1288 // matches the existing VecTy.
1289 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1290 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1291 // If we're storing/loading a vector of the right size, allow it as a
1292 // vector. If this the first vector we see, remember the type so that
1293 // we know the element size.
1294 if (VecTy == 0)
1295 VecTy = VInTy;
1296 return;
1297 }
Owen Anderson1d0be152009-08-13 21:58:54 +00001298 } else if (In == Type::getFloatTy(Context) ||
1299 In == Type::getDoubleTy(Context) ||
Chris Lattner7809ecd2009-02-03 01:30:09 +00001300 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1301 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1302 // If we're accessing something that could be an element of a vector, see
1303 // if the implied vector agrees with what we already have and if Offset is
1304 // compatible with it.
1305 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1306 if (Offset % EltSize == 0 &&
1307 AllocaSize % EltSize == 0 &&
1308 (VecTy == 0 ||
1309 cast<VectorType>(VecTy)->getElementType()
1310 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1311 if (VecTy == 0)
Owen Andersondebcb012009-07-29 22:17:13 +00001312 VecTy = VectorType::get(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001313 return;
1314 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001315 }
1316 }
1317
Chris Lattner7809ecd2009-02-03 01:30:09 +00001318 // Otherwise, we have a case that we can't handle with an optimized vector
1319 // form. We can still turn this into a large integer.
Owen Anderson1d0be152009-08-13 21:58:54 +00001320 VecTy = Type::getVoidTy(Context);
Chris Lattnera1888942005-12-12 07:19:13 +00001321}
1322
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001323/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Chris Lattner7809ecd2009-02-03 01:30:09 +00001324/// its accesses to use a to single vector type, return true, and set VecTy to
1325/// the new type. If we could convert the alloca into a single promotable
1326/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1327/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1328/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001329///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001330/// If we see at least one access to the value that is as a vector type, set the
1331/// SawVec flag.
1332///
1333bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1334 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001335 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001336 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1337 Instruction *User = cast<Instruction>(*UI);
1338
1339 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001340 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001341 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001342 return false;
Owen Andersone922c022009-07-22 00:24:57 +00001343 MergeInType(LI->getType(), Offset, VecTy,
1344 AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001345 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001346 continue;
1347 }
1348
1349 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001350 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001351 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001352 MergeInType(SI->getOperand(0)->getType(), Offset,
Owen Andersone922c022009-07-22 00:24:57 +00001353 VecTy, AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001354 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001355 continue;
1356 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001357
1358 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001359 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1360 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001361 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001362 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001363 continue;
1364 }
1365
1366 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001367 // If this is a GEP with a variable indices, we can't handle it.
1368 if (!GEP->hasAllConstantIndices())
1369 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001370
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001371 // Compute the offset that this GEP adds to the pointer.
1372 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1373 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1374 &Indices[0], Indices.size());
1375 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001376 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001377 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001378 return false;
1379 IsNotTrivial = true;
1380 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001381 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001382
Chris Lattner3d730f72009-02-03 02:01:43 +00001383 // If this is a constant sized memset of a constant value (e.g. 0) we can
1384 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001385 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1386 // Store of constant value and constant size.
1387 if (isa<ConstantInt>(MSI->getValue()) &&
1388 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001389 IsNotTrivial = true;
1390 continue;
1391 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001392 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001393
1394 // If this is a memcpy or memmove into or out of the whole allocation, we
1395 // can handle it like a load or store of the scalar type.
1396 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1397 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1398 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1399 IsNotTrivial = true;
1400 continue;
1401 }
1402 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001403
Devang Patel00e389c2009-03-06 07:03:54 +00001404 // Ignore dbg intrinsic.
1405 if (isa<DbgInfoIntrinsic>(User))
1406 continue;
1407
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001408 // Otherwise, we cannot handle this!
1409 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001410 }
1411
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001412 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001413}
1414
Chris Lattnera1888942005-12-12 07:19:13 +00001415
1416/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001417/// directly. This happens when we are converting an "integer union" to a
1418/// single integer scalar, or when we are converting a "vector union" to a
1419/// vector with insert/extractelement instructions.
1420///
1421/// Offset is an offset from the original alloca, in bits that need to be
1422/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001423void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001424 while (!Ptr->use_empty()) {
1425 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001426
Chris Lattnercf321862009-01-07 06:39:58 +00001427 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001428 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001429 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001430 continue;
1431 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001432
Chris Lattnercf321862009-01-07 06:39:58 +00001433 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001434 // Compute the offset that this GEP adds to the pointer.
1435 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1436 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1437 &Indices[0], Indices.size());
1438 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001439 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001440 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001441 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001442
Chris Lattner9bc67da2009-02-03 19:45:44 +00001443 IRBuilder<> Builder(User->getParent(), User);
1444
1445 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001446 // The load is a bit extract from NewAI shifted right by Offset bits.
1447 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1448 Value *NewLoadVal
1449 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1450 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001451 LI->eraseFromParent();
1452 continue;
1453 }
1454
1455 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1456 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Daniel Dunbar6e0d1cb2009-07-25 04:41:11 +00001457 // FIXME: Remove once builder has Twine API.
1458 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").str().c_str());
Chris Lattner9bc67da2009-02-03 19:45:44 +00001459 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1460 Builder);
1461 Builder.CreateStore(New, NewAI);
1462 SI->eraseFromParent();
1463 continue;
1464 }
1465
Chris Lattner3d730f72009-02-03 02:01:43 +00001466 // If this is a constant sized memset of a constant value (e.g. 0) we can
1467 // transform it into a store of the expanded constant value.
1468 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1469 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1470 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001471 if (NumBytes != 0) {
1472 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1473
1474 // Compute the value replicated the right number of times.
1475 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001476
Chris Lattner33e24ad2009-04-21 16:52:12 +00001477 // Splat the value if non-zero.
1478 if (Val)
1479 for (unsigned i = 1; i != NumBytes; ++i)
1480 APVal |= APVal << 8;
1481
Daniel Dunbar6e0d1cb2009-07-25 04:41:11 +00001482 // FIXME: Remove once builder has Twine API.
1483 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").str().c_str());
Owen Andersone922c022009-07-22 00:24:57 +00001484 Value *New = ConvertScalar_InsertValue(
Owen Andersoneed707b2009-07-24 23:12:02 +00001485 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001486 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001487 Builder.CreateStore(New, NewAI);
1488 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001489 MSI->eraseFromParent();
1490 continue;
1491 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001492
1493 // If this is a memcpy or memmove into or out of the whole allocation, we
1494 // can handle it like a load or store of the scalar type.
1495 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1496 assert(Offset == 0 && "must be store to start of alloca");
1497
1498 // If the source and destination are both to the same alloca, then this is
1499 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1500 // as appropriate.
1501 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1502
1503 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1504 // Dest must be OrigAI, change this to be a load from the original
1505 // pointer (bitcasted), then a store to our new alloca.
1506 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1507 Value *SrcPtr = MTI->getSource();
1508 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1509
1510 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1511 SrcVal->setAlignment(MTI->getAlignment());
1512 Builder.CreateStore(SrcVal, NewAI);
1513 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1514 // Src must be OrigAI, change this to be a load from NewAI then a store
1515 // through the original dest pointer (bitcasted).
1516 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1517 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1518
1519 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1520 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1521 NewStore->setAlignment(MTI->getAlignment());
1522 } else {
1523 // Noop transfer. Src == Dst
1524 }
1525
1526
1527 MTI->eraseFromParent();
1528 continue;
1529 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001530
Devang Patel00e389c2009-03-06 07:03:54 +00001531 // If user is a dbg info intrinsic then it is safe to remove it.
1532 if (isa<DbgInfoIntrinsic>(User)) {
1533 User->eraseFromParent();
1534 continue;
1535 }
1536
Torok Edwinc23197a2009-07-14 16:55:14 +00001537 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001538 }
1539}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001540
Chris Lattner6e011152009-02-03 21:01:03 +00001541/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1542/// or vector value FromVal, extracting the bits from the offset specified by
1543/// Offset. This returns the value, which is of type ToType.
1544///
1545/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001546/// integer scalar, or when we are converting a "vector union" to a vector with
1547/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001548///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001549/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001550/// shifted to the right.
1551Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1552 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001553 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001554 if (FromVal->getType() == ToType && Offset == 0)
1555 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001556
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001557 // If the result alloca is a vector type, this is either an element
1558 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001559 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1560 if (isa<VectorType>(ToType))
1561 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001562
1563 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001564 unsigned Elt = 0;
1565 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001566 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001567 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001568 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001569 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001570 // Return the element extracted out of it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001571 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1572 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001573 if (V->getType() != ToType)
1574 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001575 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001576 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001577
1578 // If ToType is a first class aggregate, extract out each of the pieces and
1579 // use insertvalue's to form the FCA.
1580 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1581 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001582 Value *Res = UndefValue::get(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001583 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1584 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001585 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001586 Builder);
1587 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1588 }
1589 return Res;
1590 }
1591
1592 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001593 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001594 Value *Res = UndefValue::get(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001595 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1596 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1597 Offset+i*EltSize, Builder);
1598 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1599 }
1600 return Res;
1601 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001602
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001603 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001604 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001605
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001606 // If this is a big-endian system and the load is narrower than the
1607 // full alloca type, we need to do a shift to get the right bits.
1608 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001609 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001610 // On big-endian machines, the lowest bit is stored at the bit offset
1611 // from the pointer given by getTypeStoreSizeInBits. This matters for
1612 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001613 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001614 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001615 } else {
1616 ShAmt = Offset;
1617 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001618
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001619 // Note: we support negative bitwidths (with shl) which are not defined.
1620 // We do this to support (f.e.) loads off the end of a structure where
1621 // only some bits are used.
1622 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001623 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001624 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001625 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001626 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001627 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001628 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001629 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001630
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001631 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001632 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001633 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001634 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001635 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1636 LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001637 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001638 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001639 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1640 LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001641
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001642 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner6e011152009-02-03 21:01:03 +00001643 if (isa<IntegerType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001644 // Should be done.
Chris Lattner6e011152009-02-03 21:01:03 +00001645 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001646 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001647 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001648 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001649 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001650 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001651 }
Chris Lattner6e011152009-02-03 21:01:03 +00001652 assert(FromVal->getType() == ToType && "Didn't convert right?");
1653 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001654}
1655
1656
Chris Lattner9b872db2009-02-03 19:30:11 +00001657/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1658/// or vector value "Old" at the offset specified by Offset.
1659///
1660/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001661/// single integer scalar, or when we are converting a "vector union" to a
1662/// vector with insert/extractelement instructions.
1663///
1664/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001665/// shifted to the right.
1666Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001667 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001668
Chris Lattner800de312008-02-29 07:03:13 +00001669 // Convert the stored type to the actual type, shift it left to insert
1670 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001671 const Type *AllocaType = Old->getType();
Owen Andersone922c022009-07-22 00:24:57 +00001672 LLVMContext &Context = Old->getContext();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001673
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001674 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001675 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1676 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001677
1678 // Changing the whole vector with memset or with an access of a different
1679 // vector type?
1680 if (ValSize == VecSize)
1681 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1682
Duncan Sands777d2302009-05-09 07:06:46 +00001683 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001684
1685 // Must be an element insertion.
1686 unsigned Elt = Offset/EltSize;
1687
1688 if (SV->getType() != VTy->getElementType())
1689 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1690
1691 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001692 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001693 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001694 return SV;
1695 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001696
1697 // If SV is a first-class aggregate value, insert each value recursively.
1698 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1699 const StructLayout &Layout = *TD->getStructLayout(ST);
1700 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001701 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001702 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001703 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001704 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001705 }
1706 return Old;
1707 }
1708
1709 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001710 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001711 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001712 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1713 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001714 }
1715 return Old;
1716 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001717
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001718 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001719 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001720 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1721 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1722 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1723 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1724 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001725 SV = Builder.CreateBitCast(SV,
1726 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001727 else if (isa<PointerType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001728 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001729
Chris Lattner7809ecd2009-02-03 01:30:09 +00001730 // Zero extend or truncate the value if needed.
1731 if (SV->getType() != AllocaType) {
1732 if (SV->getType()->getPrimitiveSizeInBits() <
1733 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001734 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001735 else {
1736 // Truncation may be needed if storing more than the alloca can hold
1737 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001738 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001739 SrcWidth = DestWidth;
1740 SrcStoreWidth = DestStoreWidth;
1741 }
1742 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001743
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001744 // If this is a big-endian system and the store is narrower than the
1745 // full alloca type, we need to do a shift to get the right bits.
1746 int ShAmt = 0;
1747 if (TD->isBigEndian()) {
1748 // On big-endian machines, the lowest bit is stored at the bit offset
1749 // from the pointer given by getTypeStoreSizeInBits. This matters for
1750 // integers with a bitwidth that is not a multiple of 8.
1751 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001752 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001753 ShAmt = Offset;
1754 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001755
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001756 // Note: we support negative bitwidths (with shr) which are not defined.
1757 // We do this to support (f.e.) stores off the end of a structure where
1758 // only some bits in the structure are set.
1759 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1760 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001761 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001762 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001763 Mask <<= ShAmt;
1764 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001765 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001766 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001767 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001768 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001769
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001770 // Mask out the bits we are about to insert from the old value, and or
1771 // in the new bits.
1772 if (SrcWidth != DestWidth) {
1773 assert(DestWidth > SrcWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +00001774 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001775 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001776 }
1777 return SV;
1778}
1779
1780
Chris Lattner79b3bd32007-04-25 06:40:51 +00001781
1782/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1783/// some part of a constant global variable. This intentionally only accepts
1784/// constant expressions because we don't can't rewrite arbitrary instructions.
1785static bool PointsToConstantGlobal(Value *V) {
1786 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1787 return GV->isConstant();
1788 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1789 if (CE->getOpcode() == Instruction::BitCast ||
1790 CE->getOpcode() == Instruction::GetElementPtr)
1791 return PointsToConstantGlobal(CE->getOperand(0));
1792 return false;
1793}
1794
1795/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1796/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1797/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1798/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1799/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1800/// the alloca, and if the source pointer is a pointer to a constant global, we
1801/// can optimize this.
1802static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1803 bool isOffset) {
1804 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001805 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1806 // Ignore non-volatile loads, they are always ok.
1807 if (!LI->isVolatile())
1808 continue;
1809
Chris Lattner79b3bd32007-04-25 06:40:51 +00001810 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1811 // If uses of the bitcast are ok, we are ok.
1812 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1813 return false;
1814 continue;
1815 }
1816 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1817 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1818 // doesn't, it does.
1819 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1820 isOffset || !GEP->hasAllZeroIndices()))
1821 return false;
1822 continue;
1823 }
1824
1825 // If this is isn't our memcpy/memmove, reject it as something we can't
1826 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001827 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001828 return false;
1829
1830 // If we already have seen a copy, reject the second one.
1831 if (TheCopy) return false;
1832
1833 // If the pointer has been offset from the start of the alloca, we can't
1834 // safely handle this.
1835 if (isOffset) return false;
1836
1837 // If the memintrinsic isn't using the alloca as the dest, reject it.
1838 if (UI.getOperandNo() != 1) return false;
1839
1840 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1841
1842 // If the source of the memcpy/move is not a constant global, reject it.
1843 if (!PointsToConstantGlobal(MI->getOperand(2)))
1844 return false;
1845
1846 // Otherwise, the transform is safe. Remember the copy instruction.
1847 TheCopy = MI;
1848 }
1849 return true;
1850}
1851
1852/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1853/// modified by a copy from a constant global. If we can prove this, we can
1854/// replace any uses of the alloca with uses of the global directly.
1855Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1856 Instruction *TheCopy = 0;
1857 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1858 return TheCopy;
1859 return 0;
1860}