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 they 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/DIBuilder.h" 26 #include "llvm/DebugInfo.h" 27 #include "llvm/DerivedTypes.h" 28 #include "llvm/Function.h" 29 #include "llvm/GlobalVariable.h" 30 #include "llvm/IRBuilder.h" 31 #include "llvm/Instructions.h" 32 #include "llvm/IntrinsicInst.h" 33 #include "llvm/LLVMContext.h" 34 #include "llvm/Module.h" 35 #include "llvm/Operator.h" 36 #include "llvm/Pass.h" 37 #include "llvm/ADT/SetVector.h" 38 #include "llvm/ADT/SmallVector.h" 39 #include "llvm/ADT/Statistic.h" 40 #include "llvm/Analysis/Dominators.h" 41 #include "llvm/Analysis/Loads.h" 42 #include "llvm/Analysis/ValueTracking.h" 43 #include "llvm/Support/CallSite.h" 44 #include "llvm/Support/Debug.h" 45 #include "llvm/Support/ErrorHandling.h" 46 #include "llvm/Support/GetElementPtrTypeIterator.h" 47 #include "llvm/Support/MathExtras.h" 48 #include "llvm/Support/raw_ostream.h" 49 #include "llvm/Target/TargetData.h" 50 #include "llvm/Transforms/Utils/Local.h" 51 #include "llvm/Transforms/Utils/PromoteMemToReg.h" 52 #include "llvm/Transforms/Utils/SSAUpdater.h" 53 using namespace llvm; 54 55 STATISTIC(NumReplaced, "Number of allocas broken up"); 56 STATISTIC(NumPromoted, "Number of allocas promoted"); 57 STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion"); 58 STATISTIC(NumConverted, "Number of aggregates converted to scalar"); 59 60 namespace { 61 struct SROA : public FunctionPass { 62 SROA(int T, bool hasDT, char &ID, int ST, int AT, int SLT) 63 : FunctionPass(ID), HasDomTree(hasDT) { 64 if (T == -1) 65 SRThreshold = 128; 66 else 67 SRThreshold = T; 68 if (ST == -1) 69 StructMemberThreshold = 32; 70 else 71 StructMemberThreshold = ST; 72 if (AT == -1) 73 ArrayElementThreshold = 8; 74 else 75 ArrayElementThreshold = AT; 76 if (SLT == -1) 77 // Do not limit the scalar integer load size if no threshold is given. 78 ScalarLoadThreshold = -1; 79 else 80 ScalarLoadThreshold = SLT; 81 } 82 83 bool runOnFunction(Function &F); 84 85 bool performScalarRepl(Function &F); 86 bool performPromotion(Function &F); 87 88 private: 89 bool HasDomTree; 90 TargetData *TD; 91 92 /// DeadInsts - Keep track of instructions we have made dead, so that 93 /// we can remove them after we are done working. 94 SmallVector<Value*, 32> DeadInsts; 95 96 /// AllocaInfo - When analyzing uses of an alloca instruction, this captures 97 /// information about the uses. All these fields are initialized to false 98 /// and set to true when something is learned. 99 struct AllocaInfo { 100 /// The alloca to promote. 101 AllocaInst *AI; 102 103 /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite 104 /// looping and avoid redundant work. 105 SmallPtrSet<PHINode*, 8> CheckedPHIs; 106 107 /// isUnsafe - This is set to true if the alloca cannot be SROA'd. 108 bool isUnsafe : 1; 109 110 /// isMemCpySrc - This is true if this aggregate is memcpy'd from. 111 bool isMemCpySrc : 1; 112 113 /// isMemCpyDst - This is true if this aggregate is memcpy'd into. 114 bool isMemCpyDst : 1; 115 116 /// hasSubelementAccess - This is true if a subelement of the alloca is 117 /// ever accessed, or false if the alloca is only accessed with mem 118 /// intrinsics or load/store that only access the entire alloca at once. 119 bool hasSubelementAccess : 1; 120 121 /// hasALoadOrStore - This is true if there are any loads or stores to it. 122 /// The alloca may just be accessed with memcpy, for example, which would 123 /// not set this. 124 bool hasALoadOrStore : 1; 125 126 explicit AllocaInfo(AllocaInst *ai) 127 : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false), 128 hasSubelementAccess(false), hasALoadOrStore(false) {} 129 }; 130 131 /// SRThreshold - The maximum alloca size to considered for SROA. 132 unsigned SRThreshold; 133 134 /// StructMemberThreshold - The maximum number of members a struct can 135 /// contain to be considered for SROA. 136 unsigned StructMemberThreshold; 137 138 /// ArrayElementThreshold - The maximum number of elements an array can 139 /// have to be considered for SROA. 140 unsigned ArrayElementThreshold; 141 142 /// ScalarLoadThreshold - The maximum size in bits of scalars to load when 143 /// converting to scalar 144 unsigned ScalarLoadThreshold; 145 146 void MarkUnsafe(AllocaInfo &I, Instruction *User) { 147 I.isUnsafe = true; 148 DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n'); 149 } 150 151 bool isSafeAllocaToScalarRepl(AllocaInst *AI); 152 153 void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info); 154 void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset, 155 AllocaInfo &Info); 156 void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info); 157 void isSafeMemAccess(uint64_t Offset, uint64_t MemSize, 158 Type *MemOpType, bool isStore, AllocaInfo &Info, 159 Instruction *TheAccess, bool AllowWholeAccess); 160 bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size); 161 uint64_t FindElementAndOffset(Type *&T, uint64_t &Offset, 162 Type *&IdxTy); 163 164 void DoScalarReplacement(AllocaInst *AI, 165 std::vector<AllocaInst*> &WorkList); 166 void DeleteDeadInstructions(); 167 168 void RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset, 169 SmallVector<AllocaInst*, 32> &NewElts); 170 void RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset, 171 SmallVector<AllocaInst*, 32> &NewElts); 172 void RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset, 173 SmallVector<AllocaInst*, 32> &NewElts); 174 void RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI, 175 uint64_t Offset, 176 SmallVector<AllocaInst*, 32> &NewElts); 177 void RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst, 178 AllocaInst *AI, 179 SmallVector<AllocaInst*, 32> &NewElts); 180 void RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI, 181 SmallVector<AllocaInst*, 32> &NewElts); 182 void RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI, 183 SmallVector<AllocaInst*, 32> &NewElts); 184 bool ShouldAttemptScalarRepl(AllocaInst *AI); 185 }; 186 187 // SROA_DT - SROA that uses DominatorTree. 188 struct SROA_DT : public SROA { 189 static char ID; 190 public: 191 SROA_DT(int T = -1, int ST = -1, int AT = -1, int SLT = -1) : 192 SROA(T, true, ID, ST, AT, SLT) { 193 initializeSROA_DTPass(*PassRegistry::getPassRegistry()); 194 } 195 196 // getAnalysisUsage - This pass does not require any passes, but we know it 197 // will not alter the CFG, so say so. 198 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 199 AU.addRequired<DominatorTree>(); 200 AU.setPreservesCFG(); 201 } 202 }; 203 204 // SROA_SSAUp - SROA that uses SSAUpdater. 205 struct SROA_SSAUp : public SROA { 206 static char ID; 207 public: 208 SROA_SSAUp(int T = -1, int ST = -1, int AT = -1, int SLT = -1) : 209 SROA(T, false, ID, ST, AT, SLT) { 210 initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry()); 211 } 212 213 // getAnalysisUsage - This pass does not require any passes, but we know it 214 // will not alter the CFG, so say so. 215 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 216 AU.setPreservesCFG(); 217 } 218 }; 219 220 } 221 222 char SROA_DT::ID = 0; 223 char SROA_SSAUp::ID = 0; 224 225 INITIALIZE_PASS_BEGIN(SROA_DT, "scalarrepl", 226 "Scalar Replacement of Aggregates (DT)", false, false) 227 INITIALIZE_PASS_DEPENDENCY(DominatorTree) 228 INITIALIZE_PASS_END(SROA_DT, "scalarrepl", 229 "Scalar Replacement of Aggregates (DT)", false, false) 230 231 INITIALIZE_PASS_BEGIN(SROA_SSAUp, "scalarrepl-ssa", 232 "Scalar Replacement of Aggregates (SSAUp)", false, false) 233 INITIALIZE_PASS_END(SROA_SSAUp, "scalarrepl-ssa", 234 "Scalar Replacement of Aggregates (SSAUp)", false, false) 235 236 // Public interface to the ScalarReplAggregates pass 237 FunctionPass *llvm::createScalarReplAggregatesPass(int Threshold, 238 bool UseDomTree, 239 int StructMemberThreshold, 240 int ArrayElementThreshold, 241 int ScalarLoadThreshold) { 242 if (UseDomTree) 243 return new SROA_DT(Threshold, StructMemberThreshold, ArrayElementThreshold, 244 ScalarLoadThreshold); 245 return new SROA_SSAUp(Threshold, StructMemberThreshold, 246 ArrayElementThreshold, ScalarLoadThreshold); 247 } 248 249 250 //===----------------------------------------------------------------------===// 251 // Convert To Scalar Optimization. 252 //===----------------------------------------------------------------------===// 253 254 namespace { 255 /// ConvertToScalarInfo - This class implements the "Convert To Scalar" 256 /// optimization, which scans the uses of an alloca and determines if it can 257 /// rewrite it in terms of a single new alloca that can be mem2reg'd. 258 class ConvertToScalarInfo { 259 /// AllocaSize - The size of the alloca being considered in bytes. 260 unsigned AllocaSize; 261 const TargetData &TD; 262 unsigned ScalarLoadThreshold; 263 264 /// IsNotTrivial - This is set to true if there is some access to the object 265 /// which means that mem2reg can't promote it. 266 bool IsNotTrivial; 267 268 /// ScalarKind - Tracks the kind of alloca being considered for promotion, 269 /// computed based on the uses of the alloca rather than the LLVM type system. 270 enum { 271 Unknown, 272 273 // Accesses via GEPs that are consistent with element access of a vector 274 // type. This will not be converted into a vector unless there is a later 275 // access using an actual vector type. 276 ImplicitVector, 277 278 // Accesses via vector operations and GEPs that are consistent with the 279 // layout of a vector type. 280 Vector, 281 282 // An integer bag-of-bits with bitwise operations for insertion and 283 // extraction. Any combination of types can be converted into this kind 284 // of scalar. 285 Integer 286 } ScalarKind; 287 288 /// VectorTy - This tracks the type that we should promote the vector to if 289 /// it is possible to turn it into a vector. This starts out null, and if it 290 /// isn't possible to turn into a vector type, it gets set to VoidTy. 291 VectorType *VectorTy; 292 293 /// HadNonMemTransferAccess - True if there is at least one access to the 294 /// alloca that is not a MemTransferInst. We don't want to turn structs into 295 /// large integers unless there is some potential for optimization. 296 bool HadNonMemTransferAccess; 297 298 /// HadDynamicAccess - True if some element of this alloca was dynamic. 299 /// We don't yet have support for turning a dynamic access into a large 300 /// integer. 301 bool HadDynamicAccess; 302 303 public: 304 explicit ConvertToScalarInfo(unsigned Size, const TargetData &td, 305 unsigned SLT) 306 : AllocaSize(Size), TD(td), ScalarLoadThreshold(SLT), IsNotTrivial(false), 307 ScalarKind(Unknown), VectorTy(0), HadNonMemTransferAccess(false), 308 HadDynamicAccess(false) { } 309 310 AllocaInst *TryConvert(AllocaInst *AI); 311 312 private: 313 bool CanConvertToScalar(Value *V, uint64_t Offset, Value* NonConstantIdx); 314 void MergeInTypeForLoadOrStore(Type *In, uint64_t Offset); 315 bool MergeInVectorType(VectorType *VInTy, uint64_t Offset); 316 void ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, uint64_t Offset, 317 Value *NonConstantIdx); 318 319 Value *ConvertScalar_ExtractValue(Value *NV, Type *ToType, 320 uint64_t Offset, Value* NonConstantIdx, 321 IRBuilder<> &Builder); 322 Value *ConvertScalar_InsertValue(Value *StoredVal, Value *ExistingVal, 323 uint64_t Offset, Value* NonConstantIdx, 324 IRBuilder<> &Builder); 325 }; 326 } // end anonymous namespace. 327 328 329 /// TryConvert - Analyze the specified alloca, and if it is safe to do so, 330 /// rewrite it to be a new alloca which is mem2reg'able. This returns the new 331 /// alloca if possible or null if not. 332 AllocaInst *ConvertToScalarInfo::TryConvert(AllocaInst *AI) { 333 // If we can't convert this scalar, or if mem2reg can trivially do it, bail 334 // out. 335 if (!CanConvertToScalar(AI, 0, 0) || !IsNotTrivial) 336 return 0; 337 338 // If an alloca has only memset / memcpy uses, it may still have an Unknown 339 // ScalarKind. Treat it as an Integer below. 340 if (ScalarKind == Unknown) 341 ScalarKind = Integer; 342 343 if (ScalarKind == Vector && VectorTy->getBitWidth() != AllocaSize * 8) 344 ScalarKind = Integer; 345 346 // If we were able to find a vector type that can handle this with 347 // insert/extract elements, and if there was at least one use that had 348 // a vector type, promote this to a vector. We don't want to promote 349 // random stuff that doesn't use vectors (e.g. <9 x double>) because then 350 // we just get a lot of insert/extracts. If at least one vector is 351 // involved, then we probably really do have a union of vector/array. 352 Type *NewTy; 353 if (ScalarKind == Vector) { 354 assert(VectorTy && "Missing type for vector scalar."); 355 DEBUG(dbgs() << "CONVERT TO VECTOR: " << *AI << "\n TYPE = " 356 << *VectorTy << '\n'); 357 NewTy = VectorTy; // Use the vector type. 358 } else { 359 unsigned BitWidth = AllocaSize * 8; 360 361 // Do not convert to scalar integer if the alloca size exceeds the 362 // scalar load threshold. 363 if (BitWidth > ScalarLoadThreshold) 364 return 0; 365 366 if ((ScalarKind == ImplicitVector || ScalarKind == Integer) && 367 !HadNonMemTransferAccess && !TD.fitsInLegalInteger(BitWidth)) 368 return 0; 369 // Dynamic accesses on integers aren't yet supported. They need us to shift 370 // by a dynamic amount which could be difficult to work out as we might not 371 // know whether to use a left or right shift. 372 if (ScalarKind == Integer && HadDynamicAccess) 373 return 0; 374 375 DEBUG(dbgs() << "CONVERT TO SCALAR INTEGER: " << *AI << "\n"); 376 // Create and insert the integer alloca. 377 NewTy = IntegerType::get(AI->getContext(), BitWidth); 378 } 379 AllocaInst *NewAI = new AllocaInst(NewTy, 0, "", AI->getParent()->begin()); 380 ConvertUsesToScalar(AI, NewAI, 0, 0); 381 return NewAI; 382 } 383 384 /// MergeInTypeForLoadOrStore - Add the 'In' type to the accumulated vector type 385 /// (VectorTy) so far at the offset specified by Offset (which is specified in 386 /// bytes). 387 /// 388 /// There are two cases we handle here: 389 /// 1) A union of vector types of the same size and potentially its elements. 390 /// Here we turn element accesses into insert/extract element operations. 391 /// This promotes a <4 x float> with a store of float to the third element 392 /// into a <4 x float> that uses insert element. 393 /// 2) A fully general blob of memory, which we turn into some (potentially 394 /// large) integer type with extract and insert operations where the loads 395 /// and stores would mutate the memory. We mark this by setting VectorTy 396 /// to VoidTy. 397 void ConvertToScalarInfo::MergeInTypeForLoadOrStore(Type *In, 398 uint64_t Offset) { 399 // If we already decided to turn this into a blob of integer memory, there is 400 // nothing to be done. 401 if (ScalarKind == Integer) 402 return; 403 404 // If this could be contributing to a vector, analyze it. 405 406 // If the In type is a vector that is the same size as the alloca, see if it 407 // matches the existing VecTy. 408 if (VectorType *VInTy = dyn_cast<VectorType>(In)) { 409 if (MergeInVectorType(VInTy, Offset)) 410 return; 411 } else if (In->isFloatTy() || In->isDoubleTy() || 412 (In->isIntegerTy() && In->getPrimitiveSizeInBits() >= 8 && 413 isPowerOf2_32(In->getPrimitiveSizeInBits()))) { 414 // Full width accesses can be ignored, because they can always be turned 415 // into bitcasts. 416 unsigned EltSize = In->getPrimitiveSizeInBits()/8; 417 if (EltSize == AllocaSize) 418 return; 419 420 // If we're accessing something that could be an element of a vector, see 421 // if the implied vector agrees with what we already have and if Offset is 422 // compatible with it. 423 if (Offset % EltSize == 0 && AllocaSize % EltSize == 0 && 424 (!VectorTy || EltSize == VectorTy->getElementType() 425 ->getPrimitiveSizeInBits()/8)) { 426 if (!VectorTy) { 427 ScalarKind = ImplicitVector; 428 VectorTy = VectorType::get(In, AllocaSize/EltSize); 429 } 430 return; 431 } 432 } 433 434 // Otherwise, we have a case that we can't handle with an optimized vector 435 // form. We can still turn this into a large integer. 436 ScalarKind = Integer; 437 } 438 439 /// MergeInVectorType - Handles the vector case of MergeInTypeForLoadOrStore, 440 /// returning true if the type was successfully merged and false otherwise. 441 bool ConvertToScalarInfo::MergeInVectorType(VectorType *VInTy, 442 uint64_t Offset) { 443 if (VInTy->getBitWidth()/8 == AllocaSize && Offset == 0) { 444 // If we're storing/loading a vector of the right size, allow it as a 445 // vector. If this the first vector we see, remember the type so that 446 // we know the element size. If this is a subsequent access, ignore it 447 // even if it is a differing type but the same size. Worst case we can 448 // bitcast the resultant vectors. 449 if (!VectorTy) 450 VectorTy = VInTy; 451 ScalarKind = Vector; 452 return true; 453 } 454 455 return false; 456 } 457 458 /// CanConvertToScalar - V is a pointer. If we can convert the pointee and all 459 /// its accesses to a single vector type, return true and set VecTy to 460 /// the new type. If we could convert the alloca into a single promotable 461 /// integer, return true but set VecTy to VoidTy. Further, if the use is not a 462 /// completely trivial use that mem2reg could promote, set IsNotTrivial. Offset 463 /// is the current offset from the base of the alloca being analyzed. 464 /// 465 /// If we see at least one access to the value that is as a vector type, set the 466 /// SawVec flag. 467 bool ConvertToScalarInfo::CanConvertToScalar(Value *V, uint64_t Offset, 468 Value* NonConstantIdx) { 469 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI!=E; ++UI) { 470 Instruction *User = cast<Instruction>(*UI); 471 472 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 473 // Don't break volatile loads. 474 if (!LI->isSimple()) 475 return false; 476 // Don't touch MMX operations. 477 if (LI->getType()->isX86_MMXTy()) 478 return false; 479 HadNonMemTransferAccess = true; 480 MergeInTypeForLoadOrStore(LI->getType(), Offset); 481 continue; 482 } 483 484 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 485 // Storing the pointer, not into the value? 486 if (SI->getOperand(0) == V || !SI->isSimple()) return false; 487 // Don't touch MMX operations. 488 if (SI->getOperand(0)->getType()->isX86_MMXTy()) 489 return false; 490 HadNonMemTransferAccess = true; 491 MergeInTypeForLoadOrStore(SI->getOperand(0)->getType(), Offset); 492 continue; 493 } 494 495 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) { 496 if (!onlyUsedByLifetimeMarkers(BCI)) 497 IsNotTrivial = true; // Can't be mem2reg'd. 498 if (!CanConvertToScalar(BCI, Offset, NonConstantIdx)) 499 return false; 500 continue; 501 } 502 503 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) { 504 // If this is a GEP with a variable indices, we can't handle it. 505 PointerType* PtrTy = dyn_cast<PointerType>(GEP->getPointerOperandType()); 506 if (!PtrTy) 507 return false; 508 509 // Compute the offset that this GEP adds to the pointer. 510 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end()); 511 Value *GEPNonConstantIdx = 0; 512 if (!GEP->hasAllConstantIndices()) { 513 if (!isa<VectorType>(PtrTy->getElementType())) 514 return false; 515 if (NonConstantIdx) 516 return false; 517 GEPNonConstantIdx = Indices.pop_back_val(); 518 if (!GEPNonConstantIdx->getType()->isIntegerTy(32)) 519 return false; 520 HadDynamicAccess = true; 521 } else 522 GEPNonConstantIdx = NonConstantIdx; 523 uint64_t GEPOffset = TD.getIndexedOffset(PtrTy, 524 Indices); 525 // See if all uses can be converted. 526 if (!CanConvertToScalar(GEP, Offset+GEPOffset, GEPNonConstantIdx)) 527 return false; 528 IsNotTrivial = true; // Can't be mem2reg'd. 529 HadNonMemTransferAccess = true; 530 continue; 531 } 532 533 // If this is a constant sized memset of a constant value (e.g. 0) we can 534 // handle it. 535 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) { 536 // Store to dynamic index. 537 if (NonConstantIdx) 538 return false; 539 // Store of constant value. 540 if (!isa<ConstantInt>(MSI->getValue())) 541 return false; 542 543 // Store of constant size. 544 ConstantInt *Len = dyn_cast<ConstantInt>(MSI->getLength()); 545 if (!Len) 546 return false; 547 548 // If the size differs from the alloca, we can only convert the alloca to 549 // an integer bag-of-bits. 550 // FIXME: This should handle all of the cases that are currently accepted 551 // as vector element insertions. 552 if (Len->getZExtValue() != AllocaSize || Offset != 0) 553 ScalarKind = Integer; 554 555 IsNotTrivial = true; // Can't be mem2reg'd. 556 HadNonMemTransferAccess = true; 557 continue; 558 } 559 560 // If this is a memcpy or memmove into or out of the whole allocation, we 561 // can handle it like a load or store of the scalar type. 562 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) { 563 // Store to dynamic index. 564 if (NonConstantIdx) 565 return false; 566 ConstantInt *Len = dyn_cast<ConstantInt>(MTI->getLength()); 567 if (Len == 0 || Len->getZExtValue() != AllocaSize || Offset != 0) 568 return false; 569 570 IsNotTrivial = true; // Can't be mem2reg'd. 571 continue; 572 } 573 574 // If this is a lifetime intrinsic, we can handle it. 575 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) { 576 if (II->getIntrinsicID() == Intrinsic::lifetime_start || 577 II->getIntrinsicID() == Intrinsic::lifetime_end) { 578 continue; 579 } 580 } 581 582 // Otherwise, we cannot handle this! 583 return false; 584 } 585 586 return true; 587 } 588 589 /// ConvertUsesToScalar - Convert all of the users of Ptr to use the new alloca 590 /// directly. This happens when we are converting an "integer union" to a 591 /// single integer scalar, or when we are converting a "vector union" to a 592 /// vector with insert/extractelement instructions. 593 /// 594 /// Offset is an offset from the original alloca, in bits that need to be 595 /// shifted to the right. By the end of this, there should be no uses of Ptr. 596 void ConvertToScalarInfo::ConvertUsesToScalar(Value *Ptr, AllocaInst *NewAI, 597 uint64_t Offset, 598 Value* NonConstantIdx) { 599 while (!Ptr->use_empty()) { 600 Instruction *User = cast<Instruction>(Ptr->use_back()); 601 602 if (BitCastInst *CI = dyn_cast<BitCastInst>(User)) { 603 ConvertUsesToScalar(CI, NewAI, Offset, NonConstantIdx); 604 CI->eraseFromParent(); 605 continue; 606 } 607 608 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) { 609 // Compute the offset that this GEP adds to the pointer. 610 SmallVector<Value*, 8> Indices(GEP->op_begin()+1, GEP->op_end()); 611 Value* GEPNonConstantIdx = 0; 612 if (!GEP->hasAllConstantIndices()) { 613 assert(!NonConstantIdx && 614 "Dynamic GEP reading from dynamic GEP unsupported"); 615 GEPNonConstantIdx = Indices.pop_back_val(); 616 } else 617 GEPNonConstantIdx = NonConstantIdx; 618 uint64_t GEPOffset = TD.getIndexedOffset(GEP->getPointerOperandType(), 619 Indices); 620 ConvertUsesToScalar(GEP, NewAI, Offset+GEPOffset*8, GEPNonConstantIdx); 621 GEP->eraseFromParent(); 622 continue; 623 } 624 625 IRBuilder<> Builder(User); 626 627 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 628 // The load is a bit extract from NewAI shifted right by Offset bits. 629 Value *LoadedVal = Builder.CreateLoad(NewAI); 630 Value *NewLoadVal 631 = ConvertScalar_ExtractValue(LoadedVal, LI->getType(), Offset, 632 NonConstantIdx, Builder); 633 LI->replaceAllUsesWith(NewLoadVal); 634 LI->eraseFromParent(); 635 continue; 636 } 637 638 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 639 assert(SI->getOperand(0) != Ptr && "Consistency error!"); 640 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in"); 641 Value *New = ConvertScalar_InsertValue(SI->getOperand(0), Old, Offset, 642 NonConstantIdx, Builder); 643 Builder.CreateStore(New, NewAI); 644 SI->eraseFromParent(); 645 646 // If the load we just inserted is now dead, then the inserted store 647 // overwrote the entire thing. 648 if (Old->use_empty()) 649 Old->eraseFromParent(); 650 continue; 651 } 652 653 // If this is a constant sized memset of a constant value (e.g. 0) we can 654 // transform it into a store of the expanded constant value. 655 if (MemSetInst *MSI = dyn_cast<MemSetInst>(User)) { 656 assert(MSI->getRawDest() == Ptr && "Consistency error!"); 657 assert(!NonConstantIdx && "Cannot replace dynamic memset with insert"); 658 int64_t SNumBytes = cast<ConstantInt>(MSI->getLength())->getSExtValue(); 659 if (SNumBytes > 0 && (SNumBytes >> 32) == 0) { 660 unsigned NumBytes = static_cast<unsigned>(SNumBytes); 661 unsigned Val = cast<ConstantInt>(MSI->getValue())->getZExtValue(); 662 663 // Compute the value replicated the right number of times. 664 APInt APVal(NumBytes*8, Val); 665 666 // Splat the value if non-zero. 667 if (Val) 668 for (unsigned i = 1; i != NumBytes; ++i) 669 APVal |= APVal << 8; 670 671 Instruction *Old = Builder.CreateLoad(NewAI, NewAI->getName()+".in"); 672 Value *New = ConvertScalar_InsertValue( 673 ConstantInt::get(User->getContext(), APVal), 674 Old, Offset, 0, Builder); 675 Builder.CreateStore(New, NewAI); 676 677 // If the load we just inserted is now dead, then the memset overwrote 678 // the entire thing. 679 if (Old->use_empty()) 680 Old->eraseFromParent(); 681 } 682 MSI->eraseFromParent(); 683 continue; 684 } 685 686 // If this is a memcpy or memmove into or out of the whole allocation, we 687 // can handle it like a load or store of the scalar type. 688 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(User)) { 689 assert(Offset == 0 && "must be store to start of alloca"); 690 assert(!NonConstantIdx && "Cannot replace dynamic transfer with insert"); 691 692 // If the source and destination are both to the same alloca, then this is 693 // a noop copy-to-self, just delete it. Otherwise, emit a load and store 694 // as appropriate. 695 AllocaInst *OrigAI = cast<AllocaInst>(GetUnderlyingObject(Ptr, &TD, 0)); 696 697 if (GetUnderlyingObject(MTI->getSource(), &TD, 0) != OrigAI) { 698 // Dest must be OrigAI, change this to be a load from the original 699 // pointer (bitcasted), then a store to our new alloca. 700 assert(MTI->getRawDest() == Ptr && "Neither use is of pointer?"); 701 Value *SrcPtr = MTI->getSource(); 702 PointerType* SPTy = cast<PointerType>(SrcPtr->getType()); 703 PointerType* AIPTy = cast<PointerType>(NewAI->getType()); 704 if (SPTy->getAddressSpace() != AIPTy->getAddressSpace()) { 705 AIPTy = PointerType::get(AIPTy->getElementType(), 706 SPTy->getAddressSpace()); 707 } 708 SrcPtr = Builder.CreateBitCast(SrcPtr, AIPTy); 709 710 LoadInst *SrcVal = Builder.CreateLoad(SrcPtr, "srcval"); 711 SrcVal->setAlignment(MTI->getAlignment()); 712 Builder.CreateStore(SrcVal, NewAI); 713 } else if (GetUnderlyingObject(MTI->getDest(), &TD, 0) != OrigAI) { 714 // Src must be OrigAI, change this to be a load from NewAI then a store 715 // through the original dest pointer (bitcasted). 716 assert(MTI->getRawSource() == Ptr && "Neither use is of pointer?"); 717 LoadInst *SrcVal = Builder.CreateLoad(NewAI, "srcval"); 718 719 PointerType* DPTy = cast<PointerType>(MTI->getDest()->getType()); 720 PointerType* AIPTy = cast<PointerType>(NewAI->getType()); 721 if (DPTy->getAddressSpace() != AIPTy->getAddressSpace()) { 722 AIPTy = PointerType::get(AIPTy->getElementType(), 723 DPTy->getAddressSpace()); 724 } 725 Value *DstPtr = Builder.CreateBitCast(MTI->getDest(), AIPTy); 726 727 StoreInst *NewStore = Builder.CreateStore(SrcVal, DstPtr); 728 NewStore->setAlignment(MTI->getAlignment()); 729 } else { 730 // Noop transfer. Src == Dst 731 } 732 733 MTI->eraseFromParent(); 734 continue; 735 } 736 737 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) { 738 if (II->getIntrinsicID() == Intrinsic::lifetime_start || 739 II->getIntrinsicID() == Intrinsic::lifetime_end) { 740 // There's no need to preserve these, as the resulting alloca will be 741 // converted to a register anyways. 742 II->eraseFromParent(); 743 continue; 744 } 745 } 746 747 llvm_unreachable("Unsupported operation!"); 748 } 749 } 750 751 /// ConvertScalar_ExtractValue - Extract a value of type ToType from an integer 752 /// or vector value FromVal, extracting the bits from the offset specified by 753 /// Offset. This returns the value, which is of type ToType. 754 /// 755 /// This happens when we are converting an "integer union" to a single 756 /// integer scalar, or when we are converting a "vector union" to a vector with 757 /// insert/extractelement instructions. 758 /// 759 /// Offset is an offset from the original alloca, in bits that need to be 760 /// shifted to the right. 761 Value *ConvertToScalarInfo:: 762 ConvertScalar_ExtractValue(Value *FromVal, Type *ToType, 763 uint64_t Offset, Value* NonConstantIdx, 764 IRBuilder<> &Builder) { 765 // If the load is of the whole new alloca, no conversion is needed. 766 Type *FromType = FromVal->getType(); 767 if (FromType == ToType && Offset == 0) 768 return FromVal; 769 770 // If the result alloca is a vector type, this is either an element 771 // access or a bitcast to another vector type of the same size. 772 if (VectorType *VTy = dyn_cast<VectorType>(FromType)) { 773 unsigned FromTypeSize = TD.getTypeAllocSize(FromType); 774 unsigned ToTypeSize = TD.getTypeAllocSize(ToType); 775 if (FromTypeSize == ToTypeSize) 776 return Builder.CreateBitCast(FromVal, ToType); 777 778 // Otherwise it must be an element access. 779 unsigned Elt = 0; 780 if (Offset) { 781 unsigned EltSize = TD.getTypeAllocSizeInBits(VTy->getElementType()); 782 Elt = Offset/EltSize; 783 assert(EltSize*Elt == Offset && "Invalid modulus in validity checking"); 784 } 785 // Return the element extracted out of it. 786 Value *Idx; 787 if (NonConstantIdx) { 788 if (Elt) 789 Idx = Builder.CreateAdd(NonConstantIdx, 790 Builder.getInt32(Elt), 791 "dyn.offset"); 792 else 793 Idx = NonConstantIdx; 794 } else 795 Idx = Builder.getInt32(Elt); 796 Value *V = Builder.CreateExtractElement(FromVal, Idx); 797 if (V->getType() != ToType) 798 V = Builder.CreateBitCast(V, ToType); 799 return V; 800 } 801 802 // If ToType is a first class aggregate, extract out each of the pieces and 803 // use insertvalue's to form the FCA. 804 if (StructType *ST = dyn_cast<StructType>(ToType)) { 805 assert(!NonConstantIdx && 806 "Dynamic indexing into struct types not supported"); 807 const StructLayout &Layout = *TD.getStructLayout(ST); 808 Value *Res = UndefValue::get(ST); 809 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) { 810 Value *Elt = ConvertScalar_ExtractValue(FromVal, ST->getElementType(i), 811 Offset+Layout.getElementOffsetInBits(i), 812 0, Builder); 813 Res = Builder.CreateInsertValue(Res, Elt, i); 814 } 815 return Res; 816 } 817 818 if (ArrayType *AT = dyn_cast<ArrayType>(ToType)) { 819 assert(!NonConstantIdx && 820 "Dynamic indexing into array types not supported"); 821 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType()); 822 Value *Res = UndefValue::get(AT); 823 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { 824 Value *Elt = ConvertScalar_ExtractValue(FromVal, AT->getElementType(), 825 Offset+i*EltSize, 0, Builder); 826 Res = Builder.CreateInsertValue(Res, Elt, i); 827 } 828 return Res; 829 } 830 831 // Otherwise, this must be a union that was converted to an integer value. 832 IntegerType *NTy = cast<IntegerType>(FromVal->getType()); 833 834 // If this is a big-endian system and the load is narrower than the 835 // full alloca type, we need to do a shift to get the right bits. 836 int ShAmt = 0; 837 if (TD.isBigEndian()) { 838 // On big-endian machines, the lowest bit is stored at the bit offset 839 // from the pointer given by getTypeStoreSizeInBits. This matters for 840 // integers with a bitwidth that is not a multiple of 8. 841 ShAmt = TD.getTypeStoreSizeInBits(NTy) - 842 TD.getTypeStoreSizeInBits(ToType) - Offset; 843 } else { 844 ShAmt = Offset; 845 } 846 847 // Note: we support negative bitwidths (with shl) which are not defined. 848 // We do this to support (f.e.) loads off the end of a structure where 849 // only some bits are used. 850 if (ShAmt > 0 && (unsigned)ShAmt < NTy->getBitWidth()) 851 FromVal = Builder.CreateLShr(FromVal, 852 ConstantInt::get(FromVal->getType(), ShAmt)); 853 else if (ShAmt < 0 && (unsigned)-ShAmt < NTy->getBitWidth()) 854 FromVal = Builder.CreateShl(FromVal, 855 ConstantInt::get(FromVal->getType(), -ShAmt)); 856 857 // Finally, unconditionally truncate the integer to the right width. 858 unsigned LIBitWidth = TD.getTypeSizeInBits(ToType); 859 if (LIBitWidth < NTy->getBitWidth()) 860 FromVal = 861 Builder.CreateTrunc(FromVal, IntegerType::get(FromVal->getContext(), 862 LIBitWidth)); 863 else if (LIBitWidth > NTy->getBitWidth()) 864 FromVal = 865 Builder.CreateZExt(FromVal, IntegerType::get(FromVal->getContext(), 866 LIBitWidth)); 867 868 // If the result is an integer, this is a trunc or bitcast. 869 if (ToType->isIntegerTy()) { 870 // Should be done. 871 } else if (ToType->isFloatingPointTy() || ToType->isVectorTy()) { 872 // Just do a bitcast, we know the sizes match up. 873 FromVal = Builder.CreateBitCast(FromVal, ToType); 874 } else { 875 // Otherwise must be a pointer. 876 FromVal = Builder.CreateIntToPtr(FromVal, ToType); 877 } 878 assert(FromVal->getType() == ToType && "Didn't convert right?"); 879 return FromVal; 880 } 881 882 /// ConvertScalar_InsertValue - Insert the value "SV" into the existing integer 883 /// or vector value "Old" at the offset specified by Offset. 884 /// 885 /// This happens when we are converting an "integer union" to a 886 /// single integer scalar, or when we are converting a "vector union" to a 887 /// vector with insert/extractelement instructions. 888 /// 889 /// Offset is an offset from the original alloca, in bits that need to be 890 /// shifted to the right. 891 /// 892 /// NonConstantIdx is an index value if there was a GEP with a non-constant 893 /// index value. If this is 0 then all GEPs used to find this insert address 894 /// are constant. 895 Value *ConvertToScalarInfo:: 896 ConvertScalar_InsertValue(Value *SV, Value *Old, 897 uint64_t Offset, Value* NonConstantIdx, 898 IRBuilder<> &Builder) { 899 // Convert the stored type to the actual type, shift it left to insert 900 // then 'or' into place. 901 Type *AllocaType = Old->getType(); 902 LLVMContext &Context = Old->getContext(); 903 904 if (VectorType *VTy = dyn_cast<VectorType>(AllocaType)) { 905 uint64_t VecSize = TD.getTypeAllocSizeInBits(VTy); 906 uint64_t ValSize = TD.getTypeAllocSizeInBits(SV->getType()); 907 908 // Changing the whole vector with memset or with an access of a different 909 // vector type? 910 if (ValSize == VecSize) 911 return Builder.CreateBitCast(SV, AllocaType); 912 913 // Must be an element insertion. 914 Type *EltTy = VTy->getElementType(); 915 if (SV->getType() != EltTy) 916 SV = Builder.CreateBitCast(SV, EltTy); 917 uint64_t EltSize = TD.getTypeAllocSizeInBits(EltTy); 918 unsigned Elt = Offset/EltSize; 919 Value *Idx; 920 if (NonConstantIdx) { 921 if (Elt) 922 Idx = Builder.CreateAdd(NonConstantIdx, 923 Builder.getInt32(Elt), 924 "dyn.offset"); 925 else 926 Idx = NonConstantIdx; 927 } else 928 Idx = Builder.getInt32(Elt); 929 return Builder.CreateInsertElement(Old, SV, Idx); 930 } 931 932 // If SV is a first-class aggregate value, insert each value recursively. 933 if (StructType *ST = dyn_cast<StructType>(SV->getType())) { 934 assert(!NonConstantIdx && 935 "Dynamic indexing into struct types not supported"); 936 const StructLayout &Layout = *TD.getStructLayout(ST); 937 for (unsigned i = 0, e = ST->getNumElements(); i != e; ++i) { 938 Value *Elt = Builder.CreateExtractValue(SV, i); 939 Old = ConvertScalar_InsertValue(Elt, Old, 940 Offset+Layout.getElementOffsetInBits(i), 941 0, Builder); 942 } 943 return Old; 944 } 945 946 if (ArrayType *AT = dyn_cast<ArrayType>(SV->getType())) { 947 assert(!NonConstantIdx && 948 "Dynamic indexing into array types not supported"); 949 uint64_t EltSize = TD.getTypeAllocSizeInBits(AT->getElementType()); 950 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { 951 Value *Elt = Builder.CreateExtractValue(SV, i); 952 Old = ConvertScalar_InsertValue(Elt, Old, Offset+i*EltSize, 0, Builder); 953 } 954 return Old; 955 } 956 957 // If SV is a float, convert it to the appropriate integer type. 958 // If it is a pointer, do the same. 959 unsigned SrcWidth = TD.getTypeSizeInBits(SV->getType()); 960 unsigned DestWidth = TD.getTypeSizeInBits(AllocaType); 961 unsigned SrcStoreWidth = TD.getTypeStoreSizeInBits(SV->getType()); 962 unsigned DestStoreWidth = TD.getTypeStoreSizeInBits(AllocaType); 963 if (SV->getType()->isFloatingPointTy() || SV->getType()->isVectorTy()) 964 SV = Builder.CreateBitCast(SV, IntegerType::get(SV->getContext(),SrcWidth)); 965 else if (SV->getType()->isPointerTy()) 966 SV = Builder.CreatePtrToInt(SV, TD.getIntPtrType(SV->getContext())); 967 968 // Zero extend or truncate the value if needed. 969 if (SV->getType() != AllocaType) { 970 if (SV->getType()->getPrimitiveSizeInBits() < 971 AllocaType->getPrimitiveSizeInBits()) 972 SV = Builder.CreateZExt(SV, AllocaType); 973 else { 974 // Truncation may be needed if storing more than the alloca can hold 975 // (undefined behavior). 976 SV = Builder.CreateTrunc(SV, AllocaType); 977 SrcWidth = DestWidth; 978 SrcStoreWidth = DestStoreWidth; 979 } 980 } 981 982 // If this is a big-endian system and the store is narrower than the 983 // full alloca type, we need to do a shift to get the right bits. 984 int ShAmt = 0; 985 if (TD.isBigEndian()) { 986 // On big-endian machines, the lowest bit is stored at the bit offset 987 // from the pointer given by getTypeStoreSizeInBits. This matters for 988 // integers with a bitwidth that is not a multiple of 8. 989 ShAmt = DestStoreWidth - SrcStoreWidth - Offset; 990 } else { 991 ShAmt = Offset; 992 } 993 994 // Note: we support negative bitwidths (with shr) which are not defined. 995 // We do this to support (f.e.) stores off the end of a structure where 996 // only some bits in the structure are set. 997 APInt Mask(APInt::getLowBitsSet(DestWidth, SrcWidth)); 998 if (ShAmt > 0 && (unsigned)ShAmt < DestWidth) { 999 SV = Builder.CreateShl(SV, ConstantInt::get(SV->getType(), ShAmt)); 1000 Mask <<= ShAmt; 1001 } else if (ShAmt < 0 && (unsigned)-ShAmt < DestWidth) { 1002 SV = Builder.CreateLShr(SV, ConstantInt::get(SV->getType(), -ShAmt)); 1003 Mask = Mask.lshr(-ShAmt); 1004 } 1005 1006 // Mask out the bits we are about to insert from the old value, and or 1007 // in the new bits. 1008 if (SrcWidth != DestWidth) { 1009 assert(DestWidth > SrcWidth); 1010 Old = Builder.CreateAnd(Old, ConstantInt::get(Context, ~Mask), "mask"); 1011 SV = Builder.CreateOr(Old, SV, "ins"); 1012 } 1013 return SV; 1014 } 1015 1016 1017 //===----------------------------------------------------------------------===// 1018 // SRoA Driver 1019 //===----------------------------------------------------------------------===// 1020 1021 1022 bool SROA::runOnFunction(Function &F) { 1023 TD = getAnalysisIfAvailable<TargetData>(); 1024 1025 bool Changed = performPromotion(F); 1026 1027 // FIXME: ScalarRepl currently depends on TargetData more than it 1028 // theoretically needs to. It should be refactored in order to support 1029 // target-independent IR. Until this is done, just skip the actual 1030 // scalar-replacement portion of this pass. 1031 if (!TD) return Changed; 1032 1033 while (1) { 1034 bool LocalChange = performScalarRepl(F); 1035 if (!LocalChange) break; // No need to repromote if no scalarrepl 1036 Changed = true; 1037 LocalChange = performPromotion(F); 1038 if (!LocalChange) break; // No need to re-scalarrepl if no promotion 1039 } 1040 1041 return Changed; 1042 } 1043 1044 namespace { 1045 class AllocaPromoter : public LoadAndStorePromoter { 1046 AllocaInst *AI; 1047 DIBuilder *DIB; 1048 SmallVector<DbgDeclareInst *, 4> DDIs; 1049 SmallVector<DbgValueInst *, 4> DVIs; 1050 public: 1051 AllocaPromoter(const SmallVectorImpl<Instruction*> &Insts, SSAUpdater &S, 1052 DIBuilder *DB) 1053 : LoadAndStorePromoter(Insts, S), AI(0), DIB(DB) {} 1054 1055 void run(AllocaInst *AI, const SmallVectorImpl<Instruction*> &Insts) { 1056 // Remember which alloca we're promoting (for isInstInList). 1057 this->AI = AI; 1058 if (MDNode *DebugNode = MDNode::getIfExists(AI->getContext(), AI)) { 1059 for (Value::use_iterator UI = DebugNode->use_begin(), 1060 E = DebugNode->use_end(); UI != E; ++UI) 1061 if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(*UI)) 1062 DDIs.push_back(DDI); 1063 else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(*UI)) 1064 DVIs.push_back(DVI); 1065 } 1066 1067 LoadAndStorePromoter::run(Insts); 1068 AI->eraseFromParent(); 1069 for (SmallVector<DbgDeclareInst *, 4>::iterator I = DDIs.begin(), 1070 E = DDIs.end(); I != E; ++I) { 1071 DbgDeclareInst *DDI = *I; 1072 DDI->eraseFromParent(); 1073 } 1074 for (SmallVector<DbgValueInst *, 4>::iterator I = DVIs.begin(), 1075 E = DVIs.end(); I != E; ++I) { 1076 DbgValueInst *DVI = *I; 1077 DVI->eraseFromParent(); 1078 } 1079 } 1080 1081 virtual bool isInstInList(Instruction *I, 1082 const SmallVectorImpl<Instruction*> &Insts) const { 1083 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 1084 return LI->getOperand(0) == AI; 1085 return cast<StoreInst>(I)->getPointerOperand() == AI; 1086 } 1087 1088 virtual void updateDebugInfo(Instruction *Inst) const { 1089 for (SmallVector<DbgDeclareInst *, 4>::const_iterator I = DDIs.begin(), 1090 E = DDIs.end(); I != E; ++I) { 1091 DbgDeclareInst *DDI = *I; 1092 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) 1093 ConvertDebugDeclareToDebugValue(DDI, SI, *DIB); 1094 else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) 1095 ConvertDebugDeclareToDebugValue(DDI, LI, *DIB); 1096 } 1097 for (SmallVector<DbgValueInst *, 4>::const_iterator I = DVIs.begin(), 1098 E = DVIs.end(); I != E; ++I) { 1099 DbgValueInst *DVI = *I; 1100 Value *Arg = NULL; 1101 if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 1102 // If an argument is zero extended then use argument directly. The ZExt 1103 // may be zapped by an optimization pass in future. 1104 if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0))) 1105 Arg = dyn_cast<Argument>(ZExt->getOperand(0)); 1106 if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0))) 1107 Arg = dyn_cast<Argument>(SExt->getOperand(0)); 1108 if (!Arg) 1109 Arg = SI->getOperand(0); 1110 } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) { 1111 Arg = LI->getOperand(0); 1112 } else { 1113 continue; 1114 } 1115 Instruction *DbgVal = 1116 DIB->insertDbgValueIntrinsic(Arg, 0, DIVariable(DVI->getVariable()), 1117 Inst); 1118 DbgVal->setDebugLoc(DVI->getDebugLoc()); 1119 } 1120 } 1121 }; 1122 } // end anon namespace 1123 1124 /// isSafeSelectToSpeculate - Select instructions that use an alloca and are 1125 /// subsequently loaded can be rewritten to load both input pointers and then 1126 /// select between the result, allowing the load of the alloca to be promoted. 1127 /// From this: 1128 /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other 1129 /// %V = load i32* %P2 1130 /// to: 1131 /// %V1 = load i32* %Alloca -> will be mem2reg'd 1132 /// %V2 = load i32* %Other 1133 /// %V = select i1 %cond, i32 %V1, i32 %V2 1134 /// 1135 /// We can do this to a select if its only uses are loads and if the operand to 1136 /// the select can be loaded unconditionally. 1137 static bool isSafeSelectToSpeculate(SelectInst *SI, const TargetData *TD) { 1138 bool TDerefable = SI->getTrueValue()->isDereferenceablePointer(); 1139 bool FDerefable = SI->getFalseValue()->isDereferenceablePointer(); 1140 1141 for (Value::use_iterator UI = SI->use_begin(), UE = SI->use_end(); 1142 UI != UE; ++UI) { 1143 LoadInst *LI = dyn_cast<LoadInst>(*UI); 1144 if (LI == 0 || !LI->isSimple()) return false; 1145 1146 // Both operands to the select need to be dereferencable, either absolutely 1147 // (e.g. allocas) or at this point because we can see other accesses to it. 1148 if (!TDerefable && !isSafeToLoadUnconditionally(SI->getTrueValue(), LI, 1149 LI->getAlignment(), TD)) 1150 return false; 1151 if (!FDerefable && !isSafeToLoadUnconditionally(SI->getFalseValue(), LI, 1152 LI->getAlignment(), TD)) 1153 return false; 1154 } 1155 1156 return true; 1157 } 1158 1159 /// isSafePHIToSpeculate - PHI instructions that use an alloca and are 1160 /// subsequently loaded can be rewritten to load both input pointers in the pred 1161 /// blocks and then PHI the results, allowing the load of the alloca to be 1162 /// promoted. 1163 /// From this: 1164 /// %P2 = phi [i32* %Alloca, i32* %Other] 1165 /// %V = load i32* %P2 1166 /// to: 1167 /// %V1 = load i32* %Alloca -> will be mem2reg'd 1168 /// ... 1169 /// %V2 = load i32* %Other 1170 /// ... 1171 /// %V = phi [i32 %V1, i32 %V2] 1172 /// 1173 /// We can do this to a select if its only uses are loads and if the operand to 1174 /// the select can be loaded unconditionally. 1175 static bool isSafePHIToSpeculate(PHINode *PN, const TargetData *TD) { 1176 // For now, we can only do this promotion if the load is in the same block as 1177 // the PHI, and if there are no stores between the phi and load. 1178 // TODO: Allow recursive phi users. 1179 // TODO: Allow stores. 1180 BasicBlock *BB = PN->getParent(); 1181 unsigned MaxAlign = 0; 1182 for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end(); 1183 UI != UE; ++UI) { 1184 LoadInst *LI = dyn_cast<LoadInst>(*UI); 1185 if (LI == 0 || !LI->isSimple()) return false; 1186 1187 // For now we only allow loads in the same block as the PHI. This is a 1188 // common case that happens when instcombine merges two loads through a PHI. 1189 if (LI->getParent() != BB) return false; 1190 1191 // Ensure that there are no instructions between the PHI and the load that 1192 // could store. 1193 for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI) 1194 if (BBI->mayWriteToMemory()) 1195 return false; 1196 1197 MaxAlign = std::max(MaxAlign, LI->getAlignment()); 1198 } 1199 1200 // Okay, we know that we have one or more loads in the same block as the PHI. 1201 // We can transform this if it is safe to push the loads into the predecessor 1202 // blocks. The only thing to watch out for is that we can't put a possibly 1203 // trapping load in the predecessor if it is a critical edge. 1204 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1205 BasicBlock *Pred = PN->getIncomingBlock(i); 1206 Value *InVal = PN->getIncomingValue(i); 1207 1208 // If the terminator of the predecessor has side-effects (an invoke), 1209 // there is no safe place to put a load in the predecessor. 1210 if (Pred->getTerminator()->mayHaveSideEffects()) 1211 return false; 1212 1213 // If the value is produced by the terminator of the predecessor 1214 // (an invoke), there is no valid place to put a load in the predecessor. 1215 if (Pred->getTerminator() == InVal) 1216 return false; 1217 1218 // If the predecessor has a single successor, then the edge isn't critical. 1219 if (Pred->getTerminator()->getNumSuccessors() == 1) 1220 continue; 1221 1222 // If this pointer is always safe to load, or if we can prove that there is 1223 // already a load in the block, then we can move the load to the pred block. 1224 if (InVal->isDereferenceablePointer() || 1225 isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign, TD)) 1226 continue; 1227 1228 return false; 1229 } 1230 1231 return true; 1232 } 1233 1234 1235 /// tryToMakeAllocaBePromotable - This returns true if the alloca only has 1236 /// direct (non-volatile) loads and stores to it. If the alloca is close but 1237 /// not quite there, this will transform the code to allow promotion. As such, 1238 /// it is a non-pure predicate. 1239 static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const TargetData *TD) { 1240 SetVector<Instruction*, SmallVector<Instruction*, 4>, 1241 SmallPtrSet<Instruction*, 4> > InstsToRewrite; 1242 1243 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end(); 1244 UI != UE; ++UI) { 1245 User *U = *UI; 1246 if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 1247 if (!LI->isSimple()) 1248 return false; 1249 continue; 1250 } 1251 1252 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 1253 if (SI->getOperand(0) == AI || !SI->isSimple()) 1254 return false; // Don't allow a store OF the AI, only INTO the AI. 1255 continue; 1256 } 1257 1258 if (SelectInst *SI = dyn_cast<SelectInst>(U)) { 1259 // If the condition being selected on is a constant, fold the select, yes 1260 // this does (rarely) happen early on. 1261 if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) { 1262 Value *Result = SI->getOperand(1+CI->isZero()); 1263 SI->replaceAllUsesWith(Result); 1264 SI->eraseFromParent(); 1265 1266 // This is very rare and we just scrambled the use list of AI, start 1267 // over completely. 1268 return tryToMakeAllocaBePromotable(AI, TD); 1269 } 1270 1271 // If it is safe to turn "load (select c, AI, ptr)" into a select of two 1272 // loads, then we can transform this by rewriting the select. 1273 if (!isSafeSelectToSpeculate(SI, TD)) 1274 return false; 1275 1276 InstsToRewrite.insert(SI); 1277 continue; 1278 } 1279 1280 if (PHINode *PN = dyn_cast<PHINode>(U)) { 1281 if (PN->use_empty()) { // Dead PHIs can be stripped. 1282 InstsToRewrite.insert(PN); 1283 continue; 1284 } 1285 1286 // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads 1287 // in the pred blocks, then we can transform this by rewriting the PHI. 1288 if (!isSafePHIToSpeculate(PN, TD)) 1289 return false; 1290 1291 InstsToRewrite.insert(PN); 1292 continue; 1293 } 1294 1295 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) { 1296 if (onlyUsedByLifetimeMarkers(BCI)) { 1297 InstsToRewrite.insert(BCI); 1298 continue; 1299 } 1300 } 1301 1302 return false; 1303 } 1304 1305 // If there are no instructions to rewrite, then all uses are load/stores and 1306 // we're done! 1307 if (InstsToRewrite.empty()) 1308 return true; 1309 1310 // If we have instructions that need to be rewritten for this to be promotable 1311 // take care of it now. 1312 for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) { 1313 if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) { 1314 // This could only be a bitcast used by nothing but lifetime intrinsics. 1315 for (BitCastInst::use_iterator I = BCI->use_begin(), E = BCI->use_end(); 1316 I != E;) { 1317 Use &U = I.getUse(); 1318 ++I; 1319 cast<Instruction>(U.getUser())->eraseFromParent(); 1320 } 1321 BCI->eraseFromParent(); 1322 continue; 1323 } 1324 1325 if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) { 1326 // Selects in InstsToRewrite only have load uses. Rewrite each as two 1327 // loads with a new select. 1328 while (!SI->use_empty()) { 1329 LoadInst *LI = cast<LoadInst>(SI->use_back()); 1330 1331 IRBuilder<> Builder(LI); 1332 LoadInst *TrueLoad = 1333 Builder.CreateLoad(SI->getTrueValue(), LI->getName()+".t"); 1334 LoadInst *FalseLoad = 1335 Builder.CreateLoad(SI->getFalseValue(), LI->getName()+".f"); 1336 1337 // Transfer alignment and TBAA info if present. 1338 TrueLoad->setAlignment(LI->getAlignment()); 1339 FalseLoad->setAlignment(LI->getAlignment()); 1340 if (MDNode *Tag = LI->getMetadata(LLVMContext::MD_tbaa)) { 1341 TrueLoad->setMetadata(LLVMContext::MD_tbaa, Tag); 1342 FalseLoad->setMetadata(LLVMContext::MD_tbaa, Tag); 1343 } 1344 1345 Value *V = Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad); 1346 V->takeName(LI); 1347 LI->replaceAllUsesWith(V); 1348 LI->eraseFromParent(); 1349 } 1350 1351 // Now that all the loads are gone, the select is gone too. 1352 SI->eraseFromParent(); 1353 continue; 1354 } 1355 1356 // Otherwise, we have a PHI node which allows us to push the loads into the 1357 // predecessors. 1358 PHINode *PN = cast<PHINode>(InstsToRewrite[i]); 1359 if (PN->use_empty()) { 1360 PN->eraseFromParent(); 1361 continue; 1362 } 1363 1364 Type *LoadTy = cast<PointerType>(PN->getType())->getElementType(); 1365 PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(), 1366 PN->getName()+".ld", PN); 1367 1368 // Get the TBAA tag and alignment to use from one of the loads. It doesn't 1369 // matter which one we get and if any differ, it doesn't matter. 1370 LoadInst *SomeLoad = cast<LoadInst>(PN->use_back()); 1371 MDNode *TBAATag = SomeLoad->getMetadata(LLVMContext::MD_tbaa); 1372 unsigned Align = SomeLoad->getAlignment(); 1373 1374 // Rewrite all loads of the PN to use the new PHI. 1375 while (!PN->use_empty()) { 1376 LoadInst *LI = cast<LoadInst>(PN->use_back()); 1377 LI->replaceAllUsesWith(NewPN); 1378 LI->eraseFromParent(); 1379 } 1380 1381 // Inject loads into all of the pred blocks. Keep track of which blocks we 1382 // insert them into in case we have multiple edges from the same block. 1383 DenseMap<BasicBlock*, LoadInst*> InsertedLoads; 1384 1385 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1386 BasicBlock *Pred = PN->getIncomingBlock(i); 1387 LoadInst *&Load = InsertedLoads[Pred]; 1388 if (Load == 0) { 1389 Load = new LoadInst(PN->getIncomingValue(i), 1390 PN->getName() + "." + Pred->getName(), 1391 Pred->getTerminator()); 1392 Load->setAlignment(Align); 1393 if (TBAATag) Load->setMetadata(LLVMContext::MD_tbaa, TBAATag); 1394 } 1395 1396 NewPN->addIncoming(Load, Pred); 1397 } 1398 1399 PN->eraseFromParent(); 1400 } 1401 1402 ++NumAdjusted; 1403 return true; 1404 } 1405 1406 bool SROA::performPromotion(Function &F) { 1407 std::vector<AllocaInst*> Allocas; 1408 DominatorTree *DT = 0; 1409 if (HasDomTree) 1410 DT = &getAnalysis<DominatorTree>(); 1411 1412 BasicBlock &BB = F.getEntryBlock(); // Get the entry node for the function 1413 DIBuilder DIB(*F.getParent()); 1414 bool Changed = false; 1415 SmallVector<Instruction*, 64> Insts; 1416 while (1) { 1417 Allocas.clear(); 1418 1419 // Find allocas that are safe to promote, by looking at all instructions in 1420 // the entry node 1421 for (BasicBlock::iterator I = BB.begin(), E = --BB.end(); I != E; ++I) 1422 if (AllocaInst *AI = dyn_cast<AllocaInst>(I)) // Is it an alloca? 1423 if (tryToMakeAllocaBePromotable(AI, TD)) 1424 Allocas.push_back(AI); 1425 1426 if (Allocas.empty()) break; 1427 1428 if (HasDomTree) 1429 PromoteMemToReg(Allocas, *DT); 1430 else { 1431 SSAUpdater SSA; 1432 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) { 1433 AllocaInst *AI = Allocas[i]; 1434 1435 // Build list of instructions to promote. 1436 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end(); 1437 UI != E; ++UI) 1438 Insts.push_back(cast<Instruction>(*UI)); 1439 AllocaPromoter(Insts, SSA, &DIB).run(AI, Insts); 1440 Insts.clear(); 1441 } 1442 } 1443 NumPromoted += Allocas.size(); 1444 Changed = true; 1445 } 1446 1447 return Changed; 1448 } 1449 1450 1451 /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for 1452 /// SROA. It must be a struct or array type with a small number of elements. 1453 bool SROA::ShouldAttemptScalarRepl(AllocaInst *AI) { 1454 Type *T = AI->getAllocatedType(); 1455 // Do not promote any struct that has too many members. 1456 if (StructType *ST = dyn_cast<StructType>(T)) 1457 return ST->getNumElements() <= StructMemberThreshold; 1458 // Do not promote any array that has too many elements. 1459 if (ArrayType *AT = dyn_cast<ArrayType>(T)) 1460 return AT->getNumElements() <= ArrayElementThreshold; 1461 return false; 1462 } 1463 1464 // performScalarRepl - This algorithm is a simple worklist driven algorithm, 1465 // which runs on all of the alloca instructions in the function, removing them 1466 // if they are only used by getelementptr instructions. 1467 // 1468 bool SROA::performScalarRepl(Function &F) { 1469 std::vector<AllocaInst*> WorkList; 1470 1471 // Scan the entry basic block, adding allocas to the worklist. 1472 BasicBlock &BB = F.getEntryBlock(); 1473 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) 1474 if (AllocaInst *A = dyn_cast<AllocaInst>(I)) 1475 WorkList.push_back(A); 1476 1477 // Process the worklist 1478 bool Changed = false; 1479 while (!WorkList.empty()) { 1480 AllocaInst *AI = WorkList.back(); 1481 WorkList.pop_back(); 1482 1483 // Handle dead allocas trivially. These can be formed by SROA'ing arrays 1484 // with unused elements. 1485 if (AI->use_empty()) { 1486 AI->eraseFromParent(); 1487 Changed = true; 1488 continue; 1489 } 1490 1491 // If this alloca is impossible for us to promote, reject it early. 1492 if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized()) 1493 continue; 1494 1495 // Check to see if we can perform the core SROA transformation. We cannot 1496 // transform the allocation instruction if it is an array allocation 1497 // (allocations OF arrays are ok though), and an allocation of a scalar 1498 // value cannot be decomposed at all. 1499 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType()); 1500 1501 // Do not promote [0 x %struct]. 1502 if (AllocaSize == 0) continue; 1503 1504 // Do not promote any struct whose size is too big. 1505 if (AllocaSize > SRThreshold) continue; 1506 1507 // If the alloca looks like a good candidate for scalar replacement, and if 1508 // all its users can be transformed, then split up the aggregate into its 1509 // separate elements. 1510 if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) { 1511 DoScalarReplacement(AI, WorkList); 1512 Changed = true; 1513 continue; 1514 } 1515 1516 // If we can turn this aggregate value (potentially with casts) into a 1517 // simple scalar value that can be mem2reg'd into a register value. 1518 // IsNotTrivial tracks whether this is something that mem2reg could have 1519 // promoted itself. If so, we don't want to transform it needlessly. Note 1520 // that we can't just check based on the type: the alloca may be of an i32 1521 // but that has pointer arithmetic to set byte 3 of it or something. 1522 if (AllocaInst *NewAI = ConvertToScalarInfo( 1523 (unsigned)AllocaSize, *TD, ScalarLoadThreshold).TryConvert(AI)) { 1524 NewAI->takeName(AI); 1525 AI->eraseFromParent(); 1526 ++NumConverted; 1527 Changed = true; 1528 continue; 1529 } 1530 1531 // Otherwise, couldn't process this alloca. 1532 } 1533 1534 return Changed; 1535 } 1536 1537 /// DoScalarReplacement - This alloca satisfied the isSafeAllocaToScalarRepl 1538 /// predicate, do SROA now. 1539 void SROA::DoScalarReplacement(AllocaInst *AI, 1540 std::vector<AllocaInst*> &WorkList) { 1541 DEBUG(dbgs() << "Found inst to SROA: " << *AI << '\n'); 1542 SmallVector<AllocaInst*, 32> ElementAllocas; 1543 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { 1544 ElementAllocas.reserve(ST->getNumContainedTypes()); 1545 for (unsigned i = 0, e = ST->getNumContainedTypes(); i != e; ++i) { 1546 AllocaInst *NA = new AllocaInst(ST->getContainedType(i), 0, 1547 AI->getAlignment(), 1548 AI->getName() + "." + Twine(i), AI); 1549 ElementAllocas.push_back(NA); 1550 WorkList.push_back(NA); // Add to worklist for recursive processing 1551 } 1552 } else { 1553 ArrayType *AT = cast<ArrayType>(AI->getAllocatedType()); 1554 ElementAllocas.reserve(AT->getNumElements()); 1555 Type *ElTy = AT->getElementType(); 1556 for (unsigned i = 0, e = AT->getNumElements(); i != e; ++i) { 1557 AllocaInst *NA = new AllocaInst(ElTy, 0, AI->getAlignment(), 1558 AI->getName() + "." + Twine(i), AI); 1559 ElementAllocas.push_back(NA); 1560 WorkList.push_back(NA); // Add to worklist for recursive processing 1561 } 1562 } 1563 1564 // Now that we have created the new alloca instructions, rewrite all the 1565 // uses of the old alloca. 1566 RewriteForScalarRepl(AI, AI, 0, ElementAllocas); 1567 1568 // Now erase any instructions that were made dead while rewriting the alloca. 1569 DeleteDeadInstructions(); 1570 AI->eraseFromParent(); 1571 1572 ++NumReplaced; 1573 } 1574 1575 /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list, 1576 /// recursively including all their operands that become trivially dead. 1577 void SROA::DeleteDeadInstructions() { 1578 while (!DeadInsts.empty()) { 1579 Instruction *I = cast<Instruction>(DeadInsts.pop_back_val()); 1580 1581 for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI) 1582 if (Instruction *U = dyn_cast<Instruction>(*OI)) { 1583 // Zero out the operand and see if it becomes trivially dead. 1584 // (But, don't add allocas to the dead instruction list -- they are 1585 // already on the worklist and will be deleted separately.) 1586 *OI = 0; 1587 if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U)) 1588 DeadInsts.push_back(U); 1589 } 1590 1591 I->eraseFromParent(); 1592 } 1593 } 1594 1595 /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to 1596 /// performing scalar replacement of alloca AI. The results are flagged in 1597 /// the Info parameter. Offset indicates the position within AI that is 1598 /// referenced by this instruction. 1599 void SROA::isSafeForScalarRepl(Instruction *I, uint64_t Offset, 1600 AllocaInfo &Info) { 1601 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) { 1602 Instruction *User = cast<Instruction>(*UI); 1603 1604 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) { 1605 isSafeForScalarRepl(BC, Offset, Info); 1606 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { 1607 uint64_t GEPOffset = Offset; 1608 isSafeGEP(GEPI, GEPOffset, Info); 1609 if (!Info.isUnsafe) 1610 isSafeForScalarRepl(GEPI, GEPOffset, Info); 1611 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) { 1612 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength()); 1613 if (Length == 0) 1614 return MarkUnsafe(Info, User); 1615 if (Length->isNegative()) 1616 return MarkUnsafe(Info, User); 1617 1618 isSafeMemAccess(Offset, Length->getZExtValue(), 0, 1619 UI.getOperandNo() == 0, Info, MI, 1620 true /*AllowWholeAccess*/); 1621 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 1622 if (!LI->isSimple()) 1623 return MarkUnsafe(Info, User); 1624 Type *LIType = LI->getType(); 1625 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType), 1626 LIType, false, Info, LI, true /*AllowWholeAccess*/); 1627 Info.hasALoadOrStore = true; 1628 1629 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 1630 // Store is ok if storing INTO the pointer, not storing the pointer 1631 if (!SI->isSimple() || SI->getOperand(0) == I) 1632 return MarkUnsafe(Info, User); 1633 1634 Type *SIType = SI->getOperand(0)->getType(); 1635 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType), 1636 SIType, true, Info, SI, true /*AllowWholeAccess*/); 1637 Info.hasALoadOrStore = true; 1638 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) { 1639 if (II->getIntrinsicID() != Intrinsic::lifetime_start && 1640 II->getIntrinsicID() != Intrinsic::lifetime_end) 1641 return MarkUnsafe(Info, User); 1642 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) { 1643 isSafePHISelectUseForScalarRepl(User, Offset, Info); 1644 } else { 1645 return MarkUnsafe(Info, User); 1646 } 1647 if (Info.isUnsafe) return; 1648 } 1649 } 1650 1651 1652 /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer 1653 /// derived from the alloca, we can often still split the alloca into elements. 1654 /// This is useful if we have a large alloca where one element is phi'd 1655 /// together somewhere: we can SRoA and promote all the other elements even if 1656 /// we end up not being able to promote this one. 1657 /// 1658 /// All we require is that the uses of the PHI do not index into other parts of 1659 /// the alloca. The most important use case for this is single load and stores 1660 /// that are PHI'd together, which can happen due to code sinking. 1661 void SROA::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset, 1662 AllocaInfo &Info) { 1663 // If we've already checked this PHI, don't do it again. 1664 if (PHINode *PN = dyn_cast<PHINode>(I)) 1665 if (!Info.CheckedPHIs.insert(PN)) 1666 return; 1667 1668 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI) { 1669 Instruction *User = cast<Instruction>(*UI); 1670 1671 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) { 1672 isSafePHISelectUseForScalarRepl(BC, Offset, Info); 1673 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { 1674 // Only allow "bitcast" GEPs for simplicity. We could generalize this, 1675 // but would have to prove that we're staying inside of an element being 1676 // promoted. 1677 if (!GEPI->hasAllZeroIndices()) 1678 return MarkUnsafe(Info, User); 1679 isSafePHISelectUseForScalarRepl(GEPI, Offset, Info); 1680 } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 1681 if (!LI->isSimple()) 1682 return MarkUnsafe(Info, User); 1683 Type *LIType = LI->getType(); 1684 isSafeMemAccess(Offset, TD->getTypeAllocSize(LIType), 1685 LIType, false, Info, LI, false /*AllowWholeAccess*/); 1686 Info.hasALoadOrStore = true; 1687 1688 } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 1689 // Store is ok if storing INTO the pointer, not storing the pointer 1690 if (!SI->isSimple() || SI->getOperand(0) == I) 1691 return MarkUnsafe(Info, User); 1692 1693 Type *SIType = SI->getOperand(0)->getType(); 1694 isSafeMemAccess(Offset, TD->getTypeAllocSize(SIType), 1695 SIType, true, Info, SI, false /*AllowWholeAccess*/); 1696 Info.hasALoadOrStore = true; 1697 } else if (isa<PHINode>(User) || isa<SelectInst>(User)) { 1698 isSafePHISelectUseForScalarRepl(User, Offset, Info); 1699 } else { 1700 return MarkUnsafe(Info, User); 1701 } 1702 if (Info.isUnsafe) return; 1703 } 1704 } 1705 1706 /// isSafeGEP - Check if a GEP instruction can be handled for scalar 1707 /// replacement. It is safe when all the indices are constant, in-bounds 1708 /// references, and when the resulting offset corresponds to an element within 1709 /// the alloca type. The results are flagged in the Info parameter. Upon 1710 /// return, Offset is adjusted as specified by the GEP indices. 1711 void SROA::isSafeGEP(GetElementPtrInst *GEPI, 1712 uint64_t &Offset, AllocaInfo &Info) { 1713 gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI); 1714 if (GEPIt == E) 1715 return; 1716 bool NonConstant = false; 1717 unsigned NonConstantIdxSize = 0; 1718 1719 // Walk through the GEP type indices, checking the types that this indexes 1720 // into. 1721 for (; GEPIt != E; ++GEPIt) { 1722 // Ignore struct elements, no extra checking needed for these. 1723 if ((*GEPIt)->isStructTy()) 1724 continue; 1725 1726 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand()); 1727 if (!IdxVal) { 1728 // Non constant GEPs are only a problem on arrays, structs, and pointers 1729 // Vectors can be dynamically indexed. 1730 // FIXME: Add support for dynamic indexing on arrays. This should be 1731 // ok on any subarrays of the alloca array, eg, a[0][i] is ok, but a[i][0] 1732 // isn't. 1733 if (!(*GEPIt)->isVectorTy()) 1734 return MarkUnsafe(Info, GEPI); 1735 NonConstant = true; 1736 NonConstantIdxSize = TD->getTypeAllocSize(*GEPIt); 1737 } 1738 } 1739 1740 // Compute the offset due to this GEP and check if the alloca has a 1741 // component element at that offset. 1742 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end()); 1743 // If this GEP is non constant then the last operand must have been a 1744 // dynamic index into a vector. Pop this now as it has no impact on the 1745 // constant part of the offset. 1746 if (NonConstant) 1747 Indices.pop_back(); 1748 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices); 1749 if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, 1750 NonConstantIdxSize)) 1751 MarkUnsafe(Info, GEPI); 1752 } 1753 1754 /// isHomogeneousAggregate - Check if type T is a struct or array containing 1755 /// elements of the same type (which is always true for arrays). If so, 1756 /// return true with NumElts and EltTy set to the number of elements and the 1757 /// element type, respectively. 1758 static bool isHomogeneousAggregate(Type *T, unsigned &NumElts, 1759 Type *&EltTy) { 1760 if (ArrayType *AT = dyn_cast<ArrayType>(T)) { 1761 NumElts = AT->getNumElements(); 1762 EltTy = (NumElts == 0 ? 0 : AT->getElementType()); 1763 return true; 1764 } 1765 if (StructType *ST = dyn_cast<StructType>(T)) { 1766 NumElts = ST->getNumContainedTypes(); 1767 EltTy = (NumElts == 0 ? 0 : ST->getContainedType(0)); 1768 for (unsigned n = 1; n < NumElts; ++n) { 1769 if (ST->getContainedType(n) != EltTy) 1770 return false; 1771 } 1772 return true; 1773 } 1774 return false; 1775 } 1776 1777 /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are 1778 /// "homogeneous" aggregates with the same element type and number of elements. 1779 static bool isCompatibleAggregate(Type *T1, Type *T2) { 1780 if (T1 == T2) 1781 return true; 1782 1783 unsigned NumElts1, NumElts2; 1784 Type *EltTy1, *EltTy2; 1785 if (isHomogeneousAggregate(T1, NumElts1, EltTy1) && 1786 isHomogeneousAggregate(T2, NumElts2, EltTy2) && 1787 NumElts1 == NumElts2 && 1788 EltTy1 == EltTy2) 1789 return true; 1790 1791 return false; 1792 } 1793 1794 /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI 1795 /// alloca or has an offset and size that corresponds to a component element 1796 /// within it. The offset checked here may have been formed from a GEP with a 1797 /// pointer bitcasted to a different type. 1798 /// 1799 /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a 1800 /// unit. If false, it only allows accesses known to be in a single element. 1801 void SROA::isSafeMemAccess(uint64_t Offset, uint64_t MemSize, 1802 Type *MemOpType, bool isStore, 1803 AllocaInfo &Info, Instruction *TheAccess, 1804 bool AllowWholeAccess) { 1805 // Check if this is a load/store of the entire alloca. 1806 if (Offset == 0 && AllowWholeAccess && 1807 MemSize == TD->getTypeAllocSize(Info.AI->getAllocatedType())) { 1808 // This can be safe for MemIntrinsics (where MemOpType is 0) and integer 1809 // loads/stores (which are essentially the same as the MemIntrinsics with 1810 // regard to copying padding between elements). But, if an alloca is 1811 // flagged as both a source and destination of such operations, we'll need 1812 // to check later for padding between elements. 1813 if (!MemOpType || MemOpType->isIntegerTy()) { 1814 if (isStore) 1815 Info.isMemCpyDst = true; 1816 else 1817 Info.isMemCpySrc = true; 1818 return; 1819 } 1820 // This is also safe for references using a type that is compatible with 1821 // the type of the alloca, so that loads/stores can be rewritten using 1822 // insertvalue/extractvalue. 1823 if (isCompatibleAggregate(MemOpType, Info.AI->getAllocatedType())) { 1824 Info.hasSubelementAccess = true; 1825 return; 1826 } 1827 } 1828 // Check if the offset/size correspond to a component within the alloca type. 1829 Type *T = Info.AI->getAllocatedType(); 1830 if (TypeHasComponent(T, Offset, MemSize)) { 1831 Info.hasSubelementAccess = true; 1832 return; 1833 } 1834 1835 return MarkUnsafe(Info, TheAccess); 1836 } 1837 1838 /// TypeHasComponent - Return true if T has a component type with the 1839 /// specified offset and size. If Size is zero, do not check the size. 1840 bool SROA::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size) { 1841 Type *EltTy; 1842 uint64_t EltSize; 1843 if (StructType *ST = dyn_cast<StructType>(T)) { 1844 const StructLayout *Layout = TD->getStructLayout(ST); 1845 unsigned EltIdx = Layout->getElementContainingOffset(Offset); 1846 EltTy = ST->getContainedType(EltIdx); 1847 EltSize = TD->getTypeAllocSize(EltTy); 1848 Offset -= Layout->getElementOffset(EltIdx); 1849 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) { 1850 EltTy = AT->getElementType(); 1851 EltSize = TD->getTypeAllocSize(EltTy); 1852 if (Offset >= AT->getNumElements() * EltSize) 1853 return false; 1854 Offset %= EltSize; 1855 } else if (VectorType *VT = dyn_cast<VectorType>(T)) { 1856 EltTy = VT->getElementType(); 1857 EltSize = TD->getTypeAllocSize(EltTy); 1858 if (Offset >= VT->getNumElements() * EltSize) 1859 return false; 1860 Offset %= EltSize; 1861 } else { 1862 return false; 1863 } 1864 if (Offset == 0 && (Size == 0 || EltSize == Size)) 1865 return true; 1866 // Check if the component spans multiple elements. 1867 if (Offset + Size > EltSize) 1868 return false; 1869 return TypeHasComponent(EltTy, Offset, Size); 1870 } 1871 1872 /// RewriteForScalarRepl - Alloca AI is being split into NewElts, so rewrite 1873 /// the instruction I, which references it, to use the separate elements. 1874 /// Offset indicates the position within AI that is referenced by this 1875 /// instruction. 1876 void SROA::RewriteForScalarRepl(Instruction *I, AllocaInst *AI, uint64_t Offset, 1877 SmallVector<AllocaInst*, 32> &NewElts) { 1878 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E;) { 1879 Use &TheUse = UI.getUse(); 1880 Instruction *User = cast<Instruction>(*UI++); 1881 1882 if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) { 1883 RewriteBitCast(BC, AI, Offset, NewElts); 1884 continue; 1885 } 1886 1887 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { 1888 RewriteGEP(GEPI, AI, Offset, NewElts); 1889 continue; 1890 } 1891 1892 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) { 1893 ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength()); 1894 uint64_t MemSize = Length->getZExtValue(); 1895 if (Offset == 0 && 1896 MemSize == TD->getTypeAllocSize(AI->getAllocatedType())) 1897 RewriteMemIntrinUserOfAlloca(MI, I, AI, NewElts); 1898 // Otherwise the intrinsic can only touch a single element and the 1899 // address operand will be updated, so nothing else needs to be done. 1900 continue; 1901 } 1902 1903 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) { 1904 if (II->getIntrinsicID() == Intrinsic::lifetime_start || 1905 II->getIntrinsicID() == Intrinsic::lifetime_end) { 1906 RewriteLifetimeIntrinsic(II, AI, Offset, NewElts); 1907 } 1908 continue; 1909 } 1910 1911 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 1912 Type *LIType = LI->getType(); 1913 1914 if (isCompatibleAggregate(LIType, AI->getAllocatedType())) { 1915 // Replace: 1916 // %res = load { i32, i32 }* %alloc 1917 // with: 1918 // %load.0 = load i32* %alloc.0 1919 // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0, 0 1920 // %load.1 = load i32* %alloc.1 1921 // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1 1922 // (Also works for arrays instead of structs) 1923 Value *Insert = UndefValue::get(LIType); 1924 IRBuilder<> Builder(LI); 1925 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 1926 Value *Load = Builder.CreateLoad(NewElts[i], "load"); 1927 Insert = Builder.CreateInsertValue(Insert, Load, i, "insert"); 1928 } 1929 LI->replaceAllUsesWith(Insert); 1930 DeadInsts.push_back(LI); 1931 } else if (LIType->isIntegerTy() && 1932 TD->getTypeAllocSize(LIType) == 1933 TD->getTypeAllocSize(AI->getAllocatedType())) { 1934 // If this is a load of the entire alloca to an integer, rewrite it. 1935 RewriteLoadUserOfWholeAlloca(LI, AI, NewElts); 1936 } 1937 continue; 1938 } 1939 1940 if (StoreInst *SI = dyn_cast<StoreInst>(User)) { 1941 Value *Val = SI->getOperand(0); 1942 Type *SIType = Val->getType(); 1943 if (isCompatibleAggregate(SIType, AI->getAllocatedType())) { 1944 // Replace: 1945 // store { i32, i32 } %val, { i32, i32 }* %alloc 1946 // with: 1947 // %val.0 = extractvalue { i32, i32 } %val, 0 1948 // store i32 %val.0, i32* %alloc.0 1949 // %val.1 = extractvalue { i32, i32 } %val, 1 1950 // store i32 %val.1, i32* %alloc.1 1951 // (Also works for arrays instead of structs) 1952 IRBuilder<> Builder(SI); 1953 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 1954 Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName()); 1955 Builder.CreateStore(Extract, NewElts[i]); 1956 } 1957 DeadInsts.push_back(SI); 1958 } else if (SIType->isIntegerTy() && 1959 TD->getTypeAllocSize(SIType) == 1960 TD->getTypeAllocSize(AI->getAllocatedType())) { 1961 // If this is a store of the entire alloca from an integer, rewrite it. 1962 RewriteStoreUserOfWholeAlloca(SI, AI, NewElts); 1963 } 1964 continue; 1965 } 1966 1967 if (isa<SelectInst>(User) || isa<PHINode>(User)) { 1968 // If we have a PHI user of the alloca itself (as opposed to a GEP or 1969 // bitcast) we have to rewrite it. GEP and bitcast uses will be RAUW'd to 1970 // the new pointer. 1971 if (!isa<AllocaInst>(I)) continue; 1972 1973 assert(Offset == 0 && NewElts[0] && 1974 "Direct alloca use should have a zero offset"); 1975 1976 // If we have a use of the alloca, we know the derived uses will be 1977 // utilizing just the first element of the scalarized result. Insert a 1978 // bitcast of the first alloca before the user as required. 1979 AllocaInst *NewAI = NewElts[0]; 1980 BitCastInst *BCI = new BitCastInst(NewAI, AI->getType(), "", NewAI); 1981 NewAI->moveBefore(BCI); 1982 TheUse = BCI; 1983 continue; 1984 } 1985 } 1986 } 1987 1988 /// RewriteBitCast - Update a bitcast reference to the alloca being replaced 1989 /// and recursively continue updating all of its uses. 1990 void SROA::RewriteBitCast(BitCastInst *BC, AllocaInst *AI, uint64_t Offset, 1991 SmallVector<AllocaInst*, 32> &NewElts) { 1992 RewriteForScalarRepl(BC, AI, Offset, NewElts); 1993 if (BC->getOperand(0) != AI) 1994 return; 1995 1996 // The bitcast references the original alloca. Replace its uses with 1997 // references to the alloca containing offset zero (which is normally at 1998 // index zero, but might not be in cases involving structs with elements 1999 // of size zero). 2000 Type *T = AI->getAllocatedType(); 2001 uint64_t EltOffset = 0; 2002 Type *IdxTy; 2003 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy); 2004 Instruction *Val = NewElts[Idx]; 2005 if (Val->getType() != BC->getDestTy()) { 2006 Val = new BitCastInst(Val, BC->getDestTy(), "", BC); 2007 Val->takeName(BC); 2008 } 2009 BC->replaceAllUsesWith(Val); 2010 DeadInsts.push_back(BC); 2011 } 2012 2013 /// FindElementAndOffset - Return the index of the element containing Offset 2014 /// within the specified type, which must be either a struct or an array. 2015 /// Sets T to the type of the element and Offset to the offset within that 2016 /// element. IdxTy is set to the type of the index result to be used in a 2017 /// GEP instruction. 2018 uint64_t SROA::FindElementAndOffset(Type *&T, uint64_t &Offset, 2019 Type *&IdxTy) { 2020 uint64_t Idx = 0; 2021 if (StructType *ST = dyn_cast<StructType>(T)) { 2022 const StructLayout *Layout = TD->getStructLayout(ST); 2023 Idx = Layout->getElementContainingOffset(Offset); 2024 T = ST->getContainedType(Idx); 2025 Offset -= Layout->getElementOffset(Idx); 2026 IdxTy = Type::getInt32Ty(T->getContext()); 2027 return Idx; 2028 } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) { 2029 T = AT->getElementType(); 2030 uint64_t EltSize = TD->getTypeAllocSize(T); 2031 Idx = Offset / EltSize; 2032 Offset -= Idx * EltSize; 2033 IdxTy = Type::getInt64Ty(T->getContext()); 2034 return Idx; 2035 } 2036 VectorType *VT = cast<VectorType>(T); 2037 T = VT->getElementType(); 2038 uint64_t EltSize = TD->getTypeAllocSize(T); 2039 Idx = Offset / EltSize; 2040 Offset -= Idx * EltSize; 2041 IdxTy = Type::getInt64Ty(T->getContext()); 2042 return Idx; 2043 } 2044 2045 /// RewriteGEP - Check if this GEP instruction moves the pointer across 2046 /// elements of the alloca that are being split apart, and if so, rewrite 2047 /// the GEP to be relative to the new element. 2048 void SROA::RewriteGEP(GetElementPtrInst *GEPI, AllocaInst *AI, uint64_t Offset, 2049 SmallVector<AllocaInst*, 32> &NewElts) { 2050 uint64_t OldOffset = Offset; 2051 SmallVector<Value*, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end()); 2052 // If the GEP was dynamic then it must have been a dynamic vector lookup. 2053 // In this case, it must be the last GEP operand which is dynamic so keep that 2054 // aside until we've found the constant GEP offset then add it back in at the 2055 // end. 2056 Value* NonConstantIdx = 0; 2057 if (!GEPI->hasAllConstantIndices()) 2058 NonConstantIdx = Indices.pop_back_val(); 2059 Offset += TD->getIndexedOffset(GEPI->getPointerOperandType(), Indices); 2060 2061 RewriteForScalarRepl(GEPI, AI, Offset, NewElts); 2062 2063 Type *T = AI->getAllocatedType(); 2064 Type *IdxTy; 2065 uint64_t OldIdx = FindElementAndOffset(T, OldOffset, IdxTy); 2066 if (GEPI->getOperand(0) == AI) 2067 OldIdx = ~0ULL; // Force the GEP to be rewritten. 2068 2069 T = AI->getAllocatedType(); 2070 uint64_t EltOffset = Offset; 2071 uint64_t Idx = FindElementAndOffset(T, EltOffset, IdxTy); 2072 2073 // If this GEP does not move the pointer across elements of the alloca 2074 // being split, then it does not needs to be rewritten. 2075 if (Idx == OldIdx) 2076 return; 2077 2078 Type *i32Ty = Type::getInt32Ty(AI->getContext()); 2079 SmallVector<Value*, 8> NewArgs; 2080 NewArgs.push_back(Constant::getNullValue(i32Ty)); 2081 while (EltOffset != 0) { 2082 uint64_t EltIdx = FindElementAndOffset(T, EltOffset, IdxTy); 2083 NewArgs.push_back(ConstantInt::get(IdxTy, EltIdx)); 2084 } 2085 if (NonConstantIdx) { 2086 Type* GepTy = T; 2087 // This GEP has a dynamic index. We need to add "i32 0" to index through 2088 // any structs or arrays in the original type until we get to the vector 2089 // to index. 2090 while (!isa<VectorType>(GepTy)) { 2091 NewArgs.push_back(Constant::getNullValue(i32Ty)); 2092 GepTy = cast<CompositeType>(GepTy)->getTypeAtIndex(0U); 2093 } 2094 NewArgs.push_back(NonConstantIdx); 2095 } 2096 Instruction *Val = NewElts[Idx]; 2097 if (NewArgs.size() > 1) { 2098 Val = GetElementPtrInst::CreateInBounds(Val, NewArgs, "", GEPI); 2099 Val->takeName(GEPI); 2100 } 2101 if (Val->getType() != GEPI->getType()) 2102 Val = new BitCastInst(Val, GEPI->getType(), Val->getName(), GEPI); 2103 GEPI->replaceAllUsesWith(Val); 2104 DeadInsts.push_back(GEPI); 2105 } 2106 2107 /// RewriteLifetimeIntrinsic - II is a lifetime.start/lifetime.end. Rewrite it 2108 /// to mark the lifetime of the scalarized memory. 2109 void SROA::RewriteLifetimeIntrinsic(IntrinsicInst *II, AllocaInst *AI, 2110 uint64_t Offset, 2111 SmallVector<AllocaInst*, 32> &NewElts) { 2112 ConstantInt *OldSize = cast<ConstantInt>(II->getArgOperand(0)); 2113 // Put matching lifetime markers on everything from Offset up to 2114 // Offset+OldSize. 2115 Type *AIType = AI->getAllocatedType(); 2116 uint64_t NewOffset = Offset; 2117 Type *IdxTy; 2118 uint64_t Idx = FindElementAndOffset(AIType, NewOffset, IdxTy); 2119 2120 IRBuilder<> Builder(II); 2121 uint64_t Size = OldSize->getLimitedValue(); 2122 2123 if (NewOffset) { 2124 // Splice the first element and index 'NewOffset' bytes in. SROA will 2125 // split the alloca again later. 2126 Value *V = Builder.CreateBitCast(NewElts[Idx], Builder.getInt8PtrTy()); 2127 V = Builder.CreateGEP(V, Builder.getInt64(NewOffset)); 2128 2129 IdxTy = NewElts[Idx]->getAllocatedType(); 2130 uint64_t EltSize = TD->getTypeAllocSize(IdxTy) - NewOffset; 2131 if (EltSize > Size) { 2132 EltSize = Size; 2133 Size = 0; 2134 } else { 2135 Size -= EltSize; 2136 } 2137 if (II->getIntrinsicID() == Intrinsic::lifetime_start) 2138 Builder.CreateLifetimeStart(V, Builder.getInt64(EltSize)); 2139 else 2140 Builder.CreateLifetimeEnd(V, Builder.getInt64(EltSize)); 2141 ++Idx; 2142 } 2143 2144 for (; Idx != NewElts.size() && Size; ++Idx) { 2145 IdxTy = NewElts[Idx]->getAllocatedType(); 2146 uint64_t EltSize = TD->getTypeAllocSize(IdxTy); 2147 if (EltSize > Size) { 2148 EltSize = Size; 2149 Size = 0; 2150 } else { 2151 Size -= EltSize; 2152 } 2153 if (II->getIntrinsicID() == Intrinsic::lifetime_start) 2154 Builder.CreateLifetimeStart(NewElts[Idx], 2155 Builder.getInt64(EltSize)); 2156 else 2157 Builder.CreateLifetimeEnd(NewElts[Idx], 2158 Builder.getInt64(EltSize)); 2159 } 2160 DeadInsts.push_back(II); 2161 } 2162 2163 /// RewriteMemIntrinUserOfAlloca - MI is a memcpy/memset/memmove from or to AI. 2164 /// Rewrite it to copy or set the elements of the scalarized memory. 2165 void SROA::RewriteMemIntrinUserOfAlloca(MemIntrinsic *MI, Instruction *Inst, 2166 AllocaInst *AI, 2167 SmallVector<AllocaInst*, 32> &NewElts) { 2168 // If this is a memcpy/memmove, construct the other pointer as the 2169 // appropriate type. The "Other" pointer is the pointer that goes to memory 2170 // that doesn't have anything to do with the alloca that we are promoting. For 2171 // memset, this Value* stays null. 2172 Value *OtherPtr = 0; 2173 unsigned MemAlignment = MI->getAlignment(); 2174 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy 2175 if (Inst == MTI->getRawDest()) 2176 OtherPtr = MTI->getRawSource(); 2177 else { 2178 assert(Inst == MTI->getRawSource()); 2179 OtherPtr = MTI->getRawDest(); 2180 } 2181 } 2182 2183 // If there is an other pointer, we want to convert it to the same pointer 2184 // type as AI has, so we can GEP through it safely. 2185 if (OtherPtr) { 2186 unsigned AddrSpace = 2187 cast<PointerType>(OtherPtr->getType())->getAddressSpace(); 2188 2189 // Remove bitcasts and all-zero GEPs from OtherPtr. This is an 2190 // optimization, but it's also required to detect the corner case where 2191 // both pointer operands are referencing the same memory, and where 2192 // OtherPtr may be a bitcast or GEP that currently being rewritten. (This 2193 // function is only called for mem intrinsics that access the whole 2194 // aggregate, so non-zero GEPs are not an issue here.) 2195 OtherPtr = OtherPtr->stripPointerCasts(); 2196 2197 // Copying the alloca to itself is a no-op: just delete it. 2198 if (OtherPtr == AI || OtherPtr == NewElts[0]) { 2199 // This code will run twice for a no-op memcpy -- once for each operand. 2200 // Put only one reference to MI on the DeadInsts list. 2201 for (SmallVector<Value*, 32>::const_iterator I = DeadInsts.begin(), 2202 E = DeadInsts.end(); I != E; ++I) 2203 if (*I == MI) return; 2204 DeadInsts.push_back(MI); 2205 return; 2206 } 2207 2208 // If the pointer is not the right type, insert a bitcast to the right 2209 // type. 2210 Type *NewTy = 2211 PointerType::get(AI->getType()->getElementType(), AddrSpace); 2212 2213 if (OtherPtr->getType() != NewTy) 2214 OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI); 2215 } 2216 2217 // Process each element of the aggregate. 2218 bool SROADest = MI->getRawDest() == Inst; 2219 2220 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext())); 2221 2222 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 2223 // If this is a memcpy/memmove, emit a GEP of the other element address. 2224 Value *OtherElt = 0; 2225 unsigned OtherEltAlign = MemAlignment; 2226 2227 if (OtherPtr) { 2228 Value *Idx[2] = { Zero, 2229 ConstantInt::get(Type::getInt32Ty(MI->getContext()), i) }; 2230 OtherElt = GetElementPtrInst::CreateInBounds(OtherPtr, Idx, 2231 OtherPtr->getName()+"."+Twine(i), 2232 MI); 2233 uint64_t EltOffset; 2234 PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType()); 2235 Type *OtherTy = OtherPtrTy->getElementType(); 2236 if (StructType *ST = dyn_cast<StructType>(OtherTy)) { 2237 EltOffset = TD->getStructLayout(ST)->getElementOffset(i); 2238 } else { 2239 Type *EltTy = cast<SequentialType>(OtherTy)->getElementType(); 2240 EltOffset = TD->getTypeAllocSize(EltTy)*i; 2241 } 2242 2243 // The alignment of the other pointer is the guaranteed alignment of the 2244 // element, which is affected by both the known alignment of the whole 2245 // mem intrinsic and the alignment of the element. If the alignment of 2246 // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the 2247 // known alignment is just 4 bytes. 2248 OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset); 2249 } 2250 2251 Value *EltPtr = NewElts[i]; 2252 Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType(); 2253 2254 // If we got down to a scalar, insert a load or store as appropriate. 2255 if (EltTy->isSingleValueType()) { 2256 if (isa<MemTransferInst>(MI)) { 2257 if (SROADest) { 2258 // From Other to Alloca. 2259 Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI); 2260 new StoreInst(Elt, EltPtr, MI); 2261 } else { 2262 // From Alloca to Other. 2263 Value *Elt = new LoadInst(EltPtr, "tmp", MI); 2264 new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI); 2265 } 2266 continue; 2267 } 2268 assert(isa<MemSetInst>(MI)); 2269 2270 // If the stored element is zero (common case), just store a null 2271 // constant. 2272 Constant *StoreVal; 2273 if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) { 2274 if (CI->isZero()) { 2275 StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0> 2276 } else { 2277 // If EltTy is a vector type, get the element type. 2278 Type *ValTy = EltTy->getScalarType(); 2279 2280 // Construct an integer with the right value. 2281 unsigned EltSize = TD->getTypeSizeInBits(ValTy); 2282 APInt OneVal(EltSize, CI->getZExtValue()); 2283 APInt TotalVal(OneVal); 2284 // Set each byte. 2285 for (unsigned i = 0; 8*i < EltSize; ++i) { 2286 TotalVal = TotalVal.shl(8); 2287 TotalVal |= OneVal; 2288 } 2289 2290 // Convert the integer value to the appropriate type. 2291 StoreVal = ConstantInt::get(CI->getContext(), TotalVal); 2292 if (ValTy->isPointerTy()) 2293 StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy); 2294 else if (ValTy->isFloatingPointTy()) 2295 StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy); 2296 assert(StoreVal->getType() == ValTy && "Type mismatch!"); 2297 2298 // If the requested value was a vector constant, create it. 2299 if (EltTy->isVectorTy()) { 2300 unsigned NumElts = cast<VectorType>(EltTy)->getNumElements(); 2301 StoreVal = ConstantVector::getSplat(NumElts, StoreVal); 2302 } 2303 } 2304 new StoreInst(StoreVal, EltPtr, MI); 2305 continue; 2306 } 2307 // Otherwise, if we're storing a byte variable, use a memset call for 2308 // this element. 2309 } 2310 2311 unsigned EltSize = TD->getTypeAllocSize(EltTy); 2312 if (!EltSize) 2313 continue; 2314 2315 IRBuilder<> Builder(MI); 2316 2317 // Finally, insert the meminst for this element. 2318 if (isa<MemSetInst>(MI)) { 2319 Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize, 2320 MI->isVolatile()); 2321 } else { 2322 assert(isa<MemTransferInst>(MI)); 2323 Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr 2324 Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr 2325 2326 if (isa<MemCpyInst>(MI)) 2327 Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,MI->isVolatile()); 2328 else 2329 Builder.CreateMemMove(Dst, Src, EltSize,OtherEltAlign,MI->isVolatile()); 2330 } 2331 } 2332 DeadInsts.push_back(MI); 2333 } 2334 2335 /// RewriteStoreUserOfWholeAlloca - We found a store of an integer that 2336 /// overwrites the entire allocation. Extract out the pieces of the stored 2337 /// integer and store them individually. 2338 void SROA::RewriteStoreUserOfWholeAlloca(StoreInst *SI, AllocaInst *AI, 2339 SmallVector<AllocaInst*, 32> &NewElts){ 2340 // Extract each element out of the integer according to its structure offset 2341 // and store the element value to the individual alloca. 2342 Value *SrcVal = SI->getOperand(0); 2343 Type *AllocaEltTy = AI->getAllocatedType(); 2344 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy); 2345 2346 IRBuilder<> Builder(SI); 2347 2348 // Handle tail padding by extending the operand 2349 if (TD->getTypeSizeInBits(SrcVal->getType()) != AllocaSizeBits) 2350 SrcVal = Builder.CreateZExt(SrcVal, 2351 IntegerType::get(SI->getContext(), AllocaSizeBits)); 2352 2353 DEBUG(dbgs() << "PROMOTING STORE TO WHOLE ALLOCA: " << *AI << '\n' << *SI 2354 << '\n'); 2355 2356 // There are two forms here: AI could be an array or struct. Both cases 2357 // have different ways to compute the element offset. 2358 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) { 2359 const StructLayout *Layout = TD->getStructLayout(EltSTy); 2360 2361 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 2362 // Get the number of bits to shift SrcVal to get the value. 2363 Type *FieldTy = EltSTy->getElementType(i); 2364 uint64_t Shift = Layout->getElementOffsetInBits(i); 2365 2366 if (TD->isBigEndian()) 2367 Shift = AllocaSizeBits-Shift-TD->getTypeAllocSizeInBits(FieldTy); 2368 2369 Value *EltVal = SrcVal; 2370 if (Shift) { 2371 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift); 2372 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt"); 2373 } 2374 2375 // Truncate down to an integer of the right size. 2376 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy); 2377 2378 // Ignore zero sized fields like {}, they obviously contain no data. 2379 if (FieldSizeBits == 0) continue; 2380 2381 if (FieldSizeBits != AllocaSizeBits) 2382 EltVal = Builder.CreateTrunc(EltVal, 2383 IntegerType::get(SI->getContext(), FieldSizeBits)); 2384 Value *DestField = NewElts[i]; 2385 if (EltVal->getType() == FieldTy) { 2386 // Storing to an integer field of this size, just do it. 2387 } else if (FieldTy->isFloatingPointTy() || FieldTy->isVectorTy()) { 2388 // Bitcast to the right element type (for fp/vector values). 2389 EltVal = Builder.CreateBitCast(EltVal, FieldTy); 2390 } else { 2391 // Otherwise, bitcast the dest pointer (for aggregates). 2392 DestField = Builder.CreateBitCast(DestField, 2393 PointerType::getUnqual(EltVal->getType())); 2394 } 2395 new StoreInst(EltVal, DestField, SI); 2396 } 2397 2398 } else { 2399 ArrayType *ATy = cast<ArrayType>(AllocaEltTy); 2400 Type *ArrayEltTy = ATy->getElementType(); 2401 uint64_t ElementOffset = TD->getTypeAllocSizeInBits(ArrayEltTy); 2402 uint64_t ElementSizeBits = TD->getTypeSizeInBits(ArrayEltTy); 2403 2404 uint64_t Shift; 2405 2406 if (TD->isBigEndian()) 2407 Shift = AllocaSizeBits-ElementOffset; 2408 else 2409 Shift = 0; 2410 2411 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 2412 // Ignore zero sized fields like {}, they obviously contain no data. 2413 if (ElementSizeBits == 0) continue; 2414 2415 Value *EltVal = SrcVal; 2416 if (Shift) { 2417 Value *ShiftVal = ConstantInt::get(EltVal->getType(), Shift); 2418 EltVal = Builder.CreateLShr(EltVal, ShiftVal, "sroa.store.elt"); 2419 } 2420 2421 // Truncate down to an integer of the right size. 2422 if (ElementSizeBits != AllocaSizeBits) 2423 EltVal = Builder.CreateTrunc(EltVal, 2424 IntegerType::get(SI->getContext(), 2425 ElementSizeBits)); 2426 Value *DestField = NewElts[i]; 2427 if (EltVal->getType() == ArrayEltTy) { 2428 // Storing to an integer field of this size, just do it. 2429 } else if (ArrayEltTy->isFloatingPointTy() || 2430 ArrayEltTy->isVectorTy()) { 2431 // Bitcast to the right element type (for fp/vector values). 2432 EltVal = Builder.CreateBitCast(EltVal, ArrayEltTy); 2433 } else { 2434 // Otherwise, bitcast the dest pointer (for aggregates). 2435 DestField = Builder.CreateBitCast(DestField, 2436 PointerType::getUnqual(EltVal->getType())); 2437 } 2438 new StoreInst(EltVal, DestField, SI); 2439 2440 if (TD->isBigEndian()) 2441 Shift -= ElementOffset; 2442 else 2443 Shift += ElementOffset; 2444 } 2445 } 2446 2447 DeadInsts.push_back(SI); 2448 } 2449 2450 /// RewriteLoadUserOfWholeAlloca - We found a load of the entire allocation to 2451 /// an integer. Load the individual pieces to form the aggregate value. 2452 void SROA::RewriteLoadUserOfWholeAlloca(LoadInst *LI, AllocaInst *AI, 2453 SmallVector<AllocaInst*, 32> &NewElts) { 2454 // Extract each element out of the NewElts according to its structure offset 2455 // and form the result value. 2456 Type *AllocaEltTy = AI->getAllocatedType(); 2457 uint64_t AllocaSizeBits = TD->getTypeAllocSizeInBits(AllocaEltTy); 2458 2459 DEBUG(dbgs() << "PROMOTING LOAD OF WHOLE ALLOCA: " << *AI << '\n' << *LI 2460 << '\n'); 2461 2462 // There are two forms here: AI could be an array or struct. Both cases 2463 // have different ways to compute the element offset. 2464 const StructLayout *Layout = 0; 2465 uint64_t ArrayEltBitOffset = 0; 2466 if (StructType *EltSTy = dyn_cast<StructType>(AllocaEltTy)) { 2467 Layout = TD->getStructLayout(EltSTy); 2468 } else { 2469 Type *ArrayEltTy = cast<ArrayType>(AllocaEltTy)->getElementType(); 2470 ArrayEltBitOffset = TD->getTypeAllocSizeInBits(ArrayEltTy); 2471 } 2472 2473 Value *ResultVal = 2474 Constant::getNullValue(IntegerType::get(LI->getContext(), AllocaSizeBits)); 2475 2476 for (unsigned i = 0, e = NewElts.size(); i != e; ++i) { 2477 // Load the value from the alloca. If the NewElt is an aggregate, cast 2478 // the pointer to an integer of the same size before doing the load. 2479 Value *SrcField = NewElts[i]; 2480 Type *FieldTy = 2481 cast<PointerType>(SrcField->getType())->getElementType(); 2482 uint64_t FieldSizeBits = TD->getTypeSizeInBits(FieldTy); 2483 2484 // Ignore zero sized fields like {}, they obviously contain no data. 2485 if (FieldSizeBits == 0) continue; 2486 2487 IntegerType *FieldIntTy = IntegerType::get(LI->getContext(), 2488 FieldSizeBits); 2489 if (!FieldTy->isIntegerTy() && !FieldTy->isFloatingPointTy() && 2490 !FieldTy->isVectorTy()) 2491 SrcField = new BitCastInst(SrcField, 2492 PointerType::getUnqual(FieldIntTy), 2493 "", LI); 2494 SrcField = new LoadInst(SrcField, "sroa.load.elt", LI); 2495 2496 // If SrcField is a fp or vector of the right size but that isn't an 2497 // integer type, bitcast to an integer so we can shift it. 2498 if (SrcField->getType() != FieldIntTy) 2499 SrcField = new BitCastInst(SrcField, FieldIntTy, "", LI); 2500 2501 // Zero extend the field to be the same size as the final alloca so that 2502 // we can shift and insert it. 2503 if (SrcField->getType() != ResultVal->getType()) 2504 SrcField = new ZExtInst(SrcField, ResultVal->getType(), "", LI); 2505 2506 // Determine the number of bits to shift SrcField. 2507 uint64_t Shift; 2508 if (Layout) // Struct case. 2509 Shift = Layout->getElementOffsetInBits(i); 2510 else // Array case. 2511 Shift = i*ArrayEltBitOffset; 2512 2513 if (TD->isBigEndian()) 2514 Shift = AllocaSizeBits-Shift-FieldIntTy->getBitWidth(); 2515 2516 if (Shift) { 2517 Value *ShiftVal = ConstantInt::get(SrcField->getType(), Shift); 2518 SrcField = BinaryOperator::CreateShl(SrcField, ShiftVal, "", LI); 2519 } 2520 2521 // Don't create an 'or x, 0' on the first iteration. 2522 if (!isa<Constant>(ResultVal) || 2523 !cast<Constant>(ResultVal)->isNullValue()) 2524 ResultVal = BinaryOperator::CreateOr(SrcField, ResultVal, "", LI); 2525 else 2526 ResultVal = SrcField; 2527 } 2528 2529 // Handle tail padding by truncating the result 2530 if (TD->getTypeSizeInBits(LI->getType()) != AllocaSizeBits) 2531 ResultVal = new TruncInst(ResultVal, LI->getType(), "", LI); 2532 2533 LI->replaceAllUsesWith(ResultVal); 2534 DeadInsts.push_back(LI); 2535 } 2536 2537 /// HasPadding - Return true if the specified type has any structure or 2538 /// alignment padding in between the elements that would be split apart 2539 /// by SROA; return false otherwise. 2540 static bool HasPadding(Type *Ty, const TargetData &TD) { 2541 if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) { 2542 Ty = ATy->getElementType(); 2543 return TD.getTypeSizeInBits(Ty) != TD.getTypeAllocSizeInBits(Ty); 2544 } 2545 2546 // SROA currently handles only Arrays and Structs. 2547 StructType *STy = cast<StructType>(Ty); 2548 const StructLayout *SL = TD.getStructLayout(STy); 2549 unsigned PrevFieldBitOffset = 0; 2550 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 2551 unsigned FieldBitOffset = SL->getElementOffsetInBits(i); 2552 2553 // Check to see if there is any padding between this element and the 2554 // previous one. 2555 if (i) { 2556 unsigned PrevFieldEnd = 2557 PrevFieldBitOffset+TD.getTypeSizeInBits(STy->getElementType(i-1)); 2558 if (PrevFieldEnd < FieldBitOffset) 2559 return true; 2560 } 2561 PrevFieldBitOffset = FieldBitOffset; 2562 } 2563 // Check for tail padding. 2564 if (unsigned EltCount = STy->getNumElements()) { 2565 unsigned PrevFieldEnd = PrevFieldBitOffset + 2566 TD.getTypeSizeInBits(STy->getElementType(EltCount-1)); 2567 if (PrevFieldEnd < SL->getSizeInBits()) 2568 return true; 2569 } 2570 return false; 2571 } 2572 2573 /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of 2574 /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe, 2575 /// or 1 if safe after canonicalization has been performed. 2576 bool SROA::isSafeAllocaToScalarRepl(AllocaInst *AI) { 2577 // Loop over the use list of the alloca. We can only transform it if all of 2578 // the users are safe to transform. 2579 AllocaInfo Info(AI); 2580 2581 isSafeForScalarRepl(AI, 0, Info); 2582 if (Info.isUnsafe) { 2583 DEBUG(dbgs() << "Cannot transform: " << *AI << '\n'); 2584 return false; 2585 } 2586 2587 // Okay, we know all the users are promotable. If the aggregate is a memcpy 2588 // source and destination, we have to be careful. In particular, the memcpy 2589 // could be moving around elements that live in structure padding of the LLVM 2590 // types, but may actually be used. In these cases, we refuse to promote the 2591 // struct. 2592 if (Info.isMemCpySrc && Info.isMemCpyDst && 2593 HasPadding(AI->getAllocatedType(), *TD)) 2594 return false; 2595 2596 // If the alloca never has an access to just *part* of it, but is accessed 2597 // via loads and stores, then we should use ConvertToScalarInfo to promote 2598 // the alloca instead of promoting each piece at a time and inserting fission 2599 // and fusion code. 2600 if (!Info.hasSubelementAccess && Info.hasALoadOrStore) { 2601 // If the struct/array just has one element, use basic SRoA. 2602 if (StructType *ST = dyn_cast<StructType>(AI->getAllocatedType())) { 2603 if (ST->getNumElements() > 1) return false; 2604 } else { 2605 if (cast<ArrayType>(AI->getAllocatedType())->getNumElements() > 1) 2606 return false; 2607 } 2608 } 2609 2610 return true; 2611 } 2612