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