blob: 610d874b3684e8fefc201d88d072fe6ce79b46e6 [file] [log] [blame]
Chris Lattnered7b41e2003-05-27 15:45:27 +00001//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnered7b41e2003-05-27 15:45:27 +00009//
10// This transformation implements the well known scalar replacement of
11// aggregates transformation. This xform breaks up alloca instructions of
12// aggregate type (structure or array) into individual alloca instructions for
Chris Lattner38aec322003-09-11 16:45:55 +000013// each member (if possible). Then, if possible, it transforms the individual
14// alloca instructions into nice clean scalar SSA form.
15//
16// This combines a simple SRoA algorithm with the Mem2Reg algorithm because
17// often interact, especially for C++ programs. As such, iterating between
18// SRoA, then Mem2Reg until we run out of things to promote works well.
Chris Lattnered7b41e2003-05-27 15:45:27 +000019//
20//===----------------------------------------------------------------------===//
21
Chris Lattner0e5f4992006-12-19 21:40:18 +000022#define DEBUG_TYPE "scalarrepl"
Chris Lattnered7b41e2003-05-27 15:45:27 +000023#include "llvm/Transforms/Scalar.h"
Chris Lattner38aec322003-09-11 16:45:55 +000024#include "llvm/Constants.h"
25#include "llvm/DerivedTypes.h"
Chris Lattnered7b41e2003-05-27 15:45:27 +000026#include "llvm/Function.h"
Chris Lattner79b3bd32007-04-25 06:40:51 +000027#include "llvm/GlobalVariable.h"
Misha Brukmand8e1eea2004-07-29 17:05:13 +000028#include "llvm/Instructions.h"
Chris Lattner372dda82007-03-05 07:52:57 +000029#include "llvm/IntrinsicInst.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000030#include "llvm/LLVMContext.h"
Chris Lattner372dda82007-03-05 07:52:57 +000031#include "llvm/Pass.h"
Chris Lattner38aec322003-09-11 16:45:55 +000032#include "llvm/Analysis/Dominators.h"
33#include "llvm/Target/TargetData.h"
34#include "llvm/Transforms/Utils/PromoteMemToReg.h"
Devang Patel4afc90d2009-02-10 07:00:59 +000035#include "llvm/Transforms/Utils/Local.h"
Chris Lattner95255282006-06-28 23:17:24 +000036#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000037#include "llvm/Support/ErrorHandling.h"
Chris Lattnera1888942005-12-12 07:19:13 +000038#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000039#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000040#include "llvm/Support/MathExtras.h"
Chris Lattnerbdff5482009-08-23 04:37:46 +000041#include "llvm/Support/raw_ostream.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000042#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000043#include "llvm/ADT/Statistic.h"
Chris Lattnerd8664732003-12-02 17:43:55 +000044using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000045
Chris Lattner0e5f4992006-12-19 21:40:18 +000046STATISTIC(NumReplaced, "Number of allocas broken up");
47STATISTIC(NumPromoted, "Number of allocas promoted");
48STATISTIC(NumConverted, "Number of aggregates converted to scalar");
Chris Lattner79b3bd32007-04-25 06:40:51 +000049STATISTIC(NumGlobals, "Number of allocas copied from constant global");
Chris Lattnered7b41e2003-05-27 15:45:27 +000050
Chris Lattner0e5f4992006-12-19 21:40:18 +000051namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000052 struct SROA : public FunctionPass {
Nick Lewyckyecd94c82007-05-06 13:37:16 +000053 static char ID; // Pass identification, replacement for typeid
Dan Gohmanae73dc12008-09-04 17:05:41 +000054 explicit SROA(signed T = -1) : FunctionPass(&ID) {
Devang Patelff366852007-07-09 21:19:23 +000055 if (T == -1)
Chris Lattnerb0e71ed2007-08-02 21:33:36 +000056 SRThreshold = 128;
Devang Patelff366852007-07-09 21:19:23 +000057 else
58 SRThreshold = T;
59 }
Devang Patel794fd752007-05-01 21:15:47 +000060
Chris Lattnered7b41e2003-05-27 15:45:27 +000061 bool runOnFunction(Function &F);
62
Chris Lattner38aec322003-09-11 16:45:55 +000063 bool performScalarRepl(Function &F);
64 bool performPromotion(Function &F);
65
Chris Lattnera15854c2003-08-31 00:45:13 +000066 // getAnalysisUsage - This pass does not require any passes, but we know it
67 // will not alter the CFG, so say so.
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Devang Patel326821e2007-06-07 21:57:03 +000069 AU.addRequired<DominatorTree>();
Chris Lattner38aec322003-09-11 16:45:55 +000070 AU.addRequired<DominanceFrontier>();
Chris Lattnera15854c2003-08-31 00:45:13 +000071 AU.setPreservesCFG();
72 }
73
Chris Lattnered7b41e2003-05-27 15:45:27 +000074 private:
Chris Lattner56c38522009-01-07 06:34:28 +000075 TargetData *TD;
76
Chris Lattner39a1c042007-05-30 06:11:23 +000077 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
78 /// information about the uses. All these fields are initialized to false
79 /// and set to true when something is learned.
80 struct AllocaInfo {
81 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
82 bool isUnsafe : 1;
83
Devang Patel4afc90d2009-02-10 07:00:59 +000084 /// needsCleanup - This is set to true if there is some use of the alloca
85 /// that requires cleanup.
86 bool needsCleanup : 1;
Chris Lattner39a1c042007-05-30 06:11:23 +000087
88 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
89 bool isMemCpySrc : 1;
90
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000091 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000092 bool isMemCpyDst : 1;
93
94 AllocaInfo()
Devang Patel4afc90d2009-02-10 07:00:59 +000095 : isUnsafe(false), needsCleanup(false),
Chris Lattner39a1c042007-05-30 06:11:23 +000096 isMemCpySrc(false), isMemCpyDst(false) {}
97 };
98
Devang Patelff366852007-07-09 21:19:23 +000099 unsigned SRThreshold;
100
Chris Lattner39a1c042007-05-30 06:11:23 +0000101 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
102
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000103 int isSafeAllocaToScalarRepl(AllocationInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000104
105 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
106 AllocaInfo &Info);
107 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
108 AllocaInfo &Info);
109 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
110 unsigned OpNo, AllocaInfo &Info);
111 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
112 AllocaInfo &Info);
113
Chris Lattnera10b29b2007-04-25 05:02:56 +0000114 void DoScalarReplacement(AllocationInst *AI,
115 std::vector<AllocationInst*> &WorkList);
Devang Patel4afc90d2009-02-10 07:00:59 +0000116 void CleanupGEP(GetElementPtrInst *GEP);
117 void CleanupAllocaUsers(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000118 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000119
Chris Lattner8bf99112007-03-19 00:16:43 +0000120 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000121 SmallVector<AllocaInst*, 32> &NewElts);
122
Chris Lattnerd93afec2009-01-07 07:18:45 +0000123 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
124 AllocationInst *AI,
125 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000126 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
127 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000128 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000129 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000130
Chris Lattner7809ecd2009-02-03 01:30:09 +0000131 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner1a3257b2009-02-03 18:15:05 +0000132 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000133 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000134 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000135 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000136 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000137 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner79b3bd32007-04-25 06:40:51 +0000138 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000139 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000140}
141
Dan Gohman844731a2008-05-13 00:00:25 +0000142char SROA::ID = 0;
143static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
144
Brian Gaeked0fde302003-11-11 22:41:34 +0000145// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000146FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
147 return new SROA(Threshold);
148}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000149
150
Chris Lattnered7b41e2003-05-27 15:45:27 +0000151bool SROA::runOnFunction(Function &F) {
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000152 TD = getAnalysisIfAvailable<TargetData>();
153
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000154 bool Changed = performPromotion(F);
Dan Gohmane4af1cf2009-08-19 18:22:18 +0000155
156 // FIXME: ScalarRepl currently depends on TargetData more than it
157 // theoretically needs to. It should be refactored in order to support
158 // target-independent IR. Until this is done, just skip the actual
159 // scalar-replacement portion of this pass.
160 if (!TD) return Changed;
161
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000162 while (1) {
163 bool LocalChange = performScalarRepl(F);
164 if (!LocalChange) break; // No need to repromote if no scalarrepl
165 Changed = true;
166 LocalChange = performPromotion(F);
167 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
168 }
Chris Lattner38aec322003-09-11 16:45:55 +0000169
170 return Changed;
171}
172
173
174bool SROA::performPromotion(Function &F) {
175 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000176 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000177 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000178
Chris Lattner02a3be02003-09-20 14:39:18 +0000179 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000180
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000181 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000182
Chris Lattner38aec322003-09-11 16:45:55 +0000183 while (1) {
184 Allocas.clear();
185
186 // Find allocas that are safe to promote, by looking at all instructions in
187 // the entry node
188 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
189 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000190 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000191 Allocas.push_back(AI);
192
193 if (Allocas.empty()) break;
194
Owen Andersone922c022009-07-22 00:24:57 +0000195 PromoteMemToReg(Allocas, DT, DF, F.getContext());
Chris Lattner38aec322003-09-11 16:45:55 +0000196 NumPromoted += Allocas.size();
197 Changed = true;
198 }
199
200 return Changed;
201}
202
Chris Lattner963a97f2008-06-22 17:46:21 +0000203/// getNumSAElements - Return the number of elements in the specific struct or
204/// array.
205static uint64_t getNumSAElements(const Type *T) {
206 if (const StructType *ST = dyn_cast<StructType>(T))
207 return ST->getNumElements();
208 return cast<ArrayType>(T)->getNumElements();
209}
210
Chris Lattner38aec322003-09-11 16:45:55 +0000211// performScalarRepl - This algorithm is a simple worklist driven algorithm,
212// which runs on all of the malloc/alloca instructions in the function, removing
213// them if they are only used by getelementptr instructions.
214//
215bool SROA::performScalarRepl(Function &F) {
Chris Lattnered7b41e2003-05-27 15:45:27 +0000216 std::vector<AllocationInst*> WorkList;
217
218 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000219 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000220 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
221 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
222 WorkList.push_back(A);
223
224 // Process the worklist
225 bool Changed = false;
226 while (!WorkList.empty()) {
227 AllocationInst *AI = WorkList.back();
228 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000229
Chris Lattneradd2bd72006-12-22 23:14:42 +0000230 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
231 // with unused elements.
232 if (AI->use_empty()) {
233 AI->eraseFromParent();
234 continue;
235 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000236
237 // If this alloca is impossible for us to promote, reject it early.
238 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
239 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000240
241 // Check to see if this allocation is only modified by a memcpy/memmove from
242 // a constant global. If this is the case, we can change all users to use
243 // the constant global instead. This is commonly produced by the CFE by
244 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
245 // is only subsequently read.
246 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
Nick Lewycky59136252009-09-15 07:08:25 +0000247 DEBUG(errs() << "Found alloca equal to global: " << *AI << '\n');
248 DEBUG(errs() << " memcpy = " << *TheCopy << '\n');
Chris Lattner79b3bd32007-04-25 06:40:51 +0000249 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonbaf3c402009-07-29 18:55:55 +0000250 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000251 TheCopy->eraseFromParent(); // Don't mutate the global.
252 AI->eraseFromParent();
253 ++NumGlobals;
254 Changed = true;
255 continue;
256 }
Chris Lattner15c82772009-02-02 20:44:45 +0000257
Chris Lattner7809ecd2009-02-03 01:30:09 +0000258 // Check to see if we can perform the core SROA transformation. We cannot
259 // transform the allocation instruction if it is an array allocation
260 // (allocations OF arrays are ok though), and an allocation of a scalar
261 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000262 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000263
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000264 // Do not promote [0 x %struct].
265 if (AllocaSize == 0) continue;
266
Bill Wendling5a377cb2009-03-03 12:12:58 +0000267 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000268 if (AllocaSize > SRThreshold) continue;
Nick Lewyckyd3aa25e2009-08-17 05:37:31 +0000269
Chris Lattner7809ecd2009-02-03 01:30:09 +0000270 if ((isa<StructType>(AI->getAllocatedType()) ||
271 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner7809ecd2009-02-03 01:30:09 +0000272 // Do not promote any struct into more than "32" separate vars.
Evan Cheng67fca632009-03-06 00:56:43 +0000273 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000274 // Check that all of the users of the allocation are capable of being
275 // transformed.
276 switch (isSafeAllocaToScalarRepl(AI)) {
Torok Edwinc23197a2009-07-14 16:55:14 +0000277 default: llvm_unreachable("Unexpected value!");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000278 case 0: // Not safe to scalar replace.
279 break;
280 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel4afc90d2009-02-10 07:00:59 +0000281 CleanupAllocaUsers(AI);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000282 // FALL THROUGH.
283 case 3: // Safe to scalar replace.
284 DoScalarReplacement(AI, WorkList);
285 Changed = true;
286 continue;
287 }
288 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000289
290 // If we can turn this aggregate value (potentially with casts) into a
291 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000292 // IsNotTrivial tracks whether this is something that mem2reg could have
293 // promoted itself. If so, we don't want to transform it needlessly. Note
294 // that we can't just check based on the type: the alloca may be of an i32
295 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000296 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000297 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000298 bool HadAVector = false;
299 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000300 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000301 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000302 // If we were able to find a vector type that can handle this with
303 // insert/extract elements, and if there was at least one use that had
304 // a vector type, promote this to a vector. We don't want to promote
305 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
306 // we just get a lot of insert/extracts. If at least one vector is
307 // involved, then we probably really do have a union of vector/array.
308 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Nick Lewycky59136252009-09-15 07:08:25 +0000309 DEBUG(errs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = "
Chris Lattnerbdff5482009-08-23 04:37:46 +0000310 << *VectorTy << '\n');
Chris Lattner15c82772009-02-02 20:44:45 +0000311
Chris Lattner7809ecd2009-02-03 01:30:09 +0000312 // Create and insert the vector alloca.
Owen Anderson50dead02009-07-15 23:53:25 +0000313 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000314 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000315 } else {
Chris Lattnerbdff5482009-08-23 04:37:46 +0000316 DEBUG(errs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n");
Chris Lattner7809ecd2009-02-03 01:30:09 +0000317
318 // Create and insert the integer alloca.
Owen Anderson1d0be152009-08-13 21:58:54 +0000319 const Type *NewTy = IntegerType::get(AI->getContext(), AllocaSize*8);
Owen Anderson50dead02009-07-15 23:53:25 +0000320 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
Chris Lattner7809ecd2009-02-03 01:30:09 +0000321 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000322 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000323 NewAI->takeName(AI);
324 AI->eraseFromParent();
325 ++NumConverted;
326 Changed = true;
327 continue;
328 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000329
Chris Lattner7809ecd2009-02-03 01:30:09 +0000330 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000331 }
332
333 return Changed;
334}
Chris Lattner5e062a12003-05-30 04:15:41 +0000335
Chris Lattnera10b29b2007-04-25 05:02:56 +0000336/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
337/// predicate, do SROA now.
338void SROA::DoScalarReplacement(AllocationInst *AI,
339 std::vector<AllocationInst*> &WorkList) {
Chris Lattnerff114702009-09-15 05:14:57 +0000340 DEBUG(errs() << "Found inst to SROA: " << *AI << '\n');
Chris Lattnera10b29b2007-04-25 05:02:56 +0000341 SmallVector<AllocaInst*, 32> ElementAllocas;
342 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
343 ElementAllocas.reserve(ST->getNumContainedTypes());
344 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000345 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
Chris Lattnera10b29b2007-04-25 05:02:56 +0000346 AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000347 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000348 ElementAllocas.push_back(NA);
349 WorkList.push_back(NA); // Add to worklist for recursive processing
350 }
351 } else {
352 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
353 ElementAllocas.reserve(AT->getNumElements());
354 const Type *ElTy = AT->getElementType();
355 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Owen Anderson50dead02009-07-15 23:53:25 +0000356 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000357 AI->getName() + "." + Twine(i), AI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000358 ElementAllocas.push_back(NA);
359 WorkList.push_back(NA); // Add to worklist for recursive processing
360 }
361 }
362
363 // Now that we have created the alloca instructions that we want to use,
364 // expand the getelementptr instructions to use them.
365 //
366 while (!AI->use_empty()) {
367 Instruction *User = cast<Instruction>(AI->use_back());
368 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
369 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
370 BCInst->eraseFromParent();
371 continue;
372 }
373
Chris Lattner2a6a6452008-06-23 17:11:23 +0000374 // Replace:
375 // %res = load { i32, i32 }* %alloc
376 // with:
377 // %load.0 = load i32* %alloc.0
378 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
379 // %load.1 = load i32* %alloc.1
380 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000381 // (Also works for arrays instead of structs)
382 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000383 Value *Insert = UndefValue::get(LI->getType());
Matthijs Kooijman02518142008-06-05 12:51:53 +0000384 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
385 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
386 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
387 }
388 LI->replaceAllUsesWith(Insert);
389 LI->eraseFromParent();
390 continue;
391 }
392
Chris Lattner2a6a6452008-06-23 17:11:23 +0000393 // Replace:
394 // store { i32, i32 } %val, { i32, i32 }* %alloc
395 // with:
396 // %val.0 = extractvalue { i32, i32 } %val, 0
397 // store i32 %val.0, i32* %alloc.0
398 // %val.1 = extractvalue { i32, i32 } %val, 1
399 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000400 // (Also works for arrays instead of structs)
401 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
402 Value *Val = SI->getOperand(0);
403 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
404 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
405 new StoreInst(Extract, ElementAllocas[i], SI);
406 }
407 SI->eraseFromParent();
408 continue;
409 }
410
Chris Lattnera10b29b2007-04-25 05:02:56 +0000411 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
412 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
413 unsigned Idx =
414 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
415
416 assert(Idx < ElementAllocas.size() && "Index out of range?");
417 AllocaInst *AllocaToUse = ElementAllocas[Idx];
418
419 Value *RepValue;
420 if (GEPI->getNumOperands() == 3) {
421 // Do not insert a new getelementptr instruction with zero indices, only
422 // to have it optimized out later.
423 RepValue = AllocaToUse;
424 } else {
425 // We are indexing deeply into the structure, so we still need a
426 // getelement ptr instruction to finish the indexing. This may be
427 // expanded itself once the worklist is rerun.
428 //
429 SmallVector<Value*, 8> NewArgs;
Owen Anderson1d0be152009-08-13 21:58:54 +0000430 NewArgs.push_back(Constant::getNullValue(
431 Type::getInt32Ty(AI->getContext())));
Chris Lattnera10b29b2007-04-25 05:02:56 +0000432 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +0000433 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
434 NewArgs.end(), "", GEPI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000435 RepValue->takeName(GEPI);
436 }
437
438 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000439 if (Idx == 0 && GEPI->hasAllZeroIndices())
440 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000441
442 // Move all of the users over to the new GEP.
443 GEPI->replaceAllUsesWith(RepValue);
444 // Delete the old GEP
445 GEPI->eraseFromParent();
446 }
447
448 // Finally, delete the Alloca instruction
449 AI->eraseFromParent();
450 NumReplaced++;
451}
452
Chris Lattner5e062a12003-05-30 04:15:41 +0000453
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000454/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner8bf99112007-03-19 00:16:43 +0000455/// getelementptr instruction of an array aggregate allocation. isFirstElt
456/// indicates whether Ptr is known to the start of the aggregate.
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000457///
Chris Lattner39a1c042007-05-30 06:11:23 +0000458void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
459 AllocaInfo &Info) {
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000460 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
461 I != E; ++I) {
462 Instruction *User = cast<Instruction>(*I);
463 switch (User->getOpcode()) {
464 case Instruction::Load: break;
465 case Instruction::Store:
466 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattner39a1c042007-05-30 06:11:23 +0000467 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000468 break;
469 case Instruction::GetElementPtr: {
470 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
Chris Lattner8bf99112007-03-19 00:16:43 +0000471 bool AreAllZeroIndices = isFirstElt;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000472 if (GEP->getNumOperands() > 1) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000473 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
474 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
Chris Lattner39a1c042007-05-30 06:11:23 +0000475 // Using pointer arithmetic to navigate the array.
476 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000477
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000478 if (AreAllZeroIndices)
479 AreAllZeroIndices = GEP->hasAllZeroIndices();
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000480 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000481 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
482 if (Info.isUnsafe) return;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000483 break;
484 }
Chris Lattner8bf99112007-03-19 00:16:43 +0000485 case Instruction::BitCast:
Chris Lattner39a1c042007-05-30 06:11:23 +0000486 if (isFirstElt) {
487 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
488 if (Info.isUnsafe) return;
Chris Lattner8bf99112007-03-19 00:16:43 +0000489 break;
Chris Lattner8bf99112007-03-19 00:16:43 +0000490 }
Nick Lewycky59136252009-09-15 07:08:25 +0000491 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
Chris Lattner39a1c042007-05-30 06:11:23 +0000492 return MarkUnsafe(Info);
493 case Instruction::Call:
494 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
495 if (isFirstElt) {
496 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
497 if (Info.isUnsafe) return;
498 break;
499 }
500 }
Nick Lewycky59136252009-09-15 07:08:25 +0000501 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
Chris Lattner39a1c042007-05-30 06:11:23 +0000502 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000503 default:
Nick Lewycky59136252009-09-15 07:08:25 +0000504 DEBUG(errs() << " Transformation preventing inst: " << *User << '\n');
Chris Lattner39a1c042007-05-30 06:11:23 +0000505 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000506 }
507 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000508 return; // All users look ok :)
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000509}
510
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000511/// AllUsersAreLoads - Return true if all users of this value are loads.
512static bool AllUsersAreLoads(Value *Ptr) {
513 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
514 I != E; ++I)
515 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
516 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000517 return true;
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000518}
519
Chris Lattner5e062a12003-05-30 04:15:41 +0000520/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
521/// aggregate allocation.
522///
Chris Lattner39a1c042007-05-30 06:11:23 +0000523void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
524 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000525 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
Chris Lattner39a1c042007-05-30 06:11:23 +0000526 return isSafeUseOfBitCastedAllocation(C, AI, Info);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000527
Chris Lattner6e733d32009-01-28 20:16:43 +0000528 if (LoadInst *LI = dyn_cast<LoadInst>(User))
529 if (!LI->isVolatile())
530 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman02518142008-06-05 12:51:53 +0000531
Chris Lattner6e733d32009-01-28 20:16:43 +0000532 if (StoreInst *SI = dyn_cast<StoreInst>(User))
533 if (!SI->isVolatile() && SI->getOperand(0) != AI)
534 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman02518142008-06-05 12:51:53 +0000535
Chris Lattner39a1c042007-05-30 06:11:23 +0000536 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
537 if (GEPI == 0)
538 return MarkUnsafe(Info);
539
Chris Lattnerbe883a22003-11-25 21:09:18 +0000540 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
541
Chris Lattner25de4862006-03-08 01:05:29 +0000542 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattnerbe883a22003-11-25 21:09:18 +0000543 if (I == E ||
Owen Andersona7235ea2009-07-31 20:28:14 +0000544 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000545 return MarkUnsafe(Info);
546 }
Chris Lattnerbe883a22003-11-25 21:09:18 +0000547
548 ++I;
Chris Lattner39a1c042007-05-30 06:11:23 +0000549 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
Chris Lattnerbe883a22003-11-25 21:09:18 +0000550
Chris Lattner8bf99112007-03-19 00:16:43 +0000551 bool IsAllZeroIndices = true;
552
Chris Lattner88e6dc82008-08-23 05:21:06 +0000553 // If the first index is a non-constant index into an array, see if we can
554 // handle it as a special case.
Chris Lattnerbe883a22003-11-25 21:09:18 +0000555 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000556 if (!isa<ConstantInt>(I.getOperand())) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000557 IsAllZeroIndices = 0;
Chris Lattner88e6dc82008-08-23 05:21:06 +0000558 uint64_t NumElements = AT->getNumElements();
Chris Lattner8bf99112007-03-19 00:16:43 +0000559
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000560 // If this is an array index and the index is not constant, we cannot
561 // promote... that is unless the array has exactly one or two elements in
562 // it, in which case we CAN promote it, but we have to canonicalize this
563 // out if this is the only problem.
Chris Lattner25de4862006-03-08 01:05:29 +0000564 if ((NumElements == 1 || NumElements == 2) &&
Chris Lattner39a1c042007-05-30 06:11:23 +0000565 AllUsersAreLoads(GEPI)) {
Devang Patel4afc90d2009-02-10 07:00:59 +0000566 Info.needsCleanup = true;
Chris Lattner39a1c042007-05-30 06:11:23 +0000567 return; // Canonicalization required!
568 }
569 return MarkUnsafe(Info);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000570 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000571 }
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000572
Chris Lattner88e6dc82008-08-23 05:21:06 +0000573 // Walk through the GEP type indices, checking the types that this indexes
574 // into.
575 for (; I != E; ++I) {
576 // Ignore struct elements, no extra checking needed for these.
577 if (isa<StructType>(*I))
578 continue;
579
Chris Lattner88e6dc82008-08-23 05:21:06 +0000580 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
581 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000582
583 // Are all indices still zero?
Chris Lattner88e6dc82008-08-23 05:21:06 +0000584 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000585
586 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
587 // This GEP indexes an array. Verify that this is an in-range constant
588 // integer. Specifically, consider A[0][i]. We cannot know that the user
589 // isn't doing invalid things like allowing i to index an out-of-range
590 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000591 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000592 if (IdxVal->getZExtValue() >= AT->getNumElements())
593 return MarkUnsafe(Info);
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000594 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
595 if (IdxVal->getZExtValue() >= VT->getNumElements())
596 return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000597 }
Chris Lattner88e6dc82008-08-23 05:21:06 +0000598 }
599
Chris Lattnerbe883a22003-11-25 21:09:18 +0000600 // If there are any non-simple uses of this getelementptr, make sure to reject
601 // them.
Chris Lattner39a1c042007-05-30 06:11:23 +0000602 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000603}
604
605/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
606/// intrinsic can be promoted by SROA. At this point, we know that the operand
607/// of the memintrinsic is a pointer to the beginning of the allocation.
Chris Lattner39a1c042007-05-30 06:11:23 +0000608void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
609 unsigned OpNo, AllocaInfo &Info) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000610 // If not constant length, give up.
611 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattner39a1c042007-05-30 06:11:23 +0000612 if (!Length) return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000613
614 // If not the whole aggregate, give up.
Duncan Sands3cb36502007-11-04 14:43:57 +0000615 if (Length->getZExtValue() !=
Duncan Sands777d2302009-05-09 07:06:46 +0000616 TD->getTypeAllocSize(AI->getType()->getElementType()))
Chris Lattner39a1c042007-05-30 06:11:23 +0000617 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000618
619 // We only know about memcpy/memset/memmove.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000620 if (!isa<MemIntrinsic>(MI))
Chris Lattner39a1c042007-05-30 06:11:23 +0000621 return MarkUnsafe(Info);
622
623 // Otherwise, we can transform it. Determine whether this is a memcpy/set
624 // into or out of the aggregate.
625 if (OpNo == 1)
626 Info.isMemCpyDst = true;
627 else {
628 assert(OpNo == 2);
629 Info.isMemCpySrc = true;
630 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000631}
632
Chris Lattner372dda82007-03-05 07:52:57 +0000633/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
634/// are
Chris Lattner39a1c042007-05-30 06:11:23 +0000635void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
636 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000637 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
638 UI != E; ++UI) {
639 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000640 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000641 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000642 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000643 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000644 if (SI->isVolatile())
645 return MarkUnsafe(Info);
646
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000647 // If storing the entire alloca in one chunk through a bitcasted pointer
648 // to integer, we can transform it. This happens (for example) when you
649 // cast a {i32,i32}* to i64* and store through it. This is similar to the
650 // memcpy case and occurs in various "byval" cases and emulated memcpys.
651 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000652 TD->getTypeAllocSize(SI->getOperand(0)->getType()) ==
653 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000654 Info.isMemCpyDst = true;
655 continue;
656 }
657 return MarkUnsafe(Info);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000658 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000659 if (LI->isVolatile())
660 return MarkUnsafe(Info);
661
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000662 // If loading the entire alloca in one chunk through a bitcasted pointer
663 // to integer, we can transform it. This happens (for example) when you
664 // cast a {i32,i32}* to i64* and load through it. This is similar to the
665 // memcpy case and occurs in various "byval" cases and emulated memcpys.
666 if (isa<IntegerType>(LI->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000667 TD->getTypeAllocSize(LI->getType()) ==
668 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000669 Info.isMemCpySrc = true;
670 continue;
671 }
672 return MarkUnsafe(Info);
Devang Patel4afc90d2009-02-10 07:00:59 +0000673 } else if (isa<DbgInfoIntrinsic>(UI)) {
674 // If one user is DbgInfoIntrinsic then check if all users are
675 // DbgInfoIntrinsics.
676 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
677 Info.needsCleanup = true;
678 return;
679 }
680 else
681 MarkUnsafe(Info);
682 }
683 else {
Chris Lattner39a1c042007-05-30 06:11:23 +0000684 return MarkUnsafe(Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000685 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000686 if (Info.isUnsafe) return;
Chris Lattner372dda82007-03-05 07:52:57 +0000687 }
Chris Lattner372dda82007-03-05 07:52:57 +0000688}
689
Chris Lattner8bf99112007-03-19 00:16:43 +0000690/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
691/// to its first element. Transform users of the cast to use the new values
692/// instead.
693void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000694 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000695 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
696 while (UI != UE) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000697 Instruction *User = cast<Instruction>(*UI++);
698 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Chris Lattner372dda82007-03-05 07:52:57 +0000699 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000700 if (BCU->use_empty()) BCU->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000701 continue;
702 }
703
Chris Lattnerd93afec2009-01-07 07:18:45 +0000704 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
705 // This must be memcpy/memmove/memset of the entire aggregate.
706 // Split into one per element.
707 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Chris Lattner8bf99112007-03-19 00:16:43 +0000708 continue;
709 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000710
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000711 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000712 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000713 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
714 continue;
715 }
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000716
717 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
718 // If this is a load of the entire alloca to an integer, rewrite it.
719 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
720 continue;
721 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000722
723 // Otherwise it must be some other user of a gep of the first pointer. Just
724 // leave these alone.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000725 continue;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000726 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000727}
728
729/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
730/// Rewrite it to copy or set the elements of the scalarized memory.
731void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
732 AllocationInst *AI,
733 SmallVector<AllocaInst*, 32> &NewElts) {
734
735 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000736 // appropriate type. The "Other" pointer is the pointer that goes to memory
737 // that doesn't have anything to do with the alloca that we are promoting. For
738 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000739 Value *OtherPtr = 0;
Owen Andersone922c022009-07-22 00:24:57 +0000740 LLVMContext &Context = MI->getContext();
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000741 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000742 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
743 if (BCInst == MTI->getRawDest())
744 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000745 else {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000746 assert(BCInst == MTI->getRawSource());
747 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000748 }
749 }
750
751 // If there is an other pointer, we want to convert it to the same pointer
752 // type as AI has, so we can GEP through it safely.
753 if (OtherPtr) {
754 // It is likely that OtherPtr is a bitcast, if so, remove it.
755 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
756 OtherPtr = BC->getOperand(0);
757 // All zero GEPs are effectively bitcasts.
758 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
759 if (GEP->hasAllZeroIndices())
760 OtherPtr = GEP->getOperand(0);
Chris Lattner372dda82007-03-05 07:52:57 +0000761
Chris Lattnerd93afec2009-01-07 07:18:45 +0000762 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
763 if (BCE->getOpcode() == Instruction::BitCast)
764 OtherPtr = BCE->getOperand(0);
765
766 // If the pointer is not the right type, insert a bitcast to the right
767 // type.
768 if (OtherPtr->getType() != AI->getType())
769 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
770 MI);
771 }
772
773 // Process each element of the aggregate.
774 Value *TheFn = MI->getOperand(0);
775 const Type *BytePtrTy = MI->getRawDest()->getType();
776 bool SROADest = MI->getRawDest() == BCInst;
777
Owen Anderson1d0be152009-08-13 21:58:54 +0000778 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
Chris Lattnerd93afec2009-01-07 07:18:45 +0000779
780 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
781 // If this is a memcpy/memmove, emit a GEP of the other element address.
782 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000783 unsigned OtherEltAlign = MemAlignment;
784
Chris Lattner372dda82007-03-05 07:52:57 +0000785 if (OtherPtr) {
Owen Anderson1d0be152009-08-13 21:58:54 +0000786 Value *Idx[2] = { Zero,
787 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) };
Chris Lattnerd93afec2009-01-07 07:18:45 +0000788 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Daniel Dunbarfe09b202009-07-30 17:37:43 +0000789 OtherPtr->getNameStr()+"."+Twine(i),
Chris Lattnerd93afec2009-01-07 07:18:45 +0000790 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000791 uint64_t EltOffset;
792 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
793 if (const StructType *ST =
794 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
795 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
796 } else {
797 const Type *EltTy =
798 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000799 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000800 }
801
802 // The alignment of the other pointer is the guaranteed alignment of the
803 // element, which is affected by both the known alignment of the whole
804 // mem intrinsic and the alignment of the element. If the alignment of
805 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
806 // known alignment is just 4 bytes.
807 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000808 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000809
810 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000811 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000812
813 // If we got down to a scalar, insert a load or store as appropriate.
814 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000815 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000816 if (SROADest) {
817 // From Other to Alloca.
818 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
819 new StoreInst(Elt, EltPtr, MI);
820 } else {
821 // From Alloca to Other.
822 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
823 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
824 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000825 continue;
826 }
827 assert(isa<MemSetInst>(MI));
828
829 // If the stored element is zero (common case), just store a null
830 // constant.
831 Constant *StoreVal;
832 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
833 if (CI->isZero()) {
Owen Andersona7235ea2009-07-31 20:28:14 +0000834 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000835 } else {
836 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000837 const Type *ValTy = EltTy->getScalarType();
838
Chris Lattnerd93afec2009-01-07 07:18:45 +0000839 // Construct an integer with the right value.
840 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
841 APInt OneVal(EltSize, CI->getZExtValue());
842 APInt TotalVal(OneVal);
843 // Set each byte.
844 for (unsigned i = 0; 8*i < EltSize; ++i) {
845 TotalVal = TotalVal.shl(8);
846 TotalVal |= OneVal;
847 }
848
849 // Convert the integer value to the appropriate type.
Owen Andersoneed707b2009-07-24 23:12:02 +0000850 StoreVal = ConstantInt::get(Context, TotalVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000851 if (isa<PointerType>(ValTy))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000852 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000853 else if (ValTy->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000854 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000855 assert(StoreVal->getType() == ValTy && "Type mismatch!");
856
857 // If the requested value was a vector constant, create it.
858 if (EltTy != ValTy) {
859 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
860 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonaf7ec972009-07-28 21:19:26 +0000861 StoreVal = ConstantVector::get(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000862 }
863 }
864 new StoreInst(StoreVal, EltPtr, MI);
865 continue;
866 }
867 // Otherwise, if we're storing a byte variable, use a memset call for
868 // this element.
869 }
870
871 // Cast the element pointer to BytePtrTy.
872 if (EltPtr->getType() != BytePtrTy)
873 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
874
875 // Cast the other pointer (if we have one) to BytePtrTy.
876 if (OtherElt && OtherElt->getType() != BytePtrTy)
877 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
878 MI);
879
Duncan Sands777d2302009-05-09 07:06:46 +0000880 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000881
882 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000883 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000884 Value *Ops[] = {
885 SROADest ? EltPtr : OtherElt, // Dest ptr
886 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersoneed707b2009-07-24 23:12:02 +0000887 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Owen Anderson1d0be152009-08-13 21:58:54 +0000888 // Align
889 ConstantInt::get(Type::getInt32Ty(MI->getContext()), OtherEltAlign)
Chris Lattnerd93afec2009-01-07 07:18:45 +0000890 };
891 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
892 } else {
893 assert(isa<MemSetInst>(MI));
894 Value *Ops[] = {
895 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersoneed707b2009-07-24 23:12:02 +0000896 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000897 Zero // Align
898 };
899 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
900 }
Chris Lattner372dda82007-03-05 07:52:57 +0000901 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000902 MI->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000903}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000904
905/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
906/// overwrites the entire allocation. Extract out the pieces of the stored
907/// integer and store them individually.
908void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
909 AllocationInst *AI,
910 SmallVector<AllocaInst*, 32> &NewElts){
911 // Extract each element out of the integer according to its structure offset
912 // and store the element value to the individual alloca.
913 Value *SrcVal = SI->getOperand(0);
914 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000915 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000916
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000917 // If this isn't a store of an integer to the whole alloca, it may be a store
918 // to the first element. Just ignore the store in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +0000919 // will handle it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000920 if (!isa<IntegerType>(SrcVal->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +0000921 TD->getTypeAllocSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000922 return;
Eli Friedman41b33f42009-06-01 09:14:32 +0000923 // Handle tail padding by extending the operand
924 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000925 SrcVal = new ZExtInst(SrcVal,
Owen Anderson1d0be152009-08-13 21:58:54 +0000926 IntegerType::get(SI->getContext(), AllocaSizeBits),
927 "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000928
Nick Lewycky59136252009-09-15 07:08:25 +0000929 DEBUG(errs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI
930 << '\n');
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
Nick Lewycky59136252009-09-15 07:08:25 +00001046 DEBUG(errs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI
1047 << '\n');
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001048
1049 // There are two forms here: AI could be an array or struct. Both cases
1050 // have different ways to compute the element offset.
1051 const StructLayout *Layout = 0;
1052 uint64_t ArrayEltBitOffset = 0;
1053 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1054 Layout = TD->getStructLayout(EltSTy);
1055 } else {
1056 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001057 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001058 }
Owen Andersone922c022009-07-22 00:24:57 +00001059
Owen Andersone922c022009-07-22 00:24:57 +00001060 Value *ResultVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001061 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001062
1063 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1064 // Load the value from the alloca. If the NewElt is an aggregate, cast
1065 // the pointer to an integer of the same size before doing the load.
1066 Value *SrcField = NewElts[i];
1067 const Type *FieldTy =
1068 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001069 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1070
1071 // Ignore zero sized fields like {}, they obviously contain no data.
1072 if (FieldSizeBits == 0) continue;
1073
Owen Anderson1d0be152009-08-13 21:58:54 +00001074 const IntegerType *FieldIntTy = IntegerType::get(LI->getContext(),
1075 FieldSizeBits);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001076 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1077 !isa<VectorType>(FieldTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001078 SrcField = new BitCastInst(SrcField,
Owen Andersondebcb012009-07-29 22:17:13 +00001079 PointerType::getUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001080 "", LI);
1081 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1082
1083 // If SrcField is a fp or vector of the right size but that isn't an
1084 // integer type, bitcast to an integer so we can shift it.
1085 if (SrcField->getType() != FieldIntTy)
1086 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1087
1088 // Zero extend the field to be the same size as the final alloca so that
1089 // we can shift and insert it.
1090 if (SrcField->getType() != ResultVal->getType())
1091 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1092
1093 // Determine the number of bits to shift SrcField.
1094 uint64_t Shift;
1095 if (Layout) // Struct case.
1096 Shift = Layout->getElementOffsetInBits(i);
1097 else // Array case.
1098 Shift = i*ArrayEltBitOffset;
1099
1100 if (TD->isBigEndian())
1101 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1102
1103 if (Shift) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001104 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001105 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1106 }
1107
1108 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1109 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001110
1111 // Handle tail padding by truncating the result
1112 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1113 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1114
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001115 LI->replaceAllUsesWith(ResultVal);
1116 LI->eraseFromParent();
1117}
1118
Chris Lattner372dda82007-03-05 07:52:57 +00001119
Duncan Sands3cb36502007-11-04 14:43:57 +00001120/// HasPadding - Return true if the specified type has any structure or
1121/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001122static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001123 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1124 const StructLayout *SL = TD.getStructLayout(STy);
1125 unsigned PrevFieldBitOffset = 0;
1126 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001127 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1128
Chris Lattner39a1c042007-05-30 06:11:23 +00001129 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001130 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001131 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001132
Chris Lattner39a1c042007-05-30 06:11:23 +00001133 // Check to see if there is any padding between this element and the
1134 // previous one.
1135 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001136 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001137 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1138 if (PrevFieldEnd < FieldBitOffset)
1139 return true;
1140 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001141
Chris Lattner39a1c042007-05-30 06:11:23 +00001142 PrevFieldBitOffset = FieldBitOffset;
1143 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001144
Chris Lattner39a1c042007-05-30 06:11:23 +00001145 // Check for tail padding.
1146 if (unsigned EltCount = STy->getNumElements()) {
1147 unsigned PrevFieldEnd = PrevFieldBitOffset +
1148 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001149 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001150 return true;
1151 }
1152
1153 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001154 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001155 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001156 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001157 }
Duncan Sands777d2302009-05-09 07:06:46 +00001158 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001159}
Chris Lattner372dda82007-03-05 07:52:57 +00001160
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001161/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1162/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1163/// or 1 if safe after canonicalization has been performed.
Chris Lattner5e062a12003-05-30 04:15:41 +00001164///
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001165int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001166 // Loop over the use list of the alloca. We can only transform it if all of
1167 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001168 AllocaInfo Info;
1169
Chris Lattner5e062a12003-05-30 04:15:41 +00001170 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001171 I != E; ++I) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001172 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1173 if (Info.isUnsafe) {
Nick Lewycky59136252009-09-15 07:08:25 +00001174 DEBUG(errs() << "Cannot transform: " << *AI << "\n due to user: "
1175 << **I << '\n');
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001176 return 0;
Chris Lattner5e062a12003-05-30 04:15:41 +00001177 }
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001178 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001179
1180 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1181 // source and destination, we have to be careful. In particular, the memcpy
1182 // could be moving around elements that live in structure padding of the LLVM
1183 // types, but may actually be used. In these cases, we refuse to promote the
1184 // struct.
1185 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner56c38522009-01-07 06:34:28 +00001186 HasPadding(AI->getType()->getElementType(), *TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001187 return 0;
Duncan Sands3cb36502007-11-04 14:43:57 +00001188
Chris Lattner39a1c042007-05-30 06:11:23 +00001189 // If we require cleanup, return 1, otherwise return 3.
Devang Patel4afc90d2009-02-10 07:00:59 +00001190 return Info.needsCleanup ? 1 : 3;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001191}
1192
Devang Patel4afc90d2009-02-10 07:00:59 +00001193/// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1194/// is canonicalized here.
1195void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1196 gep_type_iterator I = gep_type_begin(GEPI);
1197 ++I;
1198
Devang Patel7afe8fa2009-02-10 19:28:07 +00001199 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1200 if (!AT)
1201 return;
1202
1203 uint64_t NumElements = AT->getNumElements();
1204
1205 if (isa<ConstantInt>(I.getOperand()))
1206 return;
1207
1208 if (NumElements == 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001209 GEPI->setOperand(2,
1210 Constant::getNullValue(Type::getInt32Ty(GEPI->getContext())));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001211 return;
1212 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001213
Devang Patel7afe8fa2009-02-10 19:28:07 +00001214 assert(NumElements == 2 && "Unhandled case!");
1215 // All users of the GEP must be loads. At each use of the GEP, insert
1216 // two loads of the appropriate indexed GEP and select between them.
Owen Anderson333c4002009-07-09 23:48:35 +00001217 Value *IsOne = new ICmpInst(GEPI, ICmpInst::ICMP_NE, I.getOperand(),
Owen Andersona7235ea2009-07-31 20:28:14 +00001218 Constant::getNullValue(I.getOperand()->getType()),
Owen Anderson333c4002009-07-09 23:48:35 +00001219 "isone");
Devang Patel7afe8fa2009-02-10 19:28:07 +00001220 // Insert the new GEP instructions, which are properly indexed.
1221 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Owen Anderson1d0be152009-08-13 21:58:54 +00001222 Indices[1] = Constant::getNullValue(Type::getInt32Ty(GEPI->getContext()));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001223 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1224 Indices.begin(),
1225 Indices.end(),
1226 GEPI->getName()+".0", GEPI);
Owen Anderson1d0be152009-08-13 21:58:54 +00001227 Indices[1] = ConstantInt::get(Type::getInt32Ty(GEPI->getContext()), 1);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001228 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1229 Indices.begin(),
1230 Indices.end(),
1231 GEPI->getName()+".1", GEPI);
1232 // Replace all loads of the variable index GEP with loads from both
1233 // indexes and a select.
1234 while (!GEPI->use_empty()) {
1235 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1236 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1237 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1238 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1239 LI->replaceAllUsesWith(R);
1240 LI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001241 }
Devang Patel7afe8fa2009-02-10 19:28:07 +00001242 GEPI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001243}
1244
Devang Patel7afe8fa2009-02-10 19:28:07 +00001245
Devang Patel4afc90d2009-02-10 07:00:59 +00001246/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001247/// allocation, but only if cleaned up, perform the cleanups required.
Devang Patel4afc90d2009-02-10 07:00:59 +00001248void SROA::CleanupAllocaUsers(AllocationInst *AI) {
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001249 // At this point, we know that the end result will be SROA'd and promoted, so
1250 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1251 // up.
1252 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1253 UI != E; ) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001254 User *U = *UI++;
1255 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1256 CleanupGEP(GEPI);
Jay Foad0906b1b2009-06-06 17:49:35 +00001257 else {
1258 Instruction *I = cast<Instruction>(U);
Devang Patel4afc90d2009-02-10 07:00:59 +00001259 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
Zhou Shengb0c41992009-03-18 12:48:48 +00001260 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001261 // Safe to remove debug info uses.
1262 while (!DbgInUses.empty()) {
1263 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1264 DI->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001265 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001266 I->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001267 }
1268 }
1269 }
Chris Lattner5e062a12003-05-30 04:15:41 +00001270}
Chris Lattnera1888942005-12-12 07:19:13 +00001271
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001272/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1273/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001274///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001275/// There are two cases we handle here:
1276/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001277/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001278/// This promotes a <4 x float> with a store of float to the third element
1279/// into a <4 x float> that uses insert element.
1280/// 2) A fully general blob of memory, which we turn into some (potentially
1281/// large) integer type with extract and insert operations where the loads
1282/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001283static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001284 unsigned AllocaSize, const TargetData &TD,
Owen Andersone922c022009-07-22 00:24:57 +00001285 LLVMContext &Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001286 // If this could be contributing to a vector, analyze it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001287 if (VecTy != Type::getVoidTy(Context)) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001288
Chris Lattner7809ecd2009-02-03 01:30:09 +00001289 // If the In type is a vector that is the same size as the alloca, see if it
1290 // matches the existing VecTy.
1291 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1292 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1293 // If we're storing/loading a vector of the right size, allow it as a
1294 // vector. If this the first vector we see, remember the type so that
1295 // we know the element size.
1296 if (VecTy == 0)
1297 VecTy = VInTy;
1298 return;
1299 }
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001300 } else if (In->isFloatTy() || In->isDoubleTy() ||
Chris Lattner7809ecd2009-02-03 01:30:09 +00001301 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1302 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1303 // If we're accessing something that could be an element of a vector, see
1304 // if the implied vector agrees with what we already have and if Offset is
1305 // compatible with it.
1306 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1307 if (Offset % EltSize == 0 &&
1308 AllocaSize % EltSize == 0 &&
1309 (VecTy == 0 ||
1310 cast<VectorType>(VecTy)->getElementType()
1311 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1312 if (VecTy == 0)
Owen Andersondebcb012009-07-29 22:17:13 +00001313 VecTy = VectorType::get(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001314 return;
1315 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001316 }
1317 }
1318
Chris Lattner7809ecd2009-02-03 01:30:09 +00001319 // Otherwise, we have a case that we can't handle with an optimized vector
1320 // form. We can still turn this into a large integer.
Owen Anderson1d0be152009-08-13 21:58:54 +00001321 VecTy = Type::getVoidTy(Context);
Chris Lattnera1888942005-12-12 07:19:13 +00001322}
1323
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001324/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Chris Lattner7809ecd2009-02-03 01:30:09 +00001325/// its accesses to use a to single vector type, return true, and set VecTy to
1326/// the new type. If we could convert the alloca into a single promotable
1327/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1328/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1329/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001330///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001331/// If we see at least one access to the value that is as a vector type, set the
1332/// SawVec flag.
1333///
1334bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1335 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001336 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001337 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1338 Instruction *User = cast<Instruction>(*UI);
1339
1340 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001341 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001342 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001343 return false;
Owen Andersone922c022009-07-22 00:24:57 +00001344 MergeInType(LI->getType(), Offset, VecTy,
1345 AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001346 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001347 continue;
1348 }
1349
1350 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001351 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001352 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001353 MergeInType(SI->getOperand(0)->getType(), Offset,
Owen Andersone922c022009-07-22 00:24:57 +00001354 VecTy, AllocaSize, *TD, V->getContext());
Chris Lattner1a3257b2009-02-03 18:15:05 +00001355 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001356 continue;
1357 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001358
1359 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001360 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1361 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001362 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001363 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001364 continue;
1365 }
1366
1367 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001368 // If this is a GEP with a variable indices, we can't handle it.
1369 if (!GEP->hasAllConstantIndices())
1370 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001371
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001372 // Compute the offset that this GEP adds to the pointer.
1373 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1374 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1375 &Indices[0], Indices.size());
1376 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001377 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001378 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001379 return false;
1380 IsNotTrivial = true;
1381 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001382 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001383
Chris Lattner3d730f72009-02-03 02:01:43 +00001384 // If this is a constant sized memset of a constant value (e.g. 0) we can
1385 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001386 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1387 // Store of constant value and constant size.
1388 if (isa<ConstantInt>(MSI->getValue()) &&
1389 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001390 IsNotTrivial = true;
1391 continue;
1392 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001393 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001394
1395 // If this is a memcpy or memmove into or out of the whole allocation, we
1396 // can handle it like a load or store of the scalar type.
1397 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1398 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1399 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1400 IsNotTrivial = true;
1401 continue;
1402 }
1403 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001404
Devang Patel00e389c2009-03-06 07:03:54 +00001405 // Ignore dbg intrinsic.
1406 if (isa<DbgInfoIntrinsic>(User))
1407 continue;
1408
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001409 // Otherwise, we cannot handle this!
1410 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001411 }
1412
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001413 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001414}
1415
Chris Lattnera1888942005-12-12 07:19:13 +00001416
1417/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001418/// directly. This happens when we are converting an "integer union" to a
1419/// single integer scalar, or when we are converting a "vector union" to a
1420/// vector with insert/extractelement instructions.
1421///
1422/// Offset is an offset from the original alloca, in bits that need to be
1423/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001424void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001425 while (!Ptr->use_empty()) {
1426 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001427
Chris Lattnercf321862009-01-07 06:39:58 +00001428 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001429 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001430 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001431 continue;
1432 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001433
Chris Lattnercf321862009-01-07 06:39:58 +00001434 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001435 // Compute the offset that this GEP adds to the pointer.
1436 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1437 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1438 &Indices[0], Indices.size());
1439 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001440 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001441 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001442 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001443
Chris Lattner9bc67da2009-02-03 19:45:44 +00001444 IRBuilder<> Builder(User->getParent(), User);
1445
1446 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001447 // The load is a bit extract from NewAI shifted right by Offset bits.
1448 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1449 Value *NewLoadVal
1450 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1451 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001452 LI->eraseFromParent();
1453 continue;
1454 }
1455
1456 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1457 assert(SI->getOperand(0) != Ptr && "Consistency error!");
Daniel Dunbar6e0d1cb2009-07-25 04:41:11 +00001458 // FIXME: Remove once builder has Twine API.
1459 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").str().c_str());
Chris Lattner9bc67da2009-02-03 19:45:44 +00001460 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1461 Builder);
1462 Builder.CreateStore(New, NewAI);
1463 SI->eraseFromParent();
1464 continue;
1465 }
1466
Chris Lattner3d730f72009-02-03 02:01:43 +00001467 // If this is a constant sized memset of a constant value (e.g. 0) we can
1468 // transform it into a store of the expanded constant value.
1469 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1470 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1471 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001472 if (NumBytes != 0) {
1473 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1474
1475 // Compute the value replicated the right number of times.
1476 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001477
Chris Lattner33e24ad2009-04-21 16:52:12 +00001478 // Splat the value if non-zero.
1479 if (Val)
1480 for (unsigned i = 1; i != NumBytes; ++i)
1481 APVal |= APVal << 8;
1482
Daniel Dunbar6e0d1cb2009-07-25 04:41:11 +00001483 // FIXME: Remove once builder has Twine API.
1484 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").str().c_str());
Owen Andersone922c022009-07-22 00:24:57 +00001485 Value *New = ConvertScalar_InsertValue(
Owen Andersoneed707b2009-07-24 23:12:02 +00001486 ConstantInt::get(User->getContext(), APVal),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001487 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001488 Builder.CreateStore(New, NewAI);
1489 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001490 MSI->eraseFromParent();
1491 continue;
1492 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001493
1494 // If this is a memcpy or memmove into or out of the whole allocation, we
1495 // can handle it like a load or store of the scalar type.
1496 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1497 assert(Offset == 0 && "must be store to start of alloca");
1498
1499 // If the source and destination are both to the same alloca, then this is
1500 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1501 // as appropriate.
1502 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1503
1504 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1505 // Dest must be OrigAI, change this to be a load from the original
1506 // pointer (bitcasted), then a store to our new alloca.
1507 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1508 Value *SrcPtr = MTI->getSource();
1509 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1510
1511 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1512 SrcVal->setAlignment(MTI->getAlignment());
1513 Builder.CreateStore(SrcVal, NewAI);
1514 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1515 // Src must be OrigAI, change this to be a load from NewAI then a store
1516 // through the original dest pointer (bitcasted).
1517 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1518 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1519
1520 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1521 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1522 NewStore->setAlignment(MTI->getAlignment());
1523 } else {
1524 // Noop transfer. Src == Dst
1525 }
1526
1527
1528 MTI->eraseFromParent();
1529 continue;
1530 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001531
Devang Patel00e389c2009-03-06 07:03:54 +00001532 // If user is a dbg info intrinsic then it is safe to remove it.
1533 if (isa<DbgInfoIntrinsic>(User)) {
1534 User->eraseFromParent();
1535 continue;
1536 }
1537
Torok Edwinc23197a2009-07-14 16:55:14 +00001538 llvm_unreachable("Unsupported operation!");
Chris Lattnera1888942005-12-12 07:19:13 +00001539 }
1540}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001541
Chris Lattner6e011152009-02-03 21:01:03 +00001542/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1543/// or vector value FromVal, extracting the bits from the offset specified by
1544/// Offset. This returns the value, which is of type ToType.
1545///
1546/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001547/// integer scalar, or when we are converting a "vector union" to a vector with
1548/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001549///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001550/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001551/// shifted to the right.
1552Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1553 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001554 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001555 if (FromVal->getType() == ToType && Offset == 0)
1556 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001557
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001558 // If the result alloca is a vector type, this is either an element
1559 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001560 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1561 if (isa<VectorType>(ToType))
1562 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001563
1564 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001565 unsigned Elt = 0;
1566 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001567 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001568 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001569 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001570 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001571 // Return the element extracted out of it.
Owen Anderson1d0be152009-08-13 21:58:54 +00001572 Value *V = Builder.CreateExtractElement(FromVal, ConstantInt::get(
1573 Type::getInt32Ty(FromVal->getContext()), Elt), "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001574 if (V->getType() != ToType)
1575 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001576 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001577 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001578
1579 // If ToType is a first class aggregate, extract out each of the pieces and
1580 // use insertvalue's to form the FCA.
1581 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1582 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001583 Value *Res = UndefValue::get(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001584 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1585 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001586 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001587 Builder);
1588 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1589 }
1590 return Res;
1591 }
1592
1593 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001594 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001595 Value *Res = UndefValue::get(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001596 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1597 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1598 Offset+i*EltSize, Builder);
1599 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1600 }
1601 return Res;
1602 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001603
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001604 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001605 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001606
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001607 // If this is a big-endian system and the load is narrower than the
1608 // full alloca type, we need to do a shift to get the right bits.
1609 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001610 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001611 // On big-endian machines, the lowest bit is stored at the bit offset
1612 // from the pointer given by getTypeStoreSizeInBits. This matters for
1613 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001614 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001615 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001616 } else {
1617 ShAmt = Offset;
1618 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001619
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001620 // Note: we support negative bitwidths (with shl) which are not defined.
1621 // We do this to support (f.e.) loads off the end of a structure where
1622 // only some bits are used.
1623 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001624 FromVal = Builder.CreateLShr(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001625 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001626 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001627 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001628 FromVal = Builder.CreateShl(FromVal,
Owen Andersoneed707b2009-07-24 23:12:02 +00001629 ConstantInt::get(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001630 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001631
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001632 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001633 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001634 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001635 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001636 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(),
1637 LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001638 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001639 FromVal =
Owen Anderson1d0be152009-08-13 21:58:54 +00001640 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(),
1641 LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001642
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001643 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner6e011152009-02-03 21:01:03 +00001644 if (isa<IntegerType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001645 // Should be done.
Chris Lattner6e011152009-02-03 21:01:03 +00001646 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001647 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001648 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001649 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001650 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001651 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001652 }
Chris Lattner6e011152009-02-03 21:01:03 +00001653 assert(FromVal->getType() == ToType && "Didn't convert right?");
1654 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001655}
1656
1657
Chris Lattner9b872db2009-02-03 19:30:11 +00001658/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1659/// or vector value "Old" at the offset specified by Offset.
1660///
1661/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001662/// single integer scalar, or when we are converting a "vector union" to a
1663/// vector with insert/extractelement instructions.
1664///
1665/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001666/// shifted to the right.
1667Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001668 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001669
Chris Lattner800de312008-02-29 07:03:13 +00001670 // Convert the stored type to the actual type, shift it left to insert
1671 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001672 const Type *AllocaType = Old->getType();
Owen Andersone922c022009-07-22 00:24:57 +00001673 LLVMContext &Context = Old->getContext();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001674
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001675 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001676 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1677 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001678
1679 // Changing the whole vector with memset or with an access of a different
1680 // vector type?
1681 if (ValSize == VecSize)
1682 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1683
Duncan Sands777d2302009-05-09 07:06:46 +00001684 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001685
1686 // Must be an element insertion.
1687 unsigned Elt = Offset/EltSize;
1688
1689 if (SV->getType() != VTy->getElementType())
1690 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1691
1692 SV = Builder.CreateInsertElement(Old, SV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001693 ConstantInt::get(Type::getInt32Ty(SV->getContext()), Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001694 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001695 return SV;
1696 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001697
1698 // If SV is a first-class aggregate value, insert each value recursively.
1699 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1700 const StructLayout &Layout = *TD->getStructLayout(ST);
1701 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001702 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001703 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001704 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001705 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001706 }
1707 return Old;
1708 }
1709
1710 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001711 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001712 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001713 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1714 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001715 }
1716 return Old;
1717 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001718
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001719 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001720 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001721 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1722 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1723 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1724 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1725 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001726 SV = Builder.CreateBitCast(SV,
1727 IntegerType::get(SV->getContext(),SrcWidth), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001728 else if (isa<PointerType>(SV->getType()))
Owen Anderson1d0be152009-08-13 21:58:54 +00001729 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(SV->getContext()), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001730
Chris Lattner7809ecd2009-02-03 01:30:09 +00001731 // Zero extend or truncate the value if needed.
1732 if (SV->getType() != AllocaType) {
1733 if (SV->getType()->getPrimitiveSizeInBits() <
1734 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001735 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001736 else {
1737 // Truncation may be needed if storing more than the alloca can hold
1738 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001739 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001740 SrcWidth = DestWidth;
1741 SrcStoreWidth = DestStoreWidth;
1742 }
1743 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001744
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001745 // If this is a big-endian system and the store is narrower than the
1746 // full alloca type, we need to do a shift to get the right bits.
1747 int ShAmt = 0;
1748 if (TD->isBigEndian()) {
1749 // On big-endian machines, the lowest bit is stored at the bit offset
1750 // from the pointer given by getTypeStoreSizeInBits. This matters for
1751 // integers with a bitwidth that is not a multiple of 8.
1752 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001753 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001754 ShAmt = Offset;
1755 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001756
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001757 // Note: we support negative bitwidths (with shr) which are not defined.
1758 // We do this to support (f.e.) stores off the end of a structure where
1759 // only some bits in the structure are set.
1760 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1761 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001762 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001763 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001764 Mask <<= ShAmt;
1765 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001766 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001767 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001768 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001769 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001770
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001771 // Mask out the bits we are about to insert from the old value, and or
1772 // in the new bits.
1773 if (SrcWidth != DestWidth) {
1774 assert(DestWidth > SrcWidth);
Owen Andersoneed707b2009-07-24 23:12:02 +00001775 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001776 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001777 }
1778 return SV;
1779}
1780
1781
Chris Lattner79b3bd32007-04-25 06:40:51 +00001782
1783/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1784/// some part of a constant global variable. This intentionally only accepts
1785/// constant expressions because we don't can't rewrite arbitrary instructions.
1786static bool PointsToConstantGlobal(Value *V) {
1787 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1788 return GV->isConstant();
1789 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1790 if (CE->getOpcode() == Instruction::BitCast ||
1791 CE->getOpcode() == Instruction::GetElementPtr)
1792 return PointsToConstantGlobal(CE->getOperand(0));
1793 return false;
1794}
1795
1796/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1797/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1798/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1799/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1800/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1801/// the alloca, and if the source pointer is a pointer to a constant global, we
1802/// can optimize this.
1803static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1804 bool isOffset) {
1805 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001806 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1807 // Ignore non-volatile loads, they are always ok.
1808 if (!LI->isVolatile())
1809 continue;
1810
Chris Lattner79b3bd32007-04-25 06:40:51 +00001811 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1812 // If uses of the bitcast are ok, we are ok.
1813 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1814 return false;
1815 continue;
1816 }
1817 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1818 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1819 // doesn't, it does.
1820 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1821 isOffset || !GEP->hasAllZeroIndices()))
1822 return false;
1823 continue;
1824 }
1825
1826 // If this is isn't our memcpy/memmove, reject it as something we can't
1827 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001828 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001829 return false;
1830
1831 // If we already have seen a copy, reject the second one.
1832 if (TheCopy) return false;
1833
1834 // If the pointer has been offset from the start of the alloca, we can't
1835 // safely handle this.
1836 if (isOffset) return false;
1837
1838 // If the memintrinsic isn't using the alloca as the dest, reject it.
1839 if (UI.getOperandNo() != 1) return false;
1840
1841 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1842
1843 // If the source of the memcpy/move is not a constant global, reject it.
1844 if (!PointsToConstantGlobal(MI->getOperand(2)))
1845 return false;
1846
1847 // Otherwise, the transform is safe. Remember the copy instruction.
1848 TheCopy = MI;
1849 }
1850 return true;
1851}
1852
1853/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1854/// modified by a copy from a constant global. If we can prove this, we can
1855/// replace any uses of the alloca with uses of the global directly.
1856Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1857 Instruction *TheCopy = 0;
1858 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1859 return TheCopy;
1860 return 0;
1861}