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