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