1 //===- InstCombineLoadStoreAlloca.cpp -------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visit functions for load, store and alloca. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/MapVector.h" 15 #include "llvm/ADT/SmallString.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/Analysis/Loads.h" 19 #include "llvm/IR/ConstantRange.h" 20 #include "llvm/IR/DataLayout.h" 21 #include "llvm/IR/DebugInfoMetadata.h" 22 #include "llvm/IR/IntrinsicInst.h" 23 #include "llvm/IR/LLVMContext.h" 24 #include "llvm/IR/MDBuilder.h" 25 #include "llvm/IR/PatternMatch.h" 26 #include "llvm/Transforms/InstCombine/InstCombiner.h" 27 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 28 #include "llvm/Transforms/Utils/Local.h" 29 using namespace llvm; 30 using namespace PatternMatch; 31 32 #define DEBUG_TYPE "instcombine" 33 34 STATISTIC(NumDeadStore, "Number of dead stores eliminated"); 35 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global"); 36 37 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived) 38 /// pointer to an alloca. Ignore any reads of the pointer, return false if we 39 /// see any stores or other unknown uses. If we see pointer arithmetic, keep 40 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse 41 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to 42 /// the alloca, and if the source pointer is a pointer to a constant global, we 43 /// can optimize this. 44 static bool 45 isOnlyCopiedFromConstantMemory(AAResults *AA, 46 Value *V, MemTransferInst *&TheCopy, 47 SmallVectorImpl<Instruction *> &ToDelete) { 48 // We track lifetime intrinsics as we encounter them. If we decide to go 49 // ahead and replace the value with the global, this lets the caller quickly 50 // eliminate the markers. 51 52 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect; 53 ValuesToInspect.emplace_back(V, false); 54 while (!ValuesToInspect.empty()) { 55 auto ValuePair = ValuesToInspect.pop_back_val(); 56 const bool IsOffset = ValuePair.second; 57 for (auto &U : ValuePair.first->uses()) { 58 auto *I = cast<Instruction>(U.getUser()); 59 60 if (auto *LI = dyn_cast<LoadInst>(I)) { 61 // Ignore non-volatile loads, they are always ok. 62 if (!LI->isSimple()) return false; 63 continue; 64 } 65 66 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) { 67 // If uses of the bitcast are ok, we are ok. 68 ValuesToInspect.emplace_back(I, IsOffset); 69 continue; 70 } 71 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 72 // If the GEP has all zero indices, it doesn't offset the pointer. If it 73 // doesn't, it does. 74 ValuesToInspect.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices()); 75 continue; 76 } 77 78 if (auto *Call = dyn_cast<CallBase>(I)) { 79 // If this is the function being called then we treat it like a load and 80 // ignore it. 81 if (Call->isCallee(&U)) 82 continue; 83 84 unsigned DataOpNo = Call->getDataOperandNo(&U); 85 bool IsArgOperand = Call->isArgOperand(&U); 86 87 // Inalloca arguments are clobbered by the call. 88 if (IsArgOperand && Call->isInAllocaArgument(DataOpNo)) 89 return false; 90 91 // If this is a readonly/readnone call site, then we know it is just a 92 // load (but one that potentially returns the value itself), so we can 93 // ignore it if we know that the value isn't captured. 94 if (Call->onlyReadsMemory() && 95 (Call->use_empty() || Call->doesNotCapture(DataOpNo))) 96 continue; 97 98 // If this is being passed as a byval argument, the caller is making a 99 // copy, so it is only a read of the alloca. 100 if (IsArgOperand && Call->isByValArgument(DataOpNo)) 101 continue; 102 } 103 104 // Lifetime intrinsics can be handled by the caller. 105 if (I->isLifetimeStartOrEnd()) { 106 assert(I->use_empty() && "Lifetime markers have no result to use!"); 107 ToDelete.push_back(I); 108 continue; 109 } 110 111 // If this is isn't our memcpy/memmove, reject it as something we can't 112 // handle. 113 MemTransferInst *MI = dyn_cast<MemTransferInst>(I); 114 if (!MI) 115 return false; 116 117 // If the transfer is using the alloca as a source of the transfer, then 118 // ignore it since it is a load (unless the transfer is volatile). 119 if (U.getOperandNo() == 1) { 120 if (MI->isVolatile()) return false; 121 continue; 122 } 123 124 // If we already have seen a copy, reject the second one. 125 if (TheCopy) return false; 126 127 // If the pointer has been offset from the start of the alloca, we can't 128 // safely handle this. 129 if (IsOffset) return false; 130 131 // If the memintrinsic isn't using the alloca as the dest, reject it. 132 if (U.getOperandNo() != 0) return false; 133 134 // If the source of the memcpy/move is not a constant global, reject it. 135 if (!AA->pointsToConstantMemory(MI->getSource())) 136 return false; 137 138 // Otherwise, the transform is safe. Remember the copy instruction. 139 TheCopy = MI; 140 } 141 } 142 return true; 143 } 144 145 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only 146 /// modified by a copy from a constant global. If we can prove this, we can 147 /// replace any uses of the alloca with uses of the global directly. 148 static MemTransferInst * 149 isOnlyCopiedFromConstantMemory(AAResults *AA, 150 AllocaInst *AI, 151 SmallVectorImpl<Instruction *> &ToDelete) { 152 MemTransferInst *TheCopy = nullptr; 153 if (isOnlyCopiedFromConstantMemory(AA, AI, TheCopy, ToDelete)) 154 return TheCopy; 155 return nullptr; 156 } 157 158 /// Returns true if V is dereferenceable for size of alloca. 159 static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI, 160 const DataLayout &DL) { 161 if (AI->isArrayAllocation()) 162 return false; 163 uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType()); 164 if (!AllocaSize) 165 return false; 166 return isDereferenceableAndAlignedPointer(V, Align(AI->getAlignment()), 167 APInt(64, AllocaSize), DL); 168 } 169 170 static Instruction *simplifyAllocaArraySize(InstCombinerImpl &IC, 171 AllocaInst &AI) { 172 // Check for array size of 1 (scalar allocation). 173 if (!AI.isArrayAllocation()) { 174 // i32 1 is the canonical array size for scalar allocations. 175 if (AI.getArraySize()->getType()->isIntegerTy(32)) 176 return nullptr; 177 178 // Canonicalize it. 179 return IC.replaceOperand(AI, 0, IC.Builder.getInt32(1)); 180 } 181 182 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1 183 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) { 184 if (C->getValue().getActiveBits() <= 64) { 185 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue()); 186 AllocaInst *New = IC.Builder.CreateAlloca(NewTy, nullptr, AI.getName()); 187 New->setAlignment(AI.getAlign()); 188 189 // Scan to the end of the allocation instructions, to skip over a block of 190 // allocas if possible...also skip interleaved debug info 191 // 192 BasicBlock::iterator It(New); 193 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) 194 ++It; 195 196 // Now that I is pointing to the first non-allocation-inst in the block, 197 // insert our getelementptr instruction... 198 // 199 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType()); 200 Value *NullIdx = Constant::getNullValue(IdxTy); 201 Value *Idx[2] = {NullIdx, NullIdx}; 202 Instruction *GEP = GetElementPtrInst::CreateInBounds( 203 NewTy, New, Idx, New->getName() + ".sub"); 204 IC.InsertNewInstBefore(GEP, *It); 205 206 // Now make everything use the getelementptr instead of the original 207 // allocation. 208 return IC.replaceInstUsesWith(AI, GEP); 209 } 210 } 211 212 if (isa<UndefValue>(AI.getArraySize())) 213 return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType())); 214 215 // Ensure that the alloca array size argument has type intptr_t, so that 216 // any casting is exposed early. 217 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType()); 218 if (AI.getArraySize()->getType() != IntPtrTy) { 219 Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), IntPtrTy, false); 220 return IC.replaceOperand(AI, 0, V); 221 } 222 223 return nullptr; 224 } 225 226 namespace { 227 // If I and V are pointers in different address space, it is not allowed to 228 // use replaceAllUsesWith since I and V have different types. A 229 // non-target-specific transformation should not use addrspacecast on V since 230 // the two address space may be disjoint depending on target. 231 // 232 // This class chases down uses of the old pointer until reaching the load 233 // instructions, then replaces the old pointer in the load instructions with 234 // the new pointer. If during the chasing it sees bitcast or GEP, it will 235 // create new bitcast or GEP with the new pointer and use them in the load 236 // instruction. 237 class PointerReplacer { 238 public: 239 PointerReplacer(InstCombinerImpl &IC) : IC(IC) {} 240 241 bool collectUsers(Instruction &I); 242 void replacePointer(Instruction &I, Value *V); 243 244 private: 245 void replace(Instruction *I); 246 Value *getReplacement(Value *I); 247 248 SmallSetVector<Instruction *, 4> Worklist; 249 MapVector<Value *, Value *> WorkMap; 250 InstCombinerImpl &IC; 251 }; 252 } // end anonymous namespace 253 254 bool PointerReplacer::collectUsers(Instruction &I) { 255 for (auto U : I.users()) { 256 Instruction *Inst = cast<Instruction>(&*U); 257 if (LoadInst *Load = dyn_cast<LoadInst>(Inst)) { 258 if (Load->isVolatile()) 259 return false; 260 Worklist.insert(Load); 261 } else if (isa<GetElementPtrInst>(Inst) || isa<BitCastInst>(Inst)) { 262 Worklist.insert(Inst); 263 if (!collectUsers(*Inst)) 264 return false; 265 } else if (isa<MemTransferInst>(Inst)) { 266 Worklist.insert(Inst); 267 } else { 268 LLVM_DEBUG(dbgs() << "Cannot handle pointer user: " << *U << '\n'); 269 return false; 270 } 271 } 272 273 return true; 274 } 275 276 Value *PointerReplacer::getReplacement(Value *V) { 277 auto Loc = WorkMap.find(V); 278 if (Loc != WorkMap.end()) 279 return Loc->second; 280 return nullptr; 281 } 282 283 void PointerReplacer::replace(Instruction *I) { 284 if (getReplacement(I)) 285 return; 286 287 if (auto *LT = dyn_cast<LoadInst>(I)) { 288 auto *V = getReplacement(LT->getPointerOperand()); 289 assert(V && "Operand not replaced"); 290 auto *NewI = new LoadInst(LT->getType(), V, "", LT->isVolatile(), 291 LT->getAlign(), LT->getOrdering(), 292 LT->getSyncScopeID()); 293 NewI->takeName(LT); 294 copyMetadataForLoad(*NewI, *LT); 295 296 IC.InsertNewInstWith(NewI, *LT); 297 IC.replaceInstUsesWith(*LT, NewI); 298 WorkMap[LT] = NewI; 299 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 300 auto *V = getReplacement(GEP->getPointerOperand()); 301 assert(V && "Operand not replaced"); 302 SmallVector<Value *, 8> Indices; 303 Indices.append(GEP->idx_begin(), GEP->idx_end()); 304 auto *NewI = GetElementPtrInst::Create( 305 V->getType()->getPointerElementType(), V, Indices); 306 IC.InsertNewInstWith(NewI, *GEP); 307 NewI->takeName(GEP); 308 WorkMap[GEP] = NewI; 309 } else if (auto *BC = dyn_cast<BitCastInst>(I)) { 310 auto *V = getReplacement(BC->getOperand(0)); 311 assert(V && "Operand not replaced"); 312 auto *NewT = PointerType::get(BC->getType()->getPointerElementType(), 313 V->getType()->getPointerAddressSpace()); 314 auto *NewI = new BitCastInst(V, NewT); 315 IC.InsertNewInstWith(NewI, *BC); 316 NewI->takeName(BC); 317 WorkMap[BC] = NewI; 318 } else if (auto *MemCpy = dyn_cast<MemTransferInst>(I)) { 319 auto *SrcV = getReplacement(MemCpy->getRawSource()); 320 // The pointer may appear in the destination of a copy, but we don't want to 321 // replace it. 322 if (!SrcV) { 323 assert(getReplacement(MemCpy->getRawDest()) && 324 "destination not in replace list"); 325 return; 326 } 327 328 IC.Builder.SetInsertPoint(MemCpy); 329 auto *NewI = IC.Builder.CreateMemTransferInst( 330 MemCpy->getIntrinsicID(), MemCpy->getRawDest(), MemCpy->getDestAlign(), 331 SrcV, MemCpy->getSourceAlign(), MemCpy->getLength(), 332 MemCpy->isVolatile()); 333 AAMDNodes AAMD; 334 MemCpy->getAAMetadata(AAMD); 335 if (AAMD) 336 NewI->setAAMetadata(AAMD); 337 338 IC.eraseInstFromFunction(*MemCpy); 339 WorkMap[MemCpy] = NewI; 340 } else { 341 llvm_unreachable("should never reach here"); 342 } 343 } 344 345 void PointerReplacer::replacePointer(Instruction &I, Value *V) { 346 #ifndef NDEBUG 347 auto *PT = cast<PointerType>(I.getType()); 348 auto *NT = cast<PointerType>(V->getType()); 349 assert(PT != NT && PT->getElementType() == NT->getElementType() && 350 "Invalid usage"); 351 #endif 352 WorkMap[&I] = V; 353 354 for (Instruction *Workitem : Worklist) 355 replace(Workitem); 356 } 357 358 Instruction *InstCombinerImpl::visitAllocaInst(AllocaInst &AI) { 359 if (auto *I = simplifyAllocaArraySize(*this, AI)) 360 return I; 361 362 if (AI.getAllocatedType()->isSized()) { 363 // Move all alloca's of zero byte objects to the entry block and merge them 364 // together. Note that we only do this for alloca's, because malloc should 365 // allocate and return a unique pointer, even for a zero byte allocation. 366 if (DL.getTypeAllocSize(AI.getAllocatedType()).getKnownMinSize() == 0) { 367 // For a zero sized alloca there is no point in doing an array allocation. 368 // This is helpful if the array size is a complicated expression not used 369 // elsewhere. 370 if (AI.isArrayAllocation()) 371 return replaceOperand(AI, 0, 372 ConstantInt::get(AI.getArraySize()->getType(), 1)); 373 374 // Get the first instruction in the entry block. 375 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock(); 376 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg(); 377 if (FirstInst != &AI) { 378 // If the entry block doesn't start with a zero-size alloca then move 379 // this one to the start of the entry block. There is no problem with 380 // dominance as the array size was forced to a constant earlier already. 381 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst); 382 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() || 383 DL.getTypeAllocSize(EntryAI->getAllocatedType()) 384 .getKnownMinSize() != 0) { 385 AI.moveBefore(FirstInst); 386 return &AI; 387 } 388 389 // Replace this zero-sized alloca with the one at the start of the entry 390 // block after ensuring that the address will be aligned enough for both 391 // types. 392 const Align MaxAlign = std::max(EntryAI->getAlign(), AI.getAlign()); 393 EntryAI->setAlignment(MaxAlign); 394 if (AI.getType() != EntryAI->getType()) 395 return new BitCastInst(EntryAI, AI.getType()); 396 return replaceInstUsesWith(AI, EntryAI); 397 } 398 } 399 } 400 401 // Check to see if this allocation is only modified by a memcpy/memmove from 402 // a constant whose alignment is equal to or exceeds that of the allocation. 403 // If this is the case, we can change all users to use the constant global 404 // instead. This is commonly produced by the CFE by constructs like "void 405 // foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A' is only subsequently 406 // read. 407 SmallVector<Instruction *, 4> ToDelete; 408 if (MemTransferInst *Copy = isOnlyCopiedFromConstantMemory(AA, &AI, ToDelete)) { 409 Value *TheSrc = Copy->getSource(); 410 Align AllocaAlign = AI.getAlign(); 411 Align SourceAlign = getOrEnforceKnownAlignment( 412 TheSrc, AllocaAlign, DL, &AI, &AC, &DT); 413 if (AllocaAlign <= SourceAlign && 414 isDereferenceableForAllocaSize(TheSrc, &AI, DL)) { 415 LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n'); 416 LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n'); 417 unsigned SrcAddrSpace = TheSrc->getType()->getPointerAddressSpace(); 418 auto *DestTy = PointerType::get(AI.getAllocatedType(), SrcAddrSpace); 419 if (AI.getType()->getAddressSpace() == SrcAddrSpace) { 420 for (Instruction *Delete : ToDelete) 421 eraseInstFromFunction(*Delete); 422 423 Value *Cast = Builder.CreateBitCast(TheSrc, DestTy); 424 Instruction *NewI = replaceInstUsesWith(AI, Cast); 425 eraseInstFromFunction(*Copy); 426 ++NumGlobalCopies; 427 return NewI; 428 } 429 430 PointerReplacer PtrReplacer(*this); 431 if (PtrReplacer.collectUsers(AI)) { 432 for (Instruction *Delete : ToDelete) 433 eraseInstFromFunction(*Delete); 434 435 Value *Cast = Builder.CreateBitCast(TheSrc, DestTy); 436 PtrReplacer.replacePointer(AI, Cast); 437 ++NumGlobalCopies; 438 } 439 } 440 } 441 442 // At last, use the generic allocation site handler to aggressively remove 443 // unused allocas. 444 return visitAllocSite(AI); 445 } 446 447 // Are we allowed to form a atomic load or store of this type? 448 static bool isSupportedAtomicType(Type *Ty) { 449 return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy(); 450 } 451 452 /// Helper to combine a load to a new type. 453 /// 454 /// This just does the work of combining a load to a new type. It handles 455 /// metadata, etc., and returns the new instruction. The \c NewTy should be the 456 /// loaded *value* type. This will convert it to a pointer, cast the operand to 457 /// that pointer type, load it, etc. 458 /// 459 /// Note that this will create all of the instructions with whatever insert 460 /// point the \c InstCombinerImpl currently is using. 461 LoadInst *InstCombinerImpl::combineLoadToNewType(LoadInst &LI, Type *NewTy, 462 const Twine &Suffix) { 463 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) && 464 "can't fold an atomic load to requested type"); 465 466 Value *Ptr = LI.getPointerOperand(); 467 unsigned AS = LI.getPointerAddressSpace(); 468 Value *NewPtr = nullptr; 469 if (!(match(Ptr, m_BitCast(m_Value(NewPtr))) && 470 NewPtr->getType()->getPointerElementType() == NewTy && 471 NewPtr->getType()->getPointerAddressSpace() == AS)) 472 NewPtr = Builder.CreateBitCast(Ptr, NewTy->getPointerTo(AS)); 473 474 LoadInst *NewLoad = Builder.CreateAlignedLoad( 475 NewTy, NewPtr, LI.getAlign(), LI.isVolatile(), LI.getName() + Suffix); 476 NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 477 copyMetadataForLoad(*NewLoad, LI); 478 return NewLoad; 479 } 480 481 /// Combine a store to a new type. 482 /// 483 /// Returns the newly created store instruction. 484 static StoreInst *combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI, 485 Value *V) { 486 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) && 487 "can't fold an atomic store of requested type"); 488 489 Value *Ptr = SI.getPointerOperand(); 490 unsigned AS = SI.getPointerAddressSpace(); 491 SmallVector<std::pair<unsigned, MDNode *>, 8> MD; 492 SI.getAllMetadata(MD); 493 494 StoreInst *NewStore = IC.Builder.CreateAlignedStore( 495 V, IC.Builder.CreateBitCast(Ptr, V->getType()->getPointerTo(AS)), 496 SI.getAlign(), SI.isVolatile()); 497 NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID()); 498 for (const auto &MDPair : MD) { 499 unsigned ID = MDPair.first; 500 MDNode *N = MDPair.second; 501 // Note, essentially every kind of metadata should be preserved here! This 502 // routine is supposed to clone a store instruction changing *only its 503 // type*. The only metadata it makes sense to drop is metadata which is 504 // invalidated when the pointer type changes. This should essentially 505 // never be the case in LLVM, but we explicitly switch over only known 506 // metadata to be conservatively correct. If you are adding metadata to 507 // LLVM which pertains to stores, you almost certainly want to add it 508 // here. 509 switch (ID) { 510 case LLVMContext::MD_dbg: 511 case LLVMContext::MD_tbaa: 512 case LLVMContext::MD_prof: 513 case LLVMContext::MD_fpmath: 514 case LLVMContext::MD_tbaa_struct: 515 case LLVMContext::MD_alias_scope: 516 case LLVMContext::MD_noalias: 517 case LLVMContext::MD_nontemporal: 518 case LLVMContext::MD_mem_parallel_loop_access: 519 case LLVMContext::MD_access_group: 520 // All of these directly apply. 521 NewStore->setMetadata(ID, N); 522 break; 523 case LLVMContext::MD_invariant_load: 524 case LLVMContext::MD_nonnull: 525 case LLVMContext::MD_noundef: 526 case LLVMContext::MD_range: 527 case LLVMContext::MD_align: 528 case LLVMContext::MD_dereferenceable: 529 case LLVMContext::MD_dereferenceable_or_null: 530 // These don't apply for stores. 531 break; 532 } 533 } 534 535 return NewStore; 536 } 537 538 /// Returns true if instruction represent minmax pattern like: 539 /// select ((cmp load V1, load V2), V1, V2). 540 static bool isMinMaxWithLoads(Value *V, Type *&LoadTy) { 541 assert(V->getType()->isPointerTy() && "Expected pointer type."); 542 // Ignore possible ty* to ixx* bitcast. 543 V = InstCombiner::peekThroughBitcast(V); 544 // Check that select is select ((cmp load V1, load V2), V1, V2) - minmax 545 // pattern. 546 CmpInst::Predicate Pred; 547 Instruction *L1; 548 Instruction *L2; 549 Value *LHS; 550 Value *RHS; 551 if (!match(V, m_Select(m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2)), 552 m_Value(LHS), m_Value(RHS)))) 553 return false; 554 LoadTy = L1->getType(); 555 return (match(L1, m_Load(m_Specific(LHS))) && 556 match(L2, m_Load(m_Specific(RHS)))) || 557 (match(L1, m_Load(m_Specific(RHS))) && 558 match(L2, m_Load(m_Specific(LHS)))); 559 } 560 561 /// Combine loads to match the type of their uses' value after looking 562 /// through intervening bitcasts. 563 /// 564 /// The core idea here is that if the result of a load is used in an operation, 565 /// we should load the type most conducive to that operation. For example, when 566 /// loading an integer and converting that immediately to a pointer, we should 567 /// instead directly load a pointer. 568 /// 569 /// However, this routine must never change the width of a load or the number of 570 /// loads as that would introduce a semantic change. This combine is expected to 571 /// be a semantic no-op which just allows loads to more closely model the types 572 /// of their consuming operations. 573 /// 574 /// Currently, we also refuse to change the precise type used for an atomic load 575 /// or a volatile load. This is debatable, and might be reasonable to change 576 /// later. However, it is risky in case some backend or other part of LLVM is 577 /// relying on the exact type loaded to select appropriate atomic operations. 578 static Instruction *combineLoadToOperationType(InstCombinerImpl &IC, 579 LoadInst &LI) { 580 // FIXME: We could probably with some care handle both volatile and ordered 581 // atomic loads here but it isn't clear that this is important. 582 if (!LI.isUnordered()) 583 return nullptr; 584 585 if (LI.use_empty()) 586 return nullptr; 587 588 // swifterror values can't be bitcasted. 589 if (LI.getPointerOperand()->isSwiftError()) 590 return nullptr; 591 592 const DataLayout &DL = IC.getDataLayout(); 593 594 // Fold away bit casts of the loaded value by loading the desired type. 595 // Note that we should not do this for pointer<->integer casts, 596 // because that would result in type punning. 597 if (LI.hasOneUse()) 598 if (auto* CI = dyn_cast<CastInst>(LI.user_back())) 599 if (CI->isNoopCast(DL) && LI.getType()->isPtrOrPtrVectorTy() == 600 CI->getDestTy()->isPtrOrPtrVectorTy()) 601 if (!LI.isAtomic() || isSupportedAtomicType(CI->getDestTy())) { 602 LoadInst *NewLoad = IC.combineLoadToNewType(LI, CI->getDestTy()); 603 CI->replaceAllUsesWith(NewLoad); 604 IC.eraseInstFromFunction(*CI); 605 return &LI; 606 } 607 608 // FIXME: We should also canonicalize loads of vectors when their elements are 609 // cast to other types. 610 return nullptr; 611 } 612 613 static Instruction *unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI) { 614 // FIXME: We could probably with some care handle both volatile and atomic 615 // stores here but it isn't clear that this is important. 616 if (!LI.isSimple()) 617 return nullptr; 618 619 Type *T = LI.getType(); 620 if (!T->isAggregateType()) 621 return nullptr; 622 623 StringRef Name = LI.getName(); 624 assert(LI.getAlignment() && "Alignment must be set at this point"); 625 626 if (auto *ST = dyn_cast<StructType>(T)) { 627 // If the struct only have one element, we unpack. 628 auto NumElements = ST->getNumElements(); 629 if (NumElements == 1) { 630 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ST->getTypeAtIndex(0U), 631 ".unpack"); 632 AAMDNodes AAMD; 633 LI.getAAMetadata(AAMD); 634 NewLoad->setAAMetadata(AAMD); 635 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue( 636 UndefValue::get(T), NewLoad, 0, Name)); 637 } 638 639 // We don't want to break loads with padding here as we'd loose 640 // the knowledge that padding exists for the rest of the pipeline. 641 const DataLayout &DL = IC.getDataLayout(); 642 auto *SL = DL.getStructLayout(ST); 643 if (SL->hasPadding()) 644 return nullptr; 645 646 const auto Align = LI.getAlign(); 647 auto *Addr = LI.getPointerOperand(); 648 auto *IdxType = Type::getInt32Ty(T->getContext()); 649 auto *Zero = ConstantInt::get(IdxType, 0); 650 651 Value *V = UndefValue::get(T); 652 for (unsigned i = 0; i < NumElements; i++) { 653 Value *Indices[2] = { 654 Zero, 655 ConstantInt::get(IdxType, i), 656 }; 657 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices), 658 Name + ".elt"); 659 auto *L = IC.Builder.CreateAlignedLoad( 660 ST->getElementType(i), Ptr, 661 commonAlignment(Align, SL->getElementOffset(i)), Name + ".unpack"); 662 // Propagate AA metadata. It'll still be valid on the narrowed load. 663 AAMDNodes AAMD; 664 LI.getAAMetadata(AAMD); 665 L->setAAMetadata(AAMD); 666 V = IC.Builder.CreateInsertValue(V, L, i); 667 } 668 669 V->setName(Name); 670 return IC.replaceInstUsesWith(LI, V); 671 } 672 673 if (auto *AT = dyn_cast<ArrayType>(T)) { 674 auto *ET = AT->getElementType(); 675 auto NumElements = AT->getNumElements(); 676 if (NumElements == 1) { 677 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ET, ".unpack"); 678 AAMDNodes AAMD; 679 LI.getAAMetadata(AAMD); 680 NewLoad->setAAMetadata(AAMD); 681 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue( 682 UndefValue::get(T), NewLoad, 0, Name)); 683 } 684 685 // Bail out if the array is too large. Ideally we would like to optimize 686 // arrays of arbitrary size but this has a terrible impact on compile time. 687 // The threshold here is chosen arbitrarily, maybe needs a little bit of 688 // tuning. 689 if (NumElements > IC.MaxArraySizeForCombine) 690 return nullptr; 691 692 const DataLayout &DL = IC.getDataLayout(); 693 auto EltSize = DL.getTypeAllocSize(ET); 694 const auto Align = LI.getAlign(); 695 696 auto *Addr = LI.getPointerOperand(); 697 auto *IdxType = Type::getInt64Ty(T->getContext()); 698 auto *Zero = ConstantInt::get(IdxType, 0); 699 700 Value *V = UndefValue::get(T); 701 uint64_t Offset = 0; 702 for (uint64_t i = 0; i < NumElements; i++) { 703 Value *Indices[2] = { 704 Zero, 705 ConstantInt::get(IdxType, i), 706 }; 707 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices), 708 Name + ".elt"); 709 auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr, 710 commonAlignment(Align, Offset), 711 Name + ".unpack"); 712 AAMDNodes AAMD; 713 LI.getAAMetadata(AAMD); 714 L->setAAMetadata(AAMD); 715 V = IC.Builder.CreateInsertValue(V, L, i); 716 Offset += EltSize; 717 } 718 719 V->setName(Name); 720 return IC.replaceInstUsesWith(LI, V); 721 } 722 723 return nullptr; 724 } 725 726 // If we can determine that all possible objects pointed to by the provided 727 // pointer value are, not only dereferenceable, but also definitively less than 728 // or equal to the provided maximum size, then return true. Otherwise, return 729 // false (constant global values and allocas fall into this category). 730 // 731 // FIXME: This should probably live in ValueTracking (or similar). 732 static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize, 733 const DataLayout &DL) { 734 SmallPtrSet<Value *, 4> Visited; 735 SmallVector<Value *, 4> Worklist(1, V); 736 737 do { 738 Value *P = Worklist.pop_back_val(); 739 P = P->stripPointerCasts(); 740 741 if (!Visited.insert(P).second) 742 continue; 743 744 if (SelectInst *SI = dyn_cast<SelectInst>(P)) { 745 Worklist.push_back(SI->getTrueValue()); 746 Worklist.push_back(SI->getFalseValue()); 747 continue; 748 } 749 750 if (PHINode *PN = dyn_cast<PHINode>(P)) { 751 for (Value *IncValue : PN->incoming_values()) 752 Worklist.push_back(IncValue); 753 continue; 754 } 755 756 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) { 757 if (GA->isInterposable()) 758 return false; 759 Worklist.push_back(GA->getAliasee()); 760 continue; 761 } 762 763 // If we know how big this object is, and it is less than MaxSize, continue 764 // searching. Otherwise, return false. 765 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) { 766 if (!AI->getAllocatedType()->isSized()) 767 return false; 768 769 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize()); 770 if (!CS) 771 return false; 772 773 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType()); 774 // Make sure that, even if the multiplication below would wrap as an 775 // uint64_t, we still do the right thing. 776 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize)) 777 return false; 778 continue; 779 } 780 781 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) { 782 if (!GV->hasDefinitiveInitializer() || !GV->isConstant()) 783 return false; 784 785 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType()); 786 if (InitSize > MaxSize) 787 return false; 788 continue; 789 } 790 791 return false; 792 } while (!Worklist.empty()); 793 794 return true; 795 } 796 797 // If we're indexing into an object of a known size, and the outer index is 798 // not a constant, but having any value but zero would lead to undefined 799 // behavior, replace it with zero. 800 // 801 // For example, if we have: 802 // @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4 803 // ... 804 // %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x 805 // ... = load i32* %arrayidx, align 4 806 // Then we know that we can replace %x in the GEP with i64 0. 807 // 808 // FIXME: We could fold any GEP index to zero that would cause UB if it were 809 // not zero. Currently, we only handle the first such index. Also, we could 810 // also search through non-zero constant indices if we kept track of the 811 // offsets those indices implied. 812 static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC, 813 GetElementPtrInst *GEPI, Instruction *MemI, 814 unsigned &Idx) { 815 if (GEPI->getNumOperands() < 2) 816 return false; 817 818 // Find the first non-zero index of a GEP. If all indices are zero, return 819 // one past the last index. 820 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) { 821 unsigned I = 1; 822 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) { 823 Value *V = GEPI->getOperand(I); 824 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) 825 if (CI->isZero()) 826 continue; 827 828 break; 829 } 830 831 return I; 832 }; 833 834 // Skip through initial 'zero' indices, and find the corresponding pointer 835 // type. See if the next index is not a constant. 836 Idx = FirstNZIdx(GEPI); 837 if (Idx == GEPI->getNumOperands()) 838 return false; 839 if (isa<Constant>(GEPI->getOperand(Idx))) 840 return false; 841 842 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx); 843 Type *AllocTy = 844 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops); 845 if (!AllocTy || !AllocTy->isSized()) 846 return false; 847 const DataLayout &DL = IC.getDataLayout(); 848 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy); 849 850 // If there are more indices after the one we might replace with a zero, make 851 // sure they're all non-negative. If any of them are negative, the overall 852 // address being computed might be before the base address determined by the 853 // first non-zero index. 854 auto IsAllNonNegative = [&]() { 855 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) { 856 KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI); 857 if (Known.isNonNegative()) 858 continue; 859 return false; 860 } 861 862 return true; 863 }; 864 865 // FIXME: If the GEP is not inbounds, and there are extra indices after the 866 // one we'll replace, those could cause the address computation to wrap 867 // (rendering the IsAllNonNegative() check below insufficient). We can do 868 // better, ignoring zero indices (and other indices we can prove small 869 // enough not to wrap). 870 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds()) 871 return false; 872 873 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is 874 // also known to be dereferenceable. 875 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) && 876 IsAllNonNegative(); 877 } 878 879 // If we're indexing into an object with a variable index for the memory 880 // access, but the object has only one element, we can assume that the index 881 // will always be zero. If we replace the GEP, return it. 882 template <typename T> 883 static Instruction *replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr, 884 T &MemI) { 885 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) { 886 unsigned Idx; 887 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) { 888 Instruction *NewGEPI = GEPI->clone(); 889 NewGEPI->setOperand(Idx, 890 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0)); 891 NewGEPI->insertBefore(GEPI); 892 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI); 893 return NewGEPI; 894 } 895 } 896 897 return nullptr; 898 } 899 900 static bool canSimplifyNullStoreOrGEP(StoreInst &SI) { 901 if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace())) 902 return false; 903 904 auto *Ptr = SI.getPointerOperand(); 905 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) 906 Ptr = GEPI->getOperand(0); 907 return (isa<ConstantPointerNull>(Ptr) && 908 !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace())); 909 } 910 911 static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) { 912 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) { 913 const Value *GEPI0 = GEPI->getOperand(0); 914 if (isa<ConstantPointerNull>(GEPI0) && 915 !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace())) 916 return true; 917 } 918 if (isa<UndefValue>(Op) || 919 (isa<ConstantPointerNull>(Op) && 920 !NullPointerIsDefined(LI.getFunction(), LI.getPointerAddressSpace()))) 921 return true; 922 return false; 923 } 924 925 Instruction *InstCombinerImpl::visitLoadInst(LoadInst &LI) { 926 Value *Op = LI.getOperand(0); 927 928 // Try to canonicalize the loaded type. 929 if (Instruction *Res = combineLoadToOperationType(*this, LI)) 930 return Res; 931 932 // Attempt to improve the alignment. 933 Align KnownAlign = getOrEnforceKnownAlignment( 934 Op, DL.getPrefTypeAlign(LI.getType()), DL, &LI, &AC, &DT); 935 if (KnownAlign > LI.getAlign()) 936 LI.setAlignment(KnownAlign); 937 938 // Replace GEP indices if possible. 939 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) { 940 Worklist.push(NewGEPI); 941 return &LI; 942 } 943 944 if (Instruction *Res = unpackLoadToAggregate(*this, LI)) 945 return Res; 946 947 // Do really simple store-to-load forwarding and load CSE, to catch cases 948 // where there are several consecutive memory accesses to the same location, 949 // separated by a few arithmetic operations. 950 BasicBlock::iterator BBI(LI); 951 bool IsLoadCSE = false; 952 if (Value *AvailableVal = FindAvailableLoadedValue( 953 &LI, LI.getParent(), BBI, DefMaxInstsToScan, AA, &IsLoadCSE)) { 954 if (IsLoadCSE) 955 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false); 956 957 return replaceInstUsesWith( 958 LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(), 959 LI.getName() + ".cast")); 960 } 961 962 // None of the following transforms are legal for volatile/ordered atomic 963 // loads. Most of them do apply for unordered atomics. 964 if (!LI.isUnordered()) return nullptr; 965 966 // load(gep null, ...) -> unreachable 967 // load null/undef -> unreachable 968 // TODO: Consider a target hook for valid address spaces for this xforms. 969 if (canSimplifyNullLoadOrGEP(LI, Op)) { 970 // Insert a new store to null instruction before the load to indicate 971 // that this code is not reachable. We do this instead of inserting 972 // an unreachable instruction directly because we cannot modify the 973 // CFG. 974 StoreInst *SI = new StoreInst(UndefValue::get(LI.getType()), 975 Constant::getNullValue(Op->getType()), &LI); 976 SI->setDebugLoc(LI.getDebugLoc()); 977 return replaceInstUsesWith(LI, UndefValue::get(LI.getType())); 978 } 979 980 if (Op->hasOneUse()) { 981 // Change select and PHI nodes to select values instead of addresses: this 982 // helps alias analysis out a lot, allows many others simplifications, and 983 // exposes redundancy in the code. 984 // 985 // Note that we cannot do the transformation unless we know that the 986 // introduced loads cannot trap! Something like this is valid as long as 987 // the condition is always false: load (select bool %C, int* null, int* %G), 988 // but it would not be valid if we transformed it to load from null 989 // unconditionally. 990 // 991 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) { 992 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2). 993 Align Alignment = LI.getAlign(); 994 if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(), 995 Alignment, DL, SI) && 996 isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(), 997 Alignment, DL, SI)) { 998 LoadInst *V1 = 999 Builder.CreateLoad(LI.getType(), SI->getOperand(1), 1000 SI->getOperand(1)->getName() + ".val"); 1001 LoadInst *V2 = 1002 Builder.CreateLoad(LI.getType(), SI->getOperand(2), 1003 SI->getOperand(2)->getName() + ".val"); 1004 assert(LI.isUnordered() && "implied by above"); 1005 V1->setAlignment(Alignment); 1006 V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 1007 V2->setAlignment(Alignment); 1008 V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID()); 1009 return SelectInst::Create(SI->getCondition(), V1, V2); 1010 } 1011 1012 // load (select (cond, null, P)) -> load P 1013 if (isa<ConstantPointerNull>(SI->getOperand(1)) && 1014 !NullPointerIsDefined(SI->getFunction(), 1015 LI.getPointerAddressSpace())) 1016 return replaceOperand(LI, 0, SI->getOperand(2)); 1017 1018 // load (select (cond, P, null)) -> load P 1019 if (isa<ConstantPointerNull>(SI->getOperand(2)) && 1020 !NullPointerIsDefined(SI->getFunction(), 1021 LI.getPointerAddressSpace())) 1022 return replaceOperand(LI, 0, SI->getOperand(1)); 1023 } 1024 } 1025 return nullptr; 1026 } 1027 1028 /// Look for extractelement/insertvalue sequence that acts like a bitcast. 1029 /// 1030 /// \returns underlying value that was "cast", or nullptr otherwise. 1031 /// 1032 /// For example, if we have: 1033 /// 1034 /// %E0 = extractelement <2 x double> %U, i32 0 1035 /// %V0 = insertvalue [2 x double] undef, double %E0, 0 1036 /// %E1 = extractelement <2 x double> %U, i32 1 1037 /// %V1 = insertvalue [2 x double] %V0, double %E1, 1 1038 /// 1039 /// and the layout of a <2 x double> is isomorphic to a [2 x double], 1040 /// then %V1 can be safely approximated by a conceptual "bitcast" of %U. 1041 /// Note that %U may contain non-undef values where %V1 has undef. 1042 static Value *likeBitCastFromVector(InstCombinerImpl &IC, Value *V) { 1043 Value *U = nullptr; 1044 while (auto *IV = dyn_cast<InsertValueInst>(V)) { 1045 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand()); 1046 if (!E) 1047 return nullptr; 1048 auto *W = E->getVectorOperand(); 1049 if (!U) 1050 U = W; 1051 else if (U != W) 1052 return nullptr; 1053 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand()); 1054 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin()) 1055 return nullptr; 1056 V = IV->getAggregateOperand(); 1057 } 1058 if (!isa<UndefValue>(V) ||!U) 1059 return nullptr; 1060 1061 auto *UT = cast<VectorType>(U->getType()); 1062 auto *VT = V->getType(); 1063 // Check that types UT and VT are bitwise isomorphic. 1064 const auto &DL = IC.getDataLayout(); 1065 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) { 1066 return nullptr; 1067 } 1068 if (auto *AT = dyn_cast<ArrayType>(VT)) { 1069 if (AT->getNumElements() != cast<FixedVectorType>(UT)->getNumElements()) 1070 return nullptr; 1071 } else { 1072 auto *ST = cast<StructType>(VT); 1073 if (ST->getNumElements() != cast<FixedVectorType>(UT)->getNumElements()) 1074 return nullptr; 1075 for (const auto *EltT : ST->elements()) { 1076 if (EltT != UT->getElementType()) 1077 return nullptr; 1078 } 1079 } 1080 return U; 1081 } 1082 1083 /// Combine stores to match the type of value being stored. 1084 /// 1085 /// The core idea here is that the memory does not have any intrinsic type and 1086 /// where we can we should match the type of a store to the type of value being 1087 /// stored. 1088 /// 1089 /// However, this routine must never change the width of a store or the number of 1090 /// stores as that would introduce a semantic change. This combine is expected to 1091 /// be a semantic no-op which just allows stores to more closely model the types 1092 /// of their incoming values. 1093 /// 1094 /// Currently, we also refuse to change the precise type used for an atomic or 1095 /// volatile store. This is debatable, and might be reasonable to change later. 1096 /// However, it is risky in case some backend or other part of LLVM is relying 1097 /// on the exact type stored to select appropriate atomic operations. 1098 /// 1099 /// \returns true if the store was successfully combined away. This indicates 1100 /// the caller must erase the store instruction. We have to let the caller erase 1101 /// the store instruction as otherwise there is no way to signal whether it was 1102 /// combined or not: IC.EraseInstFromFunction returns a null pointer. 1103 static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI) { 1104 // FIXME: We could probably with some care handle both volatile and ordered 1105 // atomic stores here but it isn't clear that this is important. 1106 if (!SI.isUnordered()) 1107 return false; 1108 1109 // swifterror values can't be bitcasted. 1110 if (SI.getPointerOperand()->isSwiftError()) 1111 return false; 1112 1113 Value *V = SI.getValueOperand(); 1114 1115 // Fold away bit casts of the stored value by storing the original type. 1116 if (auto *BC = dyn_cast<BitCastInst>(V)) { 1117 V = BC->getOperand(0); 1118 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) { 1119 combineStoreToNewValue(IC, SI, V); 1120 return true; 1121 } 1122 } 1123 1124 if (Value *U = likeBitCastFromVector(IC, V)) 1125 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) { 1126 combineStoreToNewValue(IC, SI, U); 1127 return true; 1128 } 1129 1130 // FIXME: We should also canonicalize stores of vectors when their elements 1131 // are cast to other types. 1132 return false; 1133 } 1134 1135 static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI) { 1136 // FIXME: We could probably with some care handle both volatile and atomic 1137 // stores here but it isn't clear that this is important. 1138 if (!SI.isSimple()) 1139 return false; 1140 1141 Value *V = SI.getValueOperand(); 1142 Type *T = V->getType(); 1143 1144 if (!T->isAggregateType()) 1145 return false; 1146 1147 if (auto *ST = dyn_cast<StructType>(T)) { 1148 // If the struct only have one element, we unpack. 1149 unsigned Count = ST->getNumElements(); 1150 if (Count == 1) { 1151 V = IC.Builder.CreateExtractValue(V, 0); 1152 combineStoreToNewValue(IC, SI, V); 1153 return true; 1154 } 1155 1156 // We don't want to break loads with padding here as we'd loose 1157 // the knowledge that padding exists for the rest of the pipeline. 1158 const DataLayout &DL = IC.getDataLayout(); 1159 auto *SL = DL.getStructLayout(ST); 1160 if (SL->hasPadding()) 1161 return false; 1162 1163 const auto Align = SI.getAlign(); 1164 1165 SmallString<16> EltName = V->getName(); 1166 EltName += ".elt"; 1167 auto *Addr = SI.getPointerOperand(); 1168 SmallString<16> AddrName = Addr->getName(); 1169 AddrName += ".repack"; 1170 1171 auto *IdxType = Type::getInt32Ty(ST->getContext()); 1172 auto *Zero = ConstantInt::get(IdxType, 0); 1173 for (unsigned i = 0; i < Count; i++) { 1174 Value *Indices[2] = { 1175 Zero, 1176 ConstantInt::get(IdxType, i), 1177 }; 1178 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices), 1179 AddrName); 1180 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName); 1181 auto EltAlign = commonAlignment(Align, SL->getElementOffset(i)); 1182 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign); 1183 AAMDNodes AAMD; 1184 SI.getAAMetadata(AAMD); 1185 NS->setAAMetadata(AAMD); 1186 } 1187 1188 return true; 1189 } 1190 1191 if (auto *AT = dyn_cast<ArrayType>(T)) { 1192 // If the array only have one element, we unpack. 1193 auto NumElements = AT->getNumElements(); 1194 if (NumElements == 1) { 1195 V = IC.Builder.CreateExtractValue(V, 0); 1196 combineStoreToNewValue(IC, SI, V); 1197 return true; 1198 } 1199 1200 // Bail out if the array is too large. Ideally we would like to optimize 1201 // arrays of arbitrary size but this has a terrible impact on compile time. 1202 // The threshold here is chosen arbitrarily, maybe needs a little bit of 1203 // tuning. 1204 if (NumElements > IC.MaxArraySizeForCombine) 1205 return false; 1206 1207 const DataLayout &DL = IC.getDataLayout(); 1208 auto EltSize = DL.getTypeAllocSize(AT->getElementType()); 1209 const auto Align = SI.getAlign(); 1210 1211 SmallString<16> EltName = V->getName(); 1212 EltName += ".elt"; 1213 auto *Addr = SI.getPointerOperand(); 1214 SmallString<16> AddrName = Addr->getName(); 1215 AddrName += ".repack"; 1216 1217 auto *IdxType = Type::getInt64Ty(T->getContext()); 1218 auto *Zero = ConstantInt::get(IdxType, 0); 1219 1220 uint64_t Offset = 0; 1221 for (uint64_t i = 0; i < NumElements; i++) { 1222 Value *Indices[2] = { 1223 Zero, 1224 ConstantInt::get(IdxType, i), 1225 }; 1226 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices), 1227 AddrName); 1228 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName); 1229 auto EltAlign = commonAlignment(Align, Offset); 1230 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign); 1231 AAMDNodes AAMD; 1232 SI.getAAMetadata(AAMD); 1233 NS->setAAMetadata(AAMD); 1234 Offset += EltSize; 1235 } 1236 1237 return true; 1238 } 1239 1240 return false; 1241 } 1242 1243 /// equivalentAddressValues - Test if A and B will obviously have the same 1244 /// value. This includes recognizing that %t0 and %t1 will have the same 1245 /// value in code like this: 1246 /// %t0 = getelementptr \@a, 0, 3 1247 /// store i32 0, i32* %t0 1248 /// %t1 = getelementptr \@a, 0, 3 1249 /// %t2 = load i32* %t1 1250 /// 1251 static bool equivalentAddressValues(Value *A, Value *B) { 1252 // Test if the values are trivially equivalent. 1253 if (A == B) return true; 1254 1255 // Test if the values come form identical arithmetic instructions. 1256 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because 1257 // its only used to compare two uses within the same basic block, which 1258 // means that they'll always either have the same value or one of them 1259 // will have an undefined value. 1260 if (isa<BinaryOperator>(A) || 1261 isa<CastInst>(A) || 1262 isa<PHINode>(A) || 1263 isa<GetElementPtrInst>(A)) 1264 if (Instruction *BI = dyn_cast<Instruction>(B)) 1265 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI)) 1266 return true; 1267 1268 // Otherwise they may not be equivalent. 1269 return false; 1270 } 1271 1272 /// Converts store (bitcast (load (bitcast (select ...)))) to 1273 /// store (load (select ...)), where select is minmax: 1274 /// select ((cmp load V1, load V2), V1, V2). 1275 static bool removeBitcastsFromLoadStoreOnMinMax(InstCombinerImpl &IC, 1276 StoreInst &SI) { 1277 // bitcast? 1278 if (!match(SI.getPointerOperand(), m_BitCast(m_Value()))) 1279 return false; 1280 // load? integer? 1281 Value *LoadAddr; 1282 if (!match(SI.getValueOperand(), m_Load(m_BitCast(m_Value(LoadAddr))))) 1283 return false; 1284 auto *LI = cast<LoadInst>(SI.getValueOperand()); 1285 if (!LI->getType()->isIntegerTy()) 1286 return false; 1287 Type *CmpLoadTy; 1288 if (!isMinMaxWithLoads(LoadAddr, CmpLoadTy)) 1289 return false; 1290 1291 // Make sure the type would actually change. 1292 // This condition can be hit with chains of bitcasts. 1293 if (LI->getType() == CmpLoadTy) 1294 return false; 1295 1296 // Make sure we're not changing the size of the load/store. 1297 const auto &DL = IC.getDataLayout(); 1298 if (DL.getTypeStoreSizeInBits(LI->getType()) != 1299 DL.getTypeStoreSizeInBits(CmpLoadTy)) 1300 return false; 1301 1302 if (!all_of(LI->users(), [LI, LoadAddr](User *U) { 1303 auto *SI = dyn_cast<StoreInst>(U); 1304 return SI && SI->getPointerOperand() != LI && 1305 InstCombiner::peekThroughBitcast(SI->getPointerOperand()) != 1306 LoadAddr && 1307 !SI->getPointerOperand()->isSwiftError(); 1308 })) 1309 return false; 1310 1311 IC.Builder.SetInsertPoint(LI); 1312 LoadInst *NewLI = IC.combineLoadToNewType(*LI, CmpLoadTy); 1313 // Replace all the stores with stores of the newly loaded value. 1314 for (auto *UI : LI->users()) { 1315 auto *USI = cast<StoreInst>(UI); 1316 IC.Builder.SetInsertPoint(USI); 1317 combineStoreToNewValue(IC, *USI, NewLI); 1318 } 1319 IC.replaceInstUsesWith(*LI, UndefValue::get(LI->getType())); 1320 IC.eraseInstFromFunction(*LI); 1321 return true; 1322 } 1323 1324 Instruction *InstCombinerImpl::visitStoreInst(StoreInst &SI) { 1325 Value *Val = SI.getOperand(0); 1326 Value *Ptr = SI.getOperand(1); 1327 1328 // Try to canonicalize the stored type. 1329 if (combineStoreToValueType(*this, SI)) 1330 return eraseInstFromFunction(SI); 1331 1332 // Attempt to improve the alignment. 1333 const Align KnownAlign = getOrEnforceKnownAlignment( 1334 Ptr, DL.getPrefTypeAlign(Val->getType()), DL, &SI, &AC, &DT); 1335 if (KnownAlign > SI.getAlign()) 1336 SI.setAlignment(KnownAlign); 1337 1338 // Try to canonicalize the stored type. 1339 if (unpackStoreToAggregate(*this, SI)) 1340 return eraseInstFromFunction(SI); 1341 1342 if (removeBitcastsFromLoadStoreOnMinMax(*this, SI)) 1343 return eraseInstFromFunction(SI); 1344 1345 // Replace GEP indices if possible. 1346 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) { 1347 Worklist.push(NewGEPI); 1348 return &SI; 1349 } 1350 1351 // Don't hack volatile/ordered stores. 1352 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring. 1353 if (!SI.isUnordered()) return nullptr; 1354 1355 // If the RHS is an alloca with a single use, zapify the store, making the 1356 // alloca dead. 1357 if (Ptr->hasOneUse()) { 1358 if (isa<AllocaInst>(Ptr)) 1359 return eraseInstFromFunction(SI); 1360 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) { 1361 if (isa<AllocaInst>(GEP->getOperand(0))) { 1362 if (GEP->getOperand(0)->hasOneUse()) 1363 return eraseInstFromFunction(SI); 1364 } 1365 } 1366 } 1367 1368 // If we have a store to a location which is known constant, we can conclude 1369 // that the store must be storing the constant value (else the memory 1370 // wouldn't be constant), and this must be a noop. 1371 if (AA->pointsToConstantMemory(Ptr)) 1372 return eraseInstFromFunction(SI); 1373 1374 // Do really simple DSE, to catch cases where there are several consecutive 1375 // stores to the same location, separated by a few arithmetic operations. This 1376 // situation often occurs with bitfield accesses. 1377 BasicBlock::iterator BBI(SI); 1378 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts; 1379 --ScanInsts) { 1380 --BBI; 1381 // Don't count debug info directives, lest they affect codegen, 1382 // and we skip pointer-to-pointer bitcasts, which are NOPs. 1383 if (isa<DbgInfoIntrinsic>(BBI) || 1384 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) { 1385 ScanInsts++; 1386 continue; 1387 } 1388 1389 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) { 1390 // Prev store isn't volatile, and stores to the same location? 1391 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1), 1392 SI.getOperand(1))) { 1393 ++NumDeadStore; 1394 // Manually add back the original store to the worklist now, so it will 1395 // be processed after the operands of the removed store, as this may 1396 // expose additional DSE opportunities. 1397 Worklist.push(&SI); 1398 eraseInstFromFunction(*PrevSI); 1399 return nullptr; 1400 } 1401 break; 1402 } 1403 1404 // If this is a load, we have to stop. However, if the loaded value is from 1405 // the pointer we're loading and is producing the pointer we're storing, 1406 // then *this* store is dead (X = load P; store X -> P). 1407 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) { 1408 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) { 1409 assert(SI.isUnordered() && "can't eliminate ordering operation"); 1410 return eraseInstFromFunction(SI); 1411 } 1412 1413 // Otherwise, this is a load from some other location. Stores before it 1414 // may not be dead. 1415 break; 1416 } 1417 1418 // Don't skip over loads, throws or things that can modify memory. 1419 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow()) 1420 break; 1421 } 1422 1423 // store X, null -> turns into 'unreachable' in SimplifyCFG 1424 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG 1425 if (canSimplifyNullStoreOrGEP(SI)) { 1426 if (!isa<UndefValue>(Val)) 1427 return replaceOperand(SI, 0, UndefValue::get(Val->getType())); 1428 return nullptr; // Do not modify these! 1429 } 1430 1431 // store undef, Ptr -> noop 1432 if (isa<UndefValue>(Val)) 1433 return eraseInstFromFunction(SI); 1434 1435 return nullptr; 1436 } 1437 1438 /// Try to transform: 1439 /// if () { *P = v1; } else { *P = v2 } 1440 /// or: 1441 /// *P = v1; if () { *P = v2; } 1442 /// into a phi node with a store in the successor. 1443 bool InstCombinerImpl::mergeStoreIntoSuccessor(StoreInst &SI) { 1444 if (!SI.isUnordered()) 1445 return false; // This code has not been audited for volatile/ordered case. 1446 1447 // Check if the successor block has exactly 2 incoming edges. 1448 BasicBlock *StoreBB = SI.getParent(); 1449 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0); 1450 if (!DestBB->hasNPredecessors(2)) 1451 return false; 1452 1453 // Capture the other block (the block that doesn't contain our store). 1454 pred_iterator PredIter = pred_begin(DestBB); 1455 if (*PredIter == StoreBB) 1456 ++PredIter; 1457 BasicBlock *OtherBB = *PredIter; 1458 1459 // Bail out if all of the relevant blocks aren't distinct. This can happen, 1460 // for example, if SI is in an infinite loop. 1461 if (StoreBB == DestBB || OtherBB == DestBB) 1462 return false; 1463 1464 // Verify that the other block ends in a branch and is not otherwise empty. 1465 BasicBlock::iterator BBI(OtherBB->getTerminator()); 1466 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI); 1467 if (!OtherBr || BBI == OtherBB->begin()) 1468 return false; 1469 1470 // If the other block ends in an unconditional branch, check for the 'if then 1471 // else' case. There is an instruction before the branch. 1472 StoreInst *OtherStore = nullptr; 1473 if (OtherBr->isUnconditional()) { 1474 --BBI; 1475 // Skip over debugging info. 1476 while (isa<DbgInfoIntrinsic>(BBI) || 1477 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) { 1478 if (BBI==OtherBB->begin()) 1479 return false; 1480 --BBI; 1481 } 1482 // If this isn't a store, isn't a store to the same location, or is not the 1483 // right kind of store, bail out. 1484 OtherStore = dyn_cast<StoreInst>(BBI); 1485 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) || 1486 !SI.isSameOperationAs(OtherStore)) 1487 return false; 1488 } else { 1489 // Otherwise, the other block ended with a conditional branch. If one of the 1490 // destinations is StoreBB, then we have the if/then case. 1491 if (OtherBr->getSuccessor(0) != StoreBB && 1492 OtherBr->getSuccessor(1) != StoreBB) 1493 return false; 1494 1495 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an 1496 // if/then triangle. See if there is a store to the same ptr as SI that 1497 // lives in OtherBB. 1498 for (;; --BBI) { 1499 // Check to see if we find the matching store. 1500 if ((OtherStore = dyn_cast<StoreInst>(BBI))) { 1501 if (OtherStore->getOperand(1) != SI.getOperand(1) || 1502 !SI.isSameOperationAs(OtherStore)) 1503 return false; 1504 break; 1505 } 1506 // If we find something that may be using or overwriting the stored 1507 // value, or if we run out of instructions, we can't do the transform. 1508 if (BBI->mayReadFromMemory() || BBI->mayThrow() || 1509 BBI->mayWriteToMemory() || BBI == OtherBB->begin()) 1510 return false; 1511 } 1512 1513 // In order to eliminate the store in OtherBr, we have to make sure nothing 1514 // reads or overwrites the stored value in StoreBB. 1515 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) { 1516 // FIXME: This should really be AA driven. 1517 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory()) 1518 return false; 1519 } 1520 } 1521 1522 // Insert a PHI node now if we need it. 1523 Value *MergedVal = OtherStore->getOperand(0); 1524 // The debug locations of the original instructions might differ. Merge them. 1525 DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(), 1526 OtherStore->getDebugLoc()); 1527 if (MergedVal != SI.getOperand(0)) { 1528 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge"); 1529 PN->addIncoming(SI.getOperand(0), SI.getParent()); 1530 PN->addIncoming(OtherStore->getOperand(0), OtherBB); 1531 MergedVal = InsertNewInstBefore(PN, DestBB->front()); 1532 PN->setDebugLoc(MergedLoc); 1533 } 1534 1535 // Advance to a place where it is safe to insert the new store and insert it. 1536 BBI = DestBB->getFirstInsertionPt(); 1537 StoreInst *NewSI = 1538 new StoreInst(MergedVal, SI.getOperand(1), SI.isVolatile(), SI.getAlign(), 1539 SI.getOrdering(), SI.getSyncScopeID()); 1540 InsertNewInstBefore(NewSI, *BBI); 1541 NewSI->setDebugLoc(MergedLoc); 1542 1543 // If the two stores had AA tags, merge them. 1544 AAMDNodes AATags; 1545 SI.getAAMetadata(AATags); 1546 if (AATags) { 1547 OtherStore->getAAMetadata(AATags, /* Merge = */ true); 1548 NewSI->setAAMetadata(AATags); 1549 } 1550 1551 // Nuke the old stores. 1552 eraseInstFromFunction(SI); 1553 eraseInstFromFunction(*OtherStore); 1554 return true; 1555 } 1556