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