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