ScalarReplAggregates.cpp revision 996d7a97f94de45a3627b03eb3c44b2b325f3e51
1//===- ScalarReplAggregates.cpp - Scalar Replacement of Aggregates --------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 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 13// 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. 19// 20//===----------------------------------------------------------------------===// 21 22#define DEBUG_TYPE "scalarrepl" 23#include "llvm/Transforms/Scalar.h" 24#include "llvm/Constants.h" 25#include "llvm/DerivedTypes.h" 26#include "llvm/Function.h" 27#include "llvm/GlobalVariable.h" 28#include "llvm/Instructions.h" 29#include "llvm/IntrinsicInst.h" 30#include "llvm/Pass.h" 31#include "llvm/Analysis/Dominators.h" 32#include "llvm/Target/TargetData.h" 33#include "llvm/Transforms/Utils/PromoteMemToReg.h" 34#include "llvm/Support/Debug.h" 35#include "llvm/Support/GetElementPtrTypeIterator.h" 36#include "llvm/Support/MathExtras.h" 37#include "llvm/Support/Compiler.h" 38#include "llvm/ADT/SmallVector.h" 39#include "llvm/ADT/Statistic.h" 40#include "llvm/ADT/StringExtras.h" 41using namespace llvm; 42 43STATISTIC(NumReplaced, "Number of allocas broken up"); 44STATISTIC(NumPromoted, "Number of allocas promoted"); 45STATISTIC(NumConverted, "Number of aggregates converted to scalar"); 46STATISTIC(NumGlobals, "Number of allocas copied from constant global"); 47 48namespace { 49 struct VISIBILITY_HIDDEN SROA : public FunctionPass { 50 static char ID; // Pass identification, replacement for typeid 51 explicit SROA(signed T = -1) : FunctionPass(&ID) { 52 if (T == -1) 53 SRThreshold = 128; 54 else 55 SRThreshold = T; 56 } 57 58 bool runOnFunction(Function &F); 59 60 bool performScalarRepl(Function &F); 61 bool performPromotion(Function &F); 62 63 // getAnalysisUsage - This pass does not require any passes, but we know it 64 // will not alter the CFG, so say so. 65 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 66 AU.addRequired<DominatorTree>(); 67 AU.addRequired<DominanceFrontier>(); 68 AU.addRequired<TargetData>(); 69 AU.setPreservesCFG(); 70 } 71 72 private: 73 TargetData *TD; 74 75 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures 76 /// information about the uses. All these fields are initialized to false 77 /// and set to true when something is learned. 78 struct AllocaInfo { 79 /// isUnsafe - This is set to true if the alloca cannot be SROA'd. 80 bool isUnsafe : 1; 81 82 /// needsCanon - This is set to true if there is some use of the alloca 83 /// that requires canonicalization. 84 bool needsCanon : 1; 85 86 /// isMemCpySrc - This is true if this aggregate is memcpy'd from. 87 bool isMemCpySrc : 1; 88 89 /// isMemCpyDst - This is true if this aggregate is memcpy'd into. 90 bool isMemCpyDst : 1; 91 92 AllocaInfo() 93 : isUnsafe(false), needsCanon(false), 94 isMemCpySrc(false), isMemCpyDst(false) {} 95 }; 96 97 unsigned SRThreshold; 98 99 void MarkUnsafe(AllocaInfo &I) { I.isUnsafe = true; } 100 101 int isSafeAllocaToScalarRepl(AllocationInst *AI); 102 103 void isSafeUseOfAllocation(Instruction *User, AllocationInst *AI, 104 AllocaInfo &Info); 105 void isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI, 106 AllocaInfo &Info); 107 void isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI, 108 unsigned OpNo, AllocaInfo &Info); 109 void isSafeUseOfBitCastedAllocation(BitCastInst *User, AllocationInst *AI, 110 AllocaInfo &Info); 111 112 void DoScalarReplacement(AllocationInst *AI, 113 std::vector<AllocationInst*> &WorkList); 114 void CanonicalizeAllocaUsers(AllocationInst *AI); 115 AllocaInst *AddNewAlloca(Function &F, const Type *Ty, AllocationInst *Base); 116 117 void RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI, 118 SmallVector<AllocaInst*, 32> &NewElts); 119 120 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst, 121 AllocationInst *AI, 122 SmallVector<AllocaInst*, 32> &NewElts); 123 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocationInst *AI, 124 SmallVector<AllocaInst*, 32> &NewElts); 125 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI, 126 SmallVector<AllocaInst*, 32> &NewElts); 127 128 bool CanConvertToScalar(Value *V, bool &IsNotTrivial, const Type *&ResTy, 129 uint64_t Offset); 130 void ConvertToScalar(AllocationInst *AI, const Type *Ty); 131 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset); 132 Value *ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI, 133 uint64_t Offset); 134 Value *ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI, 135 uint64_t Offset); 136 static Instruction *isOnlyCopiedFromConstantGlobal(AllocationInst *AI); 137 }; 138} 139 140char SROA::ID = 0; 141static RegisterPass<SROA> X("scalarrepl", "Scalar Replacement of Aggregates"); 142 143// Public interface to the ScalarReplAggregates pass 144FunctionPass *llvm::createScalarReplAggregatesPass(signed int Threshold) { 145 return new SROA(Threshold); 146} 147 148 149bool SROA::runOnFunction(Function &F) { 150 TD = &getAnalysis<TargetData>(); 151 152 bool Changed = performPromotion(F); 153 while (1) { 154 bool LocalChange = performScalarRepl(F); 155 if (!LocalChange) break; // No need to repromote if no scalarrepl 156 Changed = true; 157 LocalChange = performPromotion(F); 158 if (!LocalChange) break; // No need to re-scalarrepl if no promotion 159 } 160 161 return Changed; 162} 163 164 165bool SROA::performPromotion(Function &F) { 166 std::vector<AllocaInst*> Allocas; 167 DominatorTree &DT = getAnalysis<DominatorTree>(); 168 DominanceFrontier &DF = getAnalysis<DominanceFrontier>(); 169 170 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function 171 172 bool Changed = false; 173 174 while (1) { 175 Allocas.clear(); 176 177 // Find allocas that are safe to promote, by looking at all instructions in 178 // the entry node 179 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) 180 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca? 181 if (isAllocaPromotable(AI)) 182 Allocas.push_back(AI); 183 184 if (Allocas.empty()) break; 185 186 PromoteMemToReg(Allocas, DT, DF); 187 NumPromoted += Allocas.size(); 188 Changed = true; 189 } 190 191 return Changed; 192} 193 194/// getNumSAElements - Return the number of elements in the specific struct or 195/// array. 196static uint64_t getNumSAElements(const Type *T) { 197 if (const StructType *ST = dyn_cast<StructType>(T)) 198 return ST->getNumElements(); 199 return cast<ArrayType>(T)->getNumElements(); 200} 201 202// performScalarRepl - This algorithm is a simple worklist driven algorithm, 203// which runs on all of the malloc/alloca instructions in the function, removing 204// them if they are only used by getelementptr instructions. 205// 206bool SROA::performScalarRepl(Function &F) { 207 std::vector<AllocationInst*> WorkList; 208 209 // Scan the entry basic block, adding any alloca's and mallocs to the worklist 210 BasicBlock &BB = F.getEntryBlock(); 211 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) 212 if (AllocationInst *A = dyn_cast<AllocationInst>(I)) 213 WorkList.push_back(A); 214 215 // Process the worklist 216 bool Changed = false; 217 while (!WorkList.empty()) { 218 AllocationInst *AI = WorkList.back(); 219 WorkList.pop_back(); 220 221 // Handle dead allocas trivially. These can be formed by SROA'ing arrays 222 // with unused elements. 223 if (AI->use_empty()) { 224 AI->eraseFromParent(); 225 continue; 226 } 227 228 // Check to see if we can perform the core SROA transformation. We cannot 229 // transform the allocation instruction if it is an array allocation 230 // (allocations OF arrays are ok though), and an allocation of a scalar 231 // value cannot be decomposed at all. 232 if (!AI->isArrayAllocation() && 233 (isa<StructType>(AI->getAllocatedType()) || 234 isa<ArrayType>(AI->getAllocatedType())) && 235 AI->getAllocatedType()->isSized() && 236 // Do not promote any struct whose size is larger than "128" bytes. 237 TD->getTypePaddedSize(AI->getAllocatedType()) < SRThreshold && 238 // Do not promote any struct into more than "32" separate vars. 239 getNumSAElements(AI->getAllocatedType()) < SRThreshold/4) { 240 // Check that all of the users of the allocation are capable of being 241 // transformed. 242 switch (isSafeAllocaToScalarRepl(AI)) { 243 default: assert(0 && "Unexpected value!"); 244 case 0: // Not safe to scalar replace. 245 break; 246 case 1: // Safe, but requires cleanup/canonicalizations first 247 CanonicalizeAllocaUsers(AI); 248 // FALL THROUGH. 249 case 3: // Safe to scalar replace. 250 DoScalarReplacement(AI, WorkList); 251 Changed = true; 252 continue; 253 } 254 } 255 256 // Check to see if this allocation is only modified by a memcpy/memmove from 257 // a constant global. If this is the case, we can change all users to use 258 // the constant global instead. This is commonly produced by the CFE by 259 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A' 260 // is only subsequently read. 261 if (Instruction *TheCopy = isOnlyCopiedFromConstantGlobal(AI)) { 262 DOUT << "Found alloca equal to global: " << *AI; 263 DOUT << " memcpy = " << *TheCopy; 264 Constant *TheSrc = cast<Constant>(TheCopy->getOperand(2)); 265 AI->replaceAllUsesWith(ConstantExpr::getBitCast(TheSrc, AI->getType())); 266 TheCopy->eraseFromParent(); // Don't mutate the global. 267 AI->eraseFromParent(); 268 ++NumGlobals; 269 Changed = true; 270 continue; 271 } 272 273 // If we can turn this aggregate value (potentially with casts) into a 274 // simple scalar value that can be mem2reg'd into a register value. 275 // IsNotTrivial tracks whether this is something that mem2reg could have 276 // promoted itself. If so, we don't want to transform it needlessly. Note 277 // that we can't just check based on the type: the alloca may be of an i32 278 // but that has pointer arithmetic to set byte 3 of it or something. 279 bool IsNotTrivial = false; 280 const Type *ActualType = 0; 281 if (CanConvertToScalar(AI, IsNotTrivial, ActualType, 0)) 282 if (IsNotTrivial && ActualType && 283 TD->getTypeSizeInBits(ActualType) < SRThreshold*8) { 284 ConvertToScalar(AI, ActualType); 285 Changed = true; 286 continue; 287 } 288 289 // Otherwise, couldn't process this. 290 } 291 292 return Changed; 293} 294 295/// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl 296/// predicate, do SROA now. 297void SROA::DoScalarReplacement(AllocationInst *AI, 298 std::vector<AllocationInst*> &WorkList) { 299 DOUT << "Found inst to SROA: " << *AI; 300 SmallVector<AllocaInst*, 32> ElementAllocas; 301 if (const StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { 302 ElementAllocas.reserve(ST->getNumContainedTypes()); 303 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) { 304 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 305 AI->getAlignment(), 306 AI->getName() + "." + utostr(i), AI); 307 ElementAllocas.push_back(NA); 308 WorkList.push_back(NA); // Add to worklist for recursive processing 309 } 310 } else { 311 const ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); 312 ElementAllocas.reserve(AT->getNumElements()); 313 const Type *ElTy = AT->getElementType(); 314 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { 315 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(), 316 AI->getName() + "." + utostr(i), AI); 317 ElementAllocas.push_back(NA); 318 WorkList.push_back(NA); // Add to worklist for recursive processing 319 } 320 } 321 322 // Now that we have created the alloca instructions that we want to use, 323 // expand the getelementptr instructions to use them. 324 // 325 while (!AI->use_empty()) { 326 Instruction *User = cast<Instruction>(AI->use_back()); 327 if (BitCastInst *BCInst = dyn_cast<BitCastInst>(User)) { 328 RewriteBitCastUserOfAlloca(BCInst, AI, ElementAllocas); 329 BCInst->eraseFromParent(); 330 continue; 331 } 332 333 // Replace: 334 // %res = load { i32, i32 }* %alloc 335 // with: 336 // %load.0 = load i32* %alloc.0 337 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0 338 // %load.1 = load i32* %alloc.1 339 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1 340 // (Also works for arrays instead of structs) 341 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 342 Value *Insert = UndefValue::get(LI->getType()); 343 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) { 344 Value *Load = new LoadInst(ElementAllocas[i], "load", LI); 345 Insert = InsertValueInst::Create(Insert, Load, i, "insert", LI); 346 } 347 LI->replaceAllUsesWith(Insert); 348 LI->eraseFromParent(); 349 continue; 350 } 351 352 // Replace: 353 // store { i32, i32 } %val, { i32, i32 }* %alloc 354 // with: 355 // %val.0 = extractvalue { i32, i32 } %val, 0 356 // store i32 %val.0, i32* %alloc.0 357 // %val.1 = extractvalue { i32, i32 } %val, 1 358 // store i32 %val.1, i32* %alloc.1 359 // (Also works for arrays instead of structs) 360 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 361 Value *Val = SI->getOperand(0); 362 for (unsigned i = 0, e = ElementAllocas.size(); i != e; ++i) { 363 Value *Extract = ExtractValueInst::Create(Val, i, Val->getName(), SI); 364 new StoreInst(Extract, ElementAllocas[i], SI); 365 } 366 SI->eraseFromParent(); 367 continue; 368 } 369 370 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User); 371 // We now know that the GEP is of the form: GEP <ptr>, 0, <cst> 372 unsigned Idx = 373 (unsigned)cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue(); 374 375 assert(Idx < ElementAllocas.size() && "Index out of range?"); 376 AllocaInst *AllocaToUse = ElementAllocas[Idx]; 377 378 Value *RepValue; 379 if (GEPI->getNumOperands() == 3) { 380 // Do not insert a new getelementptr instruction with zero indices, only 381 // to have it optimized out later. 382 RepValue = AllocaToUse; 383 } else { 384 // We are indexing deeply into the structure, so we still need a 385 // getelement ptr instruction to finish the indexing. This may be 386 // expanded itself once the worklist is rerun. 387 // 388 SmallVector<Value*, 8> NewArgs; 389 NewArgs.push_back(Constant::getNullValue(Type::Int32Ty)); 390 NewArgs.append(GEPI->op_begin()+3, GEPI->op_end()); 391 RepValue = GetElementPtrInst::Create(AllocaToUse, NewArgs.begin(), 392 NewArgs.end(), "", GEPI); 393 RepValue->takeName(GEPI); 394 } 395 396 // If this GEP is to the start of the aggregate, check for memcpys. 397 if (Idx == 0 && GEPI->hasAllZeroIndices()) 398 RewriteBitCastUserOfAlloca(GEPI, AI, ElementAllocas); 399 400 // Move all of the users over to the new GEP. 401 GEPI->replaceAllUsesWith(RepValue); 402 // Delete the old GEP 403 GEPI->eraseFromParent(); 404 } 405 406 // Finally, delete the Alloca instruction 407 AI->eraseFromParent(); 408 NumReplaced++; 409} 410 411 412/// isSafeElementUse - Check to see if this use is an allowed use for a 413/// getelementptr instruction of an array aggregate allocation. isFirstElt 414/// indicates whether Ptr is known to the start of the aggregate. 415/// 416void SROA::isSafeElementUse(Value *Ptr, bool isFirstElt, AllocationInst *AI, 417 AllocaInfo &Info) { 418 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end(); 419 I != E; ++I) { 420 Instruction *User = cast<Instruction>(*I); 421 switch (User->getOpcode()) { 422 case Instruction::Load: break; 423 case Instruction::Store: 424 // Store is ok if storing INTO the pointer, not storing the pointer 425 if (User->getOperand(0) == Ptr) return MarkUnsafe(Info); 426 break; 427 case Instruction::GetElementPtr: { 428 GetElementPtrInst *GEP = cast<GetElementPtrInst>(User); 429 bool AreAllZeroIndices = isFirstElt; 430 if (GEP->getNumOperands() > 1) { 431 if (!isa<ConstantInt>(GEP->getOperand(1)) || 432 !cast<ConstantInt>(GEP->getOperand(1))->isZero()) 433 // Using pointer arithmetic to navigate the array. 434 return MarkUnsafe(Info); 435 436 if (AreAllZeroIndices) 437 AreAllZeroIndices = GEP->hasAllZeroIndices(); 438 } 439 isSafeElementUse(GEP, AreAllZeroIndices, AI, Info); 440 if (Info.isUnsafe) return; 441 break; 442 } 443 case Instruction::BitCast: 444 if (isFirstElt) { 445 isSafeUseOfBitCastedAllocation(cast<BitCastInst>(User), AI, Info); 446 if (Info.isUnsafe) return; 447 break; 448 } 449 DOUT << " Transformation preventing inst: " << *User; 450 return MarkUnsafe(Info); 451 case Instruction::Call: 452 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) { 453 if (isFirstElt) { 454 isSafeMemIntrinsicOnAllocation(MI, AI, I.getOperandNo(), Info); 455 if (Info.isUnsafe) return; 456 break; 457 } 458 } 459 DOUT << " Transformation preventing inst: " << *User; 460 return MarkUnsafe(Info); 461 default: 462 DOUT << " Transformation preventing inst: " << *User; 463 return MarkUnsafe(Info); 464 } 465 } 466 return; // All users look ok :) 467} 468 469/// AllUsersAreLoads - Return true if all users of this value are loads. 470static bool AllUsersAreLoads(Value *Ptr) { 471 for (Value::use_iterator I = Ptr->use_begin(), E = Ptr->use_end(); 472 I != E; ++I) 473 if (cast<Instruction>(*I)->getOpcode() != Instruction::Load) 474 return false; 475 return true; 476} 477 478/// isSafeUseOfAllocation - Check to see if this user is an allowed use for an 479/// aggregate allocation. 480/// 481void SROA::isSafeUseOfAllocation(Instruction *User, AllocationInst *AI, 482 AllocaInfo &Info) { 483 if (BitCastInst *C = dyn_cast<BitCastInst>(User)) 484 return isSafeUseOfBitCastedAllocation(C, AI, Info); 485 486 if (LoadInst *LI = dyn_cast<LoadInst>(User)) 487 if (!LI->isVolatile()) 488 return;// Loads (returning a first class aggregrate) are always rewritable 489 490 if (StoreInst *SI = dyn_cast<StoreInst>(User)) 491 if (!SI->isVolatile() && SI->getOperand(0) != AI) 492 return;// Store is ok if storing INTO the pointer, not storing the pointer 493 494 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User); 495 if (GEPI == 0) 496 return MarkUnsafe(Info); 497 498 gep_type_iterator I = gep_type_begin(GEPI), E = gep_type_end(GEPI); 499 500 // The GEP is not safe to transform if not of the form "GEP <ptr>, 0, <cst>". 501 if (I == E || 502 I.getOperand() != Constant::getNullValue(I.getOperand()->getType())) { 503 return MarkUnsafe(Info); 504 } 505 506 ++I; 507 if (I == E) return MarkUnsafe(Info); // ran out of GEP indices?? 508 509 bool IsAllZeroIndices = true; 510 511 // If the first index is a non-constant index into an array, see if we can 512 // handle it as a special case. 513 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) { 514 if (!isa<ConstantInt>(I.getOperand())) { 515 IsAllZeroIndices = 0; 516 uint64_t NumElements = AT->getNumElements(); 517 518 // If this is an array index and the index is not constant, we cannot 519 // promote... that is unless the array has exactly one or two elements in 520 // it, in which case we CAN promote it, but we have to canonicalize this 521 // out if this is the only problem. 522 if ((NumElements == 1 || NumElements == 2) && 523 AllUsersAreLoads(GEPI)) { 524 Info.needsCanon = true; 525 return; // Canonicalization required! 526 } 527 return MarkUnsafe(Info); 528 } 529 } 530 531 // Walk through the GEP type indices, checking the types that this indexes 532 // into. 533 for (; I != E; ++I) { 534 // Ignore struct elements, no extra checking needed for these. 535 if (isa<StructType>(*I)) 536 continue; 537 538 ConstantInt *IdxVal = dyn_cast<ConstantInt>(I.getOperand()); 539 if (!IdxVal) return MarkUnsafe(Info); 540 541 // Are all indices still zero? 542 IsAllZeroIndices &= IdxVal->isZero(); 543 544 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) { 545 // This GEP indexes an array. Verify that this is an in-range constant 546 // integer. Specifically, consider A[0][i]. We cannot know that the user 547 // isn't doing invalid things like allowing i to index an out-of-range 548 // subscript that accesses A[1]. Because of this, we have to reject SROA 549 // of any accesses into structs where any of the components are variables. 550 if (IdxVal->getZExtValue() >= AT->getNumElements()) 551 return MarkUnsafe(Info); 552 } else if (const VectorType *VT = dyn_cast<VectorType>(*I)) { 553 if (IdxVal->getZExtValue() >= VT->getNumElements()) 554 return MarkUnsafe(Info); 555 } 556 } 557 558 // If there are any non-simple uses of this getelementptr, make sure to reject 559 // them. 560 return isSafeElementUse(GEPI, IsAllZeroIndices, AI, Info); 561} 562 563/// isSafeMemIntrinsicOnAllocation - Return true if the specified memory 564/// intrinsic can be promoted by SROA. At this point, we know that the operand 565/// of the memintrinsic is a pointer to the beginning of the allocation. 566void SROA::isSafeMemIntrinsicOnAllocation(MemIntrinsic *MI, AllocationInst *AI, 567 unsigned OpNo, AllocaInfo &Info) { 568 // If not constant length, give up. 569 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength()); 570 if (!Length) return MarkUnsafe(Info); 571 572 // If not the whole aggregate, give up. 573 if (Length->getZExtValue() != 574 TD->getTypePaddedSize(AI->getType()->getElementType())) 575 return MarkUnsafe(Info); 576 577 // We only know about memcpy/memset/memmove. 578 if (!isa<MemCpyInst>(MI) && !isa<MemSetInst>(MI) && !isa<MemMoveInst>(MI)) 579 return MarkUnsafe(Info); 580 581 // Otherwise, we can transform it. Determine whether this is a memcpy/set 582 // into or out of the aggregate. 583 if (OpNo == 1) 584 Info.isMemCpyDst = true; 585 else { 586 assert(OpNo == 2); 587 Info.isMemCpySrc = true; 588 } 589} 590 591/// isSafeUseOfBitCastedAllocation - Return true if all users of this bitcast 592/// are 593void SROA::isSafeUseOfBitCastedAllocation(BitCastInst *BC, AllocationInst *AI, 594 AllocaInfo &Info) { 595 for (Value::use_iterator UI = BC->use_begin(), E = BC->use_end(); 596 UI != E; ++UI) { 597 if (BitCastInst *BCU = dyn_cast<BitCastInst>(UI)) { 598 isSafeUseOfBitCastedAllocation(BCU, AI, Info); 599 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(UI)) { 600 isSafeMemIntrinsicOnAllocation(MI, AI, UI.getOperandNo(), Info); 601 } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) { 602 if (SI->isVolatile()) 603 return MarkUnsafe(Info); 604 605 // If storing the entire alloca in one chunk through a bitcasted pointer 606 // to integer, we can transform it. This happens (for example) when you 607 // cast a {i32,i32}* to i64* and store through it. This is similar to the 608 // memcpy case and occurs in various "byval" cases and emulated memcpys. 609 if (isa<IntegerType>(SI->getOperand(0)->getType()) && 610 TD->getTypePaddedSize(SI->getOperand(0)->getType()) == 611 TD->getTypePaddedSize(AI->getType()->getElementType())) { 612 Info.isMemCpyDst = true; 613 continue; 614 } 615 return MarkUnsafe(Info); 616 } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) { 617 if (LI->isVolatile()) 618 return MarkUnsafe(Info); 619 620 // If loading the entire alloca in one chunk through a bitcasted pointer 621 // to integer, we can transform it. This happens (for example) when you 622 // cast a {i32,i32}* to i64* and load through it. This is similar to the 623 // memcpy case and occurs in various "byval" cases and emulated memcpys. 624 if (isa<IntegerType>(LI->getType()) && 625 TD->getTypePaddedSize(LI->getType()) == 626 TD->getTypePaddedSize(AI->getType()->getElementType())) { 627 Info.isMemCpySrc = true; 628 continue; 629 } 630 return MarkUnsafe(Info); 631 } else { 632 return MarkUnsafe(Info); 633 } 634 if (Info.isUnsafe) return; 635 } 636} 637 638/// RewriteBitCastUserOfAlloca - BCInst (transitively) bitcasts AI, or indexes 639/// to its first element. Transform users of the cast to use the new values 640/// instead. 641void SROA::RewriteBitCastUserOfAlloca(Instruction *BCInst, AllocationInst *AI, 642 SmallVector<AllocaInst*, 32> &NewElts) { 643 Value::use_iterator UI = BCInst->use_begin(), UE = BCInst->use_end(); 644 while (UI != UE) { 645 Instruction *User = cast<Instruction>(*UI++); 646 if (BitCastInst *BCU = dyn_cast<BitCastInst>(User)) { 647 RewriteBitCastUserOfAlloca(BCU, AI, NewElts); 648 if (BCU->use_empty()) BCU->eraseFromParent(); 649 continue; 650 } 651 652 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) { 653 // This must be memcpy/memmove/memset of the entire aggregate. 654 // Split into one per element. 655 RewriteMemIntrinUserOfAlloca(MI, BCInst, AI, NewElts); 656 continue; 657 } 658 659 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 660 // If this is a store of the entire alloca from an integer, rewrite it. 661 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts); 662 continue; 663 } 664 665 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 666 // If this is a load of the entire alloca to an integer, rewrite it. 667 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts); 668 continue; 669 } 670 671 // Otherwise it must be some other user of a gep of the first pointer. Just 672 // leave these alone. 673 continue; 674 } 675} 676 677/// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI. 678/// Rewrite it to copy or set the elements of the scalarized memory. 679void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *BCInst, 680 AllocationInst *AI, 681 SmallVector<AllocaInst*, 32> &NewElts) { 682 683 // If this is a memcpy/memmove, construct the other pointer as the 684 // appropriate type. 685 Value *OtherPtr = 0; 686 if (MemCpyInst *MCI = dyn_cast<MemCpyInst>(MI)) { 687 if (BCInst == MCI->getRawDest()) 688 OtherPtr = MCI->getRawSource(); 689 else { 690 assert(BCInst == MCI->getRawSource()); 691 OtherPtr = MCI->getRawDest(); 692 } 693 } else if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) { 694 if (BCInst == MMI->getRawDest()) 695 OtherPtr = MMI->getRawSource(); 696 else { 697 assert(BCInst == MMI->getRawSource()); 698 OtherPtr = MMI->getRawDest(); 699 } 700 } 701 702 // If there is an other pointer, we want to convert it to the same pointer 703 // type as AI has, so we can GEP through it safely. 704 if (OtherPtr) { 705 // It is likely that OtherPtr is a bitcast, if so, remove it. 706 if (BitCastInst *BC = dyn_cast<BitCastInst>(OtherPtr)) 707 OtherPtr = BC->getOperand(0); 708 // All zero GEPs are effectively bitcasts. 709 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(OtherPtr)) 710 if (GEP->hasAllZeroIndices()) 711 OtherPtr = GEP->getOperand(0); 712 713 if (ConstantExpr *BCE = dyn_cast<ConstantExpr>(OtherPtr)) 714 if (BCE->getOpcode() == Instruction::BitCast) 715 OtherPtr = BCE->getOperand(0); 716 717 // If the pointer is not the right type, insert a bitcast to the right 718 // type. 719 if (OtherPtr->getType() != AI->getType()) 720 OtherPtr = new BitCastInst(OtherPtr, AI->getType(), OtherPtr->getName(), 721 MI); 722 } 723 724 // Process each element of the aggregate. 725 Value *TheFn = MI->getOperand(0); 726 const Type *BytePtrTy = MI->getRawDest()->getType(); 727 bool SROADest = MI->getRawDest() == BCInst; 728 729 Constant *Zero = Constant::getNullValue(Type::Int32Ty); 730 731 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 732 // If this is a memcpy/memmove, emit a GEP of the other element address. 733 Value *OtherElt = 0; 734 if (OtherPtr) { 735 Value *Idx[2] = { Zero, ConstantInt::get(Type::Int32Ty, i) }; 736 OtherElt = GetElementPtrInst::Create(OtherPtr, Idx, Idx + 2, 737 OtherPtr->getNameStr()+"."+utostr(i), 738 MI); 739 } 740 741 Value *EltPtr = NewElts[i]; 742 const Type *EltTy =cast<PointerType>(EltPtr->getType())->getElementType(); 743 744 // If we got down to a scalar, insert a load or store as appropriate. 745 if (EltTy->isSingleValueType()) { 746 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) { 747 Value *Elt = new LoadInst(SROADest ? OtherElt : EltPtr, "tmp", 748 MI); 749 new StoreInst(Elt, SROADest ? EltPtr : OtherElt, MI); 750 continue; 751 } 752 assert(isa<MemSetInst>(MI)); 753 754 // If the stored element is zero (common case), just store a null 755 // constant. 756 Constant *StoreVal; 757 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getOperand(2))) { 758 if (CI->isZero()) { 759 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0> 760 } else { 761 // If EltTy is a vector type, get the element type. 762 const Type *ValTy = EltTy; 763 if (const VectorType *VTy = dyn_cast<VectorType>(ValTy)) 764 ValTy = VTy->getElementType(); 765 766 // Construct an integer with the right value. 767 unsigned EltSize = TD->getTypeSizeInBits(ValTy); 768 APInt OneVal(EltSize, CI->getZExtValue()); 769 APInt TotalVal(OneVal); 770 // Set each byte. 771 for (unsigned i = 0; 8*i < EltSize; ++i) { 772 TotalVal = TotalVal.shl(8); 773 TotalVal |= OneVal; 774 } 775 776 // Convert the integer value to the appropriate type. 777 StoreVal = ConstantInt::get(TotalVal); 778 if (isa<PointerType>(ValTy)) 779 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy); 780 else if (ValTy->isFloatingPoint()) 781 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy); 782 assert(StoreVal->getType() == ValTy && "Type mismatch!"); 783 784 // If the requested value was a vector constant, create it. 785 if (EltTy != ValTy) { 786 unsigned NumElts = cast<VectorType>(ValTy)->getNumElements(); 787 SmallVector<Constant*, 16> Elts(NumElts, StoreVal); 788 StoreVal = ConstantVector::get(&Elts[0], NumElts); 789 } 790 } 791 new StoreInst(StoreVal, EltPtr, MI); 792 continue; 793 } 794 // Otherwise, if we're storing a byte variable, use a memset call for 795 // this element. 796 } 797 798 // Cast the element pointer to BytePtrTy. 799 if (EltPtr->getType() != BytePtrTy) 800 EltPtr = new BitCastInst(EltPtr, BytePtrTy, EltPtr->getNameStr(), MI); 801 802 // Cast the other pointer (if we have one) to BytePtrTy. 803 if (OtherElt && OtherElt->getType() != BytePtrTy) 804 OtherElt = new BitCastInst(OtherElt, BytePtrTy,OtherElt->getNameStr(), 805 MI); 806 807 unsigned EltSize = TD->getTypePaddedSize(EltTy); 808 809 // Finally, insert the meminst for this element. 810 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) { 811 Value *Ops[] = { 812 SROADest ? EltPtr : OtherElt, // Dest ptr 813 SROADest ? OtherElt : EltPtr, // Src ptr 814 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size 815 Zero // Align 816 }; 817 CallInst::Create(TheFn, Ops, Ops + 4, "", MI); 818 } else { 819 assert(isa<MemSetInst>(MI)); 820 Value *Ops[] = { 821 EltPtr, MI->getOperand(2), // Dest, Value, 822 ConstantInt::get(MI->getOperand(3)->getType(), EltSize), // Size 823 Zero // Align 824 }; 825 CallInst::Create(TheFn, Ops, Ops + 4, "", MI); 826 } 827 } 828 MI->eraseFromParent(); 829} 830 831/// RewriteStoreUserOfWholeAlloca - We found an store of an integer that 832/// overwrites the entire allocation. Extract out the pieces of the stored 833/// integer and store them individually. 834void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, 835 AllocationInst *AI, 836 SmallVector<AllocaInst*, 32> &NewElts){ 837 // Extract each element out of the integer according to its structure offset 838 // and store the element value to the individual alloca. 839 Value *SrcVal = SI->getOperand(0); 840 const Type *AllocaEltTy = AI->getType()->getElementType(); 841 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy); 842 843 // If this isn't a store of an integer to the whole alloca, it may be a store 844 // to the first element. Just ignore the store in this case and normal SROA 845 // will handle it. 846 if (!isa<IntegerType>(SrcVal->getType()) || 847 TD->getTypePaddedSizeInBits(SrcVal->getType()) != AllocaSizeBits) 848 return; 849 850 DOUT << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << *SI; 851 852 // There are two forms here: AI could be an array or struct. Both cases 853 // have different ways to compute the element offset. 854 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) { 855 const StructLayout *Layout = TD->getStructLayout(EltSTy); 856 857 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 858 // Get the number of bits to shift SrcVal to get the value. 859 const Type *FieldTy = EltSTy->getElementType(i); 860 uint64_t Shift = Layout->getElementOffsetInBits(i); 861 862 if (TD->isBigEndian()) 863 Shift = AllocaSizeBits-Shift-TD->getTypePaddedSizeInBits(FieldTy); 864 865 Value *EltVal = SrcVal; 866 if (Shift) { 867 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift); 868 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal, 869 "sroa.store.elt", SI); 870 } 871 872 // Truncate down to an integer of the right size. 873 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy); 874 875 // Ignore zero sized fields like {}, they obviously contain no data. 876 if (FieldSizeBits == 0) continue; 877 878 if (FieldSizeBits != AllocaSizeBits) 879 EltVal = new TruncInst(EltVal, IntegerType::get(FieldSizeBits), "", SI); 880 Value *DestField = NewElts[i]; 881 if (EltVal->getType() == FieldTy) { 882 // Storing to an integer field of this size, just do it. 883 } else if (FieldTy->isFloatingPoint() || isa<VectorType>(FieldTy)) { 884 // Bitcast to the right element type (for fp/vector values). 885 EltVal = new BitCastInst(EltVal, FieldTy, "", SI); 886 } else { 887 // Otherwise, bitcast the dest pointer (for aggregates). 888 DestField = new BitCastInst(DestField, 889 PointerType::getUnqual(EltVal->getType()), 890 "", SI); 891 } 892 new StoreInst(EltVal, DestField, SI); 893 } 894 895 } else { 896 const ArrayType *ATy = cast<ArrayType>(AllocaEltTy); 897 const Type *ArrayEltTy = ATy->getElementType(); 898 uint64_t ElementOffset = TD->getTypePaddedSizeInBits(ArrayEltTy); 899 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy); 900 901 uint64_t Shift; 902 903 if (TD->isBigEndian()) 904 Shift = AllocaSizeBits-ElementOffset; 905 else 906 Shift = 0; 907 908 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 909 // Ignore zero sized fields like {}, they obviously contain no data. 910 if (ElementSizeBits == 0) continue; 911 912 Value *EltVal = SrcVal; 913 if (Shift) { 914 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift); 915 EltVal = BinaryOperator::CreateLShr(EltVal, ShiftVal, 916 "sroa.store.elt", SI); 917 } 918 919 // Truncate down to an integer of the right size. 920 if (ElementSizeBits != AllocaSizeBits) 921 EltVal = new TruncInst(EltVal, IntegerType::get(ElementSizeBits),"",SI); 922 Value *DestField = NewElts[i]; 923 if (EltVal->getType() == ArrayEltTy) { 924 // Storing to an integer field of this size, just do it. 925 } else if (ArrayEltTy->isFloatingPoint() || isa<VectorType>(ArrayEltTy)) { 926 // Bitcast to the right element type (for fp/vector values). 927 EltVal = new BitCastInst(EltVal, ArrayEltTy, "", SI); 928 } else { 929 // Otherwise, bitcast the dest pointer (for aggregates). 930 DestField = new BitCastInst(DestField, 931 PointerType::getUnqual(EltVal->getType()), 932 "", SI); 933 } 934 new StoreInst(EltVal, DestField, SI); 935 936 if (TD->isBigEndian()) 937 Shift -= ElementOffset; 938 else 939 Shift += ElementOffset; 940 } 941 } 942 943 SI->eraseFromParent(); 944} 945 946/// RewriteLoadUserOfWholeAlloca - We found an load of the entire allocation to 947/// an integer. Load the individual pieces to form the aggregate value. 948void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocationInst *AI, 949 SmallVector<AllocaInst*, 32> &NewElts) { 950 // Extract each element out of the NewElts according to its structure offset 951 // and form the result value. 952 const Type *AllocaEltTy = AI->getType()->getElementType(); 953 uint64_t AllocaSizeBits = TD->getTypePaddedSizeInBits(AllocaEltTy); 954 955 // If this isn't a load of the whole alloca to an integer, it may be a load 956 // of the first element. Just ignore the load in this case and normal SROA 957 // will handle it. 958 if (!isa<IntegerType>(LI->getType()) || 959 TD->getTypePaddedSizeInBits(LI->getType()) != AllocaSizeBits) 960 return; 961 962 DOUT << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << *LI; 963 964 // There are two forms here: AI could be an array or struct. Both cases 965 // have different ways to compute the element offset. 966 const StructLayout *Layout = 0; 967 uint64_t ArrayEltBitOffset = 0; 968 if (const StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) { 969 Layout = TD->getStructLayout(EltSTy); 970 } else { 971 const Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType(); 972 ArrayEltBitOffset = TD->getTypePaddedSizeInBits(ArrayEltTy); 973 } 974 975 Value *ResultVal = Constant::getNullValue(LI->getType()); 976 977 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 978 // Load the value from the alloca. If the NewElt is an aggregate, cast 979 // the pointer to an integer of the same size before doing the load. 980 Value *SrcField = NewElts[i]; 981 const Type *FieldTy = 982 cast<PointerType>(SrcField->getType())->getElementType(); 983 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy); 984 985 // Ignore zero sized fields like {}, they obviously contain no data. 986 if (FieldSizeBits == 0) continue; 987 988 const IntegerType *FieldIntTy = IntegerType::get(FieldSizeBits); 989 if (!isa<IntegerType>(FieldTy) && !FieldTy->isFloatingPoint() && 990 !isa<VectorType>(FieldTy)) 991 SrcField = new BitCastInst(SrcField, PointerType::getUnqual(FieldIntTy), 992 "", LI); 993 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI); 994 995 // If SrcField is a fp or vector of the right size but that isn't an 996 // integer type, bitcast to an integer so we can shift it. 997 if (SrcField->getType() != FieldIntTy) 998 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI); 999 1000 // Zero extend the field to be the same size as the final alloca so that 1001 // we can shift and insert it. 1002 if (SrcField->getType() != ResultVal->getType()) 1003 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI); 1004 1005 // Determine the number of bits to shift SrcField. 1006 uint64_t Shift; 1007 if (Layout) // Struct case. 1008 Shift = Layout->getElementOffsetInBits(i); 1009 else // Array case. 1010 Shift = i*ArrayEltBitOffset; 1011 1012 if (TD->isBigEndian()) 1013 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth(); 1014 1015 if (Shift) { 1016 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift); 1017 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI); 1018 } 1019 1020 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI); 1021 } 1022 1023 LI->replaceAllUsesWith(ResultVal); 1024 LI->eraseFromParent(); 1025} 1026 1027 1028/// HasPadding - Return true if the specified type has any structure or 1029/// alignment padding, false otherwise. 1030static bool HasPadding(const Type *Ty, const TargetData &TD) { 1031 if (const StructType *STy = dyn_cast<StructType>(Ty)) { 1032 const StructLayout *SL = TD.getStructLayout(STy); 1033 unsigned PrevFieldBitOffset = 0; 1034 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1035 unsigned FieldBitOffset = SL->getElementOffsetInBits(i); 1036 1037 // Padding in sub-elements? 1038 if (HasPadding(STy->getElementType(i), TD)) 1039 return true; 1040 1041 // Check to see if there is any padding between this element and the 1042 // previous one. 1043 if (i) { 1044 unsigned PrevFieldEnd = 1045 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1)); 1046 if (PrevFieldEnd < FieldBitOffset) 1047 return true; 1048 } 1049 1050 PrevFieldBitOffset = FieldBitOffset; 1051 } 1052 1053 // Check for tail padding. 1054 if (unsigned EltCount = STy->getNumElements()) { 1055 unsigned PrevFieldEnd = PrevFieldBitOffset + 1056 TD.getTypeSizeInBits(STy->getElementType(EltCount-1)); 1057 if (PrevFieldEnd < SL->getSizeInBits()) 1058 return true; 1059 } 1060 1061 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 1062 return HasPadding(ATy->getElementType(), TD); 1063 } else if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) { 1064 return HasPadding(VTy->getElementType(), TD); 1065 } 1066 return TD.getTypeSizeInBits(Ty) != TD.getTypePaddedSizeInBits(Ty); 1067} 1068 1069/// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of 1070/// an aggregate can be broken down into elements. Return 0 if not, 3 if safe, 1071/// or 1 if safe after canonicalization has been performed. 1072/// 1073int SROA::isSafeAllocaToScalarRepl(AllocationInst *AI) { 1074 // Loop over the use list of the alloca. We can only transform it if all of 1075 // the users are safe to transform. 1076 AllocaInfo Info; 1077 1078 for (Value::use_iterator I = AI->use_begin(), E = AI->use_end(); 1079 I != E; ++I) { 1080 isSafeUseOfAllocation(cast<Instruction>(*I), AI, Info); 1081 if (Info.isUnsafe) { 1082 DOUT << "Cannot transform: " << *AI << " due to user: " << **I; 1083 return 0; 1084 } 1085 } 1086 1087 // Okay, we know all the users are promotable. If the aggregate is a memcpy 1088 // source and destination, we have to be careful. In particular, the memcpy 1089 // could be moving around elements that live in structure padding of the LLVM 1090 // types, but may actually be used. In these cases, we refuse to promote the 1091 // struct. 1092 if (Info.isMemCpySrc && Info.isMemCpyDst && 1093 HasPadding(AI->getType()->getElementType(), *TD)) 1094 return 0; 1095 1096 // If we require cleanup, return 1, otherwise return 3. 1097 return Info.needsCanon ? 1 : 3; 1098} 1099 1100/// CanonicalizeAllocaUsers - If SROA reported that it can promote the specified 1101/// allocation, but only if cleaned up, perform the cleanups required. 1102void SROA::CanonicalizeAllocaUsers(AllocationInst *AI) { 1103 // At this point, we know that the end result will be SROA'd and promoted, so 1104 // we can insert ugly code if required so long as sroa+mem2reg will clean it 1105 // up. 1106 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); 1107 UI != E; ) { 1108 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI++); 1109 if (!GEPI) continue; 1110 gep_type_iterator I = gep_type_begin(GEPI); 1111 ++I; 1112 1113 if (const ArrayType *AT = dyn_cast<ArrayType>(*I)) { 1114 uint64_t NumElements = AT->getNumElements(); 1115 1116 if (!isa<ConstantInt>(I.getOperand())) { 1117 if (NumElements == 1) { 1118 GEPI->setOperand(2, Constant::getNullValue(Type::Int32Ty)); 1119 } else { 1120 assert(NumElements == 2 && "Unhandled case!"); 1121 // All users of the GEP must be loads. At each use of the GEP, insert 1122 // two loads of the appropriate indexed GEP and select between them. 1123 Value *IsOne = new ICmpInst(ICmpInst::ICMP_NE, I.getOperand(), 1124 Constant::getNullValue(I.getOperand()->getType()), 1125 "isone", GEPI); 1126 // Insert the new GEP instructions, which are properly indexed. 1127 SmallVector<Value*, 8> Indices(GEPI->op_begin()+1, GEPI->op_end()); 1128 Indices[1] = Constant::getNullValue(Type::Int32Ty); 1129 Value *ZeroIdx = GetElementPtrInst::Create(GEPI->getOperand(0), 1130 Indices.begin(), 1131 Indices.end(), 1132 GEPI->getName()+".0", GEPI); 1133 Indices[1] = ConstantInt::get(Type::Int32Ty, 1); 1134 Value *OneIdx = GetElementPtrInst::Create(GEPI->getOperand(0), 1135 Indices.begin(), 1136 Indices.end(), 1137 GEPI->getName()+".1", GEPI); 1138 // Replace all loads of the variable index GEP with loads from both 1139 // indexes and a select. 1140 while (!GEPI->use_empty()) { 1141 LoadInst *LI = cast<LoadInst>(GEPI->use_back()); 1142 Value *Zero = new LoadInst(ZeroIdx, LI->getName()+".0", LI); 1143 Value *One = new LoadInst(OneIdx , LI->getName()+".1", LI); 1144 Value *R = SelectInst::Create(IsOne, One, Zero, LI->getName(), LI); 1145 LI->replaceAllUsesWith(R); 1146 LI->eraseFromParent(); 1147 } 1148 GEPI->eraseFromParent(); 1149 } 1150 } 1151 } 1152 } 1153} 1154 1155/// MergeInType - Add the 'In' type to the accumulated type (Accum) so far at 1156/// the offset specified by Offset (which is specified in bytes). 1157/// 1158/// There are two cases we handle here: 1159/// 1) A union of vector types of the same size and potentially its elements. 1160/// Here we turn element accesses into insert/extract element operations. 1161/// This promotes a <4 x float> with a store of float to the third element 1162/// into a <4 x float> that uses insert element. 1163/// 2) A fully general blob of memory, which we turn into some (potentially 1164/// large) integer type with extract and insert operations where the loads 1165/// and stores would mutate the memory. 1166static void MergeInType(const Type *In, uint64_t Offset, const Type *&Accum, 1167 const TargetData &TD) { 1168 // If this is our first type, just use it. 1169 if ((Accum == 0 && Offset == 0) || In == Type::VoidTy || 1170 // Or if this is a same type, keep it. 1171 (In == Accum && Offset == 0)) { 1172 Accum = In; 1173 return; 1174 } 1175 1176 // Merging something like i32 into offset 8 means that a "field" is merged in 1177 // before the basic type is. Make sure to consider the offset below. 1178 if (Accum == 0) 1179 Accum = Type::Int8Ty; 1180 1181 if (const VectorType *VATy = dyn_cast<VectorType>(Accum)) { 1182 if (VATy->getElementType() == In && 1183 Offset % TD.getTypePaddedSize(In) == 0 && 1184 Offset < TD.getTypePaddedSize(VATy)) 1185 return; // Accum is a vector, and we are accessing an element: ok. 1186 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) 1187 if (VInTy->getBitWidth() == VATy->getBitWidth() && Offset == 0) 1188 return; // Two vectors of the same size: keep either one of them. 1189 } 1190 1191 if (const VectorType *VInTy = dyn_cast<VectorType>(In)) { 1192 // In is a vector, and we are accessing an element: keep V. 1193 if (VInTy->getElementType() == Accum && 1194 Offset % TD.getTypePaddedSize(Accum) == 0 && 1195 Offset < TD.getTypePaddedSize(VInTy)) { 1196 Accum = VInTy; 1197 return; 1198 } 1199 } 1200 1201 // Otherwise, we have a case that we can't handle with an optimized form. 1202 // Convert the alloca to an integer that is as large as the largest store size 1203 // of the value values. 1204 uint64_t InSize = TD.getTypeStoreSizeInBits(In)+8*Offset; 1205 uint64_t ASize = TD.getTypeStoreSizeInBits(Accum); 1206 if (InSize > ASize) ASize = InSize; 1207 Accum = IntegerType::get(ASize); 1208} 1209 1210/// CanConvertToScalar - V is a pointer. If we can convert the pointee and all 1211/// its accesses to use a to single scalar type, return true, and set ResTy to 1212/// the new type. Further, if the use is not a completely trivial use that 1213/// mem2reg could promote, set IsNotTrivial. Offset is the current offset from 1214/// the base of the alloca being analyzed. 1215/// 1216bool SROA::CanConvertToScalar(Value *V, bool &IsNotTrivial, 1217 const Type *&ResTy, uint64_t Offset) { 1218 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) { 1219 Instruction *User = cast<Instruction>(*UI); 1220 1221 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 1222 // Don't break volatile loads. 1223 if (LI->isVolatile()) 1224 return false; 1225 MergeInType(LI->getType(), Offset, ResTy, *TD); 1226 continue; 1227 } 1228 1229 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 1230 // Storing the pointer, not into the value? 1231 if (SI->getOperand(0) == V || SI->isVolatile()) return 0; 1232 MergeInType(SI->getOperand(0)->getType(), Offset, ResTy, *TD); 1233 continue; 1234 } 1235 1236 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) { 1237 if (!CanConvertToScalar(BCI, IsNotTrivial, ResTy, Offset)) 1238 return false; 1239 IsNotTrivial = true; 1240 continue; 1241 } 1242 1243 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) { 1244 // If this is a GEP with a variable indices, we can't handle it. 1245 if (!GEP->hasAllConstantIndices()) 1246 return false; 1247 1248 // Compute the offset that this GEP adds to the pointer. 1249 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end()); 1250 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(), 1251 &Indices[0], Indices.size()); 1252 // See if all uses can be converted. 1253 if (!CanConvertToScalar(GEP, IsNotTrivial, ResTy, Offset+GEPOffset)) 1254 return false; 1255 IsNotTrivial = true; 1256 continue; 1257 } 1258 1259 // Otherwise, we cannot handle this! 1260 return false; 1261 } 1262 1263 return true; 1264} 1265 1266/// ConvertToScalar - The specified alloca passes the CanConvertToScalar 1267/// predicate and is non-trivial. Convert it to something that can be trivially 1268/// promoted into a register by mem2reg. 1269void SROA::ConvertToScalar(AllocationInst *AI, const Type *ActualTy) { 1270 DOUT << "CONVERT TO SCALAR: " << *AI << " TYPE = " << *ActualTy << "\n"; 1271 ++NumConverted; 1272 1273 // Create and insert the alloca. 1274 AllocaInst *NewAI = new AllocaInst(ActualTy, 0, AI->getName(), 1275 AI->getParent()->begin()); 1276 ConvertUsesToScalar(AI, NewAI, 0); 1277 AI->eraseFromParent(); 1278} 1279 1280 1281/// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca 1282/// directly. This happens when we are converting an "integer union" to a 1283/// single integer scalar, or when we are converting a "vector union" to a 1284/// vector with insert/extractelement instructions. 1285/// 1286/// Offset is an offset from the original alloca, in bits that need to be 1287/// shifted to the right. By the end of this, there should be no uses of Ptr. 1288void SROA::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset) { 1289 while (!Ptr->use_empty()) { 1290 Instruction *User = cast<Instruction>(Ptr->use_back()); 1291 1292 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 1293 LI->replaceAllUsesWith(ConvertUsesOfLoadToScalar(LI, NewAI, Offset)); 1294 LI->eraseFromParent(); 1295 continue; 1296 } 1297 1298 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 1299 assert(SI->getOperand(0) != Ptr && "Consistency error!"); 1300 new StoreInst(ConvertUsesOfStoreToScalar(SI, NewAI, Offset), NewAI, SI); 1301 SI->eraseFromParent(); 1302 continue; 1303 } 1304 1305 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) { 1306 ConvertUsesToScalar(CI, NewAI, Offset); 1307 CI->eraseFromParent(); 1308 continue; 1309 } 1310 1311 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) { 1312 // Compute the offset that this GEP adds to the pointer. 1313 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end()); 1314 uint64_t GEPOffset = TD->getIndexedOffset(GEP->getOperand(0)->getType(), 1315 &Indices[0], Indices.size()); 1316 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8); 1317 GEP->eraseFromParent(); 1318 continue; 1319 } 1320 assert(0 && "Unsupported operation!"); 1321 abort(); 1322 } 1323} 1324 1325/// ConvertUsesOfLoadToScalar - Convert all of the users of the specified load 1326/// to use the new alloca directly, returning the value that should replace the 1327/// load. This happens when we are converting an "integer union" to a single 1328/// integer scalar, or when we are converting a "vector union" to a vector with 1329/// insert/extractelement instructions. 1330/// 1331/// Offset is an offset from the original alloca, in bits that need to be 1332/// shifted to the right. By the end of this, there should be no uses of Ptr. 1333Value *SROA::ConvertUsesOfLoadToScalar(LoadInst *LI, AllocaInst *NewAI, 1334 uint64_t Offset) { 1335 // The load is a bit extract from NewAI shifted right by Offset bits. 1336 Value *NV = new LoadInst(NewAI, LI->getName(), LI); 1337 1338 // If the load is of the whole new alloca, no conversion is needed. 1339 if (NV->getType() == LI->getType() && Offset == 0) 1340 return NV; 1341 1342 // If the result alloca is a vector type, this is either an element 1343 // access or a bitcast to another vector type of the same size. 1344 if (const VectorType *VTy = dyn_cast<VectorType>(NV->getType())) { 1345 if (isa<VectorType>(LI->getType())) 1346 return new BitCastInst(NV, LI->getType(), LI->getName(), LI); 1347 1348 // Otherwise it must be an element access. 1349 unsigned Elt = 0; 1350 if (Offset) { 1351 unsigned EltSize = TD->getTypePaddedSizeInBits(VTy->getElementType()); 1352 Elt = Offset/EltSize; 1353 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking"); 1354 } 1355 // Return the element extracted out of it. 1356 return new ExtractElementInst(NV, ConstantInt::get(Type::Int32Ty, Elt), 1357 "tmp", LI); 1358 } 1359 1360 // Otherwise, this must be a union that was converted to an integer value. 1361 const IntegerType *NTy = cast<IntegerType>(NV->getType()); 1362 1363 // If this is a big-endian system and the load is narrower than the 1364 // full alloca type, we need to do a shift to get the right bits. 1365 int ShAmt = 0; 1366 if (TD->isBigEndian()) { 1367 // On big-endian machines, the lowest bit is stored at the bit offset 1368 // from the pointer given by getTypeStoreSizeInBits. This matters for 1369 // integers with a bitwidth that is not a multiple of 8. 1370 ShAmt = TD->getTypeStoreSizeInBits(NTy) - 1371 TD->getTypeStoreSizeInBits(LI->getType()) - Offset; 1372 } else { 1373 ShAmt = Offset; 1374 } 1375 1376 // Note: we support negative bitwidths (with shl) which are not defined. 1377 // We do this to support (f.e.) loads off the end of a structure where 1378 // only some bits are used. 1379 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth()) 1380 NV = BinaryOperator::CreateLShr(NV, 1381 ConstantInt::get(NV->getType(), ShAmt), 1382 LI->getName(), LI); 1383 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth()) 1384 NV = BinaryOperator::CreateShl(NV, 1385 ConstantInt::get(NV->getType(), -ShAmt), 1386 LI->getName(), LI); 1387 1388 // Finally, unconditionally truncate the integer to the right width. 1389 unsigned LIBitWidth = TD->getTypeSizeInBits(LI->getType()); 1390 if (LIBitWidth < NTy->getBitWidth()) 1391 NV = new TruncInst(NV, IntegerType::get(LIBitWidth), 1392 LI->getName(), LI); 1393 1394 // If the result is an integer, this is a trunc or bitcast. 1395 if (isa<IntegerType>(LI->getType())) { 1396 // Should be done. 1397 } else if (LI->getType()->isFloatingPoint() || 1398 isa<VectorType>(LI->getType())) { 1399 // Just do a bitcast, we know the sizes match up. 1400 NV = new BitCastInst(NV, LI->getType(), LI->getName(), LI); 1401 } else { 1402 // Otherwise must be a pointer. 1403 NV = new IntToPtrInst(NV, LI->getType(), LI->getName(), LI); 1404 } 1405 assert(NV->getType() == LI->getType() && "Didn't convert right?"); 1406 return NV; 1407} 1408 1409 1410/// ConvertUsesOfStoreToScalar - Convert the specified store to a load+store 1411/// pair of the new alloca directly, returning the value that should be stored 1412/// to the alloca. This happens when we are converting an "integer union" to a 1413/// single integer scalar, or when we are converting a "vector union" to a 1414/// vector with insert/extractelement instructions. 1415/// 1416/// Offset is an offset from the original alloca, in bits that need to be 1417/// shifted to the right. By the end of this, there should be no uses of Ptr. 1418Value *SROA::ConvertUsesOfStoreToScalar(StoreInst *SI, AllocaInst *NewAI, 1419 uint64_t Offset) { 1420 1421 // Convert the stored type to the actual type, shift it left to insert 1422 // then 'or' into place. 1423 Value *SV = SI->getOperand(0); 1424 const Type *AllocaType = NewAI->getType()->getElementType(); 1425 if (SV->getType() == AllocaType && Offset == 0) { 1426 return SV; 1427 } 1428 1429 if (const VectorType *VTy = dyn_cast<VectorType>(AllocaType)) { 1430 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI); 1431 1432 // If the result alloca is a vector type, this is either an element 1433 // access or a bitcast to another vector type. 1434 if (isa<VectorType>(SV->getType())) { 1435 SV = new BitCastInst(SV, AllocaType, SV->getName(), SI); 1436 } else { 1437 // Must be an element insertion. 1438 unsigned Elt = Offset/TD->getTypePaddedSizeInBits(VTy->getElementType()); 1439 SV = InsertElementInst::Create(Old, SV, 1440 ConstantInt::get(Type::Int32Ty, Elt), 1441 "tmp", SI); 1442 } 1443 return SV; 1444 } 1445 1446 1447 Value *Old = new LoadInst(NewAI, NewAI->getName()+".in", SI); 1448 1449 // If SV is a float, convert it to the appropriate integer type. 1450 // If it is a pointer, do the same, and also handle ptr->ptr casts 1451 // here. 1452 unsigned SrcWidth = TD->getTypeSizeInBits(SV->getType()); 1453 unsigned DestWidth = TD->getTypeSizeInBits(AllocaType); 1454 unsigned SrcStoreWidth = TD->getTypeStoreSizeInBits(SV->getType()); 1455 unsigned DestStoreWidth = TD->getTypeStoreSizeInBits(AllocaType); 1456 if (SV->getType()->isFloatingPoint() || isa<VectorType>(SV->getType())) 1457 SV = new BitCastInst(SV, IntegerType::get(SrcWidth), SV->getName(), SI); 1458 else if (isa<PointerType>(SV->getType())) 1459 SV = new PtrToIntInst(SV, TD->getIntPtrType(), SV->getName(), SI); 1460 1461 // Always zero extend the value if needed. 1462 if (SV->getType() != AllocaType) 1463 SV = new ZExtInst(SV, AllocaType, SV->getName(), SI); 1464 1465 // If this is a big-endian system and the store is narrower than the 1466 // full alloca type, we need to do a shift to get the right bits. 1467 int ShAmt = 0; 1468 if (TD->isBigEndian()) { 1469 // On big-endian machines, the lowest bit is stored at the bit offset 1470 // from the pointer given by getTypeStoreSizeInBits. This matters for 1471 // integers with a bitwidth that is not a multiple of 8. 1472 ShAmt = DestStoreWidth - SrcStoreWidth - Offset; 1473 } else { 1474 ShAmt = Offset; 1475 } 1476 1477 // Note: we support negative bitwidths (with shr) which are not defined. 1478 // We do this to support (f.e.) stores off the end of a structure where 1479 // only some bits in the structure are set. 1480 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth)); 1481 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) { 1482 SV = BinaryOperator::CreateShl(SV, 1483 ConstantInt::get(SV->getType(), ShAmt), 1484 SV->getName(), SI); 1485 Mask <<= ShAmt; 1486 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) { 1487 SV = BinaryOperator::CreateLShr(SV, 1488 ConstantInt::get(SV->getType(),-ShAmt), 1489 SV->getName(), SI); 1490 Mask = Mask.lshr(-ShAmt); 1491 } 1492 1493 // Mask out the bits we are about to insert from the old value, and or 1494 // in the new bits. 1495 if (SrcWidth != DestWidth) { 1496 assert(DestWidth > SrcWidth); 1497 Old = BinaryOperator::CreateAnd(Old, ConstantInt::get(~Mask), 1498 Old->getName()+".mask", SI); 1499 SV = BinaryOperator::CreateOr(Old, SV, SV->getName()+".ins", SI); 1500 } 1501 return SV; 1502} 1503 1504 1505 1506/// PointsToConstantGlobal - Return true if V (possibly indirectly) points to 1507/// some part of a constant global variable. This intentionally only accepts 1508/// constant expressions because we don't can't rewrite arbitrary instructions. 1509static bool PointsToConstantGlobal(Value *V) { 1510 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) 1511 return GV->isConstant(); 1512 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) 1513 if (CE->getOpcode() == Instruction::BitCast || 1514 CE->getOpcode() == Instruction::GetElementPtr) 1515 return PointsToConstantGlobal(CE->getOperand(0)); 1516 return false; 1517} 1518 1519/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived) 1520/// pointer to an alloca. Ignore any reads of the pointer, return false if we 1521/// see any stores or other unknown uses. If we see pointer arithmetic, keep 1522/// track of whether it moves the pointer (with isOffset) but otherwise traverse 1523/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to 1524/// the alloca, and if the source pointer is a pointer to a constant global, we 1525/// can optimize this. 1526static bool isOnlyCopiedFromConstantGlobal(Value *V, Instruction *&TheCopy, 1527 bool isOffset) { 1528 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) { 1529 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) 1530 // Ignore non-volatile loads, they are always ok. 1531 if (!LI->isVolatile()) 1532 continue; 1533 1534 if (BitCastInst *BCI = dyn_cast<BitCastInst>(*UI)) { 1535 // If uses of the bitcast are ok, we are ok. 1536 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, isOffset)) 1537 return false; 1538 continue; 1539 } 1540 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(*UI)) { 1541 // If the GEP has all zero indices, it doesn't offset the pointer. If it 1542 // doesn't, it does. 1543 if (!isOnlyCopiedFromConstantGlobal(GEP, TheCopy, 1544 isOffset || !GEP->hasAllZeroIndices())) 1545 return false; 1546 continue; 1547 } 1548 1549 // If this is isn't our memcpy/memmove, reject it as something we can't 1550 // handle. 1551 if (!isa<MemCpyInst>(*UI) && !isa<MemMoveInst>(*UI)) 1552 return false; 1553 1554 // If we already have seen a copy, reject the second one. 1555 if (TheCopy) return false; 1556 1557 // If the pointer has been offset from the start of the alloca, we can't 1558 // safely handle this. 1559 if (isOffset) return false; 1560 1561 // If the memintrinsic isn't using the alloca as the dest, reject it. 1562 if (UI.getOperandNo() != 1) return false; 1563 1564 MemIntrinsic *MI = cast<MemIntrinsic>(*UI); 1565 1566 // If the source of the memcpy/move is not a constant global, reject it. 1567 if (!PointsToConstantGlobal(MI->getOperand(2))) 1568 return false; 1569 1570 // Otherwise, the transform is safe. Remember the copy instruction. 1571 TheCopy = MI; 1572 } 1573 return true; 1574} 1575 1576/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only 1577/// modified by a copy from a constant global. If we can prove this, we can 1578/// replace any uses of the alloca with uses of the global directly. 1579Instruction *SROA::isOnlyCopiedFromConstantGlobal(AllocationInst *AI) { 1580 Instruction *TheCopy = 0; 1581 if (::isOnlyCopiedFromConstantGlobal(AI, TheCopy, false)) 1582 return TheCopy; 1583 return 0; 1584} 1585