LLVM 19.0.0git
InstCombineLoadStoreAlloca.cpp
Go to the documentation of this file.
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"
16#include "llvm/ADT/Statistic.h"
18#include "llvm/Analysis/Loads.h"
19#include "llvm/IR/DataLayout.h"
22#include "llvm/IR/LLVMContext.h"
26using namespace llvm;
27using namespace PatternMatch;
28
29#define DEBUG_TYPE "instcombine"
30
31STATISTIC(NumDeadStore, "Number of dead stores eliminated");
32STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
33
35 "instcombine-max-copied-from-constant-users", cl::init(300),
36 cl::desc("Maximum users to visit in copy from constant transform"),
38
39namespace llvm {
41 "enable-infer-alignment-pass", cl::init(true), cl::Hidden, cl::ZeroOrMore,
42 cl::desc("Enable the InferAlignment pass, disabling alignment inference in "
43 "InstCombine"));
44}
45
46/// isOnlyCopiedFromConstantMemory - Recursively walk the uses of a (derived)
47/// pointer to an alloca. Ignore any reads of the pointer, return false if we
48/// see any stores or other unknown uses. If we see pointer arithmetic, keep
49/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
50/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
51/// the alloca, and if the source pointer is a pointer to a constant memory
52/// location, we can optimize this.
53static bool
55 MemTransferInst *&TheCopy,
57 // We track lifetime intrinsics as we encounter them. If we decide to go
58 // ahead and replace the value with the memory location, this lets the caller
59 // quickly eliminate the markers.
60
61 using ValueAndIsOffset = PointerIntPair<Value *, 1, bool>;
64 Worklist.emplace_back(V, false);
65 while (!Worklist.empty()) {
66 ValueAndIsOffset Elem = Worklist.pop_back_val();
67 if (!Visited.insert(Elem).second)
68 continue;
69 if (Visited.size() > MaxCopiedFromConstantUsers)
70 return false;
71
72 const auto [Value, IsOffset] = Elem;
73 for (auto &U : Value->uses()) {
74 auto *I = cast<Instruction>(U.getUser());
75
76 if (auto *LI = dyn_cast<LoadInst>(I)) {
77 // Ignore non-volatile loads, they are always ok.
78 if (!LI->isSimple()) return false;
79 continue;
80 }
81
82 if (isa<PHINode, SelectInst>(I)) {
83 // We set IsOffset=true, to forbid the memcpy from occurring after the
84 // phi: If one of the phi operands is not based on the alloca, we
85 // would incorrectly omit a write.
86 Worklist.emplace_back(I, true);
87 continue;
88 }
89 if (isa<BitCastInst, AddrSpaceCastInst>(I)) {
90 // If uses of the bitcast are ok, we are ok.
91 Worklist.emplace_back(I, IsOffset);
92 continue;
93 }
94 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
95 // If the GEP has all zero indices, it doesn't offset the pointer. If it
96 // doesn't, it does.
97 Worklist.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());
98 continue;
99 }
100
101 if (auto *Call = dyn_cast<CallBase>(I)) {
102 // If this is the function being called then we treat it like a load and
103 // ignore it.
104 if (Call->isCallee(&U))
105 continue;
106
107 unsigned DataOpNo = Call->getDataOperandNo(&U);
108 bool IsArgOperand = Call->isArgOperand(&U);
109
110 // Inalloca arguments are clobbered by the call.
111 if (IsArgOperand && Call->isInAllocaArgument(DataOpNo))
112 return false;
113
114 // If this call site doesn't modify the memory, then we know it is just
115 // a load (but one that potentially returns the value itself), so we can
116 // ignore it if we know that the value isn't captured.
117 bool NoCapture = Call->doesNotCapture(DataOpNo);
118 if ((Call->onlyReadsMemory() && (Call->use_empty() || NoCapture)) ||
119 (Call->onlyReadsMemory(DataOpNo) && NoCapture))
120 continue;
121
122 // If this is being passed as a byval argument, the caller is making a
123 // copy, so it is only a read of the alloca.
124 if (IsArgOperand && Call->isByValArgument(DataOpNo))
125 continue;
126 }
127
128 // Lifetime intrinsics can be handled by the caller.
129 if (I->isLifetimeStartOrEnd()) {
130 assert(I->use_empty() && "Lifetime markers have no result to use!");
131 ToDelete.push_back(I);
132 continue;
133 }
134
135 // If this is isn't our memcpy/memmove, reject it as something we can't
136 // handle.
137 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
138 if (!MI)
139 return false;
140
141 // If the transfer is volatile, reject it.
142 if (MI->isVolatile())
143 return false;
144
145 // If the transfer is using the alloca as a source of the transfer, then
146 // ignore it since it is a load (unless the transfer is volatile).
147 if (U.getOperandNo() == 1)
148 continue;
149
150 // If we already have seen a copy, reject the second one.
151 if (TheCopy) return false;
152
153 // If the pointer has been offset from the start of the alloca, we can't
154 // safely handle this.
155 if (IsOffset) return false;
156
157 // If the memintrinsic isn't using the alloca as the dest, reject it.
158 if (U.getOperandNo() != 0) return false;
159
160 // If the source of the memcpy/move is not constant, reject it.
161 if (isModSet(AA->getModRefInfoMask(MI->getSource())))
162 return false;
163
164 // Otherwise, the transform is safe. Remember the copy instruction.
165 TheCopy = MI;
166 }
167 }
168 return true;
169}
170
171/// isOnlyCopiedFromConstantMemory - Return true if the specified alloca is only
172/// modified by a copy from a constant memory location. If we can prove this, we
173/// can replace any uses of the alloca with uses of the memory location
174/// directly.
175static MemTransferInst *
177 AllocaInst *AI,
179 MemTransferInst *TheCopy = nullptr;
180 if (isOnlyCopiedFromConstantMemory(AA, AI, TheCopy, ToDelete))
181 return TheCopy;
182 return nullptr;
183}
184
185/// Returns true if V is dereferenceable for size of alloca.
186static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,
187 const DataLayout &DL) {
188 if (AI->isArrayAllocation())
189 return false;
190 uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType());
191 if (!AllocaSize)
192 return false;
194 APInt(64, AllocaSize), DL);
195}
196
198 AllocaInst &AI, DominatorTree &DT) {
199 // Check for array size of 1 (scalar allocation).
200 if (!AI.isArrayAllocation()) {
201 // i32 1 is the canonical array size for scalar allocations.
202 if (AI.getArraySize()->getType()->isIntegerTy(32))
203 return nullptr;
204
205 // Canonicalize it.
206 return IC.replaceOperand(AI, 0, IC.Builder.getInt32(1));
207 }
208
209 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
210 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
211 if (C->getValue().getActiveBits() <= 64) {
212 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
213 AllocaInst *New = IC.Builder.CreateAlloca(NewTy, AI.getAddressSpace(),
214 nullptr, AI.getName());
215 New->setAlignment(AI.getAlign());
216 New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
217
218 replaceAllDbgUsesWith(AI, *New, *New, DT);
219 return IC.replaceInstUsesWith(AI, New);
220 }
221 }
222
223 if (isa<UndefValue>(AI.getArraySize()))
225
226 // Ensure that the alloca array size argument has type equal to the offset
227 // size of the alloca() pointer, which, in the tyical case, is intptr_t,
228 // so that any casting is exposed early.
229 Type *PtrIdxTy = IC.getDataLayout().getIndexType(AI.getType());
230 if (AI.getArraySize()->getType() != PtrIdxTy) {
231 Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), PtrIdxTy, false);
232 return IC.replaceOperand(AI, 0, V);
233 }
234
235 return nullptr;
236}
237
238namespace {
239// If I and V are pointers in different address space, it is not allowed to
240// use replaceAllUsesWith since I and V have different types. A
241// non-target-specific transformation should not use addrspacecast on V since
242// the two address space may be disjoint depending on target.
243//
244// This class chases down uses of the old pointer until reaching the load
245// instructions, then replaces the old pointer in the load instructions with
246// the new pointer. If during the chasing it sees bitcast or GEP, it will
247// create new bitcast or GEP with the new pointer and use them in the load
248// instruction.
249class PointerReplacer {
250public:
251 PointerReplacer(InstCombinerImpl &IC, Instruction &Root, unsigned SrcAS)
252 : IC(IC), Root(Root), FromAS(SrcAS) {}
253
254 bool collectUsers();
255 void replacePointer(Value *V);
256
257private:
258 bool collectUsersRecursive(Instruction &I);
259 void replace(Instruction *I);
260 Value *getReplacement(Value *I);
261 bool isAvailable(Instruction *I) const {
262 return I == &Root || Worklist.contains(I);
263 }
264
265 bool isEqualOrValidAddrSpaceCast(const Instruction *I,
266 unsigned FromAS) const {
267 const auto *ASC = dyn_cast<AddrSpaceCastInst>(I);
268 if (!ASC)
269 return false;
270 unsigned ToAS = ASC->getDestAddressSpace();
271 return (FromAS == ToAS) || IC.isValidAddrSpaceCast(FromAS, ToAS);
272 }
273
274 SmallPtrSet<Instruction *, 32> ValuesToRevisit;
278 Instruction &Root;
279 unsigned FromAS;
280};
281} // end anonymous namespace
282
283bool PointerReplacer::collectUsers() {
284 if (!collectUsersRecursive(Root))
285 return false;
286
287 // Ensure that all outstanding (indirect) users of I
288 // are inserted into the Worklist. Return false
289 // otherwise.
290 for (auto *Inst : ValuesToRevisit)
291 if (!Worklist.contains(Inst))
292 return false;
293 return true;
294}
295
296bool PointerReplacer::collectUsersRecursive(Instruction &I) {
297 for (auto *U : I.users()) {
298 auto *Inst = cast<Instruction>(&*U);
299 if (auto *Load = dyn_cast<LoadInst>(Inst)) {
300 if (Load->isVolatile())
301 return false;
302 Worklist.insert(Load);
303 } else if (auto *PHI = dyn_cast<PHINode>(Inst)) {
304 // All incoming values must be instructions for replacability
305 if (any_of(PHI->incoming_values(),
306 [](Value *V) { return !isa<Instruction>(V); }))
307 return false;
308
309 // If at least one incoming value of the PHI is not in Worklist,
310 // store the PHI for revisiting and skip this iteration of the
311 // loop.
312 if (any_of(PHI->incoming_values(), [this](Value *V) {
313 return !isAvailable(cast<Instruction>(V));
314 })) {
315 ValuesToRevisit.insert(Inst);
316 continue;
317 }
318
319 Worklist.insert(PHI);
320 if (!collectUsersRecursive(*PHI))
321 return false;
322 } else if (auto *SI = dyn_cast<SelectInst>(Inst)) {
323 if (!isa<Instruction>(SI->getTrueValue()) ||
324 !isa<Instruction>(SI->getFalseValue()))
325 return false;
326
327 if (!isAvailable(cast<Instruction>(SI->getTrueValue())) ||
328 !isAvailable(cast<Instruction>(SI->getFalseValue()))) {
329 ValuesToRevisit.insert(Inst);
330 continue;
331 }
332 Worklist.insert(SI);
333 if (!collectUsersRecursive(*SI))
334 return false;
335 } else if (isa<GetElementPtrInst, BitCastInst>(Inst)) {
336 Worklist.insert(Inst);
337 if (!collectUsersRecursive(*Inst))
338 return false;
339 } else if (auto *MI = dyn_cast<MemTransferInst>(Inst)) {
340 if (MI->isVolatile())
341 return false;
342 Worklist.insert(Inst);
343 } else if (isEqualOrValidAddrSpaceCast(Inst, FromAS)) {
344 Worklist.insert(Inst);
345 if (!collectUsersRecursive(*Inst))
346 return false;
347 } else if (Inst->isLifetimeStartOrEnd()) {
348 continue;
349 } else {
350 // TODO: For arbitrary uses with address space mismatches, should we check
351 // if we can introduce a valid addrspacecast?
352 LLVM_DEBUG(dbgs() << "Cannot handle pointer user: " << *U << '\n');
353 return false;
354 }
355 }
356
357 return true;
358}
359
360Value *PointerReplacer::getReplacement(Value *V) { return WorkMap.lookup(V); }
361
362void PointerReplacer::replace(Instruction *I) {
363 if (getReplacement(I))
364 return;
365
366 if (auto *LT = dyn_cast<LoadInst>(I)) {
367 auto *V = getReplacement(LT->getPointerOperand());
368 assert(V && "Operand not replaced");
369 auto *NewI = new LoadInst(LT->getType(), V, "", LT->isVolatile(),
370 LT->getAlign(), LT->getOrdering(),
371 LT->getSyncScopeID());
372 NewI->takeName(LT);
373 copyMetadataForLoad(*NewI, *LT);
374
375 IC.InsertNewInstWith(NewI, LT->getIterator());
376 IC.replaceInstUsesWith(*LT, NewI);
377 WorkMap[LT] = NewI;
378 } else if (auto *PHI = dyn_cast<PHINode>(I)) {
379 Type *NewTy = getReplacement(PHI->getIncomingValue(0))->getType();
380 auto *NewPHI = PHINode::Create(NewTy, PHI->getNumIncomingValues(),
381 PHI->getName(), PHI->getIterator());
382 for (unsigned int I = 0; I < PHI->getNumIncomingValues(); ++I)
383 NewPHI->addIncoming(getReplacement(PHI->getIncomingValue(I)),
384 PHI->getIncomingBlock(I));
385 WorkMap[PHI] = NewPHI;
386 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
387 auto *V = getReplacement(GEP->getPointerOperand());
388 assert(V && "Operand not replaced");
389 SmallVector<Value *, 8> Indices(GEP->indices());
390 auto *NewI =
391 GetElementPtrInst::Create(GEP->getSourceElementType(), V, Indices);
392 IC.InsertNewInstWith(NewI, GEP->getIterator());
393 NewI->takeName(GEP);
394 NewI->setIsInBounds(GEP->isInBounds());
395 WorkMap[GEP] = NewI;
396 } else if (auto *BC = dyn_cast<BitCastInst>(I)) {
397 auto *V = getReplacement(BC->getOperand(0));
398 assert(V && "Operand not replaced");
399 auto *NewT = PointerType::get(BC->getType()->getContext(),
400 V->getType()->getPointerAddressSpace());
401 auto *NewI = new BitCastInst(V, NewT);
402 IC.InsertNewInstWith(NewI, BC->getIterator());
403 NewI->takeName(BC);
404 WorkMap[BC] = NewI;
405 } else if (auto *SI = dyn_cast<SelectInst>(I)) {
406 auto *NewSI = SelectInst::Create(
407 SI->getCondition(), getReplacement(SI->getTrueValue()),
408 getReplacement(SI->getFalseValue()), SI->getName(), nullptr, SI);
409 IC.InsertNewInstWith(NewSI, SI->getIterator());
410 NewSI->takeName(SI);
411 WorkMap[SI] = NewSI;
412 } else if (auto *MemCpy = dyn_cast<MemTransferInst>(I)) {
413 auto *DestV = MemCpy->getRawDest();
414 auto *SrcV = MemCpy->getRawSource();
415
416 if (auto *DestReplace = getReplacement(DestV))
417 DestV = DestReplace;
418 if (auto *SrcReplace = getReplacement(SrcV))
419 SrcV = SrcReplace;
420
421 IC.Builder.SetInsertPoint(MemCpy);
422 auto *NewI = IC.Builder.CreateMemTransferInst(
423 MemCpy->getIntrinsicID(), DestV, MemCpy->getDestAlign(), SrcV,
424 MemCpy->getSourceAlign(), MemCpy->getLength(), MemCpy->isVolatile());
425 AAMDNodes AAMD = MemCpy->getAAMetadata();
426 if (AAMD)
427 NewI->setAAMetadata(AAMD);
428
429 IC.eraseInstFromFunction(*MemCpy);
430 WorkMap[MemCpy] = NewI;
431 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(I)) {
432 auto *V = getReplacement(ASC->getPointerOperand());
433 assert(V && "Operand not replaced");
434 assert(isEqualOrValidAddrSpaceCast(
435 ASC, V->getType()->getPointerAddressSpace()) &&
436 "Invalid address space cast!");
437
438 if (V->getType()->getPointerAddressSpace() !=
439 ASC->getType()->getPointerAddressSpace()) {
440 auto *NewI = new AddrSpaceCastInst(V, ASC->getType(), "");
441 NewI->takeName(ASC);
442 IC.InsertNewInstWith(NewI, ASC->getIterator());
443 WorkMap[ASC] = NewI;
444 } else {
445 WorkMap[ASC] = V;
446 }
447
448 } else {
449 llvm_unreachable("should never reach here");
450 }
451}
452
453void PointerReplacer::replacePointer(Value *V) {
454#ifndef NDEBUG
455 auto *PT = cast<PointerType>(Root.getType());
456 auto *NT = cast<PointerType>(V->getType());
457 assert(PT != NT && "Invalid usage");
458#endif
459 WorkMap[&Root] = V;
460
461 for (Instruction *Workitem : Worklist)
462 replace(Workitem);
463}
464
466 if (auto *I = simplifyAllocaArraySize(*this, AI, DT))
467 return I;
468
469 if (AI.getAllocatedType()->isSized()) {
470 // Move all alloca's of zero byte objects to the entry block and merge them
471 // together. Note that we only do this for alloca's, because malloc should
472 // allocate and return a unique pointer, even for a zero byte allocation.
474 // For a zero sized alloca there is no point in doing an array allocation.
475 // This is helpful if the array size is a complicated expression not used
476 // elsewhere.
477 if (AI.isArrayAllocation())
478 return replaceOperand(AI, 0,
479 ConstantInt::get(AI.getArraySize()->getType(), 1));
480
481 // Get the first instruction in the entry block.
482 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
483 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
484 if (FirstInst != &AI) {
485 // If the entry block doesn't start with a zero-size alloca then move
486 // this one to the start of the entry block. There is no problem with
487 // dominance as the array size was forced to a constant earlier already.
488 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
489 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
491 .getKnownMinValue() != 0) {
492 AI.moveBefore(FirstInst);
493 return &AI;
494 }
495
496 // Replace this zero-sized alloca with the one at the start of the entry
497 // block after ensuring that the address will be aligned enough for both
498 // types.
499 const Align MaxAlign = std::max(EntryAI->getAlign(), AI.getAlign());
500 EntryAI->setAlignment(MaxAlign);
501 return replaceInstUsesWith(AI, EntryAI);
502 }
503 }
504 }
505
506 // Check to see if this allocation is only modified by a memcpy/memmove from
507 // a memory location whose alignment is equal to or exceeds that of the
508 // allocation. If this is the case, we can change all users to use the
509 // constant memory location instead. This is commonly produced by the CFE by
510 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
511 // is only subsequently read.
513 if (MemTransferInst *Copy = isOnlyCopiedFromConstantMemory(AA, &AI, ToDelete)) {
514 Value *TheSrc = Copy->getSource();
515 Align AllocaAlign = AI.getAlign();
516 Align SourceAlign = getOrEnforceKnownAlignment(
517 TheSrc, AllocaAlign, DL, &AI, &AC, &DT);
518 if (AllocaAlign <= SourceAlign &&
519 isDereferenceableForAllocaSize(TheSrc, &AI, DL) &&
520 !isa<Instruction>(TheSrc)) {
521 // FIXME: Can we sink instructions without violating dominance when TheSrc
522 // is an instruction instead of a constant or argument?
523 LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
524 LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
525 unsigned SrcAddrSpace = TheSrc->getType()->getPointerAddressSpace();
526 if (AI.getAddressSpace() == SrcAddrSpace) {
527 for (Instruction *Delete : ToDelete)
528 eraseInstFromFunction(*Delete);
529
530 Instruction *NewI = replaceInstUsesWith(AI, TheSrc);
532 ++NumGlobalCopies;
533 return NewI;
534 }
535
536 PointerReplacer PtrReplacer(*this, AI, SrcAddrSpace);
537 if (PtrReplacer.collectUsers()) {
538 for (Instruction *Delete : ToDelete)
539 eraseInstFromFunction(*Delete);
540
541 PtrReplacer.replacePointer(TheSrc);
542 ++NumGlobalCopies;
543 }
544 }
545 }
546
547 // At last, use the generic allocation site handler to aggressively remove
548 // unused allocas.
549 return visitAllocSite(AI);
550}
551
552// Are we allowed to form a atomic load or store of this type?
553static bool isSupportedAtomicType(Type *Ty) {
554 return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();
555}
556
557/// Helper to combine a load to a new type.
558///
559/// This just does the work of combining a load to a new type. It handles
560/// metadata, etc., and returns the new instruction. The \c NewTy should be the
561/// loaded *value* type. This will convert it to a pointer, cast the operand to
562/// that pointer type, load it, etc.
563///
564/// Note that this will create all of the instructions with whatever insert
565/// point the \c InstCombinerImpl currently is using.
567 const Twine &Suffix) {
568 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
569 "can't fold an atomic load to requested type");
570
571 LoadInst *NewLoad =
572 Builder.CreateAlignedLoad(NewTy, LI.getPointerOperand(), LI.getAlign(),
573 LI.isVolatile(), LI.getName() + Suffix);
574 NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
575 copyMetadataForLoad(*NewLoad, LI);
576 return NewLoad;
577}
578
579/// Combine a store to a new type.
580///
581/// Returns the newly created store instruction.
583 Value *V) {
584 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
585 "can't fold an atomic store of requested type");
586
587 Value *Ptr = SI.getPointerOperand();
589 SI.getAllMetadata(MD);
590
591 StoreInst *NewStore =
592 IC.Builder.CreateAlignedStore(V, Ptr, SI.getAlign(), SI.isVolatile());
593 NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
594 for (const auto &MDPair : MD) {
595 unsigned ID = MDPair.first;
596 MDNode *N = MDPair.second;
597 // Note, essentially every kind of metadata should be preserved here! This
598 // routine is supposed to clone a store instruction changing *only its
599 // type*. The only metadata it makes sense to drop is metadata which is
600 // invalidated when the pointer type changes. This should essentially
601 // never be the case in LLVM, but we explicitly switch over only known
602 // metadata to be conservatively correct. If you are adding metadata to
603 // LLVM which pertains to stores, you almost certainly want to add it
604 // here.
605 switch (ID) {
606 case LLVMContext::MD_dbg:
607 case LLVMContext::MD_DIAssignID:
608 case LLVMContext::MD_tbaa:
609 case LLVMContext::MD_prof:
610 case LLVMContext::MD_fpmath:
611 case LLVMContext::MD_tbaa_struct:
612 case LLVMContext::MD_alias_scope:
613 case LLVMContext::MD_noalias:
614 case LLVMContext::MD_nontemporal:
615 case LLVMContext::MD_mem_parallel_loop_access:
616 case LLVMContext::MD_access_group:
617 // All of these directly apply.
618 NewStore->setMetadata(ID, N);
619 break;
620 case LLVMContext::MD_invariant_load:
621 case LLVMContext::MD_nonnull:
622 case LLVMContext::MD_noundef:
623 case LLVMContext::MD_range:
624 case LLVMContext::MD_align:
625 case LLVMContext::MD_dereferenceable:
626 case LLVMContext::MD_dereferenceable_or_null:
627 // These don't apply for stores.
628 break;
629 }
630 }
631
632 return NewStore;
633}
634
635/// Combine loads to match the type of their uses' value after looking
636/// through intervening bitcasts.
637///
638/// The core idea here is that if the result of a load is used in an operation,
639/// we should load the type most conducive to that operation. For example, when
640/// loading an integer and converting that immediately to a pointer, we should
641/// instead directly load a pointer.
642///
643/// However, this routine must never change the width of a load or the number of
644/// loads as that would introduce a semantic change. This combine is expected to
645/// be a semantic no-op which just allows loads to more closely model the types
646/// of their consuming operations.
647///
648/// Currently, we also refuse to change the precise type used for an atomic load
649/// or a volatile load. This is debatable, and might be reasonable to change
650/// later. However, it is risky in case some backend or other part of LLVM is
651/// relying on the exact type loaded to select appropriate atomic operations.
653 LoadInst &Load) {
654 // FIXME: We could probably with some care handle both volatile and ordered
655 // atomic loads here but it isn't clear that this is important.
656 if (!Load.isUnordered())
657 return nullptr;
658
659 if (Load.use_empty())
660 return nullptr;
661
662 // swifterror values can't be bitcasted.
663 if (Load.getPointerOperand()->isSwiftError())
664 return nullptr;
665
666 // Fold away bit casts of the loaded value by loading the desired type.
667 // Note that we should not do this for pointer<->integer casts,
668 // because that would result in type punning.
669 if (Load.hasOneUse()) {
670 // Don't transform when the type is x86_amx, it makes the pass that lower
671 // x86_amx type happy.
672 Type *LoadTy = Load.getType();
673 if (auto *BC = dyn_cast<BitCastInst>(Load.user_back())) {
674 assert(!LoadTy->isX86_AMXTy() && "Load from x86_amx* should not happen!");
675 if (BC->getType()->isX86_AMXTy())
676 return nullptr;
677 }
678
679 if (auto *CastUser = dyn_cast<CastInst>(Load.user_back())) {
680 Type *DestTy = CastUser->getDestTy();
681 if (CastUser->isNoopCast(IC.getDataLayout()) &&
682 LoadTy->isPtrOrPtrVectorTy() == DestTy->isPtrOrPtrVectorTy() &&
683 (!Load.isAtomic() || isSupportedAtomicType(DestTy))) {
684 LoadInst *NewLoad = IC.combineLoadToNewType(Load, DestTy);
685 CastUser->replaceAllUsesWith(NewLoad);
686 IC.eraseInstFromFunction(*CastUser);
687 return &Load;
688 }
689 }
690 }
691
692 // FIXME: We should also canonicalize loads of vectors when their elements are
693 // cast to other types.
694 return nullptr;
695}
696
698 // FIXME: We could probably with some care handle both volatile and atomic
699 // stores here but it isn't clear that this is important.
700 if (!LI.isSimple())
701 return nullptr;
702
703 Type *T = LI.getType();
704 if (!T->isAggregateType())
705 return nullptr;
706
707 StringRef Name = LI.getName();
708
709 if (auto *ST = dyn_cast<StructType>(T)) {
710 // If the struct only have one element, we unpack.
711 auto NumElements = ST->getNumElements();
712 if (NumElements == 1) {
713 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ST->getTypeAtIndex(0U),
714 ".unpack");
715 NewLoad->setAAMetadata(LI.getAAMetadata());
717 PoisonValue::get(T), NewLoad, 0, Name));
718 }
719
720 // We don't want to break loads with padding here as we'd loose
721 // the knowledge that padding exists for the rest of the pipeline.
722 const DataLayout &DL = IC.getDataLayout();
723 auto *SL = DL.getStructLayout(ST);
724
725 // Don't unpack for structure with scalable vector.
726 if (SL->getSizeInBits().isScalable())
727 return nullptr;
728
729 if (SL->hasPadding())
730 return nullptr;
731
732 const auto Align = LI.getAlign();
733 auto *Addr = LI.getPointerOperand();
734 auto *IdxType = Type::getInt32Ty(T->getContext());
735 auto *Zero = ConstantInt::get(IdxType, 0);
736
738 for (unsigned i = 0; i < NumElements; i++) {
739 Value *Indices[2] = {
740 Zero,
741 ConstantInt::get(IdxType, i),
742 };
743 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, ArrayRef(Indices),
744 Name + ".elt");
745 auto *L = IC.Builder.CreateAlignedLoad(
746 ST->getElementType(i), Ptr,
747 commonAlignment(Align, SL->getElementOffset(i)), Name + ".unpack");
748 // Propagate AA metadata. It'll still be valid on the narrowed load.
749 L->setAAMetadata(LI.getAAMetadata());
750 V = IC.Builder.CreateInsertValue(V, L, i);
751 }
752
753 V->setName(Name);
754 return IC.replaceInstUsesWith(LI, V);
755 }
756
757 if (auto *AT = dyn_cast<ArrayType>(T)) {
758 auto *ET = AT->getElementType();
759 auto NumElements = AT->getNumElements();
760 if (NumElements == 1) {
761 LoadInst *NewLoad = IC.combineLoadToNewType(LI, ET, ".unpack");
762 NewLoad->setAAMetadata(LI.getAAMetadata());
764 PoisonValue::get(T), NewLoad, 0, Name));
765 }
766
767 // Bail out if the array is too large. Ideally we would like to optimize
768 // arrays of arbitrary size but this has a terrible impact on compile time.
769 // The threshold here is chosen arbitrarily, maybe needs a little bit of
770 // tuning.
771 if (NumElements > IC.MaxArraySizeForCombine)
772 return nullptr;
773
774 const DataLayout &DL = IC.getDataLayout();
775 TypeSize EltSize = DL.getTypeAllocSize(ET);
776 const auto Align = LI.getAlign();
777
778 auto *Addr = LI.getPointerOperand();
779 auto *IdxType = Type::getInt64Ty(T->getContext());
780 auto *Zero = ConstantInt::get(IdxType, 0);
781
784 for (uint64_t i = 0; i < NumElements; i++) {
785 Value *Indices[2] = {
786 Zero,
787 ConstantInt::get(IdxType, i),
788 };
789 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, ArrayRef(Indices),
790 Name + ".elt");
791 auto EltAlign = commonAlignment(Align, Offset.getKnownMinValue());
792 auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr,
793 EltAlign, Name + ".unpack");
794 L->setAAMetadata(LI.getAAMetadata());
795 V = IC.Builder.CreateInsertValue(V, L, i);
796 Offset += EltSize;
797 }
798
799 V->setName(Name);
800 return IC.replaceInstUsesWith(LI, V);
801 }
802
803 return nullptr;
804}
805
806// If we can determine that all possible objects pointed to by the provided
807// pointer value are, not only dereferenceable, but also definitively less than
808// or equal to the provided maximum size, then return true. Otherwise, return
809// false (constant global values and allocas fall into this category).
810//
811// FIXME: This should probably live in ValueTracking (or similar).
813 const DataLayout &DL) {
815 SmallVector<Value *, 4> Worklist(1, V);
816
817 do {
818 Value *P = Worklist.pop_back_val();
819 P = P->stripPointerCasts();
820
821 if (!Visited.insert(P).second)
822 continue;
823
824 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
825 Worklist.push_back(SI->getTrueValue());
826 Worklist.push_back(SI->getFalseValue());
827 continue;
828 }
829
830 if (PHINode *PN = dyn_cast<PHINode>(P)) {
831 append_range(Worklist, PN->incoming_values());
832 continue;
833 }
834
835 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
836 if (GA->isInterposable())
837 return false;
838 Worklist.push_back(GA->getAliasee());
839 continue;
840 }
841
842 // If we know how big this object is, and it is less than MaxSize, continue
843 // searching. Otherwise, return false.
844 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
845 if (!AI->getAllocatedType()->isSized())
846 return false;
847
848 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
849 if (!CS)
850 return false;
851
852 TypeSize TS = DL.getTypeAllocSize(AI->getAllocatedType());
853 if (TS.isScalable())
854 return false;
855 // Make sure that, even if the multiplication below would wrap as an
856 // uint64_t, we still do the right thing.
857 if ((CS->getValue().zext(128) * APInt(128, TS.getFixedValue()))
858 .ugt(MaxSize))
859 return false;
860 continue;
861 }
862
863 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
864 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
865 return false;
866
867 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
868 if (InitSize > MaxSize)
869 return false;
870 continue;
871 }
872
873 return false;
874 } while (!Worklist.empty());
875
876 return true;
877}
878
879// If we're indexing into an object of a known size, and the outer index is
880// not a constant, but having any value but zero would lead to undefined
881// behavior, replace it with zero.
882//
883// For example, if we have:
884// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
885// ...
886// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
887// ... = load i32* %arrayidx, align 4
888// Then we know that we can replace %x in the GEP with i64 0.
889//
890// FIXME: We could fold any GEP index to zero that would cause UB if it were
891// not zero. Currently, we only handle the first such index. Also, we could
892// also search through non-zero constant indices if we kept track of the
893// offsets those indices implied.
895 GetElementPtrInst *GEPI, Instruction *MemI,
896 unsigned &Idx) {
897 if (GEPI->getNumOperands() < 2)
898 return false;
899
900 // Find the first non-zero index of a GEP. If all indices are zero, return
901 // one past the last index.
902 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
903 unsigned I = 1;
904 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
905 Value *V = GEPI->getOperand(I);
906 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
907 if (CI->isZero())
908 continue;
909
910 break;
911 }
912
913 return I;
914 };
915
916 // Skip through initial 'zero' indices, and find the corresponding pointer
917 // type. See if the next index is not a constant.
918 Idx = FirstNZIdx(GEPI);
919 if (Idx == GEPI->getNumOperands())
920 return false;
921 if (isa<Constant>(GEPI->getOperand(Idx)))
922 return false;
923
924 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
925 Type *SourceElementType = GEPI->getSourceElementType();
926 // Size information about scalable vectors is not available, so we cannot
927 // deduce whether indexing at n is undefined behaviour or not. Bail out.
928 if (SourceElementType->isScalableTy())
929 return false;
930
931 Type *AllocTy = GetElementPtrInst::getIndexedType(SourceElementType, Ops);
932 if (!AllocTy || !AllocTy->isSized())
933 return false;
934 const DataLayout &DL = IC.getDataLayout();
935 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy).getFixedValue();
936
937 // If there are more indices after the one we might replace with a zero, make
938 // sure they're all non-negative. If any of them are negative, the overall
939 // address being computed might be before the base address determined by the
940 // first non-zero index.
941 auto IsAllNonNegative = [&]() {
942 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
943 KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI);
944 if (Known.isNonNegative())
945 continue;
946 return false;
947 }
948
949 return true;
950 };
951
952 // FIXME: If the GEP is not inbounds, and there are extra indices after the
953 // one we'll replace, those could cause the address computation to wrap
954 // (rendering the IsAllNonNegative() check below insufficient). We can do
955 // better, ignoring zero indices (and other indices we can prove small
956 // enough not to wrap).
957 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
958 return false;
959
960 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
961 // also known to be dereferenceable.
962 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
963 IsAllNonNegative();
964}
965
966// If we're indexing into an object with a variable index for the memory
967// access, but the object has only one element, we can assume that the index
968// will always be zero. If we replace the GEP, return it.
970 Instruction &MemI) {
971 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
972 unsigned Idx;
973 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
974 Instruction *NewGEPI = GEPI->clone();
975 NewGEPI->setOperand(Idx,
976 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
977 IC.InsertNewInstBefore(NewGEPI, GEPI->getIterator());
978 return NewGEPI;
979 }
980 }
981
982 return nullptr;
983}
984
986 if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))
987 return false;
988
989 auto *Ptr = SI.getPointerOperand();
990 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
991 Ptr = GEPI->getOperand(0);
992 return (isa<ConstantPointerNull>(Ptr) &&
993 !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));
994}
995
997 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
998 const Value *GEPI0 = GEPI->getOperand(0);
999 if (isa<ConstantPointerNull>(GEPI0) &&
1000 !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))
1001 return true;
1002 }
1003 if (isa<UndefValue>(Op) ||
1004 (isa<ConstantPointerNull>(Op) &&
1006 return true;
1007 return false;
1008}
1009
1011 Value *Op = LI.getOperand(0);
1013 return replaceInstUsesWith(LI, Res);
1014
1015 // Try to canonicalize the loaded type.
1016 if (Instruction *Res = combineLoadToOperationType(*this, LI))
1017 return Res;
1018
1020 // Attempt to improve the alignment.
1021 Align KnownAlign = getOrEnforceKnownAlignment(
1022 Op, DL.getPrefTypeAlign(LI.getType()), DL, &LI, &AC, &DT);
1023 if (KnownAlign > LI.getAlign())
1024 LI.setAlignment(KnownAlign);
1025 }
1026
1027 // Replace GEP indices if possible.
1028 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI))
1029 return replaceOperand(LI, 0, NewGEPI);
1030
1031 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
1032 return Res;
1033
1034 // Do really simple store-to-load forwarding and load CSE, to catch cases
1035 // where there are several consecutive memory accesses to the same location,
1036 // separated by a few arithmetic operations.
1037 bool IsLoadCSE = false;
1038 BatchAAResults BatchAA(*AA);
1039 if (Value *AvailableVal = FindAvailableLoadedValue(&LI, BatchAA, &IsLoadCSE)) {
1040 if (IsLoadCSE)
1041 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false);
1042
1043 return replaceInstUsesWith(
1044 LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),
1045 LI.getName() + ".cast"));
1046 }
1047
1048 // None of the following transforms are legal for volatile/ordered atomic
1049 // loads. Most of them do apply for unordered atomics.
1050 if (!LI.isUnordered()) return nullptr;
1051
1052 // load(gep null, ...) -> unreachable
1053 // load null/undef -> unreachable
1054 // TODO: Consider a target hook for valid address spaces for this xforms.
1057 return replaceInstUsesWith(LI, PoisonValue::get(LI.getType()));
1058 }
1059
1060 if (Op->hasOneUse()) {
1061 // Change select and PHI nodes to select values instead of addresses: this
1062 // helps alias analysis out a lot, allows many others simplifications, and
1063 // exposes redundancy in the code.
1064 //
1065 // Note that we cannot do the transformation unless we know that the
1066 // introduced loads cannot trap! Something like this is valid as long as
1067 // the condition is always false: load (select bool %C, int* null, int* %G),
1068 // but it would not be valid if we transformed it to load from null
1069 // unconditionally.
1070 //
1071 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
1072 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
1073 Align Alignment = LI.getAlign();
1074 if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(),
1075 Alignment, DL, SI) &&
1076 isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(),
1077 Alignment, DL, SI)) {
1078 LoadInst *V1 =
1079 Builder.CreateLoad(LI.getType(), SI->getOperand(1),
1080 SI->getOperand(1)->getName() + ".val");
1081 LoadInst *V2 =
1082 Builder.CreateLoad(LI.getType(), SI->getOperand(2),
1083 SI->getOperand(2)->getName() + ".val");
1084 assert(LI.isUnordered() && "implied by above");
1085 V1->setAlignment(Alignment);
1086 V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
1087 V2->setAlignment(Alignment);
1088 V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
1089 return SelectInst::Create(SI->getCondition(), V1, V2);
1090 }
1091
1092 // load (select (cond, null, P)) -> load P
1093 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
1094 !NullPointerIsDefined(SI->getFunction(),
1095 LI.getPointerAddressSpace()))
1096 return replaceOperand(LI, 0, SI->getOperand(2));
1097
1098 // load (select (cond, P, null)) -> load P
1099 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
1100 !NullPointerIsDefined(SI->getFunction(),
1101 LI.getPointerAddressSpace()))
1102 return replaceOperand(LI, 0, SI->getOperand(1));
1103 }
1104 }
1105 return nullptr;
1106}
1107
1108/// Look for extractelement/insertvalue sequence that acts like a bitcast.
1109///
1110/// \returns underlying value that was "cast", or nullptr otherwise.
1111///
1112/// For example, if we have:
1113///
1114/// %E0 = extractelement <2 x double> %U, i32 0
1115/// %V0 = insertvalue [2 x double] undef, double %E0, 0
1116/// %E1 = extractelement <2 x double> %U, i32 1
1117/// %V1 = insertvalue [2 x double] %V0, double %E1, 1
1118///
1119/// and the layout of a <2 x double> is isomorphic to a [2 x double],
1120/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
1121/// Note that %U may contain non-undef values where %V1 has undef.
1123 Value *U = nullptr;
1124 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
1125 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
1126 if (!E)
1127 return nullptr;
1128 auto *W = E->getVectorOperand();
1129 if (!U)
1130 U = W;
1131 else if (U != W)
1132 return nullptr;
1133 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
1134 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
1135 return nullptr;
1136 V = IV->getAggregateOperand();
1137 }
1138 if (!match(V, m_Undef()) || !U)
1139 return nullptr;
1140
1141 auto *UT = cast<VectorType>(U->getType());
1142 auto *VT = V->getType();
1143 // Check that types UT and VT are bitwise isomorphic.
1144 const auto &DL = IC.getDataLayout();
1145 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
1146 return nullptr;
1147 }
1148 if (auto *AT = dyn_cast<ArrayType>(VT)) {
1149 if (AT->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
1150 return nullptr;
1151 } else {
1152 auto *ST = cast<StructType>(VT);
1153 if (ST->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())
1154 return nullptr;
1155 for (const auto *EltT : ST->elements()) {
1156 if (EltT != UT->getElementType())
1157 return nullptr;
1158 }
1159 }
1160 return U;
1161}
1162
1163/// Combine stores to match the type of value being stored.
1164///
1165/// The core idea here is that the memory does not have any intrinsic type and
1166/// where we can we should match the type of a store to the type of value being
1167/// stored.
1168///
1169/// However, this routine must never change the width of a store or the number of
1170/// stores as that would introduce a semantic change. This combine is expected to
1171/// be a semantic no-op which just allows stores to more closely model the types
1172/// of their incoming values.
1173///
1174/// Currently, we also refuse to change the precise type used for an atomic or
1175/// volatile store. This is debatable, and might be reasonable to change later.
1176/// However, it is risky in case some backend or other part of LLVM is relying
1177/// on the exact type stored to select appropriate atomic operations.
1178///
1179/// \returns true if the store was successfully combined away. This indicates
1180/// the caller must erase the store instruction. We have to let the caller erase
1181/// the store instruction as otherwise there is no way to signal whether it was
1182/// combined or not: IC.EraseInstFromFunction returns a null pointer.
1184 // FIXME: We could probably with some care handle both volatile and ordered
1185 // atomic stores here but it isn't clear that this is important.
1186 if (!SI.isUnordered())
1187 return false;
1188
1189 // swifterror values can't be bitcasted.
1190 if (SI.getPointerOperand()->isSwiftError())
1191 return false;
1192
1193 Value *V = SI.getValueOperand();
1194
1195 // Fold away bit casts of the stored value by storing the original type.
1196 if (auto *BC = dyn_cast<BitCastInst>(V)) {
1197 assert(!BC->getType()->isX86_AMXTy() &&
1198 "store to x86_amx* should not happen!");
1199 V = BC->getOperand(0);
1200 // Don't transform when the type is x86_amx, it makes the pass that lower
1201 // x86_amx type happy.
1202 if (V->getType()->isX86_AMXTy())
1203 return false;
1204 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
1205 combineStoreToNewValue(IC, SI, V);
1206 return true;
1207 }
1208 }
1209
1210 if (Value *U = likeBitCastFromVector(IC, V))
1211 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
1212 combineStoreToNewValue(IC, SI, U);
1213 return true;
1214 }
1215
1216 // FIXME: We should also canonicalize stores of vectors when their elements
1217 // are cast to other types.
1218 return false;
1219}
1220
1222 // FIXME: We could probably with some care handle both volatile and atomic
1223 // stores here but it isn't clear that this is important.
1224 if (!SI.isSimple())
1225 return false;
1226
1227 Value *V = SI.getValueOperand();
1228 Type *T = V->getType();
1229
1230 if (!T->isAggregateType())
1231 return false;
1232
1233 if (auto *ST = dyn_cast<StructType>(T)) {
1234 // If the struct only have one element, we unpack.
1235 unsigned Count = ST->getNumElements();
1236 if (Count == 1) {
1237 V = IC.Builder.CreateExtractValue(V, 0);
1238 combineStoreToNewValue(IC, SI, V);
1239 return true;
1240 }
1241
1242 // We don't want to break loads with padding here as we'd loose
1243 // the knowledge that padding exists for the rest of the pipeline.
1244 const DataLayout &DL = IC.getDataLayout();
1245 auto *SL = DL.getStructLayout(ST);
1246
1247 // Don't unpack for structure with scalable vector.
1248 if (SL->getSizeInBits().isScalable())
1249 return false;
1250
1251 if (SL->hasPadding())
1252 return false;
1253
1254 const auto Align = SI.getAlign();
1255
1256 SmallString<16> EltName = V->getName();
1257 EltName += ".elt";
1258 auto *Addr = SI.getPointerOperand();
1259 SmallString<16> AddrName = Addr->getName();
1260 AddrName += ".repack";
1261
1262 auto *IdxType = Type::getInt32Ty(ST->getContext());
1263 auto *Zero = ConstantInt::get(IdxType, 0);
1264 for (unsigned i = 0; i < Count; i++) {
1265 Value *Indices[2] = {
1266 Zero,
1267 ConstantInt::get(IdxType, i),
1268 };
1269 auto *Ptr =
1270 IC.Builder.CreateInBoundsGEP(ST, Addr, ArrayRef(Indices), AddrName);
1271 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1272 auto EltAlign = commonAlignment(Align, SL->getElementOffset(i));
1273 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1274 NS->setAAMetadata(SI.getAAMetadata());
1275 }
1276
1277 return true;
1278 }
1279
1280 if (auto *AT = dyn_cast<ArrayType>(T)) {
1281 // If the array only have one element, we unpack.
1282 auto NumElements = AT->getNumElements();
1283 if (NumElements == 1) {
1284 V = IC.Builder.CreateExtractValue(V, 0);
1285 combineStoreToNewValue(IC, SI, V);
1286 return true;
1287 }
1288
1289 // Bail out if the array is too large. Ideally we would like to optimize
1290 // arrays of arbitrary size but this has a terrible impact on compile time.
1291 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1292 // tuning.
1293 if (NumElements > IC.MaxArraySizeForCombine)
1294 return false;
1295
1296 const DataLayout &DL = IC.getDataLayout();
1297 TypeSize EltSize = DL.getTypeAllocSize(AT->getElementType());
1298 const auto Align = SI.getAlign();
1299
1300 SmallString<16> EltName = V->getName();
1301 EltName += ".elt";
1302 auto *Addr = SI.getPointerOperand();
1303 SmallString<16> AddrName = Addr->getName();
1304 AddrName += ".repack";
1305
1306 auto *IdxType = Type::getInt64Ty(T->getContext());
1307 auto *Zero = ConstantInt::get(IdxType, 0);
1308
1310 for (uint64_t i = 0; i < NumElements; i++) {
1311 Value *Indices[2] = {
1312 Zero,
1313 ConstantInt::get(IdxType, i),
1314 };
1315 auto *Ptr =
1316 IC.Builder.CreateInBoundsGEP(AT, Addr, ArrayRef(Indices), AddrName);
1317 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1318 auto EltAlign = commonAlignment(Align, Offset.getKnownMinValue());
1319 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1320 NS->setAAMetadata(SI.getAAMetadata());
1321 Offset += EltSize;
1322 }
1323
1324 return true;
1325 }
1326
1327 return false;
1328}
1329
1330/// equivalentAddressValues - Test if A and B will obviously have the same
1331/// value. This includes recognizing that %t0 and %t1 will have the same
1332/// value in code like this:
1333/// %t0 = getelementptr \@a, 0, 3
1334/// store i32 0, i32* %t0
1335/// %t1 = getelementptr \@a, 0, 3
1336/// %t2 = load i32* %t1
1337///
1339 // Test if the values are trivially equivalent.
1340 if (A == B) return true;
1341
1342 // Test if the values come form identical arithmetic instructions.
1343 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1344 // its only used to compare two uses within the same basic block, which
1345 // means that they'll always either have the same value or one of them
1346 // will have an undefined value.
1347 if (isa<BinaryOperator>(A) ||
1348 isa<CastInst>(A) ||
1349 isa<PHINode>(A) ||
1350 isa<GetElementPtrInst>(A))
1351 if (Instruction *BI = dyn_cast<Instruction>(B))
1352 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1353 return true;
1354
1355 // Otherwise they may not be equivalent.
1356 return false;
1357}
1358
1360 Value *Val = SI.getOperand(0);
1361 Value *Ptr = SI.getOperand(1);
1362
1363 // Try to canonicalize the stored type.
1364 if (combineStoreToValueType(*this, SI))
1365 return eraseInstFromFunction(SI);
1366
1368 // Attempt to improve the alignment.
1369 const Align KnownAlign = getOrEnforceKnownAlignment(
1370 Ptr, DL.getPrefTypeAlign(Val->getType()), DL, &SI, &AC, &DT);
1371 if (KnownAlign > SI.getAlign())
1372 SI.setAlignment(KnownAlign);
1373 }
1374
1375 // Try to canonicalize the stored type.
1376 if (unpackStoreToAggregate(*this, SI))
1377 return eraseInstFromFunction(SI);
1378
1379 // Replace GEP indices if possible.
1380 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI))
1381 return replaceOperand(SI, 1, NewGEPI);
1382
1383 // Don't hack volatile/ordered stores.
1384 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1385 if (!SI.isUnordered()) return nullptr;
1386
1387 // If the RHS is an alloca with a single use, zapify the store, making the
1388 // alloca dead.
1389 if (Ptr->hasOneUse()) {
1390 if (isa<AllocaInst>(Ptr))
1391 return eraseInstFromFunction(SI);
1392 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1393 if (isa<AllocaInst>(GEP->getOperand(0))) {
1394 if (GEP->getOperand(0)->hasOneUse())
1395 return eraseInstFromFunction(SI);
1396 }
1397 }
1398 }
1399
1400 // If we have a store to a location which is known constant, we can conclude
1401 // that the store must be storing the constant value (else the memory
1402 // wouldn't be constant), and this must be a noop.
1404 return eraseInstFromFunction(SI);
1405
1406 // Do really simple DSE, to catch cases where there are several consecutive
1407 // stores to the same location, separated by a few arithmetic operations. This
1408 // situation often occurs with bitfield accesses.
1409 BasicBlock::iterator BBI(SI);
1410 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1411 --ScanInsts) {
1412 --BBI;
1413 // Don't count debug info directives, lest they affect codegen,
1414 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1415 if (BBI->isDebugOrPseudoInst()) {
1416 ScanInsts++;
1417 continue;
1418 }
1419
1420 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1421 // Prev store isn't volatile, and stores to the same location?
1422 if (PrevSI->isUnordered() &&
1423 equivalentAddressValues(PrevSI->getOperand(1), SI.getOperand(1)) &&
1424 PrevSI->getValueOperand()->getType() ==
1425 SI.getValueOperand()->getType()) {
1426 ++NumDeadStore;
1427 // Manually add back the original store to the worklist now, so it will
1428 // be processed after the operands of the removed store, as this may
1429 // expose additional DSE opportunities.
1430 Worklist.push(&SI);
1431 eraseInstFromFunction(*PrevSI);
1432 return nullptr;
1433 }
1434 break;
1435 }
1436
1437 // If this is a load, we have to stop. However, if the loaded value is from
1438 // the pointer we're loading and is producing the pointer we're storing,
1439 // then *this* store is dead (X = load P; store X -> P).
1440 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
1441 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1442 assert(SI.isUnordered() && "can't eliminate ordering operation");
1443 return eraseInstFromFunction(SI);
1444 }
1445
1446 // Otherwise, this is a load from some other location. Stores before it
1447 // may not be dead.
1448 break;
1449 }
1450
1451 // Don't skip over loads, throws or things that can modify memory.
1452 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
1453 break;
1454 }
1455
1456 // store X, null -> turns into 'unreachable' in SimplifyCFG
1457 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG
1458 if (canSimplifyNullStoreOrGEP(SI)) {
1459 if (!isa<PoisonValue>(Val))
1460 return replaceOperand(SI, 0, PoisonValue::get(Val->getType()));
1461 return nullptr; // Do not modify these!
1462 }
1463
1464 // This is a non-terminator unreachable marker. Don't remove it.
1465 if (isa<UndefValue>(Ptr)) {
1466 // Remove guaranteed-to-transfer instructions before the marker.
1468 return &SI;
1469
1470 // Remove all instructions after the marker and handle dead blocks this
1471 // implies.
1473 handleUnreachableFrom(SI.getNextNode(), Worklist);
1475 return nullptr;
1476 }
1477
1478 // store undef, Ptr -> noop
1479 // FIXME: This is technically incorrect because it might overwrite a poison
1480 // value. Change to PoisonValue once #52930 is resolved.
1481 if (isa<UndefValue>(Val))
1482 return eraseInstFromFunction(SI);
1483
1484 return nullptr;
1485}
1486
1487/// Try to transform:
1488/// if () { *P = v1; } else { *P = v2 }
1489/// or:
1490/// *P = v1; if () { *P = v2; }
1491/// into a phi node with a store in the successor.
1493 if (!SI.isUnordered())
1494 return false; // This code has not been audited for volatile/ordered case.
1495
1496 // Check if the successor block has exactly 2 incoming edges.
1497 BasicBlock *StoreBB = SI.getParent();
1498 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
1499 if (!DestBB->hasNPredecessors(2))
1500 return false;
1501
1502 // Capture the other block (the block that doesn't contain our store).
1503 pred_iterator PredIter = pred_begin(DestBB);
1504 if (*PredIter == StoreBB)
1505 ++PredIter;
1506 BasicBlock *OtherBB = *PredIter;
1507
1508 // Bail out if all of the relevant blocks aren't distinct. This can happen,
1509 // for example, if SI is in an infinite loop.
1510 if (StoreBB == DestBB || OtherBB == DestBB)
1511 return false;
1512
1513 // Verify that the other block ends in a branch and is not otherwise empty.
1514 BasicBlock::iterator BBI(OtherBB->getTerminator());
1515 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1516 if (!OtherBr || BBI == OtherBB->begin())
1517 return false;
1518
1519 auto OtherStoreIsMergeable = [&](StoreInst *OtherStore) -> bool {
1520 if (!OtherStore ||
1521 OtherStore->getPointerOperand() != SI.getPointerOperand())
1522 return false;
1523
1524 auto *SIVTy = SI.getValueOperand()->getType();
1525 auto *OSVTy = OtherStore->getValueOperand()->getType();
1526 return CastInst::isBitOrNoopPointerCastable(OSVTy, SIVTy, DL) &&
1527 SI.hasSameSpecialState(OtherStore);
1528 };
1529
1530 // If the other block ends in an unconditional branch, check for the 'if then
1531 // else' case. There is an instruction before the branch.
1532 StoreInst *OtherStore = nullptr;
1533 if (OtherBr->isUnconditional()) {
1534 --BBI;
1535 // Skip over debugging info and pseudo probes.
1536 while (BBI->isDebugOrPseudoInst()) {
1537 if (BBI==OtherBB->begin())
1538 return false;
1539 --BBI;
1540 }
1541 // If this isn't a store, isn't a store to the same location, or is not the
1542 // right kind of store, bail out.
1543 OtherStore = dyn_cast<StoreInst>(BBI);
1544 if (!OtherStoreIsMergeable(OtherStore))
1545 return false;
1546 } else {
1547 // Otherwise, the other block ended with a conditional branch. If one of the
1548 // destinations is StoreBB, then we have the if/then case.
1549 if (OtherBr->getSuccessor(0) != StoreBB &&
1550 OtherBr->getSuccessor(1) != StoreBB)
1551 return false;
1552
1553 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1554 // if/then triangle. See if there is a store to the same ptr as SI that
1555 // lives in OtherBB.
1556 for (;; --BBI) {
1557 // Check to see if we find the matching store.
1558 OtherStore = dyn_cast<StoreInst>(BBI);
1559 if (OtherStoreIsMergeable(OtherStore))
1560 break;
1561
1562 // If we find something that may be using or overwriting the stored
1563 // value, or if we run out of instructions, we can't do the transform.
1564 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1565 BBI->mayWriteToMemory() || BBI == OtherBB->begin())
1566 return false;
1567 }
1568
1569 // In order to eliminate the store in OtherBr, we have to make sure nothing
1570 // reads or overwrites the stored value in StoreBB.
1571 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1572 // FIXME: This should really be AA driven.
1573 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
1574 return false;
1575 }
1576 }
1577
1578 // Insert a PHI node now if we need it.
1579 Value *MergedVal = OtherStore->getValueOperand();
1580 // The debug locations of the original instructions might differ. Merge them.
1581 DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(),
1582 OtherStore->getDebugLoc());
1583 if (MergedVal != SI.getValueOperand()) {
1584 PHINode *PN =
1585 PHINode::Create(SI.getValueOperand()->getType(), 2, "storemerge");
1586 PN->addIncoming(SI.getValueOperand(), SI.getParent());
1587 Builder.SetInsertPoint(OtherStore);
1588 PN->addIncoming(Builder.CreateBitOrPointerCast(MergedVal, PN->getType()),
1589 OtherBB);
1590 MergedVal = InsertNewInstBefore(PN, DestBB->begin());
1591 PN->setDebugLoc(MergedLoc);
1592 }
1593
1594 // Advance to a place where it is safe to insert the new store and insert it.
1595 BBI = DestBB->getFirstInsertionPt();
1596 StoreInst *NewSI =
1597 new StoreInst(MergedVal, SI.getOperand(1), SI.isVolatile(), SI.getAlign(),
1598 SI.getOrdering(), SI.getSyncScopeID());
1599 InsertNewInstBefore(NewSI, BBI);
1600 NewSI->setDebugLoc(MergedLoc);
1601 NewSI->mergeDIAssignID({&SI, OtherStore});
1602
1603 // If the two stores had AA tags, merge them.
1604 AAMDNodes AATags = SI.getAAMetadata();
1605 if (AATags)
1606 NewSI->setAAMetadata(AATags.merge(OtherStore->getAAMetadata()));
1607
1608 // Nuke the old stores.
1610 eraseInstFromFunction(*OtherStore);
1611 return true;
1612}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
Rewrite undef for PHI
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
uint64_t Addr
std::string Name
Hexagon Common GEP
IRTranslator LLVM IR MI
This file provides internal interfaces used to implement the InstCombine.
static StoreInst * combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI, Value *V)
Combine a store to a new type.
static Instruction * combineLoadToOperationType(InstCombinerImpl &IC, LoadInst &Load)
Combine loads to match the type of their uses' value after looking through intervening bitcasts.
static Instruction * replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr, Instruction &MemI)
static Instruction * simplifyAllocaArraySize(InstCombinerImpl &IC, AllocaInst &AI, DominatorTree &DT)
static bool canSimplifyNullStoreOrGEP(StoreInst &SI)
static bool equivalentAddressValues(Value *A, Value *B)
equivalentAddressValues - Test if A and B will obviously have the same value.
static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC, GetElementPtrInst *GEPI, Instruction *MemI, unsigned &Idx)
static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op)
static bool isSupportedAtomicType(Type *Ty)
static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI, const DataLayout &DL)
Returns true if V is dereferenceable for size of alloca.
static Instruction * unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI)
static cl::opt< unsigned > MaxCopiedFromConstantUsers("instcombine-max-copied-from-constant-users", cl::init(300), cl::desc("Maximum users to visit in copy from constant transform"), cl::Hidden)
static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI)
Combine stores to match the type of value being stored.
static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI)
static Value * likeBitCastFromVector(InstCombinerImpl &IC, Value *V)
Look for extractelement/insertvalue sequence that acts like a bitcast.
static bool isOnlyCopiedFromConstantMemory(AAResults *AA, AllocaInst *V, MemTransferInst *&TheCopy, SmallVectorImpl< Instruction * > &ToDelete)
isOnlyCopiedFromConstantMemory - Recursively walk the uses of a (derived) pointer to an alloca.
static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize, const DataLayout &DL)
This file provides the interface for the instcombine pass implementation.
#define I(x, y, z)
Definition: MD5.cpp:58
This file implements a map that provides insertion order iteration.
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file defines the SmallString class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
static const uint32_t IV[8]
Definition: blake3_impl.h:78
ModRefInfo getModRefInfoMask(const MemoryLocation &Loc, bool IgnoreLocals=false)
Returns a bitmask that should be unconditionally applied to the ModRef info of a memory location.
Class for arbitrary precision integers.
Definition: APInt.h:76
APInt zext(unsigned width) const
Zero extend to a new width.
Definition: APInt.cpp:981
This class represents a conversion between pointers from one address space to another.
an instruction to allocate memory on the stack
Definition: Instructions.h:59
Align getAlign() const
Return the alignment of the memory that is being allocated by the instruction.
Definition: Instructions.h:132
PointerType * getType() const
Overload to return most specific pointer type.
Definition: Instructions.h:107
Type * getAllocatedType() const
Return the type that is being allocated by the instruction.
Definition: Instructions.h:125
bool isUsedWithInAlloca() const
Return true if this alloca is used as an inalloca argument to a call.
Definition: Instructions.h:147
unsigned getAddressSpace() const
Return the address space for the allocation.
Definition: Instructions.h:112
bool isArrayAllocation() const
Return true if there is an allocation size parameter to the allocation instruction that is not 1.
void setAlignment(Align Align)
Definition: Instructions.h:136
const Value * getArraySize() const
Get the number of elements allocated.
Definition: Instructions.h:103
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:430
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:409
bool hasNPredecessors(unsigned N) const
Return true if this block has exactly N predecessors.
Definition: BasicBlock.cpp:474
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:206
const Instruction * getFirstNonPHIOrDbg(bool SkipPseudoOp=true) const
Returns a pointer to the first instruction in this block that is not a PHINode or a debug intrinsic,...
Definition: BasicBlock.cpp:379
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.h:221
This class is a wrapper over an AAResults, and it is intended to be used only when there are no IR ch...
This class represents a no-op cast from one type to another.
Conditional or Unconditional Branch instruction.
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
static bool isBitOrNoopPointerCastable(Type *SrcTy, Type *DestTy, const DataLayout &DL)
Check whether a bitcast, inttoptr, or ptrtoint cast between these types is valid and a no-op.
This is the shared class of boolean and integer constants.
Definition: Constants.h:80
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:145
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
Definition: Constants.cpp:370
static DILocation * getMergedLocation(DILocation *LocA, DILocation *LocB)
When two instructions are combined into a single instruction we also need to combine the original loc...
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
Definition: DataLayout.cpp:905
TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
Definition: DataLayout.h:504
Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
Definition: DataLayout.cpp:874
A debug info location.
Definition: DebugLoc.h:33
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
const BasicBlock & getEntryBlock() const
Definition: Function.h:787
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
Definition: Instructions.h:973
bool isInBounds() const
Determine whether the GEP has the inbounds flag.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr, BasicBlock::iterator InsertBefore)
static Type * getIndexedType(Type *Ty, ArrayRef< Value * > IdxList)
Returns the result type of a getelementptr with the given source element type and indexes.
Type * getSourceElementType() const
AllocaInst * CreateAlloca(Type *Ty, unsigned AddrSpace, Value *ArraySize=nullptr, const Twine &Name="")
Definition: IRBuilder.h:1773
Value * CreateInsertValue(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2523
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1807
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition: IRBuilder.h:2516
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:1876
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:486
Value * CreateBitOrPointerCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2205
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1790
Value * CreateIntCast(Value *V, Type *DestTy, bool isSigned, const Twine &Name="")
Definition: IRBuilder.h:2196
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
StoreInst * CreateAlignedStore(Value *Val, Value *Ptr, MaybeAlign Align, bool isVolatile=false)
Definition: IRBuilder.h:1826
void handleUnreachableFrom(Instruction *I, SmallVectorImpl< BasicBlock * > &Worklist)
Instruction * visitLoadInst(LoadInst &LI)
void handlePotentiallyDeadBlocks(SmallVectorImpl< BasicBlock * > &Worklist)
Instruction * eraseInstFromFunction(Instruction &I) override
Combiner aware instruction erasure.
Instruction * visitStoreInst(StoreInst &SI)
bool mergeStoreIntoSuccessor(StoreInst &SI)
Try to transform: if () { *P = v1; } else { *P = v2 } or: *P = v1; if () { *P = v2; } into a phi node...
void CreateNonTerminatorUnreachable(Instruction *InsertAt)
Create and insert the idiom we use to indicate a block is unreachable without having to rewrite the C...
bool removeInstructionsBeforeUnreachable(Instruction &I)
LoadInst * combineLoadToNewType(LoadInst &LI, Type *NewTy, const Twine &Suffix="")
Helper to combine a load to a new type.
Instruction * visitAllocSite(Instruction &FI)
Instruction * visitAllocaInst(AllocaInst &AI)
SimplifyQuery SQ
Definition: InstCombiner.h:76
const DataLayout & getDataLayout() const
Definition: InstCombiner.h:341
Instruction * InsertNewInstBefore(Instruction *New, BasicBlock::iterator Old)
Inserts an instruction New before instruction Old.
Definition: InstCombiner.h:366
AAResults * AA
Definition: InstCombiner.h:69
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
Definition: InstCombiner.h:386
uint64_t MaxArraySizeForCombine
Maximum size of array considered when transforming.
Definition: InstCombiner.h:55
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Definition: InstCombiner.h:64
const DataLayout & DL
Definition: InstCombiner.h:75
AssumptionCache & AC
Definition: InstCombiner.h:72
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
Definition: InstCombiner.h:410
DominatorTree & DT
Definition: InstCombiner.h:74
void computeKnownBits(const Value *V, KnownBits &Known, unsigned Depth, const Instruction *CxtI) const
Definition: InstCombiner.h:431
BuilderTy & Builder
Definition: InstCombiner.h:60
void push(Instruction *I)
Push the instruction onto the worklist stack.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following:
void mergeDIAssignID(ArrayRef< const Instruction * > SourceInstructions)
Merge the DIAssignID metadata from this instruction and those attached to instructions in SourceInstr...
Definition: DebugInfo.cpp:936
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Definition: Instruction.h:454
void setAAMetadata(const AAMDNodes &N)
Sets the AA metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1720
const BasicBlock * getParent() const
Definition: Instruction.h:152
const Function * getFunction() const
Return the function this instruction belongs to.
Definition: Instruction.cpp:87
BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
Definition: Metadata.cpp:1635
AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
Definition: Metadata.cpp:1706
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:451
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
An instruction for reading from memory.
Definition: Instructions.h:184
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:286
void setAlignment(Align Align)
Definition: Instructions.h:240
Value * getPointerOperand()
Definition: Instructions.h:280
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this load instruction.
Definition: Instructions.h:266
bool isSimple() const
Definition: Instructions.h:272
Align getAlign() const
Return the alignment of the access that is being performed.
Definition: Instructions.h:236
Metadata node.
Definition: Metadata.h:1067
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
This class wraps the llvm.memcpy/memmove intrinsics.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr, BasicBlock::iterator InsertBefore)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
PointerIntPair - This class implements a pair of a pointer and small integer.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1827
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr, BasicBlock::iterator InsertBefore, Instruction *MDFrom=nullptr)
size_type size() const
Definition: SmallPtrSet.h:94
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:94
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:586
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:317
Value * getValueOperand()
Definition: Instructions.h:414
void setAtomic(AtomicOrdering Ordering, SyncScope::ID SSID=SyncScope::System)
Sets the ordering constraint and the synchronization scope ID of this store instruction.
Definition: Instructions.h:400
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
static constexpr TypeSize getZero()
Definition: TypeSize.h:348
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
bool isSized(SmallPtrSetImpl< Type * > *Visited=nullptr) const
Return true if it makes sense to take the size of this type.
Definition: Type.h:302
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:185
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Definition: Type.h:262
bool isX86_AMXTy() const
Return true if this is X86 AMX.
Definition: Type.h:204
bool isScalableTy() const
Return true if this is a type whose size is a known multiple of vscale.
bool isIntOrPtrTy() const
Return true if this is an integer type or a pointer type.
Definition: Type.h:243
static IntegerType * getInt32Ty(LLVMContext &C)
static IntegerType * getInt64Ty(LLVMContext &C)
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
Value * getOperand(unsigned i) const
Definition: User.h:169
unsigned getNumOperands() const
Definition: User.h:191
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< use_iterator > uses()
Definition: Value.h:376
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
constexpr ScalarTy getFixedValue() const
Definition: TypeSize.h:199
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition: TypeSize.h:171
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition: TypeSize.h:168
self_iterator getIterator()
Definition: ilist_node.h:109
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:152
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:456
bool isDereferenceableAndAlignedPointer(const Value *V, Type *Ty, Align Alignment, const DataLayout &DL, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested.
Definition: Loads.cpp:201
void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
Definition: Local.cpp:3363
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition: STLExtras.h:2073
Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, BatchAAResults *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
Definition: Loads.cpp:455
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
pred_iterator pred_begin(BasicBlock *BB)
Definition: CFG.h:110
Align getOrEnforceKnownAlignment(Value *V, MaybeAlign PrefAlign, const DataLayout &DL, const Instruction *CxtI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr)
Try to ensure that the alignment of V is at least PrefAlign bytes.
Definition: Local.cpp:1543
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
bool NullPointerIsDefined(const Function *F, unsigned AS=0)
Check whether null pointer dereferencing is considered undefined behavior for a given function or an ...
Definition: Function.cpp:2058
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Definition: Local.cpp:2711
Value * simplifyLoadInst(LoadInst *LI, Value *PtrOp, const SimplifyQuery &Q)
Given a load instruction and its pointer operand, fold the result or return null.
void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition: Local.cpp:3341
cl::opt< bool > EnableInferAlignmentPass
void replace(Container &Cont, typename Container::iterator ContIt, typename Container::iterator ContEnd, RandomAccessIterator ValIt, RandomAccessIterator ValEnd)
Given a sequence container Cont, replace the range [ContIt, ContEnd) with the range [ValIt,...
Definition: STLExtras.h:2088
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:212
bool isSafeToLoadUnconditionally(Value *V, Align Alignment, APInt &Size, const DataLayout &DL, Instruction *ScanFrom=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if we know that executing a load from this value cannot trap.
Definition: Loads.cpp:352
#define N
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:760
AAMDNodes merge(const AAMDNodes &Other) const
Given two sets of AAMDNodes applying to potentially different locations, determine the best AAMDNodes...
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
bool isNonNegative() const
Returns true if this value is known to be non-negative.
Definition: KnownBits.h:104
SimplifyQuery getWithInstruction(const Instruction *I) const
Definition: SimplifyQuery.h:96