blob: cdb06285e0ea35e201866f49606926b4a4e8d9ce [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"
Chris Lattnera1888942005-12-12 07:19:13 +000037#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattner65a65022009-02-03 19:41:50 +000038#include "llvm/Support/IRBuilder.h"
Chris Lattnera1888942005-12-12 07:19:13 +000039#include "llvm/Support/MathExtras.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000040#include "llvm/Support/Compiler.h"
Chris Lattner1ccd1852007-02-12 22:56:41 +000041#include "llvm/ADT/SmallVector.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000042#include "llvm/ADT/Statistic.h"
43#include "llvm/ADT/StringExtras.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 Lattner95255282006-06-28 23:17:24 +000052 struct VISIBILITY_HIDDEN 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>();
71 AU.addRequired<TargetData>();
Chris Lattnera15854c2003-08-31 00:45:13 +000072 AU.setPreservesCFG();
73 }
74
Chris Lattnered7b41e2003-05-27 15:45:27 +000075 private:
Chris Lattner56c38522009-01-07 06:34:28 +000076 TargetData *TD;
77
Chris Lattner39a1c042007-05-30 06:11:23 +000078 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
79 /// information about the uses. All these fields are initialized to false
80 /// and set to true when something is learned.
81 struct AllocaInfo {
82 /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
83 bool isUnsafe : 1;
84
Devang Patel4afc90d2009-02-10 07:00:59 +000085 /// needsCleanup - This is set to true if there is some use of the alloca
86 /// that requires cleanup.
87 bool needsCleanup : 1;
Chris Lattner39a1c042007-05-30 06:11:23 +000088
89 /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
90 bool isMemCpySrc : 1;
91
Zhou Sheng33b0b8d2007-07-06 06:01:16 +000092 /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
Chris Lattner39a1c042007-05-30 06:11:23 +000093 bool isMemCpyDst : 1;
94
95 AllocaInfo()
Devang Patel4afc90d2009-02-10 07:00:59 +000096 : isUnsafe(false), needsCleanup(false),
Chris Lattner39a1c042007-05-30 06:11:23 +000097 isMemCpySrc(false), isMemCpyDst(false) {}
98 };
99
Devang Patelff366852007-07-09 21:19:23 +0000100 unsigned SRThreshold;
101
Chris Lattner39a1c042007-05-30 06:11:23 +0000102 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; }
103
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000104 int isSafeAllocaToScalarRepl(AllocationInst *AI);
Chris Lattner39a1c042007-05-30 06:11:23 +0000105
106 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
107 AllocaInfo &Info);
108 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
109 AllocaInfo &Info);
110 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
111 unsigned OpNo, AllocaInfo &Info);
112 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI,
113 AllocaInfo &Info);
114
Chris Lattnera10b29b2007-04-25 05:02:56 +0000115 void DoScalarReplacement(AllocationInst *AI,
116 std::vector<AllocationInst*> &WorkList);
Devang Patel4afc90d2009-02-10 07:00:59 +0000117 void CleanupGEP(GetElementPtrInst *GEP);
118 void CleanupAllocaUsers(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000119 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base);
Chris Lattnera1888942005-12-12 07:19:13 +0000120
Chris Lattner8bf99112007-03-19 00:16:43 +0000121 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000122 SmallVector<AllocaInst*, 32> &NewElts);
123
Chris Lattnerd93afec2009-01-07 07:18:45 +0000124 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
125 AllocationInst *AI,
126 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000127 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI,
128 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000129 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
Chris Lattner6e733d32009-01-28 20:16:43 +0000130 SmallVector<AllocaInst*, 32> &NewElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000131
Chris Lattner7809ecd2009-02-03 01:30:09 +0000132 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
Chris Lattner1a3257b2009-02-03 18:15:05 +0000133 bool &SawVec, uint64_t Offset, unsigned AllocaSize);
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000134 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset);
Chris Lattner6e011152009-02-03 21:01:03 +0000135 Value *ConvertScalar_ExtractValue(Value *NV, const Type *ToType,
Chris Lattner9bc67da2009-02-03 19:45:44 +0000136 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +0000137 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal,
Chris Lattner65a65022009-02-03 19:41:50 +0000138 uint64_t Offset, IRBuilder<> &Builder);
Chris Lattner79b3bd32007-04-25 06:40:51 +0000139 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI);
Chris Lattnered7b41e2003-05-27 15:45:27 +0000140 };
Chris Lattnered7b41e2003-05-27 15:45:27 +0000141}
142
Dan Gohman844731a2008-05-13 00:00:25 +0000143char SROA::ID = 0;
144static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates");
145
Brian Gaeked0fde302003-11-11 22:41:34 +0000146// Public interface to the ScalarReplAggregates pass
Devang Patelff366852007-07-09 21:19:23 +0000147FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) {
148 return new SROA(Threshold);
149}
Chris Lattnered7b41e2003-05-27 15:45:27 +0000150
151
Chris Lattnered7b41e2003-05-27 15:45:27 +0000152bool SROA::runOnFunction(Function &F) {
Chris Lattner56c38522009-01-07 06:34:28 +0000153 TD = &getAnalysis<TargetData>();
154
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000155 bool Changed = performPromotion(F);
156 while (1) {
157 bool LocalChange = performScalarRepl(F);
158 if (!LocalChange) break; // No need to repromote if no scalarrepl
159 Changed = true;
160 LocalChange = performPromotion(F);
161 if (!LocalChange) break; // No need to re-scalarrepl if no promotion
162 }
Chris Lattner38aec322003-09-11 16:45:55 +0000163
164 return Changed;
165}
166
167
168bool SROA::performPromotion(Function &F) {
169 std::vector<AllocaInst*> Allocas;
Devang Patel326821e2007-06-07 21:57:03 +0000170 DominatorTree &DT = getAnalysis<DominatorTree>();
Chris Lattner43f820d2003-10-05 21:20:13 +0000171 DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
Chris Lattner38aec322003-09-11 16:45:55 +0000172
Chris Lattner02a3be02003-09-20 14:39:18 +0000173 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function
Chris Lattner38aec322003-09-11 16:45:55 +0000174
Chris Lattnerfe7ea0d2003-09-12 15:36:03 +0000175 bool Changed = false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000176
Chris Lattner38aec322003-09-11 16:45:55 +0000177 while (1) {
178 Allocas.clear();
179
180 // Find allocas that are safe to promote, by looking at all instructions in
181 // the entry node
182 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I)
183 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca?
Devang Patel41968df2007-04-25 17:15:20 +0000184 if (isAllocaPromotable(AI))
Chris Lattner38aec322003-09-11 16:45:55 +0000185 Allocas.push_back(AI);
186
187 if (Allocas.empty()) break;
188
Owen Anderson0a205a42009-07-05 22:41:43 +0000189 PromoteMemToReg(Allocas, DT, DF, Context);
Chris Lattner38aec322003-09-11 16:45:55 +0000190 NumPromoted += Allocas.size();
191 Changed = true;
192 }
193
194 return Changed;
195}
196
Chris Lattner963a97f2008-06-22 17:46:21 +0000197/// getNumSAElements - Return the number of elements in the specific struct or
198/// array.
199static uint64_t getNumSAElements(const Type *T) {
200 if (const StructType *ST = dyn_cast<StructType>(T))
201 return ST->getNumElements();
202 return cast<ArrayType>(T)->getNumElements();
203}
204
Chris Lattner38aec322003-09-11 16:45:55 +0000205// performScalarRepl - This algorithm is a simple worklist driven algorithm,
206// which runs on all of the malloc/alloca instructions in the function, removing
207// them if they are only used by getelementptr instructions.
208//
209bool SROA::performScalarRepl(Function &F) {
Chris Lattnered7b41e2003-05-27 15:45:27 +0000210 std::vector<AllocationInst*> WorkList;
211
212 // Scan the entry basic block, adding any alloca's and mallocs to the worklist
Chris Lattner02a3be02003-09-20 14:39:18 +0000213 BasicBlock &BB = F.getEntryBlock();
Chris Lattnered7b41e2003-05-27 15:45:27 +0000214 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
215 if (AllocationInst *A = dyn_cast<AllocationInst>(I))
216 WorkList.push_back(A);
217
218 // Process the worklist
219 bool Changed = false;
220 while (!WorkList.empty()) {
221 AllocationInst *AI = WorkList.back();
222 WorkList.pop_back();
Chris Lattnera1888942005-12-12 07:19:13 +0000223
Chris Lattneradd2bd72006-12-22 23:14:42 +0000224 // Handle dead allocas trivially. These can be formed by SROA'ing arrays
225 // with unused elements.
226 if (AI->use_empty()) {
227 AI->eraseFromParent();
228 continue;
229 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000230
231 // If this alloca is impossible for us to promote, reject it early.
232 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
233 continue;
Chris Lattner79b3bd32007-04-25 06:40:51 +0000234
235 // Check to see if this allocation is only modified by a memcpy/memmove from
236 // a constant global. If this is the case, we can change all users to use
237 // the constant global instead. This is commonly produced by the CFE by
238 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
239 // is only subsequently read.
240 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) {
241 DOUT << "Found alloca equal to global: " << *AI;
242 DOUT << " memcpy = " << *TheCopy;
243 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2));
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000244 AI->replaceAllUsesWith(
245 Context->getConstantExprBitCast(TheSrc, AI->getType()));
Chris Lattner79b3bd32007-04-25 06:40:51 +0000246 TheCopy->eraseFromParent(); // Don't mutate the global.
247 AI->eraseFromParent();
248 ++NumGlobals;
249 Changed = true;
250 continue;
251 }
Chris Lattner15c82772009-02-02 20:44:45 +0000252
Chris Lattner7809ecd2009-02-03 01:30:09 +0000253 // Check to see if we can perform the core SROA transformation. We cannot
254 // transform the allocation instruction if it is an array allocation
255 // (allocations OF arrays are ok though), and an allocation of a scalar
256 // value cannot be decomposed at all.
Duncan Sands777d2302009-05-09 07:06:46 +0000257 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
Bill Wendling5a377cb2009-03-03 12:12:58 +0000258
259 // Do not promote any struct whose size is too big.
Bill Wendling3aaf5d92009-03-03 19:18:49 +0000260 if (AllocaSize > SRThreshold) continue;
Bill Wendling8fe40812009-03-01 03:55:12 +0000261
Chris Lattner7809ecd2009-02-03 01:30:09 +0000262 if ((isa<StructType>(AI->getAllocatedType()) ||
263 isa<ArrayType>(AI->getAllocatedType())) &&
Chris Lattner7809ecd2009-02-03 01:30:09 +0000264 // Do not promote any struct into more than "32" separate vars.
Evan Cheng67fca632009-03-06 00:56:43 +0000265 getNumSAElements(AI->getAllocatedType()) <= SRThreshold/4) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000266 // Check that all of the users of the allocation are capable of being
267 // transformed.
268 switch (isSafeAllocaToScalarRepl(AI)) {
269 default: assert(0 && "Unexpected value!");
270 case 0: // Not safe to scalar replace.
271 break;
272 case 1: // Safe, but requires cleanup/canonicalizations first
Devang Patel4afc90d2009-02-10 07:00:59 +0000273 CleanupAllocaUsers(AI);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000274 // FALL THROUGH.
275 case 3: // Safe to scalar replace.
276 DoScalarReplacement(AI, WorkList);
277 Changed = true;
278 continue;
279 }
280 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000281
282 // If we can turn this aggregate value (potentially with casts) into a
283 // simple scalar value that can be mem2reg'd into a register value.
Chris Lattner2e0d5f82009-01-31 02:28:54 +0000284 // IsNotTrivial tracks whether this is something that mem2reg could have
285 // promoted itself. If so, we don't want to transform it needlessly. Note
286 // that we can't just check based on the type: the alloca may be of an i32
287 // but that has pointer arithmetic to set byte 3 of it or something.
Chris Lattner6e733d32009-01-28 20:16:43 +0000288 bool IsNotTrivial = false;
Chris Lattner7809ecd2009-02-03 01:30:09 +0000289 const Type *VectorTy = 0;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000290 bool HadAVector = false;
291 if (CanConvertToScalar(AI, IsNotTrivial, VectorTy, HadAVector,
Chris Lattner0ff83ab2009-03-04 19:22:30 +0000292 0, unsigned(AllocaSize)) && IsNotTrivial) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000293 AllocaInst *NewAI;
Chris Lattner1a3257b2009-02-03 18:15:05 +0000294 // If we were able to find a vector type that can handle this with
295 // insert/extract elements, and if there was at least one use that had
296 // a vector type, promote this to a vector. We don't want to promote
297 // random stuff that doesn't use vectors (e.g. <9 x double>) because then
298 // we just get a lot of insert/extracts. If at least one vector is
299 // involved, then we probably really do have a union of vector/array.
300 if (VectorTy && isa<VectorType>(VectorTy) && HadAVector) {
Chris Lattner7809ecd2009-02-03 01:30:09 +0000301 DOUT << "CONVERT TO VECTOR: " << *AI << " TYPE = " << *VectorTy <<"\n";
Chris Lattner15c82772009-02-02 20:44:45 +0000302
Chris Lattner7809ecd2009-02-03 01:30:09 +0000303 // Create and insert the vector alloca.
304 NewAI = new AllocaInst(VectorTy, 0, "", AI->getParent()->begin());
Chris Lattner15c82772009-02-02 20:44:45 +0000305 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000306 } else {
307 DOUT << "CONVERT TO SCALAR INTEGER: " << *AI << "\n";
308
309 // Create and insert the integer alloca.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000310 const Type *NewTy = Context->getIntegerType(AllocaSize*8);
Chris Lattner7809ecd2009-02-03 01:30:09 +0000311 NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin());
312 ConvertUsesToScalar(AI, NewAI, 0);
Chris Lattner6e733d32009-01-28 20:16:43 +0000313 }
Chris Lattner7809ecd2009-02-03 01:30:09 +0000314 NewAI->takeName(AI);
315 AI->eraseFromParent();
316 ++NumConverted;
317 Changed = true;
318 continue;
319 }
Chris Lattner6e733d32009-01-28 20:16:43 +0000320
Chris Lattner7809ecd2009-02-03 01:30:09 +0000321 // Otherwise, couldn't process this alloca.
Chris Lattnered7b41e2003-05-27 15:45:27 +0000322 }
323
324 return Changed;
325}
Chris Lattner5e062a12003-05-30 04:15:41 +0000326
Chris Lattnera10b29b2007-04-25 05:02:56 +0000327/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl
328/// predicate, do SROA now.
329void SROA::DoScalarReplacement(AllocationInst *AI,
330 std::vector<AllocationInst*> &WorkList) {
Chris Lattner79b3bd32007-04-25 06:40:51 +0000331 DOUT << "Found inst to SROA: " << *AI;
Chris Lattnera10b29b2007-04-25 05:02:56 +0000332 SmallVector<AllocaInst*, 32> ElementAllocas;
333 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) {
334 ElementAllocas.reserve(ST->getNumContainedTypes());
335 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) {
336 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0,
337 AI->getAlignment(),
338 AI->getName() + "." + utostr(i), AI);
339 ElementAllocas.push_back(NA);
340 WorkList.push_back(NA); // Add to worklist for recursive processing
341 }
342 } else {
343 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType());
344 ElementAllocas.reserve(AT->getNumElements());
345 const Type *ElTy = AT->getElementType();
346 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
347 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(),
348 AI->getName() + "." + utostr(i), AI);
349 ElementAllocas.push_back(NA);
350 WorkList.push_back(NA); // Add to worklist for recursive processing
351 }
352 }
353
354 // Now that we have created the alloca instructions that we want to use,
355 // expand the getelementptr instructions to use them.
356 //
357 while (!AI->use_empty()) {
358 Instruction *User = cast<Instruction>(AI->use_back());
359 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) {
360 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas);
361 BCInst->eraseFromParent();
362 continue;
363 }
364
Chris Lattner2a6a6452008-06-23 17:11:23 +0000365 // Replace:
366 // %res = load { i32, i32 }* %alloc
367 // with:
368 // %load.0 = load i32* %alloc.0
369 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0
370 // %load.1 = load i32* %alloc.1
371 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000372 // (Also works for arrays instead of structs)
373 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000374 Value *Insert = Context->getUndef(LI->getType());
Matthijs Kooijman02518142008-06-05 12:51:53 +0000375 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
376 Value *Load = new LoadInst(ElementAllocas[i], "load", LI);
377 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI);
378 }
379 LI->replaceAllUsesWith(Insert);
380 LI->eraseFromParent();
381 continue;
382 }
383
Chris Lattner2a6a6452008-06-23 17:11:23 +0000384 // Replace:
385 // store { i32, i32 } %val, { i32, i32 }* %alloc
386 // with:
387 // %val.0 = extractvalue { i32, i32 } %val, 0
388 // store i32 %val.0, i32* %alloc.0
389 // %val.1 = extractvalue { i32, i32 } %val, 1
390 // store i32 %val.1, i32* %alloc.1
Matthijs Kooijman02518142008-06-05 12:51:53 +0000391 // (Also works for arrays instead of structs)
392 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
393 Value *Val = SI->getOperand(0);
394 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) {
395 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI);
396 new StoreInst(Extract, ElementAllocas[i], SI);
397 }
398 SI->eraseFromParent();
399 continue;
400 }
401
Chris Lattnera10b29b2007-04-25 05:02:56 +0000402 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
403 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst>
404 unsigned Idx =
405 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
406
407 assert(Idx < ElementAllocas.size() && "Index out of range?");
408 AllocaInst *AllocaToUse = ElementAllocas[Idx];
409
410 Value *RepValue;
411 if (GEPI->getNumOperands() == 3) {
412 // Do not insert a new getelementptr instruction with zero indices, only
413 // to have it optimized out later.
414 RepValue = AllocaToUse;
415 } else {
416 // We are indexing deeply into the structure, so we still need a
417 // getelement ptr instruction to finish the indexing. This may be
418 // expanded itself once the worklist is rerun.
419 //
420 SmallVector<Value*, 8> NewArgs;
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000421 NewArgs.push_back(Context->getNullValue(Type::Int32Ty));
Chris Lattnera10b29b2007-04-25 05:02:56 +0000422 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end());
Gabor Greif051a9502008-04-06 20:25:17 +0000423 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(),
424 NewArgs.end(), "", GEPI);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000425 RepValue->takeName(GEPI);
426 }
427
428 // If this GEP is to the start of the aggregate, check for memcpys.
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000429 if (Idx == 0 && GEPI->hasAllZeroIndices())
430 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas);
Chris Lattnera10b29b2007-04-25 05:02:56 +0000431
432 // Move all of the users over to the new GEP.
433 GEPI->replaceAllUsesWith(RepValue);
434 // Delete the old GEP
435 GEPI->eraseFromParent();
436 }
437
438 // Finally, delete the Alloca instruction
439 AI->eraseFromParent();
440 NumReplaced++;
441}
442
Chris Lattner5e062a12003-05-30 04:15:41 +0000443
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000444/// isSafeElementUse - Check to see if this use is an allowed use for a
Chris Lattner8bf99112007-03-19 00:16:43 +0000445/// getelementptr instruction of an array aggregate allocation. isFirstElt
446/// indicates whether Ptr is known to the start of the aggregate.
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000447///
Chris Lattner39a1c042007-05-30 06:11:23 +0000448void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI,
449 AllocaInfo &Info) {
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000450 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
451 I != E; ++I) {
452 Instruction *User = cast<Instruction>(*I);
453 switch (User->getOpcode()) {
454 case Instruction::Load: break;
455 case Instruction::Store:
456 // Store is ok if storing INTO the pointer, not storing the pointer
Chris Lattner39a1c042007-05-30 06:11:23 +0000457 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000458 break;
459 case Instruction::GetElementPtr: {
460 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User);
Chris Lattner8bf99112007-03-19 00:16:43 +0000461 bool AreAllZeroIndices = isFirstElt;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000462 if (GEP->getNumOperands() > 1) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000463 if (!isa<ConstantInt>(GEP->getOperand(1)) ||
464 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
Chris Lattner39a1c042007-05-30 06:11:23 +0000465 // Using pointer arithmetic to navigate the array.
466 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000467
Chris Lattnerd356a7e2009-01-07 06:25:07 +0000468 if (AreAllZeroIndices)
469 AreAllZeroIndices = GEP->hasAllZeroIndices();
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000470 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000471 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info);
472 if (Info.isUnsafe) return;
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000473 break;
474 }
Chris Lattner8bf99112007-03-19 00:16:43 +0000475 case Instruction::BitCast:
Chris Lattner39a1c042007-05-30 06:11:23 +0000476 if (isFirstElt) {
477 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info);
478 if (Info.isUnsafe) return;
Chris Lattner8bf99112007-03-19 00:16:43 +0000479 break;
Chris Lattner8bf99112007-03-19 00:16:43 +0000480 }
481 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner39a1c042007-05-30 06:11:23 +0000482 return MarkUnsafe(Info);
483 case Instruction::Call:
484 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
485 if (isFirstElt) {
486 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info);
487 if (Info.isUnsafe) return;
488 break;
489 }
490 }
491 DOUT << " Transformation preventing inst: " << *User;
492 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000493 default:
Bill Wendlingb7427032006-11-26 09:46:52 +0000494 DOUT << " Transformation preventing inst: " << *User;
Chris Lattner39a1c042007-05-30 06:11:23 +0000495 return MarkUnsafe(Info);
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000496 }
497 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000498 return; // All users look ok :)
Chris Lattnerf5990ed2004-11-14 04:24:28 +0000499}
500
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000501/// AllUsersAreLoads - Return true if all users of this value are loads.
502static bool AllUsersAreLoads(Value *Ptr) {
503 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end();
504 I != E; ++I)
505 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load)
506 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +0000507 return true;
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000508}
509
Chris Lattner5e062a12003-05-30 04:15:41 +0000510/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an
511/// aggregate allocation.
512///
Chris Lattner39a1c042007-05-30 06:11:23 +0000513void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI,
514 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000515 if (BitCastInst *C = dyn_cast<BitCastInst>(User))
Chris Lattner39a1c042007-05-30 06:11:23 +0000516 return isSafeUseOfBitCastedAllocation(C, AI, Info);
Chris Lattnerbe883a22003-11-25 21:09:18 +0000517
Chris Lattner6e733d32009-01-28 20:16:43 +0000518 if (LoadInst *LI = dyn_cast<LoadInst>(User))
519 if (!LI->isVolatile())
520 return;// Loads (returning a first class aggregrate) are always rewritable
Matthijs Kooijman02518142008-06-05 12:51:53 +0000521
Chris Lattner6e733d32009-01-28 20:16:43 +0000522 if (StoreInst *SI = dyn_cast<StoreInst>(User))
523 if (!SI->isVolatile() && SI->getOperand(0) != AI)
524 return;// Store is ok if storing INTO the pointer, not storing the pointer
Matthijs Kooijman02518142008-06-05 12:51:53 +0000525
Chris Lattner39a1c042007-05-30 06:11:23 +0000526 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User);
527 if (GEPI == 0)
528 return MarkUnsafe(Info);
529
Chris Lattnerbe883a22003-11-25 21:09:18 +0000530 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI);
531
Chris Lattner25de4862006-03-08 01:05:29 +0000532 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>".
Chris Lattnerbe883a22003-11-25 21:09:18 +0000533 if (I == E ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000534 I.getOperand() != Context->getNullValue(I.getOperand()->getType())) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000535 return MarkUnsafe(Info);
536 }
Chris Lattnerbe883a22003-11-25 21:09:18 +0000537
538 ++I;
Chris Lattner39a1c042007-05-30 06:11:23 +0000539 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices??
Chris Lattnerbe883a22003-11-25 21:09:18 +0000540
Chris Lattner8bf99112007-03-19 00:16:43 +0000541 bool IsAllZeroIndices = true;
542
Chris Lattner88e6dc82008-08-23 05:21:06 +0000543 // If the first index is a non-constant index into an array, see if we can
544 // handle it as a special case.
Chris Lattnerbe883a22003-11-25 21:09:18 +0000545 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
Chris Lattner88e6dc82008-08-23 05:21:06 +0000546 if (!isa<ConstantInt>(I.getOperand())) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000547 IsAllZeroIndices = 0;
Chris Lattner88e6dc82008-08-23 05:21:06 +0000548 uint64_t NumElements = AT->getNumElements();
Chris Lattner8bf99112007-03-19 00:16:43 +0000549
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000550 // If this is an array index and the index is not constant, we cannot
551 // promote... that is unless the array has exactly one or two elements in
552 // it, in which case we CAN promote it, but we have to canonicalize this
553 // out if this is the only problem.
Chris Lattner25de4862006-03-08 01:05:29 +0000554 if ((NumElements == 1 || NumElements == 2) &&
Chris Lattner39a1c042007-05-30 06:11:23 +0000555 AllUsersAreLoads(GEPI)) {
Devang Patel4afc90d2009-02-10 07:00:59 +0000556 Info.needsCleanup = true;
Chris Lattner39a1c042007-05-30 06:11:23 +0000557 return; // Canonicalization required!
558 }
559 return MarkUnsafe(Info);
Chris Lattnerd878ecd2004-11-14 05:00:19 +0000560 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000561 }
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000562
Chris Lattner88e6dc82008-08-23 05:21:06 +0000563 // Walk through the GEP type indices, checking the types that this indexes
564 // into.
565 for (; I != E; ++I) {
566 // Ignore struct elements, no extra checking needed for these.
567 if (isa<StructType>(*I))
568 continue;
569
Chris Lattner88e6dc82008-08-23 05:21:06 +0000570 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand());
571 if (!IdxVal) return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000572
573 // Are all indices still zero?
Chris Lattner88e6dc82008-08-23 05:21:06 +0000574 IsAllZeroIndices &= IdxVal->isZero();
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000575
576 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) {
577 // This GEP indexes an array. Verify that this is an in-range constant
578 // integer. Specifically, consider A[0][i]. We cannot know that the user
579 // isn't doing invalid things like allowing i to index an out-of-range
580 // subscript that accesses A[1]. Because of this, we have to reject SROA
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000581 // of any accesses into structs where any of the components are variables.
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000582 if (IdxVal->getZExtValue() >= AT->getNumElements())
583 return MarkUnsafe(Info);
Dale Johannesenc0bc5472008-11-04 20:54:03 +0000584 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) {
585 if (IdxVal->getZExtValue() >= VT->getNumElements())
586 return MarkUnsafe(Info);
Matthijs Kooijman5fac55f2008-10-06 16:23:31 +0000587 }
Chris Lattner88e6dc82008-08-23 05:21:06 +0000588 }
589
Chris Lattnerbe883a22003-11-25 21:09:18 +0000590 // If there are any non-simple uses of this getelementptr, make sure to reject
591 // them.
Chris Lattner39a1c042007-05-30 06:11:23 +0000592 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000593}
594
595/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory
596/// intrinsic can be promoted by SROA. At this point, we know that the operand
597/// of the memintrinsic is a pointer to the beginning of the allocation.
Chris Lattner39a1c042007-05-30 06:11:23 +0000598void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI,
599 unsigned OpNo, AllocaInfo &Info) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000600 // If not constant length, give up.
601 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
Chris Lattner39a1c042007-05-30 06:11:23 +0000602 if (!Length) return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000603
604 // If not the whole aggregate, give up.
Duncan Sands3cb36502007-11-04 14:43:57 +0000605 if (Length->getZExtValue() !=
Duncan Sands777d2302009-05-09 07:06:46 +0000606 TD->getTypeAllocSize(AI->getType()->getElementType()))
Chris Lattner39a1c042007-05-30 06:11:23 +0000607 return MarkUnsafe(Info);
Chris Lattner8bf99112007-03-19 00:16:43 +0000608
609 // We only know about memcpy/memset/memmove.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000610 if (!isa<MemIntrinsic>(MI))
Chris Lattner39a1c042007-05-30 06:11:23 +0000611 return MarkUnsafe(Info);
612
613 // Otherwise, we can transform it. Determine whether this is a memcpy/set
614 // into or out of the aggregate.
615 if (OpNo == 1)
616 Info.isMemCpyDst = true;
617 else {
618 assert(OpNo == 2);
619 Info.isMemCpySrc = true;
620 }
Chris Lattner5e062a12003-05-30 04:15:41 +0000621}
622
Chris Lattner372dda82007-03-05 07:52:57 +0000623/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast
624/// are
Chris Lattner39a1c042007-05-30 06:11:23 +0000625void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI,
626 AllocaInfo &Info) {
Chris Lattner372dda82007-03-05 07:52:57 +0000627 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end();
628 UI != E; ++UI) {
629 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000630 isSafeUseOfBitCastedAllocation(BCU, AI, Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000631 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) {
Chris Lattner39a1c042007-05-30 06:11:23 +0000632 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000633 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000634 if (SI->isVolatile())
635 return MarkUnsafe(Info);
636
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000637 // If storing the entire alloca in one chunk through a bitcasted pointer
638 // to integer, we can transform it. This happens (for example) when you
639 // cast a {i32,i32}* to i64* and store through it. This is similar to the
640 // memcpy case and occurs in various "byval" cases and emulated memcpys.
641 if (isa<IntegerType>(SI->getOperand(0)->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000642 TD->getTypeAllocSize(SI->getOperand(0)->getType()) ==
643 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000644 Info.isMemCpyDst = true;
645 continue;
646 }
647 return MarkUnsafe(Info);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000648 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
Chris Lattner6e733d32009-01-28 20:16:43 +0000649 if (LI->isVolatile())
650 return MarkUnsafe(Info);
651
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000652 // If loading the entire alloca in one chunk through a bitcasted pointer
653 // to integer, we can transform it. This happens (for example) when you
654 // cast a {i32,i32}* to i64* and load through it. This is similar to the
655 // memcpy case and occurs in various "byval" cases and emulated memcpys.
656 if (isa<IntegerType>(LI->getType()) &&
Duncan Sands777d2302009-05-09 07:06:46 +0000657 TD->getTypeAllocSize(LI->getType()) ==
658 TD->getTypeAllocSize(AI->getType()->getElementType())) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000659 Info.isMemCpySrc = true;
660 continue;
661 }
662 return MarkUnsafe(Info);
Devang Patel4afc90d2009-02-10 07:00:59 +0000663 } else if (isa<DbgInfoIntrinsic>(UI)) {
664 // If one user is DbgInfoIntrinsic then check if all users are
665 // DbgInfoIntrinsics.
666 if (OnlyUsedByDbgInfoIntrinsics(BC)) {
667 Info.needsCleanup = true;
668 return;
669 }
670 else
671 MarkUnsafe(Info);
672 }
673 else {
Chris Lattner39a1c042007-05-30 06:11:23 +0000674 return MarkUnsafe(Info);
Chris Lattner372dda82007-03-05 07:52:57 +0000675 }
Chris Lattner39a1c042007-05-30 06:11:23 +0000676 if (Info.isUnsafe) return;
Chris Lattner372dda82007-03-05 07:52:57 +0000677 }
Chris Lattner372dda82007-03-05 07:52:57 +0000678}
679
Chris Lattner8bf99112007-03-19 00:16:43 +0000680/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes
681/// to its first element. Transform users of the cast to use the new values
682/// instead.
683void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI,
Chris Lattner372dda82007-03-05 07:52:57 +0000684 SmallVector<AllocaInst*, 32> &NewElts) {
Chris Lattner8bf99112007-03-19 00:16:43 +0000685 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end();
686 while (UI != UE) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000687 Instruction *User = cast<Instruction>(*UI++);
688 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) {
Chris Lattner372dda82007-03-05 07:52:57 +0000689 RewriteBitCastUserOfAlloca(BCU, AI, NewElts);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000690 if (BCU->use_empty()) BCU->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000691 continue;
692 }
693
Chris Lattnerd93afec2009-01-07 07:18:45 +0000694 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
695 // This must be memcpy/memmove/memset of the entire aggregate.
696 // Split into one per element.
697 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts);
Chris Lattner8bf99112007-03-19 00:16:43 +0000698 continue;
699 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000700
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000701 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000702 // If this is a store of the entire alloca from an integer, rewrite it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000703 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts);
704 continue;
705 }
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000706
707 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
708 // If this is a load of the entire alloca to an integer, rewrite it.
709 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts);
710 continue;
711 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000712
713 // Otherwise it must be some other user of a gep of the first pointer. Just
714 // leave these alone.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000715 continue;
Chris Lattner5ffe6ac2009-01-08 05:42:05 +0000716 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000717}
718
719/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI.
720/// Rewrite it to copy or set the elements of the scalarized memory.
721void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst,
722 AllocationInst *AI,
723 SmallVector<AllocaInst*, 32> &NewElts) {
724
725 // If this is a memcpy/memmove, construct the other pointer as the
Chris Lattner88fe1ad2009-03-04 19:23:25 +0000726 // appropriate type. The "Other" pointer is the pointer that goes to memory
727 // that doesn't have anything to do with the alloca that we are promoting. For
728 // memset, this Value* stays null.
Chris Lattnerd93afec2009-01-07 07:18:45 +0000729 Value *OtherPtr = 0;
Chris Lattnerdfe964c2009-03-08 03:59:00 +0000730 unsigned MemAlignment = MI->getAlignment();
Chris Lattner3ce5e882009-03-08 03:37:16 +0000731 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
732 if (BCInst == MTI->getRawDest())
733 OtherPtr = MTI->getRawSource();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000734 else {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000735 assert(BCInst == MTI->getRawSource());
736 OtherPtr = MTI->getRawDest();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000737 }
738 }
739
740 // If there is an other pointer, we want to convert it to the same pointer
741 // type as AI has, so we can GEP through it safely.
742 if (OtherPtr) {
743 // It is likely that OtherPtr is a bitcast, if so, remove it.
744 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr))
745 OtherPtr = BC->getOperand(0);
746 // All zero GEPs are effectively bitcasts.
747 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr))
748 if (GEP->hasAllZeroIndices())
749 OtherPtr = GEP->getOperand(0);
Chris Lattner372dda82007-03-05 07:52:57 +0000750
Chris Lattnerd93afec2009-01-07 07:18:45 +0000751 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr))
752 if (BCE->getOpcode() == Instruction::BitCast)
753 OtherPtr = BCE->getOperand(0);
754
755 // If the pointer is not the right type, insert a bitcast to the right
756 // type.
757 if (OtherPtr->getType() != AI->getType())
758 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(),
759 MI);
760 }
761
762 // Process each element of the aggregate.
763 Value *TheFn = MI->getOperand(0);
764 const Type *BytePtrTy = MI->getRawDest()->getType();
765 bool SROADest = MI->getRawDest() == BCInst;
766
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000767 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000768
769 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
770 // If this is a memcpy/memmove, emit a GEP of the other element address.
771 Value *OtherElt = 0;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000772 unsigned OtherEltAlign = MemAlignment;
773
Chris Lattner372dda82007-03-05 07:52:57 +0000774 if (OtherPtr) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000775 Value *Idx[2] = { Zero, Context->getConstantInt(Type::Int32Ty, i) };
Chris Lattnerd93afec2009-01-07 07:18:45 +0000776 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2,
Chris Lattner963a97f2008-06-22 17:46:21 +0000777 OtherPtr->getNameStr()+"."+utostr(i),
Chris Lattnerd93afec2009-01-07 07:18:45 +0000778 MI);
Chris Lattner1541e0f2009-03-04 19:20:50 +0000779 uint64_t EltOffset;
780 const PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
781 if (const StructType *ST =
782 dyn_cast<StructType>(OtherPtrTy->getElementType())) {
783 EltOffset = TD->getStructLayout(ST)->getElementOffset(i);
784 } else {
785 const Type *EltTy =
786 cast<SequentialType>(OtherPtr->getType())->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000787 EltOffset = TD->getTypeAllocSize(EltTy)*i;
Chris Lattner1541e0f2009-03-04 19:20:50 +0000788 }
789
790 // The alignment of the other pointer is the guaranteed alignment of the
791 // element, which is affected by both the known alignment of the whole
792 // mem intrinsic and the alignment of the element. If the alignment of
793 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
794 // known alignment is just 4 bytes.
795 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
Chris Lattnerc14d3ca2007-03-08 06:36:54 +0000796 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000797
798 Value *EltPtr = NewElts[i];
Chris Lattner1541e0f2009-03-04 19:20:50 +0000799 const Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
Chris Lattnerd93afec2009-01-07 07:18:45 +0000800
801 // If we got down to a scalar, insert a load or store as appropriate.
802 if (EltTy->isSingleValueType()) {
Chris Lattner3ce5e882009-03-08 03:37:16 +0000803 if (isa<MemTransferInst>(MI)) {
Chris Lattner1541e0f2009-03-04 19:20:50 +0000804 if (SROADest) {
805 // From Other to Alloca.
806 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
807 new StoreInst(Elt, EltPtr, MI);
808 } else {
809 // From Alloca to Other.
810 Value *Elt = new LoadInst(EltPtr, "tmp", MI);
811 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
812 }
Chris Lattnerd93afec2009-01-07 07:18:45 +0000813 continue;
814 }
815 assert(isa<MemSetInst>(MI));
816
817 // If the stored element is zero (common case), just store a null
818 // constant.
819 Constant *StoreVal;
820 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) {
821 if (CI->isZero()) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000822 StoreVal = Context->getNullValue(EltTy); // 0.0, null, 0, <0,0>
Chris Lattnerd93afec2009-01-07 07:18:45 +0000823 } else {
824 // If EltTy is a vector type, get the element type.
Dan Gohman44118f02009-06-16 00:20:26 +0000825 const Type *ValTy = EltTy->getScalarType();
826
Chris Lattnerd93afec2009-01-07 07:18:45 +0000827 // Construct an integer with the right value.
828 unsigned EltSize = TD->getTypeSizeInBits(ValTy);
829 APInt OneVal(EltSize, CI->getZExtValue());
830 APInt TotalVal(OneVal);
831 // Set each byte.
832 for (unsigned i = 0; 8*i < EltSize; ++i) {
833 TotalVal = TotalVal.shl(8);
834 TotalVal |= OneVal;
835 }
836
837 // Convert the integer value to the appropriate type.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000838 StoreVal = Context->getConstantInt(TotalVal);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000839 if (isa<PointerType>(ValTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000840 StoreVal = Context->getConstantExprIntToPtr(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000841 else if (ValTy->isFloatingPoint())
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000842 StoreVal = Context->getConstantExprBitCast(StoreVal, ValTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000843 assert(StoreVal->getType() == ValTy && "Type mismatch!");
844
845 // If the requested value was a vector constant, create it.
846 if (EltTy != ValTy) {
847 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements();
848 SmallVector<Constant*, 16> Elts(NumElts, StoreVal);
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000849 StoreVal = Context->getConstantVector(&Elts[0], NumElts);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000850 }
851 }
852 new StoreInst(StoreVal, EltPtr, MI);
853 continue;
854 }
855 // Otherwise, if we're storing a byte variable, use a memset call for
856 // this element.
857 }
858
859 // Cast the element pointer to BytePtrTy.
860 if (EltPtr->getType() != BytePtrTy)
861 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI);
862
863 // Cast the other pointer (if we have one) to BytePtrTy.
864 if (OtherElt && OtherElt->getType() != BytePtrTy)
865 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(),
866 MI);
867
Duncan Sands777d2302009-05-09 07:06:46 +0000868 unsigned EltSize = TD->getTypeAllocSize(EltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000869
870 // Finally, insert the meminst for this element.
Chris Lattner3ce5e882009-03-08 03:37:16 +0000871 if (isa<MemTransferInst>(MI)) {
Chris Lattnerd93afec2009-01-07 07:18:45 +0000872 Value *Ops[] = {
873 SROADest ? EltPtr : OtherElt, // Dest ptr
874 SROADest ? OtherElt : EltPtr, // Src ptr
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000875 Context->getConstantInt(MI->getOperand(3)->getType(), EltSize), // Size
876 Context->getConstantInt(Type::Int32Ty, OtherEltAlign) // Align
Chris Lattnerd93afec2009-01-07 07:18:45 +0000877 };
878 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
879 } else {
880 assert(isa<MemSetInst>(MI));
881 Value *Ops[] = {
882 EltPtr, MI->getOperand(2), // Dest, Value,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000883 Context->getConstantInt(MI->getOperand(3)->getType(), EltSize), // Size
Chris Lattnerd93afec2009-01-07 07:18:45 +0000884 Zero // Align
885 };
886 CallInst::Create(TheFn, Ops, Ops + 4, "", MI);
887 }
Chris Lattner372dda82007-03-05 07:52:57 +0000888 }
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000889 MI->eraseFromParent();
Chris Lattner372dda82007-03-05 07:52:57 +0000890}
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000891
892/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that
893/// overwrites the entire allocation. Extract out the pieces of the stored
894/// integer and store them individually.
895void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI,
896 AllocationInst *AI,
897 SmallVector<AllocaInst*, 32> &NewElts){
898 // Extract each element out of the integer according to its structure offset
899 // and store the element value to the individual alloca.
900 Value *SrcVal = SI->getOperand(0);
901 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000902 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattnerd93afec2009-01-07 07:18:45 +0000903
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000904 // If this isn't a store of an integer to the whole alloca, it may be a store
905 // to the first element. Just ignore the store in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +0000906 // will handle it.
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000907 if (!isa<IntegerType>(SrcVal->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +0000908 TD->getTypeAllocSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000909 return;
Eli Friedman41b33f42009-06-01 09:14:32 +0000910 // Handle tail padding by extending the operand
911 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000912 SrcVal = new ZExtInst(SrcVal,
913 Context->getIntegerType(AllocaSizeBits), "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000914
915 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI;
916
917 // There are two forms here: AI could be an array or struct. Both cases
918 // have different ways to compute the element offset.
919 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
920 const StructLayout *Layout = TD->getStructLayout(EltSTy);
921
922 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
923 // Get the number of bits to shift SrcVal to get the value.
924 const Type *FieldTy = EltSTy->getElementType(i);
925 uint64_t Shift = Layout->getElementOffsetInBits(i);
926
927 if (TD->isBigEndian())
Duncan Sands777d2302009-05-09 07:06:46 +0000928 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000929
930 Value *EltVal = SrcVal;
931 if (Shift) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000932 Value *ShiftVal = Context->getConstantInt(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000933 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
934 "sroa.store.elt", SI);
935 }
936
937 // Truncate down to an integer of the right size.
938 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
Chris Lattner583dd602009-01-09 18:18:43 +0000939
940 // Ignore zero sized fields like {}, they obviously contain no data.
941 if (FieldSizeBits == 0) continue;
942
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000943 if (FieldSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000944 EltVal = new TruncInst(EltVal,
945 Context->getIntegerType(FieldSizeBits), "", SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000946 Value *DestField = NewElts[i];
947 if (EltVal->getType() == FieldTy) {
948 // Storing to an integer field of this size, just do it.
949 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) {
950 // Bitcast to the right element type (for fp/vector values).
951 EltVal = new BitCastInst(EltVal, FieldTy, "", SI);
952 } else {
953 // Otherwise, bitcast the dest pointer (for aggregates).
954 DestField = new BitCastInst(DestField,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000955 Context->getPointerTypeUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000956 "", SI);
957 }
958 new StoreInst(EltVal, DestField, SI);
959 }
960
961 } else {
962 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy);
963 const Type *ArrayEltTy = ATy->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +0000964 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000965 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy);
966
967 uint64_t Shift;
968
969 if (TD->isBigEndian())
970 Shift = AllocaSizeBits-ElementOffset;
971 else
972 Shift = 0;
973
974 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
Chris Lattner583dd602009-01-09 18:18:43 +0000975 // Ignore zero sized fields like {}, they obviously contain no data.
976 if (ElementSizeBits == 0) continue;
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000977
978 Value *EltVal = SrcVal;
979 if (Shift) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000980 Value *ShiftVal = Context->getConstantInt(EltVal->getType(), Shift);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000981 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal,
982 "sroa.store.elt", SI);
983 }
984
985 // Truncate down to an integer of the right size.
986 if (ElementSizeBits != AllocaSizeBits)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000987 EltVal = new TruncInst(EltVal,
988 Context->getIntegerType(ElementSizeBits),"",SI);
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000989 Value *DestField = NewElts[i];
990 if (EltVal->getType() == ArrayEltTy) {
991 // Storing to an integer field of this size, just do it.
992 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) {
993 // Bitcast to the right element type (for fp/vector values).
994 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI);
995 } else {
996 // Otherwise, bitcast the dest pointer (for aggregates).
997 DestField = new BitCastInst(DestField,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000998 Context->getPointerTypeUnqual(EltVal->getType()),
Chris Lattnerd2fa7812009-01-07 08:11:13 +0000999 "", SI);
1000 }
1001 new StoreInst(EltVal, DestField, SI);
1002
1003 if (TD->isBigEndian())
1004 Shift -= ElementOffset;
1005 else
1006 Shift += ElementOffset;
1007 }
1008 }
1009
1010 SI->eraseFromParent();
1011}
1012
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001013/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to
1014/// an integer. Load the individual pieces to form the aggregate value.
1015void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI,
1016 SmallVector<AllocaInst*, 32> &NewElts) {
1017 // Extract each element out of the NewElts according to its structure offset
1018 // and form the result value.
1019 const Type *AllocaEltTy = AI->getType()->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001020 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001021
1022 // If this isn't a load of the whole alloca to an integer, it may be a load
1023 // of the first element. Just ignore the load in this case and normal SROA
Eli Friedman41b33f42009-06-01 09:14:32 +00001024 // will handle it.
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001025 if (!isa<IntegerType>(LI->getType()) ||
Eli Friedman41b33f42009-06-01 09:14:32 +00001026 TD->getTypeAllocSizeInBits(LI->getType()) != AllocaSizeBits)
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001027 return;
1028
1029 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI;
1030
1031 // There are two forms here: AI could be an array or struct. Both cases
1032 // have different ways to compute the element offset.
1033 const StructLayout *Layout = 0;
1034 uint64_t ArrayEltBitOffset = 0;
1035 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) {
1036 Layout = TD->getStructLayout(EltSTy);
1037 } else {
1038 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType();
Duncan Sands777d2302009-05-09 07:06:46 +00001039 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001040 }
1041
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001042 Value *ResultVal =
1043 Context->getNullValue(Context->getIntegerType(AllocaSizeBits));
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001044
1045 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
1046 // Load the value from the alloca. If the NewElt is an aggregate, cast
1047 // the pointer to an integer of the same size before doing the load.
1048 Value *SrcField = NewElts[i];
1049 const Type *FieldTy =
1050 cast<PointerType>(SrcField->getType())->getElementType();
Chris Lattner583dd602009-01-09 18:18:43 +00001051 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy);
1052
1053 // Ignore zero sized fields like {}, they obviously contain no data.
1054 if (FieldSizeBits == 0) continue;
1055
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001056 const IntegerType *FieldIntTy = Context->getIntegerType(FieldSizeBits);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001057 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() &&
1058 !isa<VectorType>(FieldTy))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001059 SrcField = new BitCastInst(SrcField,
1060 Context->getPointerTypeUnqual(FieldIntTy),
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001061 "", LI);
1062 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI);
1063
1064 // If SrcField is a fp or vector of the right size but that isn't an
1065 // integer type, bitcast to an integer so we can shift it.
1066 if (SrcField->getType() != FieldIntTy)
1067 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI);
1068
1069 // Zero extend the field to be the same size as the final alloca so that
1070 // we can shift and insert it.
1071 if (SrcField->getType() != ResultVal->getType())
1072 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI);
1073
1074 // Determine the number of bits to shift SrcField.
1075 uint64_t Shift;
1076 if (Layout) // Struct case.
1077 Shift = Layout->getElementOffsetInBits(i);
1078 else // Array case.
1079 Shift = i*ArrayEltBitOffset;
1080
1081 if (TD->isBigEndian())
1082 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth();
1083
1084 if (Shift) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001085 Value *ShiftVal = Context->getConstantInt(SrcField->getType(), Shift);
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001086 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI);
1087 }
1088
1089 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI);
1090 }
Eli Friedman41b33f42009-06-01 09:14:32 +00001091
1092 // Handle tail padding by truncating the result
1093 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits)
1094 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI);
1095
Chris Lattner5ffe6ac2009-01-08 05:42:05 +00001096 LI->replaceAllUsesWith(ResultVal);
1097 LI->eraseFromParent();
1098}
1099
Chris Lattner372dda82007-03-05 07:52:57 +00001100
Duncan Sands3cb36502007-11-04 14:43:57 +00001101/// HasPadding - Return true if the specified type has any structure or
1102/// alignment padding, false otherwise.
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001103static bool HasPadding(const Type *Ty, const TargetData &TD) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001104 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1105 const StructLayout *SL = TD.getStructLayout(STy);
1106 unsigned PrevFieldBitOffset = 0;
1107 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001108 unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
1109
Chris Lattner39a1c042007-05-30 06:11:23 +00001110 // Padding in sub-elements?
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001111 if (HasPadding(STy->getElementType(i), TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001112 return true;
Duncan Sands3cb36502007-11-04 14:43:57 +00001113
Chris Lattner39a1c042007-05-30 06:11:23 +00001114 // Check to see if there is any padding between this element and the
1115 // previous one.
1116 if (i) {
Duncan Sands3cb36502007-11-04 14:43:57 +00001117 unsigned PrevFieldEnd =
Chris Lattner39a1c042007-05-30 06:11:23 +00001118 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1));
1119 if (PrevFieldEnd < FieldBitOffset)
1120 return true;
1121 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001122
Chris Lattner39a1c042007-05-30 06:11:23 +00001123 PrevFieldBitOffset = FieldBitOffset;
1124 }
Duncan Sands3cb36502007-11-04 14:43:57 +00001125
Chris Lattner39a1c042007-05-30 06:11:23 +00001126 // Check for tail padding.
1127 if (unsigned EltCount = STy->getNumElements()) {
1128 unsigned PrevFieldEnd = PrevFieldBitOffset +
1129 TD.getTypeSizeInBits(STy->getElementType(EltCount-1));
Duncan Sands3cb36502007-11-04 14:43:57 +00001130 if (PrevFieldEnd < SL->getSizeInBits())
Chris Lattner39a1c042007-05-30 06:11:23 +00001131 return true;
1132 }
1133
1134 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001135 return HasPadding(ATy->getElementType(), TD);
Duncan Sands3cb36502007-11-04 14:43:57 +00001136 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
Duncan Sandsa0fcc082008-06-04 08:21:45 +00001137 return HasPadding(VTy->getElementType(), TD);
Chris Lattner39a1c042007-05-30 06:11:23 +00001138 }
Duncan Sands777d2302009-05-09 07:06:46 +00001139 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty);
Chris Lattner39a1c042007-05-30 06:11:23 +00001140}
Chris Lattner372dda82007-03-05 07:52:57 +00001141
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001142/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
1143/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
1144/// or 1 if safe after canonicalization has been performed.
Chris Lattner5e062a12003-05-30 04:15:41 +00001145///
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001146int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) {
Chris Lattner5e062a12003-05-30 04:15:41 +00001147 // Loop over the use list of the alloca. We can only transform it if all of
1148 // the users are safe to transform.
Chris Lattner39a1c042007-05-30 06:11:23 +00001149 AllocaInfo Info;
1150
Chris Lattner5e062a12003-05-30 04:15:41 +00001151 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end();
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001152 I != E; ++I) {
Chris Lattner39a1c042007-05-30 06:11:23 +00001153 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info);
1154 if (Info.isUnsafe) {
Bill Wendlingb7427032006-11-26 09:46:52 +00001155 DOUT << "Cannot transform: " << *AI << " due to user: " << **I;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001156 return 0;
Chris Lattner5e062a12003-05-30 04:15:41 +00001157 }
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001158 }
Chris Lattner39a1c042007-05-30 06:11:23 +00001159
1160 // Okay, we know all the users are promotable. If the aggregate is a memcpy
1161 // source and destination, we have to be careful. In particular, the memcpy
1162 // could be moving around elements that live in structure padding of the LLVM
1163 // types, but may actually be used. In these cases, we refuse to promote the
1164 // struct.
1165 if (Info.isMemCpySrc && Info.isMemCpyDst &&
Chris Lattner56c38522009-01-07 06:34:28 +00001166 HasPadding(AI->getType()->getElementType(), *TD))
Chris Lattner39a1c042007-05-30 06:11:23 +00001167 return 0;
Duncan Sands3cb36502007-11-04 14:43:57 +00001168
Chris Lattner39a1c042007-05-30 06:11:23 +00001169 // If we require cleanup, return 1, otherwise return 3.
Devang Patel4afc90d2009-02-10 07:00:59 +00001170 return Info.needsCleanup ? 1 : 3;
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001171}
1172
Devang Patel4afc90d2009-02-10 07:00:59 +00001173/// CleanupGEP - GEP is used by an Alloca, which can be prompted after the GEP
1174/// is canonicalized here.
1175void SROA::CleanupGEP(GetElementPtrInst *GEPI) {
1176 gep_type_iterator I = gep_type_begin(GEPI);
1177 ++I;
1178
Devang Patel7afe8fa2009-02-10 19:28:07 +00001179 const ArrayType *AT = dyn_cast<ArrayType>(*I);
1180 if (!AT)
1181 return;
1182
1183 uint64_t NumElements = AT->getNumElements();
1184
1185 if (isa<ConstantInt>(I.getOperand()))
1186 return;
1187
1188 if (NumElements == 1) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001189 GEPI->setOperand(2, Context->getNullValue(Type::Int32Ty));
Devang Patel7afe8fa2009-02-10 19:28:07 +00001190 return;
1191 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001192
Devang Patel7afe8fa2009-02-10 19:28:07 +00001193 assert(NumElements == 2 && "Unhandled case!");
1194 // All users of the GEP must be loads. At each use of the GEP, insert
1195 // two loads of the appropriate indexed GEP and select between them.
1196 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001197 Context->getNullValue(I.getOperand()->getType()),
Devang Patel7afe8fa2009-02-10 19:28:07 +00001198 "isone", GEPI);
1199 // Insert the new GEP instructions, which are properly indexed.
1200 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end());
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001201 Indices[1] = Context->getNullValue(Type::Int32Ty);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001202 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1203 Indices.begin(),
1204 Indices.end(),
1205 GEPI->getName()+".0", GEPI);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001206 Indices[1] = Context->getConstantInt(Type::Int32Ty, 1);
Devang Patel7afe8fa2009-02-10 19:28:07 +00001207 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0),
1208 Indices.begin(),
1209 Indices.end(),
1210 GEPI->getName()+".1", GEPI);
1211 // Replace all loads of the variable index GEP with loads from both
1212 // indexes and a select.
1213 while (!GEPI->use_empty()) {
1214 LoadInst *LI = cast<LoadInst>(GEPI->use_back());
1215 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI);
1216 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI);
1217 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI);
1218 LI->replaceAllUsesWith(R);
1219 LI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001220 }
Devang Patel7afe8fa2009-02-10 19:28:07 +00001221 GEPI->eraseFromParent();
Devang Patel4afc90d2009-02-10 07:00:59 +00001222}
1223
Devang Patel7afe8fa2009-02-10 19:28:07 +00001224
Devang Patel4afc90d2009-02-10 07:00:59 +00001225/// CleanupAllocaUsers - If SROA reported that it can promote the specified
Chris Lattnerf5990ed2004-11-14 04:24:28 +00001226/// allocation, but only if cleaned up, perform the cleanups required.
Devang Patel4afc90d2009-02-10 07:00:59 +00001227void SROA::CleanupAllocaUsers(AllocationInst *AI) {
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001228 // At this point, we know that the end result will be SROA'd and promoted, so
1229 // we can insert ugly code if required so long as sroa+mem2reg will clean it
1230 // up.
1231 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
1232 UI != E; ) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001233 User *U = *UI++;
1234 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U))
1235 CleanupGEP(GEPI);
Jay Foad0906b1b2009-06-06 17:49:35 +00001236 else {
1237 Instruction *I = cast<Instruction>(U);
Devang Patel4afc90d2009-02-10 07:00:59 +00001238 SmallVector<DbgInfoIntrinsic *, 2> DbgInUses;
Zhou Shengb0c41992009-03-18 12:48:48 +00001239 if (!isa<StoreInst>(I) && OnlyUsedByDbgInfoIntrinsics(I, &DbgInUses)) {
Devang Patel4afc90d2009-02-10 07:00:59 +00001240 // Safe to remove debug info uses.
1241 while (!DbgInUses.empty()) {
1242 DbgInfoIntrinsic *DI = DbgInUses.back(); DbgInUses.pop_back();
1243 DI->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001244 }
Devang Patel4afc90d2009-02-10 07:00:59 +00001245 I->eraseFromParent();
Chris Lattnerd878ecd2004-11-14 05:00:19 +00001246 }
1247 }
1248 }
Chris Lattner5e062a12003-05-30 04:15:41 +00001249}
Chris Lattnera1888942005-12-12 07:19:13 +00001250
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001251/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at
1252/// the offset specified by Offset (which is specified in bytes).
Chris Lattnerde6df882006-04-14 21:42:41 +00001253///
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001254/// There are two cases we handle here:
1255/// 1) A union of vector types of the same size and potentially its elements.
Chris Lattnerd22dbdf2006-12-15 07:32:38 +00001256/// Here we turn element accesses into insert/extract element operations.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001257/// This promotes a <4 x float> with a store of float to the third element
1258/// into a <4 x float> that uses insert element.
1259/// 2) A fully general blob of memory, which we turn into some (potentially
1260/// large) integer type with extract and insert operations where the loads
1261/// and stores would mutate the memory.
Chris Lattner7809ecd2009-02-03 01:30:09 +00001262static void MergeInType(const Type *In, uint64_t Offset, const Type *&VecTy,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001263 unsigned AllocaSize, const TargetData &TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00001264 LLVMContext *Context) {
Chris Lattner7809ecd2009-02-03 01:30:09 +00001265 // If this could be contributing to a vector, analyze it.
1266 if (VecTy != Type::VoidTy) { // either null or a vector type.
Chris Lattner996d7a92009-02-02 18:02:59 +00001267
Chris Lattner7809ecd2009-02-03 01:30:09 +00001268 // If the In type is a vector that is the same size as the alloca, see if it
1269 // matches the existing VecTy.
1270 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) {
1271 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) {
1272 // If we're storing/loading a vector of the right size, allow it as a
1273 // vector. If this the first vector we see, remember the type so that
1274 // we know the element size.
1275 if (VecTy == 0)
1276 VecTy = VInTy;
1277 return;
1278 }
1279 } else if (In == Type::FloatTy || In == Type::DoubleTy ||
1280 (isa<IntegerType>(In) && In->getPrimitiveSizeInBits() >= 8 &&
1281 isPowerOf2_32(In->getPrimitiveSizeInBits()))) {
1282 // If we're accessing something that could be an element of a vector, see
1283 // if the implied vector agrees with what we already have and if Offset is
1284 // compatible with it.
1285 unsigned EltSize = In->getPrimitiveSizeInBits()/8;
1286 if (Offset % EltSize == 0 &&
1287 AllocaSize % EltSize == 0 &&
1288 (VecTy == 0 ||
1289 cast<VectorType>(VecTy)->getElementType()
1290 ->getPrimitiveSizeInBits()/8 == EltSize)) {
1291 if (VecTy == 0)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001292 VecTy = Context->getVectorType(In, AllocaSize/EltSize);
Chris Lattner7809ecd2009-02-03 01:30:09 +00001293 return;
1294 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001295 }
1296 }
1297
Chris Lattner7809ecd2009-02-03 01:30:09 +00001298 // Otherwise, we have a case that we can't handle with an optimized vector
1299 // form. We can still turn this into a large integer.
1300 VecTy = Type::VoidTy;
Chris Lattnera1888942005-12-12 07:19:13 +00001301}
1302
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001303/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all
Chris Lattner7809ecd2009-02-03 01:30:09 +00001304/// its accesses to use a to single vector type, return true, and set VecTy to
1305/// the new type. If we could convert the alloca into a single promotable
1306/// integer, return true but set VecTy to VoidTy. Further, if the use is not a
1307/// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset
1308/// is the current offset from the base of the alloca being analyzed.
Chris Lattnera1888942005-12-12 07:19:13 +00001309///
Chris Lattner1a3257b2009-02-03 18:15:05 +00001310/// If we see at least one access to the value that is as a vector type, set the
1311/// SawVec flag.
1312///
1313bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&VecTy,
1314 bool &SawVec, uint64_t Offset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001315 unsigned AllocaSize) {
Chris Lattnera1888942005-12-12 07:19:13 +00001316 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
1317 Instruction *User = cast<Instruction>(*UI);
1318
1319 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001320 // Don't break volatile loads.
Chris Lattner6e733d32009-01-28 20:16:43 +00001321 if (LI->isVolatile())
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001322 return false;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001323 MergeInType(LI->getType(), Offset, VecTy, AllocaSize, *TD, Context);
Chris Lattner1a3257b2009-02-03 18:15:05 +00001324 SawVec |= isa<VectorType>(LI->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001325 continue;
1326 }
1327
1328 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
Reid Spencer24d6da52007-01-21 00:29:26 +00001329 // Storing the pointer, not into the value?
Chris Lattner6e733d32009-01-28 20:16:43 +00001330 if (SI->getOperand(0) == V || SI->isVolatile()) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001331 MergeInType(SI->getOperand(0)->getType(), Offset,
1332 VecTy, AllocaSize, *TD, Context);
Chris Lattner1a3257b2009-02-03 18:15:05 +00001333 SawVec |= isa<VectorType>(SI->getOperand(0)->getType());
Chris Lattnercf321862009-01-07 06:39:58 +00001334 continue;
1335 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001336
1337 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
Chris Lattner1a3257b2009-02-03 18:15:05 +00001338 if (!CanConvertToScalar(BCI, IsNotTrivial, VecTy, SawVec, Offset,
1339 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001340 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001341 IsNotTrivial = true;
Chris Lattnercf321862009-01-07 06:39:58 +00001342 continue;
1343 }
1344
1345 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001346 // If this is a GEP with a variable indices, we can't handle it.
1347 if (!GEP->hasAllConstantIndices())
1348 return false;
Chris Lattnercf321862009-01-07 06:39:58 +00001349
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001350 // Compute the offset that this GEP adds to the pointer.
1351 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1352 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1353 &Indices[0], Indices.size());
1354 // See if all uses can be converted.
Chris Lattner1a3257b2009-02-03 18:15:05 +00001355 if (!CanConvertToScalar(GEP, IsNotTrivial, VecTy, SawVec,Offset+GEPOffset,
Chris Lattner7809ecd2009-02-03 01:30:09 +00001356 AllocaSize))
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001357 return false;
1358 IsNotTrivial = true;
1359 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001360 }
Chris Lattner3ce5e882009-03-08 03:37:16 +00001361
Chris Lattner3d730f72009-02-03 02:01:43 +00001362 // If this is a constant sized memset of a constant value (e.g. 0) we can
1363 // handle it.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001364 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1365 // Store of constant value and constant size.
1366 if (isa<ConstantInt>(MSI->getValue()) &&
1367 isa<ConstantInt>(MSI->getLength())) {
Chris Lattner3ce5e882009-03-08 03:37:16 +00001368 IsNotTrivial = true;
1369 continue;
1370 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001371 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001372
1373 // If this is a memcpy or memmove into or out of the whole allocation, we
1374 // can handle it like a load or store of the scalar type.
1375 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1376 if (ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()))
1377 if (Len->getZExtValue() == AllocaSize && Offset == 0) {
1378 IsNotTrivial = true;
1379 continue;
1380 }
1381 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001382
Devang Patel00e389c2009-03-06 07:03:54 +00001383 // Ignore dbg intrinsic.
1384 if (isa<DbgInfoIntrinsic>(User))
1385 continue;
1386
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001387 // Otherwise, we cannot handle this!
1388 return false;
Chris Lattnera1888942005-12-12 07:19:13 +00001389 }
1390
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001391 return true;
Chris Lattnera1888942005-12-12 07:19:13 +00001392}
1393
Chris Lattnera1888942005-12-12 07:19:13 +00001394
1395/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca
Chris Lattnerde6df882006-04-14 21:42:41 +00001396/// directly. This happens when we are converting an "integer union" to a
1397/// single integer scalar, or when we are converting a "vector union" to a
1398/// vector with insert/extractelement instructions.
1399///
1400/// Offset is an offset from the original alloca, in bits that need to be
1401/// shifted to the right. By the end of this, there should be no uses of Ptr.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001402void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) {
Chris Lattnera1888942005-12-12 07:19:13 +00001403 while (!Ptr->use_empty()) {
1404 Instruction *User = cast<Instruction>(Ptr->use_back());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001405
Chris Lattnercf321862009-01-07 06:39:58 +00001406 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) {
Chris Lattnerb10e0da2008-01-30 00:39:15 +00001407 ConvertUsesToScalar(CI, NewAI, Offset);
Chris Lattnera1888942005-12-12 07:19:13 +00001408 CI->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001409 continue;
1410 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001411
Chris Lattnercf321862009-01-07 06:39:58 +00001412 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001413 // Compute the offset that this GEP adds to the pointer.
1414 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end());
1415 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(),
1416 &Indices[0], Indices.size());
1417 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8);
Chris Lattnera1888942005-12-12 07:19:13 +00001418 GEP->eraseFromParent();
Chris Lattnercf321862009-01-07 06:39:58 +00001419 continue;
Chris Lattnera1888942005-12-12 07:19:13 +00001420 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001421
Chris Lattner9bc67da2009-02-03 19:45:44 +00001422 IRBuilder<> Builder(User->getParent(), User);
1423
1424 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
Chris Lattner6e011152009-02-03 21:01:03 +00001425 // The load is a bit extract from NewAI shifted right by Offset bits.
1426 Value *LoadedVal = Builder.CreateLoad(NewAI, "tmp");
1427 Value *NewLoadVal
1428 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, Builder);
1429 LI->replaceAllUsesWith(NewLoadVal);
Chris Lattner9bc67da2009-02-03 19:45:44 +00001430 LI->eraseFromParent();
1431 continue;
1432 }
1433
1434 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
1435 assert(SI->getOperand(0) != Ptr && "Consistency error!");
1436 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
1437 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset,
1438 Builder);
1439 Builder.CreateStore(New, NewAI);
1440 SI->eraseFromParent();
1441 continue;
1442 }
1443
Chris Lattner3d730f72009-02-03 02:01:43 +00001444 // If this is a constant sized memset of a constant value (e.g. 0) we can
1445 // transform it into a store of the expanded constant value.
1446 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) {
1447 assert(MSI->getRawDest() == Ptr && "Consistency error!");
1448 unsigned NumBytes = cast<ConstantInt>(MSI->getLength())->getZExtValue();
Chris Lattner33e24ad2009-04-21 16:52:12 +00001449 if (NumBytes != 0) {
1450 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue();
1451
1452 // Compute the value replicated the right number of times.
1453 APInt APVal(NumBytes*8, Val);
Chris Lattner3d730f72009-02-03 02:01:43 +00001454
Chris Lattner33e24ad2009-04-21 16:52:12 +00001455 // Splat the value if non-zero.
1456 if (Val)
1457 for (unsigned i = 1; i != NumBytes; ++i)
1458 APVal |= APVal << 8;
1459
1460 Value *Old = Builder.CreateLoad(NewAI, (NewAI->getName()+".in").c_str());
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001461 Value *New = ConvertScalar_InsertValue(Context->getConstantInt(APVal),
1462 Old, Offset, Builder);
Chris Lattner33e24ad2009-04-21 16:52:12 +00001463 Builder.CreateStore(New, NewAI);
1464 }
Chris Lattner3d730f72009-02-03 02:01:43 +00001465 MSI->eraseFromParent();
1466 continue;
1467 }
Chris Lattnerc5704872009-03-08 04:04:21 +00001468
1469 // If this is a memcpy or memmove into or out of the whole allocation, we
1470 // can handle it like a load or store of the scalar type.
1471 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) {
1472 assert(Offset == 0 && "must be store to start of alloca");
1473
1474 // If the source and destination are both to the same alloca, then this is
1475 // a noop copy-to-self, just delete it. Otherwise, emit a load and store
1476 // as appropriate.
1477 AllocaInst *OrigAI = cast<AllocaInst>(Ptr->getUnderlyingObject());
1478
1479 if (MTI->getSource()->getUnderlyingObject() != OrigAI) {
1480 // Dest must be OrigAI, change this to be a load from the original
1481 // pointer (bitcasted), then a store to our new alloca.
1482 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?");
1483 Value *SrcPtr = MTI->getSource();
1484 SrcPtr = Builder.CreateBitCast(SrcPtr, NewAI->getType());
1485
1486 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval");
1487 SrcVal->setAlignment(MTI->getAlignment());
1488 Builder.CreateStore(SrcVal, NewAI);
1489 } else if (MTI->getDest()->getUnderlyingObject() != OrigAI) {
1490 // Src must be OrigAI, change this to be a load from NewAI then a store
1491 // through the original dest pointer (bitcasted).
1492 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?");
1493 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval");
1494
1495 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), NewAI->getType());
1496 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr);
1497 NewStore->setAlignment(MTI->getAlignment());
1498 } else {
1499 // Noop transfer. Src == Dst
1500 }
1501
1502
1503 MTI->eraseFromParent();
1504 continue;
1505 }
Chris Lattnerdfe964c2009-03-08 03:59:00 +00001506
Devang Patel00e389c2009-03-06 07:03:54 +00001507 // If user is a dbg info intrinsic then it is safe to remove it.
1508 if (isa<DbgInfoIntrinsic>(User)) {
1509 User->eraseFromParent();
1510 continue;
1511 }
1512
Chris Lattnercf321862009-01-07 06:39:58 +00001513 assert(0 && "Unsupported operation!");
1514 abort();
Chris Lattnera1888942005-12-12 07:19:13 +00001515 }
1516}
Chris Lattner79b3bd32007-04-25 06:40:51 +00001517
Chris Lattner6e011152009-02-03 21:01:03 +00001518/// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer
1519/// or vector value FromVal, extracting the bits from the offset specified by
1520/// Offset. This returns the value, which is of type ToType.
1521///
1522/// This happens when we are converting an "integer union" to a single
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001523/// integer scalar, or when we are converting a "vector union" to a vector with
1524/// insert/extractelement instructions.
Chris Lattner800de312008-02-29 07:03:13 +00001525///
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001526/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner6e011152009-02-03 21:01:03 +00001527/// shifted to the right.
1528Value *SROA::ConvertScalar_ExtractValue(Value *FromVal, const Type *ToType,
1529 uint64_t Offset, IRBuilder<> &Builder) {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001530 // If the load is of the whole new alloca, no conversion is needed.
Chris Lattner6e011152009-02-03 21:01:03 +00001531 if (FromVal->getType() == ToType && Offset == 0)
1532 return FromVal;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001533
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001534 // If the result alloca is a vector type, this is either an element
1535 // access or a bitcast to another vector type of the same size.
Chris Lattner6e011152009-02-03 21:01:03 +00001536 if (const VectorType *VTy = dyn_cast<VectorType>(FromVal->getType())) {
1537 if (isa<VectorType>(ToType))
1538 return Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001539
1540 // Otherwise it must be an element access.
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001541 unsigned Elt = 0;
1542 if (Offset) {
Duncan Sands777d2302009-05-09 07:06:46 +00001543 unsigned EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001544 Elt = Offset/EltSize;
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001545 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking");
Chris Lattner800de312008-02-29 07:03:13 +00001546 }
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001547 // Return the element extracted out of it.
Chris Lattner6e011152009-02-03 21:01:03 +00001548 Value *V = Builder.CreateExtractElement(FromVal,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001549 Context->getConstantInt(Type::Int32Ty,Elt),
Chris Lattner9bc67da2009-02-03 19:45:44 +00001550 "tmp");
Chris Lattner6e011152009-02-03 21:01:03 +00001551 if (V->getType() != ToType)
1552 V = Builder.CreateBitCast(V, ToType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001553 return V;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001554 }
Chris Lattner1aa70562009-02-03 21:08:45 +00001555
1556 // If ToType is a first class aggregate, extract out each of the pieces and
1557 // use insertvalue's to form the FCA.
1558 if (const StructType *ST = dyn_cast<StructType>(ToType)) {
1559 const StructLayout &Layout = *TD->getStructLayout(ST);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001560 Value *Res = Context->getUndef(ST);
Chris Lattner1aa70562009-02-03 21:08:45 +00001561 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
1562 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i),
Chris Lattnere991ced2009-02-06 04:34:07 +00001563 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner1aa70562009-02-03 21:08:45 +00001564 Builder);
1565 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1566 }
1567 return Res;
1568 }
1569
1570 if (const ArrayType *AT = dyn_cast<ArrayType>(ToType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001571 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001572 Value *Res = Context->getUndef(AT);
Chris Lattner1aa70562009-02-03 21:08:45 +00001573 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
1574 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(),
1575 Offset+i*EltSize, Builder);
1576 Res = Builder.CreateInsertValue(Res, Elt, i, "tmp");
1577 }
1578 return Res;
1579 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001580
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001581 // Otherwise, this must be a union that was converted to an integer value.
Chris Lattner6e011152009-02-03 21:01:03 +00001582 const IntegerType *NTy = cast<IntegerType>(FromVal->getType());
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001583
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001584 // If this is a big-endian system and the load is narrower than the
1585 // full alloca type, we need to do a shift to get the right bits.
1586 int ShAmt = 0;
Chris Lattner56c38522009-01-07 06:34:28 +00001587 if (TD->isBigEndian()) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001588 // On big-endian machines, the lowest bit is stored at the bit offset
1589 // from the pointer given by getTypeStoreSizeInBits. This matters for
1590 // integers with a bitwidth that is not a multiple of 8.
Chris Lattner56c38522009-01-07 06:34:28 +00001591 ShAmt = TD->getTypeStoreSizeInBits(NTy) -
Chris Lattner6e011152009-02-03 21:01:03 +00001592 TD->getTypeStoreSizeInBits(ToType) - Offset;
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001593 } else {
1594 ShAmt = Offset;
1595 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001596
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001597 // Note: we support negative bitwidths (with shl) which are not defined.
1598 // We do this to support (f.e.) loads off the end of a structure where
1599 // only some bits are used.
1600 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001601 FromVal = Builder.CreateLShr(FromVal,
1602 Context->getConstantInt(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001603 ShAmt), "tmp");
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001604 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001605 FromVal = Builder.CreateShl(FromVal,
1606 Context->getConstantInt(FromVal->getType(),
Chris Lattner1aa70562009-02-03 21:08:45 +00001607 -ShAmt), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001608
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001609 // Finally, unconditionally truncate the integer to the right width.
Chris Lattner6e011152009-02-03 21:01:03 +00001610 unsigned LIBitWidth = TD->getTypeSizeInBits(ToType);
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001611 if (LIBitWidth < NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001612 FromVal =
1613 Builder.CreateTrunc(FromVal, Context->getIntegerType(LIBitWidth), "tmp");
Chris Lattner55a683d2009-02-03 07:08:57 +00001614 else if (LIBitWidth > NTy->getBitWidth())
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001615 FromVal =
1616 Builder.CreateZExt(FromVal, Context->getIntegerType(LIBitWidth), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001617
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001618 // If the result is an integer, this is a trunc or bitcast.
Chris Lattner6e011152009-02-03 21:01:03 +00001619 if (isa<IntegerType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001620 // Should be done.
Chris Lattner6e011152009-02-03 21:01:03 +00001621 } else if (ToType->isFloatingPoint() || isa<VectorType>(ToType)) {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001622 // Just do a bitcast, we know the sizes match up.
Chris Lattner6e011152009-02-03 21:01:03 +00001623 FromVal = Builder.CreateBitCast(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001624 } else {
Chris Lattner9d34c4d2008-02-29 07:12:06 +00001625 // Otherwise must be a pointer.
Chris Lattner6e011152009-02-03 21:01:03 +00001626 FromVal = Builder.CreateIntToPtr(FromVal, ToType, "tmp");
Chris Lattner800de312008-02-29 07:03:13 +00001627 }
Chris Lattner6e011152009-02-03 21:01:03 +00001628 assert(FromVal->getType() == ToType && "Didn't convert right?");
1629 return FromVal;
Chris Lattner800de312008-02-29 07:03:13 +00001630}
1631
1632
Chris Lattner9b872db2009-02-03 19:30:11 +00001633/// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer
1634/// or vector value "Old" at the offset specified by Offset.
1635///
1636/// This happens when we are converting an "integer union" to a
Chris Lattner800de312008-02-29 07:03:13 +00001637/// single integer scalar, or when we are converting a "vector union" to a
1638/// vector with insert/extractelement instructions.
1639///
1640/// Offset is an offset from the original alloca, in bits that need to be
Chris Lattner9b872db2009-02-03 19:30:11 +00001641/// shifted to the right.
1642Value *SROA::ConvertScalar_InsertValue(Value *SV, Value *Old,
Chris Lattner65a65022009-02-03 19:41:50 +00001643 uint64_t Offset, IRBuilder<> &Builder) {
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001644
Chris Lattner800de312008-02-29 07:03:13 +00001645 // Convert the stored type to the actual type, shift it left to insert
1646 // then 'or' into place.
Chris Lattner9b872db2009-02-03 19:30:11 +00001647 const Type *AllocaType = Old->getType();
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001648
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001649 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) {
Duncan Sands777d2302009-05-09 07:06:46 +00001650 uint64_t VecSize = TD->getTypeAllocSizeInBits(VTy);
1651 uint64_t ValSize = TD->getTypeAllocSizeInBits(SV->getType());
Chris Lattner29e64172009-03-08 04:17:04 +00001652
1653 // Changing the whole vector with memset or with an access of a different
1654 // vector type?
1655 if (ValSize == VecSize)
1656 return Builder.CreateBitCast(SV, AllocaType, "tmp");
1657
Duncan Sands777d2302009-05-09 07:06:46 +00001658 uint64_t EltSize = TD->getTypeAllocSizeInBits(VTy->getElementType());
Chris Lattner29e64172009-03-08 04:17:04 +00001659
1660 // Must be an element insertion.
1661 unsigned Elt = Offset/EltSize;
1662
1663 if (SV->getType() != VTy->getElementType())
1664 SV = Builder.CreateBitCast(SV, VTy->getElementType(), "tmp");
1665
1666 SV = Builder.CreateInsertElement(Old, SV,
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001667 Context->getConstantInt(Type::Int32Ty, Elt),
Chris Lattner29e64172009-03-08 04:17:04 +00001668 "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001669 return SV;
1670 }
Chris Lattner9b872db2009-02-03 19:30:11 +00001671
1672 // If SV is a first-class aggregate value, insert each value recursively.
1673 if (const StructType *ST = dyn_cast<StructType>(SV->getType())) {
1674 const StructLayout &Layout = *TD->getStructLayout(ST);
1675 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001676 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
Chris Lattner9b872db2009-02-03 19:30:11 +00001677 Old = ConvertScalar_InsertValue(Elt, Old,
Chris Lattnere991ced2009-02-06 04:34:07 +00001678 Offset+Layout.getElementOffsetInBits(i),
Chris Lattner65a65022009-02-03 19:41:50 +00001679 Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001680 }
1681 return Old;
1682 }
1683
1684 if (const ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) {
Duncan Sands777d2302009-05-09 07:06:46 +00001685 uint64_t EltSize = TD->getTypeAllocSizeInBits(AT->getElementType());
Chris Lattner9b872db2009-02-03 19:30:11 +00001686 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) {
Chris Lattner65a65022009-02-03 19:41:50 +00001687 Value *Elt = Builder.CreateExtractValue(SV, i, "tmp");
1688 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, Builder);
Chris Lattner9b872db2009-02-03 19:30:11 +00001689 }
1690 return Old;
1691 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001692
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001693 // If SV is a float, convert it to the appropriate integer type.
Chris Lattner9b872db2009-02-03 19:30:11 +00001694 // If it is a pointer, do the same.
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001695 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType());
1696 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType);
1697 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType());
1698 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType);
1699 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType()))
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001700 SV = Builder.CreateBitCast(SV, Context->getIntegerType(SrcWidth), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001701 else if (isa<PointerType>(SV->getType()))
Chris Lattner65a65022009-02-03 19:41:50 +00001702 SV = Builder.CreatePtrToInt(SV, TD->getIntPtrType(), "tmp");
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001703
Chris Lattner7809ecd2009-02-03 01:30:09 +00001704 // Zero extend or truncate the value if needed.
1705 if (SV->getType() != AllocaType) {
1706 if (SV->getType()->getPrimitiveSizeInBits() <
1707 AllocaType->getPrimitiveSizeInBits())
Chris Lattner65a65022009-02-03 19:41:50 +00001708 SV = Builder.CreateZExt(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001709 else {
1710 // Truncation may be needed if storing more than the alloca can hold
1711 // (undefined behavior).
Chris Lattner65a65022009-02-03 19:41:50 +00001712 SV = Builder.CreateTrunc(SV, AllocaType, "tmp");
Chris Lattner7809ecd2009-02-03 01:30:09 +00001713 SrcWidth = DestWidth;
1714 SrcStoreWidth = DestStoreWidth;
1715 }
1716 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001717
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001718 // If this is a big-endian system and the store is narrower than the
1719 // full alloca type, we need to do a shift to get the right bits.
1720 int ShAmt = 0;
1721 if (TD->isBigEndian()) {
1722 // On big-endian machines, the lowest bit is stored at the bit offset
1723 // from the pointer given by getTypeStoreSizeInBits. This matters for
1724 // integers with a bitwidth that is not a multiple of 8.
1725 ShAmt = DestStoreWidth - SrcStoreWidth - Offset;
Chris Lattner800de312008-02-29 07:03:13 +00001726 } else {
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001727 ShAmt = Offset;
1728 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001729
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001730 // Note: we support negative bitwidths (with shr) which are not defined.
1731 // We do this to support (f.e.) stores off the end of a structure where
1732 // only some bits in the structure are set.
1733 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth));
1734 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001735 SV = Builder.CreateShl(SV, Context->getConstantInt(SV->getType(),
1736 ShAmt), "tmp");
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001737 Mask <<= ShAmt;
1738 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001739 SV = Builder.CreateLShr(SV, Context->getConstantInt(SV->getType(),
1740 -ShAmt), "tmp");
Duncan Sands0e7c46b2009-02-02 09:53:14 +00001741 Mask = Mask.lshr(-ShAmt);
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001742 }
Duncan Sands4b3dfbd2009-02-02 10:06:20 +00001743
Chris Lattner2e0d5f82009-01-31 02:28:54 +00001744 // Mask out the bits we are about to insert from the old value, and or
1745 // in the new bits.
1746 if (SrcWidth != DestWidth) {
1747 assert(DestWidth > SrcWidth);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001748 Old = Builder.CreateAnd(Old, Context->getConstantInt(~Mask), "mask");
Chris Lattner65a65022009-02-03 19:41:50 +00001749 SV = Builder.CreateOr(Old, SV, "ins");
Chris Lattner800de312008-02-29 07:03:13 +00001750 }
1751 return SV;
1752}
1753
1754
Chris Lattner79b3bd32007-04-25 06:40:51 +00001755
1756/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to
1757/// some part of a constant global variable. This intentionally only accepts
1758/// constant expressions because we don't can't rewrite arbitrary instructions.
1759static bool PointsToConstantGlobal(Value *V) {
1760 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
1761 return GV->isConstant();
1762 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1763 if (CE->getOpcode() == Instruction::BitCast ||
1764 CE->getOpcode() == Instruction::GetElementPtr)
1765 return PointsToConstantGlobal(CE->getOperand(0));
1766 return false;
1767}
1768
1769/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
1770/// pointer to an alloca. Ignore any reads of the pointer, return false if we
1771/// see any stores or other unknown uses. If we see pointer arithmetic, keep
1772/// track of whether it moves the pointer (with isOffset) but otherwise traverse
1773/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
1774/// the alloca, and if the source pointer is a pointer to a constant global, we
1775/// can optimize this.
1776static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy,
1777 bool isOffset) {
1778 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) {
Chris Lattner6e733d32009-01-28 20:16:43 +00001779 if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
1780 // Ignore non-volatile loads, they are always ok.
1781 if (!LI->isVolatile())
1782 continue;
1783
Chris Lattner79b3bd32007-04-25 06:40:51 +00001784 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) {
1785 // If uses of the bitcast are ok, we are ok.
1786 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset))
1787 return false;
1788 continue;
1789 }
1790 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) {
1791 // If the GEP has all zero indices, it doesn't offset the pointer. If it
1792 // doesn't, it does.
1793 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy,
1794 isOffset || !GEP->hasAllZeroIndices()))
1795 return false;
1796 continue;
1797 }
1798
1799 // If this is isn't our memcpy/memmove, reject it as something we can't
1800 // handle.
Chris Lattner3ce5e882009-03-08 03:37:16 +00001801 if (!isa<MemTransferInst>(*UI))
Chris Lattner79b3bd32007-04-25 06:40:51 +00001802 return false;
1803
1804 // If we already have seen a copy, reject the second one.
1805 if (TheCopy) return false;
1806
1807 // If the pointer has been offset from the start of the alloca, we can't
1808 // safely handle this.
1809 if (isOffset) return false;
1810
1811 // If the memintrinsic isn't using the alloca as the dest, reject it.
1812 if (UI.getOperandNo() != 1) return false;
1813
1814 MemIntrinsic *MI = cast<MemIntrinsic>(*UI);
1815
1816 // If the source of the memcpy/move is not a constant global, reject it.
1817 if (!PointsToConstantGlobal(MI->getOperand(2)))
1818 return false;
1819
1820 // Otherwise, the transform is safe. Remember the copy instruction.
1821 TheCopy = MI;
1822 }
1823 return true;
1824}
1825
1826/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
1827/// modified by a copy from a constant global. If we can prove this, we can
1828/// replace any uses of the alloca with uses of the global directly.
1829Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) {
1830 Instruction *TheCopy = 0;
1831 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false))
1832 return TheCopy;
1833 return 0;
1834}