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/SmallString.h"
15#include "llvm/ADT/Statistic.h"
16#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/Analysis/Loads.h"
18#include "llvm/Analysis/VectorUtils.h"
19#include "llvm/IR/DataLayout.h"
20#include "llvm/IR/IntrinsicInst.h"
21#include "llvm/IR/LLVMContext.h"
22#include "llvm/IR/PatternMatch.h"
23#include "llvm/Transforms/InstCombine/InstCombiner.h"
24#include "llvm/Transforms/Utils/Local.h"
25using namespace llvm;
26using namespace PatternMatch;
27
28#define DEBUG_TYPE "instcombine"
29
30namespace llvm {
31extern cl::opt<bool> ProfcheckDisableMetadataFixes;
32}
33
34STATISTIC(NumDeadStore, "Number of dead stores eliminated");
35STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
36
37static cl::opt<unsigned> MaxCopiedFromConstantUsers(
38 "instcombine-max-copied-from-constant-users", cl::init(Val: 300),
39 cl::desc("Maximum users to visit in copy from constant transform"),
40 cl::Hidden);
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
50isOnlyCopiedFromConstantMemory(AAResults *AA, AllocaInst *V,
51 MemTransferInst *&TheCopy,
52 SmallVectorImpl<Instruction *> &ToDelete) {
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>;
58 SmallVector<ValueAndIsOffset, 32> Worklist;
59 SmallPtrSet<ValueAndIsOffset, 32> Visited;
60 Worklist.emplace_back(Args&: V, Args: false);
61 while (!Worklist.empty()) {
62 ValueAndIsOffset Elem = Worklist.pop_back_val();
63 if (!Visited.insert(Ptr: 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>(Val: U.getUser());
71
72 if (auto *LI = dyn_cast<LoadInst>(Val: I)) {
73 // Ignore non-volatile loads, they are always ok.
74 if (!LI->isSimple()) return false;
75 continue;
76 }
77
78 if (isa<PHINode, SelectInst>(Val: I)) {
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(Args&: I, Args: true);
83 continue;
84 }
85 if (isa<BitCastInst, AddrSpaceCastInst>(Val: I)) {
86 // If uses of the bitcast are ok, we are ok.
87 Worklist.emplace_back(Args&: I, Args: IsOffset);
88 continue;
89 }
90 if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: 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(Args&: I, Args: IsOffset || !GEP->hasAllZeroIndices());
94 continue;
95 }
96
97 if (auto *Call = dyn_cast<CallBase>(Val: 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: &U))
101 continue;
102
103 unsigned DataOpNo = Call->getDataOperandNo(U: &U);
104 bool IsArgOperand = Call->isArgOperand(U: &U);
105
106 // Inalloca arguments are clobbered by the call.
107 if (IsArgOperand && Call->isInAllocaArgument(ArgNo: 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(OpNo: DataOpNo);
114 if (NoCapture &&
115 (Call->onlyReadsMemory() || Call->onlyReadsMemory(OpNo: 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(Elt: I);
123 continue;
124 }
125
126 // If this is isn't our memcpy/memmove, reject it as something we can't
127 // handle.
128 MemTransferInst *MI = dyn_cast<MemTransferInst>(Val: I);
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(MRI: AA->getModRefInfoMask(P: 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 *
167isOnlyCopiedFromConstantMemory(AAResults *AA,
168 AllocaInst *AI,
169 SmallVectorImpl<Instruction *> &ToDelete) {
170 MemTransferInst *TheCopy = nullptr;
171 if (isOnlyCopiedFromConstantMemory(AA, V: 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;
182 return isDereferenceableAndAlignedPointer(V, Alignment: AI->getAlign(),
183 Size: APInt(64, *AllocaSize), Q: DL);
184}
185
186static Instruction *simplifyAllocaArraySize(InstCombinerImpl &IC,
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(BitWidth: 32))
192 return nullptr;
193
194 // Canonicalize it.
195 return IC.replaceOperand(I&: AI, OpNum: 0, V: IC.Builder.getInt32(C: 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>(Val: AI.getArraySize())) {
200 if (C->getValue().getActiveBits() <= 64) {
201 Type *NewTy = ArrayType::get(ElementType: AI.getAllocatedType(), NumElements: C->getZExtValue());
202 AllocaInst *New = IC.Builder.CreateAlloca(Ty: NewTy, AddrSpace: AI.getAddressSpace(),
203 ArraySize: nullptr, Name: AI.getName());
204 New->setAlignment(AI.getAlign());
205 New->setUsedWithInAlloca(AI.isUsedWithInAlloca());
206
207 replaceAllDbgUsesWith(From&: AI, To&: *New, DomPoint&: *New, DT);
208 return IC.replaceInstUsesWith(I&: AI, V: New);
209 }
210 }
211
212 if (isa<UndefValue>(Val: AI.getArraySize()))
213 return IC.replaceInstUsesWith(I&: AI, V: PoisonValue::get(T: 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(PtrTy: AI.getType());
219 if (AI.getArraySize()->getType() != PtrIdxTy) {
220 Value *V = IC.Builder.CreateIntCast(V: AI.getArraySize(), DestTy: PtrIdxTy, isSigned: false);
221 return IC.replaceOperand(I&: AI, OpNum: 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(Val: V); }
249 bool isAvailable(Instruction *I) const {
250 return I == &Root || UsersToReplace.contains(key: I);
251 }
252
253 bool isEqualOrValidAddrSpaceCast(const Instruction *I,
254 unsigned FromAS) const {
255 const auto *ASC = dyn_cast<AddrSpaceCastInst>(Val: 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>(Val: U))
277 if (!isAvailable(I) && !ValuesToRevisit.contains(key: I))
278 Worklist.emplace_back(Args&: I);
279 };
280
281 auto TryPushInstOperand = [&](Instruction *InstOp) {
282 if (!UsersToReplace.contains(key: InstOp)) {
283 if (!ValuesToRevisit.insert(X: InstOp))
284 return false;
285 Worklist.emplace_back(Args&: 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>(Val: Inst)) {
294 if (Load->isVolatile())
295 return false;
296 UsersToReplace.insert(X: Load);
297 } else if (auto *PHI = dyn_cast<PHINode>(Val: 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(Range: PHI->incoming_values(),
302 P: [](Value *V) { return isa<Instruction>(Val: V); });
303 if (IsReplaceable && all_of(Range: PHI->incoming_values(), P: [&](Value *V) {
304 return isAvailable(I: cast<Instruction>(Val: V));
305 })) {
306 UsersToReplace.insert(X: 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(X: PHI))
315 return false;
316
317 // Push PHI back into the stack, followed by unavailable
318 // incoming values.
319 Worklist.emplace_back(Args&: PHI);
320 for (unsigned Idx = 0; Idx < PHI->getNumIncomingValues(); ++Idx) {
321 if (!TryPushInstOperand(cast<Instruction>(Val: PHI->getIncomingValue(i: Idx))))
322 return false;
323 }
324 } else if (auto *SI = dyn_cast<SelectInst>(Val: Inst)) {
325 auto *TrueInst = dyn_cast<Instruction>(Val: SI->getTrueValue());
326 auto *FalseInst = dyn_cast<Instruction>(Val: SI->getFalseValue());
327 if (!TrueInst || !FalseInst)
328 return false;
329
330 if (isAvailable(I: TrueInst) && isAvailable(I: FalseInst)) {
331 UsersToReplace.insert(X: 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(Args&: SI);
339 if (!TryPushInstOperand(TrueInst) || !TryPushInstOperand(FalseInst))
340 return false;
341 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: Inst)) {
342 auto *PtrOp = dyn_cast<Instruction>(Val: GEP->getPointerOperand());
343 if (!PtrOp)
344 return false;
345 if (isAvailable(I: PtrOp)) {
346 UsersToReplace.insert(X: GEP);
347 PushUsersToWorklist(GEP);
348 continue;
349 }
350
351 Worklist.emplace_back(Args&: GEP);
352 if (!TryPushInstOperand(PtrOp))
353 return false;
354 } else if (auto *MI = dyn_cast<MemTransferInst>(Val: Inst)) {
355 if (MI->isVolatile())
356 return false;
357 UsersToReplace.insert(X: Inst);
358 } else if (isEqualOrValidAddrSpaceCast(I: Inst, FromAS)) {
359 UsersToReplace.insert(X: 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(Elt: &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(Ptr: I).second) {
390 for (auto *U : I->users()) {
391 auto *UserInst = cast<Instruction>(Val: U);
392 if (UsersToReplace.contains(key: UserInst) && !Visited.contains(Ptr: UserInst))
393 Worklist.push_back(Elt: UserInst);
394 }
395 // Otherwise, users of I have already been pushed into
396 // the PostOrderWorklist. Push I as well.
397 } else {
398 PostOrderWorklist.insert(X: I);
399 Worklist.pop_back();
400 }
401 }
402
403 // Replace pointers in reverse-postorder.
404 for (Instruction *I : reverse(C&: PostOrderWorklist))
405 replace(I);
406}
407
408void PointerReplacer::replace(Instruction *I) {
409 if (getReplacement(V: I))
410 return;
411
412 if (auto *LT = dyn_cast<LoadInst>(Val: I)) {
413 auto *V = getReplacement(V: LT->getPointerOperand());
414 assert(V && "Operand not replaced");
415 auto *NewI = new LoadInst(LT->getType(), V, "", LT->getProperties());
416 NewI->takeName(V: LT);
417 NewI->copyMetadata(SrcInst: *LT);
418
419 IC.InsertNewInstWith(New: NewI, Old: LT->getIterator());
420 IC.replaceInstUsesWith(I&: *LT, V: 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>(Val: I)) {
426 Value *FirstIncoming = PHI->getIncomingValue(i: 0);
427 Value *V = WorkMap.lookup(Val: 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(Val: PHI->getIncomingValue(i: I));
432 PHI->setIncomingValue(i: I, V: V ? V : PHI->getIncomingValue(i: I));
433 }
434 WorkMap[PHI] = PHI;
435 return;
436 }
437
438 auto *NewPHI = PHINode::Create(Ty: NewType, NumReservedValues: PHI->getNumIncomingValues(), NameStr: "");
439 IC.InsertNewInstWith(New: NewPHI, Old: PHI->getIterator());
440 NewPHI->takeName(V: PHI);
441 NewPHI->copyMetadata(SrcInst: *PHI);
442 WorkMap[PHI] = NewPHI;
443 for (auto [IncomingValue, IncomingBlock] :
444 zip_equal(t: PHI->incoming_values(), u: PHI->blocks())) {
445 Value *V = WorkMap.lookup(Val: IncomingValue);
446 assert(V && V->getType() == NewType &&
447 "Type-changing PHI incoming value was not replaced");
448 NewPHI->addIncoming(V, BB: IncomingBlock);
449 }
450 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(Val: I)) {
451 auto *V = getReplacement(V: GEP->getPointerOperand());
452 assert(V && "Operand not replaced");
453 SmallVector<Value *, 8> Indices(GEP->indices());
454 auto *NewI =
455 GetElementPtrInst::Create(PointeeType: GEP->getSourceElementType(), Ptr: V, IdxList: Indices);
456 IC.InsertNewInstWith(New: NewI, Old: GEP->getIterator());
457 NewI->takeName(V: GEP);
458 NewI->setNoWrapFlags(GEP->getNoWrapFlags());
459 WorkMap[GEP] = NewI;
460 } else if (auto *SI = dyn_cast<SelectInst>(Val: I)) {
461 Value *TrueValue = SI->getTrueValue();
462 Value *FalseValue = SI->getFalseValue();
463 if (Value *Replacement = getReplacement(V: TrueValue))
464 TrueValue = Replacement;
465 if (Value *Replacement = getReplacement(V: FalseValue))
466 FalseValue = Replacement;
467 auto *NewSI = SelectInst::Create(C: SI->getCondition(), S1: TrueValue, S2: FalseValue,
468 NameStr: SI->getName(), InsertBefore: nullptr, MDFrom: SI);
469 IC.InsertNewInstWith(New: NewSI, Old: SI->getIterator());
470 NewSI->takeName(V: SI);
471 WorkMap[SI] = NewSI;
472 } else if (auto *MemCpy = dyn_cast<MemTransferInst>(Val: I)) {
473 auto *DestV = MemCpy->getRawDest();
474 auto *SrcV = MemCpy->getRawSource();
475
476 if (auto *DestReplace = getReplacement(V: DestV))
477 DestV = DestReplace;
478 if (auto *SrcReplace = getReplacement(V: SrcV))
479 SrcV = SrcReplace;
480
481 IC.Builder.SetInsertPoint(MemCpy);
482 auto *NewI = IC.Builder.CreateMemTransferInst(
483 IntrID: MemCpy->getIntrinsicID(), Dst: DestV, DstAlign: MemCpy->getDestAlign(), Src: SrcV,
484 SrcAlign: MemCpy->getSourceAlign(), Size: MemCpy->getLength(), isVolatile: MemCpy->isVolatile());
485 AAMDNodes AAMD = MemCpy->getAAMetadata();
486 if (AAMD)
487 NewI->setAAMetadata(AAMD);
488
489 IC.eraseInstFromFunction(I&: *MemCpy);
490 WorkMap[MemCpy] = NewI;
491 } else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(Val: I)) {
492 auto *V = getReplacement(V: 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(V: ASC);
502 IC.InsertNewInstWith(New: NewI, Old: 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
513Instruction *InstCombinerImpl::visitAllocaInst(AllocaInst &AI) {
514 if (auto *I = simplifyAllocaArraySize(IC&: *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(I&: AI, OpNum: 0,
527 V: ConstantInt::get(Ty: AI.getArraySize()->getType(), V: 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>(Val&: FirstInst);
537 std::optional<TypeSize> EntryAISize =
538 EntryAI ? EntryAI->getAllocationSize(DL) : std::nullopt;
539 if (!EntryAISize || !EntryAISize->isZero()) {
540 AI.moveBefore(InsertPos: 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(a: EntryAI->getAlign(), b: AI.getAlign());
548 EntryAI->setAlignment(MaxAlign);
549 return replaceInstUsesWith(I&: AI, V: 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.
559 SmallVector<Instruction *, 4> ToDelete;
560 if (MemTransferInst *Copy = isOnlyCopiedFromConstantMemory(AA, AI: &AI, ToDelete)) {
561 Value *TheSrc = Copy->getSource();
562 Align AllocaAlign = AI.getAlign();
563 Align SourceAlign = getOrEnforceKnownAlignment(
564 V: TheSrc, PrefAlign: AllocaAlign, DL, CxtI: &AI, AC: &AC, DT: &DT);
565 if (AllocaAlign <= SourceAlign &&
566 isDereferenceableForAllocaSize(V: TheSrc, AI: &AI, DL) &&
567 !isa<Instruction>(Val: 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(I&: *Delete);
576
577 Instruction *NewI = replaceInstUsesWith(I&: AI, V: TheSrc);
578 eraseInstFromFunction(I&: *Copy);
579 ++NumGlobalCopies;
580 return NewI;
581 }
582
583 PointerReplacer PtrReplacer(*this, AI, SrcAddrSpace);
584 if (PtrReplacer.collectUsers()) {
585 for (Instruction *Delete : ToDelete)
586 eraseInstFromFunction(I&: *Delete);
587
588 PtrReplacer.replacePointer(V: 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(FI&: 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.
613LoadInst *InstCombinerImpl::combineLoadToNewType(LoadInst &LI, Type *NewTy,
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 Ty: NewTy, Ptr: LI.getPointerOperand(), Props: LI.getProperties(), Name: LI.getName() + Suffix);
620 copyMetadataForLoad(Dest&: *NewLoad, Source: LI);
621 return NewLoad;
622}
623
624/// Combine a store to a new type.
625///
626/// Returns the newly created store instruction.
627static StoreInst *combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI,
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();
633 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
634 SI.getAllMetadata(MDs&: MD);
635
636 StoreInst *NewStore = IC.Builder.CreateStore(Val: V, Ptr, Props: 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(KindID: ID, Node: 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.
695static Instruction *combineLoadToOperationType(InstCombinerImpl &IC,
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>(Val: 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>(Val: Load.user_back())) {
726 Type *DestTy = CastUser->getDestTy();
727 if (CastUser->isNoopCast(DL: IC.getDataLayout()) &&
728 LoadTy->isPtrOrPtrVectorTy() == DestTy->isPtrOrPtrVectorTy() &&
729 (!Load.isAtomic() || isSupportedAtomicType(Ty: DestTy))) {
730 LoadInst *NewLoad = IC.combineLoadToNewType(LI&: Load, NewTy: DestTy);
731 CastUser->replaceAllUsesWith(V: NewLoad);
732 IC.eraseInstFromFunction(I&: *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
743static Instruction *unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI) {
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>(Val: 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, NewTy: ST->getTypeAtIndex(N: 0U),
760 Suffix: ".unpack");
761 NewLoad->setAAMetadata(LI.getAAMetadata());
762 // Copy invariant metadata from parent load.
763 NewLoad->copyMetadata(SrcInst: LI, WL: LLVMContext::MD_invariant_load);
764 return IC.replaceInstUsesWith(I&: LI, V: IC.Builder.CreateInsertValue(
765 Agg: PoisonValue::get(T), Val: NewLoad, Idxs: 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(Ty: 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(PtrTy: Addr->getType());
779
780 Value *V = PoisonValue::get(T);
781 for (unsigned i = 0; i < NumElements; i++) {
782 auto *Ptr = IC.Builder.CreateInBoundsPtrAdd(
783 Ptr: Addr, Offset: IC.Builder.CreateTypeSize(Ty: IdxType, Size: SL->getElementOffset(Idx: i)),
784 Name: Name + ".elt");
785 auto *L = IC.Builder.CreateAlignedLoad(
786 Ty: ST->getElementType(N: i), Ptr,
787 Align: commonAlignment(A: Align, Offset: SL->getElementOffset(Idx: i).getKnownMinValue()),
788 Name: 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(SrcInst: LI, WL: LLVMContext::MD_invariant_load);
793 V = IC.Builder.CreateInsertValue(Agg: V, Val: L, Idxs: i);
794 }
795
796 V->setName(Name);
797 return IC.replaceInstUsesWith(I&: LI, V);
798 }
799
800 if (auto *AT = dyn_cast<ArrayType>(Val: T)) {
801 auto *ET = AT->getElementType();
802 auto NumElements = AT->getNumElements();
803 if (NumElements == 1) {
804 LoadInst *NewLoad = IC.combineLoadToNewType(LI, NewTy: ET, Suffix: ".unpack");
805 NewLoad->setAAMetadata(LI.getAAMetadata());
806 return IC.replaceInstUsesWith(I&: LI, V: IC.Builder.CreateInsertValue(
807 Agg: PoisonValue::get(T), Val: NewLoad, Idxs: 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(Ty: ET);
819 const auto Align = LI.getAlign();
820
821 auto *Addr = LI.getPointerOperand();
822 auto *IdxType = Type::getInt64Ty(C&: T->getContext());
823 auto *Zero = ConstantInt::get(Ty: IdxType, V: 0);
824
825 Value *V = PoisonValue::get(T);
826 TypeSize Offset = TypeSize::getZero();
827 for (uint64_t i = 0; i < NumElements; i++) {
828 Value *Indices[2] = {
829 Zero,
830 ConstantInt::get(Ty: IdxType, V: i),
831 };
832 auto *Ptr = IC.Builder.CreateInBoundsGEP(Ty: AT, Ptr: Addr, IdxList: ArrayRef(Indices),
833 Name: Name + ".elt");
834 auto EltAlign = commonAlignment(A: Align, Offset: Offset.getKnownMinValue());
835 auto *L = IC.Builder.CreateAlignedLoad(Ty: AT->getElementType(), Ptr,
836 Align: EltAlign, Name: Name + ".unpack");
837 L->setAAMetadata(LI.getAAMetadata());
838 V = IC.Builder.CreateInsertValue(Agg: V, Val: L, Idxs: i);
839 Offset += EltSize;
840 }
841
842 V->setName(Name);
843 return IC.replaceInstUsesWith(I&: 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).
855static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
856 const DataLayout &DL) {
857 SmallPtrSet<Value *, 4> Visited;
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(Ptr: P).second)
865 continue;
866
867 if (SelectInst *SI = dyn_cast<SelectInst>(Val: P)) {
868 Worklist.push_back(Elt: SI->getTrueValue());
869 Worklist.push_back(Elt: SI->getFalseValue());
870 continue;
871 }
872
873 if (PHINode *PN = dyn_cast<PHINode>(Val: P)) {
874 append_range(C&: Worklist, R: PN->incoming_values());
875 continue;
876 }
877
878 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(Val: P)) {
879 if (GA->isInterposable())
880 return false;
881 Worklist.push_back(Elt: 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>(Val: 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
895 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Val: P)) {
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.
926static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC,
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_nocapture: I);
938 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Val: 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>(Val: GEPI->getOperand(i_nocapture: 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(Ty: SourceElementType, IdxList: Ops);
964 if (!AllocTy || !AllocTy->isSized())
965 return false;
966 const DataLayout &DL = IC.getDataLayout();
967 uint64_t TyAllocSize = DL.getTypeAllocSize(Ty: 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(V: GEPI->getOperand(i_nocapture: i), CxtI: 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(V: GEPI->getOperand(i_nocapture: 0), MaxSize: 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.
1001static Instruction *replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr,
1002 Instruction &MemI) {
1003 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Val: Ptr)) {
1004 unsigned Idx;
1005 if (canReplaceGEPIdxWithZero(IC, GEPI, MemI: &MemI, Idx)) {
1006 Instruction *NewGEPI = GEPI->clone();
1007 NewGEPI->setOperand(i: Idx,
1008 Val: ConstantInt::get(Ty: GEPI->getOperand(i_nocapture: Idx)->getType(), V: 0));
1009 IC.InsertNewInstBefore(New: NewGEPI, Old: 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() &&
1014 isGuaranteedToTransferExecutionToSuccessor(Begin: GEPI->getIterator(),
1015 End: MemI.getIterator())) {
1016 IC.replaceInstUsesWith(I&: *GEPI, V: NewGEPI);
1017 IC.eraseInstFromFunction(I&: *GEPI);
1018 }
1019 return NewGEPI;
1020 }
1021 }
1022
1023 return nullptr;
1024}
1025
1026static bool canSimplifyNullStoreOrGEP(StoreInst &SI) {
1027 if (NullPointerIsDefined(F: SI.getFunction(), AS: SI.getPointerAddressSpace()))
1028 return false;
1029
1030 auto *Ptr = SI.getPointerOperand();
1031 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Val: Ptr))
1032 Ptr = GEPI->getOperand(i_nocapture: 0);
1033 return (isa<ConstantPointerNull>(Val: Ptr) &&
1034 !NullPointerIsDefined(F: SI.getFunction(), AS: SI.getPointerAddressSpace()));
1035}
1036
1037static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
1038 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Val: Op)) {
1039 const Value *GEPI0 = GEPI->getOperand(i_nocapture: 0);
1040 if (isa<ConstantPointerNull>(Val: GEPI0) &&
1041 !NullPointerIsDefined(F: LI.getFunction(), AS: GEPI->getPointerAddressSpace()))
1042 return true;
1043 }
1044 if (isa<UndefValue>(Val: Op) ||
1045 (isa<ConstantPointerNull>(Val: Op) &&
1046 !NullPointerIsDefined(F: LI.getFunction(), AS: LI.getPointerAddressSpace())))
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>(Val: V)) {
1055 if (isa<ConstantPointerNull>(Val: Sel->getOperand(i_nocapture: 1)))
1056 return Sel->getOperand(i_nocapture: 2);
1057
1058 if (isa<ConstantPointerNull>(Val: Sel->getOperand(i_nocapture: 2)))
1059 return Sel->getOperand(i_nocapture: 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>(Val: V)) {
1070 if (HasDereferenceable || GEP->isInBounds()) {
1071 if (auto *Res = simplifyNonNullOperand(V: GEP->getPointerOperand(),
1072 HasDereferenceable, Depth: Depth + 1)) {
1073 replaceOperand(I&: *GEP, OpNum: 0, V: Res);
1074 addToWorklist(I: GEP);
1075 return nullptr;
1076 }
1077 }
1078 }
1079
1080 if (auto *PHI = dyn_cast<PHINode>(Val: 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(V: U.get(), HasDereferenceable,
1085 Depth: RecursionLimit)) {
1086 replaceUse(U, NewValue: Res);
1087 Changed = true;
1088 }
1089 }
1090 if (Changed)
1091 addToWorklist(I: PHI);
1092 return nullptr;
1093 }
1094
1095 return nullptr;
1096}
1097
1098Instruction *InstCombinerImpl::visitLoadInst(LoadInst &LI) {
1099 Value *Op = LI.getOperand(i_nocapture: 0);
1100 if (Value *Res = simplifyLoadInst(LI: &LI, PtrOp: Op, Q: SQ.getWithInstruction(I: &LI)))
1101 return replaceInstUsesWith(I&: LI, V: Res);
1102
1103 // Try to canonicalize the loaded type.
1104 if (Instruction *Res = combineLoadToOperationType(IC&: *this, Load&: LI))
1105 return Res;
1106
1107 // Replace GEP indices if possible.
1108 if (Instruction *NewGEPI = replaceGEPIdxWithZero(IC&: *this, Ptr: Op, MemI&: LI))
1109 return replaceOperand(I&: LI, OpNum: 0, V: NewGEPI);
1110
1111 if (Instruction *Res = unpackLoadToAggregate(IC&: *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(Load: &LI, AA&: BatchAA, IsLoadCSE: &IsLoadCSE)) {
1120 if (IsLoadCSE)
1121 combineMetadataForCSE(K: cast<LoadInst>(Val: AvailableVal), J: &LI, DoesKMove: false);
1122
1123 return replaceInstUsesWith(
1124 I&: LI, V: Builder.CreateBitOrPointerCast(V: AvailableVal, DestTy: LI.getType(),
1125 Name: 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)) {
1136 CreateNonTerminatorUnreachable(InsertAt: &LI);
1137 return replaceInstUsesWith(I&: LI, V: PoisonValue::get(T: LI.getType()));
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
1152 AddrSpaceCastInst *ASC = dyn_cast<AddrSpaceCastInst>(Val: Op);
1153 Value *SelectOp = Op;
1154 if (ASC && ASC->getOperand(i_nocapture: 0)->hasOneUse())
1155 SelectOp = ASC->getOperand(i_nocapture: 0);
1156 if (SelectInst *SI = dyn_cast<SelectInst>(Val: 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(V: SI->getOperand(i_nocapture: 1), Ty: LI.getType(),
1163 Alignment, SQ: SQ.getWithInstruction(I: SI)) &&
1164 isSafeToLoadUnconditionally(V: SI->getOperand(i_nocapture: 2), Ty: LI.getType(),
1165 Alignment, SQ: SQ.getWithInstruction(I: SI))) {
1166
1167 auto MaybeCastedLoadOperand = [&](Value *Op) {
1168 if (ASC)
1169 return Builder.CreateAddrSpaceCast(V: Op, DestTy: ASC->getType(),
1170 Name: Op->getName() + ".cast");
1171 return Op;
1172 };
1173 Value *LoadOp1 = MaybeCastedLoadOperand(SI->getOperand(i_nocapture: 1));
1174 LoadInst *V1 =
1175 Builder.CreateLoad(Ty: LI.getType(), Ptr: LoadOp1, Props: LI.getProperties(),
1176 Name: LoadOp1->getName() + ".val");
1177
1178 Value *LoadOp2 = MaybeCastedLoadOperand(SI->getOperand(i_nocapture: 2));
1179 LoadInst *V2 =
1180 Builder.CreateLoad(Ty: LI.getType(), Ptr: LoadOp2, Props: LI.getProperties(),
1181 Name: 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(SrcInst: LI, WL: Metadata::PoisonGeneratingIDs);
1186 V2->copyMetadata(SrcInst: LI, WL: Metadata::PoisonGeneratingIDs);
1187 return SelectInst::Create(C: SI->getCondition(), S1: V1, S2: V2, NameStr: "", InsertBefore: nullptr,
1188 MDFrom: ProfcheckDisableMetadataFixes ? nullptr : SI);
1189 }
1190 }
1191 }
1192
1193 if (!NullPointerIsDefined(F: LI.getFunction(), AS: LI.getPointerAddressSpace()))
1194 if (Value *V = simplifyNonNullOperand(V: Op, /*HasDereferenceable=*/true))
1195 return replaceOperand(I&: LI, OpNum: 0, V);
1196
1197 // load(llvm.protected.field.ptr(ptr)) -> llvm.ptrauth.auth(load(ptr))
1198 if (isa<PointerType>(Val: LI.getType())) {
1199 if (auto *II = dyn_cast<IntrinsicInst>(Val: Op)) {
1200 if (II->getIntrinsicID() == Intrinsic::protected_field_ptr) {
1201 std::vector<OperandBundleDef> DSBundle;
1202 if (auto Bundle =
1203 II->getOperandBundle(ID: LLVMContext::OB_deactivation_symbol))
1204 DSBundle.push_back(x: OperandBundleDef(
1205 "deactivation-symbol", cast<GlobalValue>(Val: Bundle->Inputs[0])));
1206
1207 IRBuilderBase::InsertPointGuard Guard(Builder);
1208 Builder.SetInsertPoint(&LI);
1209
1210 auto *NewLI = cast<LoadInst>(Val: LI.clone());
1211 NewLI->setOperand(i_nocapture: 0, Val_nocapture: II->getOperand(i_nocapture: 0));
1212 Builder.Insert(I: NewLI);
1213
1214 Function *AuthIntr = Intrinsic::getOrInsertDeclaration(
1215 M: F.getParent(), id: Intrinsic::ptrauth_auth, OverloadTys: {});
1216 auto *LIInt = Builder.CreatePtrToInt(V: NewLI, DestTy: Builder.getInt64Ty());
1217 Value *Auth = Builder.CreateCall(
1218 Callee: AuthIntr,
1219 Args: {LIInt, Builder.getInt32(/*AArch64PACKey::DA*/ C: 2),
1220 II->getOperand(i_nocapture: 1)},
1221 OpBundles: DSBundle);
1222 Auth = Builder.CreateIntToPtr(V: Auth, DestTy: Builder.getPtrTy());
1223 return replaceInstUsesWith(I&: LI, V: 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.
1245static Value *likeBitCastFromVector(InstCombinerImpl &IC, Value *V) {
1246 Value *U = nullptr;
1247 while (auto *IV = dyn_cast<InsertValueInst>(Val: V)) {
1248 auto *E = dyn_cast<ExtractElementInst>(Val: 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>(Val: 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, P: m_Undef()) || !U)
1262 return nullptr;
1263
1264 auto *UT = cast<VectorType>(Val: 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(Ty: UT) != DL.getTypeStoreSizeInBits(Ty: VT)) {
1269 return nullptr;
1270 }
1271 if (auto *AT = dyn_cast<ArrayType>(Val: VT)) {
1272 if (AT->getNumElements() != cast<FixedVectorType>(Val: UT)->getNumElements())
1273 return nullptr;
1274 } else {
1275 auto *ST = cast<StructType>(Val: VT);
1276 if (ST->getNumElements() != cast<FixedVectorType>(Val: 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.
1306static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI) {
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 if (SI.isElementwise())
1313 return false;
1314
1315 // swifterror values can't be bitcasted.
1316 if (SI.getPointerOperand()->isSwiftError())
1317 return false;
1318
1319 Value *V = SI.getValueOperand();
1320
1321 // Fold away bit casts of the stored value by storing the original type.
1322 if (auto *BC = dyn_cast<BitCastInst>(Val: V)) {
1323 assert(!BC->getType()->isX86_AMXTy() &&
1324 "store to x86_amx* should not happen!");
1325 V = BC->getOperand(i_nocapture: 0);
1326 // Don't transform when the type is x86_amx, it makes the pass that lower
1327 // x86_amx type happy.
1328 if (V->getType()->isX86_AMXTy())
1329 return false;
1330 if (!SI.isAtomic() || isSupportedAtomicType(Ty: V->getType())) {
1331 combineStoreToNewValue(IC, SI, V);
1332 return true;
1333 }
1334 }
1335
1336 if (Value *U = likeBitCastFromVector(IC, V))
1337 if (!SI.isAtomic() || isSupportedAtomicType(Ty: U->getType())) {
1338 combineStoreToNewValue(IC, SI, V: U);
1339 return true;
1340 }
1341
1342 // FIXME: We should also canonicalize stores of vectors when their elements
1343 // are cast to other types.
1344 return false;
1345}
1346
1347static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI) {
1348 // FIXME: We could probably with some care handle both volatile and atomic
1349 // stores here but it isn't clear that this is important.
1350 if (!SI.isSimple())
1351 return false;
1352
1353 Value *V = SI.getValueOperand();
1354 Type *T = V->getType();
1355
1356 if (!T->isAggregateType())
1357 return false;
1358
1359 if (auto *ST = dyn_cast<StructType>(Val: T)) {
1360 // If the struct only have one element, we unpack.
1361 unsigned Count = ST->getNumElements();
1362 if (Count == 1) {
1363 V = IC.Builder.CreateExtractValue(Agg: V, Idxs: 0);
1364 combineStoreToNewValue(IC, SI, V);
1365 return true;
1366 }
1367
1368 // We don't want to break loads with padding here as we'd loose
1369 // the knowledge that padding exists for the rest of the pipeline.
1370 const DataLayout &DL = IC.getDataLayout();
1371 auto *SL = DL.getStructLayout(Ty: ST);
1372
1373 if (SL->hasPadding())
1374 return false;
1375
1376 const auto Align = SI.getAlign();
1377
1378 SmallString<16> EltName = V->getName();
1379 EltName += ".elt";
1380 auto *Addr = SI.getPointerOperand();
1381 SmallString<16> AddrName = Addr->getName();
1382 AddrName += ".repack";
1383
1384 auto *IdxType = DL.getIndexType(PtrTy: Addr->getType());
1385 for (unsigned i = 0; i < Count; i++) {
1386 auto *Ptr = IC.Builder.CreateInBoundsPtrAdd(
1387 Ptr: Addr, Offset: IC.Builder.CreateTypeSize(Ty: IdxType, Size: SL->getElementOffset(Idx: i)),
1388 Name: AddrName);
1389 auto *Val = IC.Builder.CreateExtractValue(Agg: V, Idxs: i, Name: EltName);
1390 auto EltAlign =
1391 commonAlignment(A: Align, Offset: SL->getElementOffset(Idx: i).getKnownMinValue());
1392 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, Align: EltAlign);
1393 NS->setAAMetadata(SI.getAAMetadata());
1394 }
1395
1396 return true;
1397 }
1398
1399 if (auto *AT = dyn_cast<ArrayType>(Val: T)) {
1400 // If the array only have one element, we unpack.
1401 auto NumElements = AT->getNumElements();
1402 if (NumElements == 1) {
1403 V = IC.Builder.CreateExtractValue(Agg: V, Idxs: 0);
1404 combineStoreToNewValue(IC, SI, V);
1405 return true;
1406 }
1407
1408 // Bail out if the array is too large. Ideally we would like to optimize
1409 // arrays of arbitrary size but this has a terrible impact on compile time.
1410 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1411 // tuning.
1412 if (NumElements > IC.MaxArraySizeForCombine)
1413 return false;
1414
1415 const DataLayout &DL = IC.getDataLayout();
1416 TypeSize EltSize = DL.getTypeAllocSize(Ty: AT->getElementType());
1417 const auto Align = SI.getAlign();
1418
1419 SmallString<16> EltName = V->getName();
1420 EltName += ".elt";
1421 auto *Addr = SI.getPointerOperand();
1422 SmallString<16> AddrName = Addr->getName();
1423 AddrName += ".repack";
1424
1425 auto *IdxType = Type::getInt64Ty(C&: T->getContext());
1426 auto *Zero = ConstantInt::get(Ty: IdxType, V: 0);
1427
1428 TypeSize Offset = TypeSize::getZero();
1429 for (uint64_t i = 0; i < NumElements; i++) {
1430 Value *Indices[2] = {
1431 Zero,
1432 ConstantInt::get(Ty: IdxType, V: i),
1433 };
1434 auto *Ptr =
1435 IC.Builder.CreateInBoundsGEP(Ty: AT, Ptr: Addr, IdxList: ArrayRef(Indices), Name: AddrName);
1436 auto *Val = IC.Builder.CreateExtractValue(Agg: V, Idxs: i, Name: EltName);
1437 auto EltAlign = commonAlignment(A: Align, Offset: Offset.getKnownMinValue());
1438 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, Align: EltAlign);
1439 NS->setAAMetadata(SI.getAAMetadata());
1440 Offset += EltSize;
1441 }
1442
1443 return true;
1444 }
1445
1446 return false;
1447}
1448
1449/// equivalentAddressValues - Test if A and B will obviously have the same
1450/// value. This includes recognizing that %t0 and %t1 will have the same
1451/// value in code like this:
1452/// %t0 = getelementptr \@a, 0, 3
1453/// store i32 0, i32* %t0
1454/// %t1 = getelementptr \@a, 0, 3
1455/// %t2 = load i32* %t1
1456///
1457static bool equivalentAddressValues(Value *A, Value *B) {
1458 // Test if the values are trivially equivalent.
1459 if (A == B) return true;
1460
1461 // Test if the values come form identical arithmetic instructions.
1462 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1463 // its only used to compare two uses within the same basic block, which
1464 // means that they'll always either have the same value or one of them
1465 // will have an undefined value.
1466 if (isa<BinaryOperator>(Val: A) ||
1467 isa<CastInst>(Val: A) ||
1468 isa<PHINode>(Val: A) ||
1469 isa<GetElementPtrInst>(Val: A))
1470 if (Instruction *BI = dyn_cast<Instruction>(Val: B))
1471 if (cast<Instruction>(Val: A)->isIdenticalToWhenDefined(I: BI))
1472 return true;
1473
1474 // Otherwise they may not be equivalent.
1475 return false;
1476}
1477
1478Instruction *InstCombinerImpl::visitStoreInst(StoreInst &SI) {
1479 Value *Val = SI.getOperand(i_nocapture: 0);
1480 Value *Ptr = SI.getOperand(i_nocapture: 1);
1481
1482 // Try to canonicalize the stored type.
1483 if (combineStoreToValueType(IC&: *this, SI))
1484 return eraseInstFromFunction(I&: SI);
1485
1486 // Try to canonicalize the stored type.
1487 if (unpackStoreToAggregate(IC&: *this, SI))
1488 return eraseInstFromFunction(I&: SI);
1489
1490 // Replace GEP indices if possible.
1491 if (Instruction *NewGEPI = replaceGEPIdxWithZero(IC&: *this, Ptr, MemI&: SI))
1492 return replaceOperand(I&: SI, OpNum: 1, V: NewGEPI);
1493
1494 // Don't hack volatile/ordered stores.
1495 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1496 if (!SI.isUnordered()) return nullptr;
1497
1498 // If the RHS is an alloca with a single use, zapify the store, making the
1499 // alloca dead.
1500 if (Ptr->hasOneUse()) {
1501 if (isa<AllocaInst>(Val: Ptr))
1502 return eraseInstFromFunction(I&: SI);
1503 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Val: Ptr)) {
1504 if (isa<AllocaInst>(Val: GEP->getOperand(i_nocapture: 0))) {
1505 if (GEP->getOperand(i_nocapture: 0)->hasOneUse())
1506 return eraseInstFromFunction(I&: SI);
1507 }
1508 }
1509 }
1510
1511 // If we have a store to a location which is known constant, we can conclude
1512 // that the store must be storing the constant value (else the memory
1513 // wouldn't be constant), and this must be a noop.
1514 if (!isModSet(MRI: AA->getModRefInfoMask(P: Ptr)))
1515 return eraseInstFromFunction(I&: SI);
1516
1517 // Do really simple DSE, to catch cases where there are several consecutive
1518 // stores to the same location, separated by a few arithmetic operations. This
1519 // situation often occurs with bitfield accesses.
1520 BasicBlock::iterator BBI(SI);
1521 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1522 --ScanInsts) {
1523 --BBI;
1524 // Don't count debug info directives, lest they affect codegen,
1525 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1526 if (BBI->isDebugOrPseudoInst()) {
1527 ScanInsts++;
1528 continue;
1529 }
1530
1531 if (StoreInst *PrevSI = dyn_cast<StoreInst>(Val&: BBI)) {
1532 // Prev store isn't volatile, and stores to the same location?
1533 if (PrevSI->isUnordered() &&
1534 equivalentAddressValues(A: PrevSI->getOperand(i_nocapture: 1), B: SI.getOperand(i_nocapture: 1)) &&
1535 PrevSI->getValueOperand()->getType() ==
1536 SI.getValueOperand()->getType()) {
1537 ++NumDeadStore;
1538 // Manually add back the original store to the worklist now, so it will
1539 // be processed after the operands of the removed store, as this may
1540 // expose additional DSE opportunities.
1541 Worklist.push(I: &SI);
1542 eraseInstFromFunction(I&: *PrevSI);
1543 return nullptr;
1544 }
1545 break;
1546 }
1547
1548 // If this is a load, we have to stop. However, if the loaded value is from
1549 // the pointer we're loading and is producing the pointer we're storing,
1550 // then *this* store is dead (X = load P; store X -> P).
1551 if (LoadInst *LI = dyn_cast<LoadInst>(Val&: BBI)) {
1552 if (LI == Val && equivalentAddressValues(A: LI->getOperand(i_nocapture: 0), B: Ptr)) {
1553 assert(SI.isUnordered() && "can't eliminate ordering operation");
1554 return eraseInstFromFunction(I&: SI);
1555 }
1556
1557 // Otherwise, this is a load from some other location. Stores before it
1558 // may not be dead.
1559 break;
1560 }
1561
1562 // Don't skip over loads, throws or things that can modify memory.
1563 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
1564 break;
1565 }
1566
1567 // store X, null -> turns into 'unreachable' in SimplifyCFG
1568 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG
1569 if (canSimplifyNullStoreOrGEP(SI)) {
1570 if (!isa<PoisonValue>(Val))
1571 return replaceOperand(I&: SI, OpNum: 0, V: PoisonValue::get(T: Val->getType()));
1572 return nullptr; // Do not modify these!
1573 }
1574
1575 // This is a non-terminator unreachable marker. Don't remove it.
1576 if (isa<UndefValue>(Val: Ptr)) {
1577 // Remove guaranteed-to-transfer instructions before the marker.
1578 removeInstructionsBeforeUnreachable(I&: SI);
1579
1580 // Remove all instructions after the marker and handle dead blocks this
1581 // implies.
1582 SmallVector<BasicBlock *> Worklist;
1583 handleUnreachableFrom(I: SI.getNextNode(), Worklist);
1584 handlePotentiallyDeadBlocks(Worklist);
1585 return nullptr;
1586 }
1587
1588 // store undef, Ptr -> noop
1589 // FIXME: This is technically incorrect because it might overwrite a poison
1590 // value. Change to PoisonValue once #52930 is resolved.
1591 if (isa<UndefValue>(Val))
1592 return eraseInstFromFunction(I&: SI);
1593
1594 // Replace byte constants with integer constants in stores.
1595 Constant *C;
1596 if (Val->getType()->isByteOrByteVectorTy() && match(V: Val, P: m_ImmConstant(C)))
1597 return replaceOperand(
1598 I&: SI, OpNum: 0,
1599 V: ConstantExpr::getBitCast(C, Ty: Type::getIntFromByteType(C->getType())));
1600
1601 if (!NullPointerIsDefined(F: SI.getFunction(), AS: SI.getPointerAddressSpace()))
1602 if (Value *V = simplifyNonNullOperand(V: Ptr, /*HasDereferenceable=*/true))
1603 return replaceOperand(I&: SI, OpNum: 1, V);
1604
1605 // store(ptr1, llvm.protected.field.ptr(ptr2)) ->
1606 // store(llvm.ptrauth.sign(ptr1), ptr2)
1607 if (isa<PointerType>(Val: Val->getType())) {
1608 if (auto *II = dyn_cast<IntrinsicInst>(Val: Ptr)) {
1609 if (II->getIntrinsicID() == Intrinsic::protected_field_ptr) {
1610 std::vector<OperandBundleDef> DSBundle;
1611 if (auto Bundle =
1612 II->getOperandBundle(ID: LLVMContext::OB_deactivation_symbol))
1613 DSBundle.push_back(x: OperandBundleDef(
1614 "deactivation-symbol", cast<GlobalValue>(Val: Bundle->Inputs[0])));
1615
1616 IRBuilderBase::InsertPointGuard Guard(Builder);
1617 Builder.SetInsertPoint(&SI);
1618
1619 Function *SignIntr = Intrinsic::getOrInsertDeclaration(
1620 M: F.getParent(), id: Intrinsic::ptrauth_sign, OverloadTys: {});
1621 auto *ValInt = Builder.CreatePtrToInt(V: Val, DestTy: Builder.getInt64Ty());
1622 Value *Sign = Builder.CreateCall(
1623 Callee: SignIntr,
1624 Args: {ValInt, Builder.getInt32(/*AArch64PACKey::DA*/ C: 2),
1625 II->getOperand(i_nocapture: 1)},
1626 OpBundles: DSBundle);
1627 Sign = Builder.CreateIntToPtr(V: Sign, DestTy: Builder.getPtrTy());
1628
1629 replaceOperand(I&: SI, OpNum: 0, V: Sign);
1630 replaceOperand(I&: SI, OpNum: 1, V: II->getOperand(i_nocapture: 0));
1631 return &SI;
1632 }
1633 }
1634 }
1635
1636 return nullptr;
1637}
1638
1639/// Try to transform:
1640/// if () { *P = v1; } else { *P = v2 }
1641/// or:
1642/// *P = v1; if () { *P = v2; }
1643/// into a phi node with a store in the successor.
1644bool InstCombinerImpl::mergeStoreIntoSuccessor(StoreInst &SI) {
1645 if (!SI.isUnordered())
1646 return false; // This code has not been audited for volatile/ordered case.
1647
1648 // Check if the successor block has exactly 2 incoming edges.
1649 BasicBlock *StoreBB = SI.getParent();
1650 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(Idx: 0);
1651 if (!DestBB->hasNPredecessors(N: 2))
1652 return false;
1653
1654 // Capture the other block (the block that doesn't contain our store).
1655 pred_iterator PredIter = pred_begin(BB: DestBB);
1656 if (*PredIter == StoreBB)
1657 ++PredIter;
1658 BasicBlock *OtherBB = *PredIter;
1659
1660 // Bail out if all of the relevant blocks aren't distinct. This can happen,
1661 // for example, if SI is in an infinite loop.
1662 if (StoreBB == DestBB || OtherBB == DestBB)
1663 return false;
1664
1665 // Verify that the other block is not empty apart from the terminator.
1666 BasicBlock::iterator BBI(OtherBB->getTerminator());
1667 if (BBI == OtherBB->begin())
1668 return false;
1669
1670 auto OtherStoreIsMergeable = [&](StoreInst *OtherStore) -> bool {
1671 if (!OtherStore ||
1672 OtherStore->getPointerOperand() != SI.getPointerOperand())
1673 return false;
1674
1675 auto *SIVTy = SI.getValueOperand()->getType();
1676 auto *OSVTy = OtherStore->getValueOperand()->getType();
1677 return CastInst::isBitOrNoopPointerCastable(SrcTy: OSVTy, DestTy: SIVTy, DL) &&
1678 SI.hasSameSpecialState(I2: OtherStore);
1679 };
1680
1681 // If the other block ends in an unconditional branch, check for the 'if then
1682 // else' case. There is an instruction before the branch.
1683 StoreInst *OtherStore = nullptr;
1684 if (isa<UncondBrInst>(Val: BBI)) {
1685 --BBI;
1686 // Skip over debugging info and pseudo probes.
1687 while (BBI->isDebugOrPseudoInst()) {
1688 if (BBI==OtherBB->begin())
1689 return false;
1690 --BBI;
1691 }
1692 // If this isn't a store, isn't a store to the same location, or is not the
1693 // right kind of store, bail out.
1694 OtherStore = dyn_cast<StoreInst>(Val&: BBI);
1695 if (!OtherStoreIsMergeable(OtherStore))
1696 return false;
1697 } else if (auto *OtherBr = dyn_cast<CondBrInst>(Val&: BBI)) {
1698 // Otherwise, the other block ended with a conditional branch. If one of the
1699 // destinations is StoreBB, then we have the if/then case.
1700 if (OtherBr->getSuccessor(i: 0) != StoreBB &&
1701 OtherBr->getSuccessor(i: 1) != StoreBB)
1702 return false;
1703
1704 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1705 // if/then triangle. See if there is a store to the same ptr as SI that
1706 // lives in OtherBB.
1707 for (;; --BBI) {
1708 // Check to see if we find the matching store.
1709 OtherStore = dyn_cast<StoreInst>(Val&: BBI);
1710 if (OtherStoreIsMergeable(OtherStore))
1711 break;
1712
1713 // If we find something that may be using or overwriting the stored
1714 // value, or if we run out of instructions, we can't do the transform.
1715 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1716 BBI->mayWriteToMemory() || BBI == OtherBB->begin())
1717 return false;
1718 }
1719
1720 // In order to eliminate the store in OtherBr, we have to make sure nothing
1721 // reads or overwrites the stored value in StoreBB.
1722 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1723 // FIXME: This should really be AA driven.
1724 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
1725 return false;
1726 }
1727 } else
1728 return false;
1729
1730 // Insert a PHI node now if we need it.
1731 Value *MergedVal = OtherStore->getValueOperand();
1732 // The debug locations of the original instructions might differ. Merge them.
1733 DebugLoc MergedLoc =
1734 DebugLoc::getMergedLocation(LocA: SI.getDebugLoc(), LocB: OtherStore->getDebugLoc());
1735 if (MergedVal != SI.getValueOperand()) {
1736 PHINode *PN =
1737 PHINode::Create(Ty: SI.getValueOperand()->getType(), NumReservedValues: 2, NameStr: "storemerge");
1738 PN->addIncoming(V: SI.getValueOperand(), BB: SI.getParent());
1739 Builder.SetInsertPoint(OtherStore);
1740 PN->addIncoming(V: Builder.CreateBitOrPointerCast(V: MergedVal, DestTy: PN->getType()),
1741 BB: OtherBB);
1742 MergedVal = InsertNewInstBefore(New: PN, Old: DestBB->begin());
1743 PN->setDebugLoc(MergedLoc);
1744 }
1745
1746 // Advance to a place where it is safe to insert the new store and insert it.
1747 BBI = DestBB->getFirstInsertionPt();
1748 StoreInst *NewSI =
1749 new StoreInst(MergedVal, SI.getOperand(i_nocapture: 1), SI.getProperties());
1750 InsertNewInstBefore(New: NewSI, Old: BBI);
1751 NewSI->setDebugLoc(MergedLoc);
1752 NewSI->mergeDIAssignID(SourceInstructions: {&SI, OtherStore});
1753
1754 // If the two stores had AA tags, merge them.
1755 AAMDNodes AATags = SI.getAAMetadata();
1756 if (AATags)
1757 NewSI->setAAMetadata(AATags.merge(Other: OtherStore->getAAMetadata()));
1758
1759 // If the two stores had access groups, intersect them.
1760 NewSI->setMetadata(KindID: LLVMContext::MD_access_group,
1761 Node: intersectAccessGroups(Inst1: &SI, Inst2: OtherStore));
1762
1763 // Nuke the old stores.
1764 eraseInstFromFunction(I&: SI);
1765 eraseInstFromFunction(I&: *OtherStore);
1766 return true;
1767}
1768