1//===- DeadStoreElimination.cpp - MemorySSA Backed Dead Store Elimination -===//
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// The code below implements dead store elimination using MemorySSA. It uses
10// the following general approach: given a MemoryDef, walk upwards to find
11// clobbering MemoryDefs that may be killed by the starting def. Then check
12// that there are no uses that may read the location of the original MemoryDef
13// in between both MemoryDefs. A bit more concretely:
14//
15// For all MemoryDefs StartDef:
16// 1. Get the next dominating clobbering MemoryDef (MaybeDeadAccess) by walking
17// upwards.
18// 2. Check that there are no reads between MaybeDeadAccess and the StartDef by
19// checking all uses starting at MaybeDeadAccess and walking until we see
20// StartDef.
21// 3. For each found CurrentDef, check that:
22// 1. There are no barrier instructions between CurrentDef and StartDef (like
23// throws or stores with ordering constraints).
24// 2. StartDef is executed whenever CurrentDef is executed.
25// 3. StartDef completely overwrites CurrentDef.
26// 4. Erase CurrentDef from the function and MemorySSA.
27//
28//===----------------------------------------------------------------------===//
29
30#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
31#include "ScalarOptions.h"
32#include "llvm/ADT/APInt.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/MapVector.h"
35#include "llvm/ADT/PostOrderIterator.h"
36#include "llvm/ADT/STLExtras.h"
37#include "llvm/ADT/ScopedHashTable.h"
38#include "llvm/ADT/SetVector.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/SmallVector.h"
41#include "llvm/ADT/Statistic.h"
42#include "llvm/ADT/StringRef.h"
43#include "llvm/Analysis/AliasAnalysis.h"
44#include "llvm/Analysis/AssumptionCache.h"
45#include "llvm/Analysis/CaptureTracking.h"
46#include "llvm/Analysis/CycleAnalysis.h"
47#include "llvm/Analysis/GlobalsModRef.h"
48#include "llvm/Analysis/Loads.h"
49#include "llvm/Analysis/MemoryBuiltins.h"
50#include "llvm/Analysis/MemoryLocation.h"
51#include "llvm/Analysis/MemorySSA.h"
52#include "llvm/Analysis/MemorySSAUpdater.h"
53#include "llvm/Analysis/MustExecute.h"
54#include "llvm/Analysis/PostDominators.h"
55#include "llvm/Analysis/TargetLibraryInfo.h"
56#include "llvm/Analysis/ValueTracking.h"
57#include "llvm/IR/Argument.h"
58#include "llvm/IR/AttributeMask.h"
59#include "llvm/IR/BasicBlock.h"
60#include "llvm/IR/Constant.h"
61#include "llvm/IR/ConstantRangeList.h"
62#include "llvm/IR/Constants.h"
63#include "llvm/IR/DataLayout.h"
64#include "llvm/IR/DebugInfo.h"
65#include "llvm/IR/Dominators.h"
66#include "llvm/IR/Function.h"
67#include "llvm/IR/IRBuilder.h"
68#include "llvm/IR/InstIterator.h"
69#include "llvm/IR/InstrTypes.h"
70#include "llvm/IR/Instruction.h"
71#include "llvm/IR/Instructions.h"
72#include "llvm/IR/IntrinsicInst.h"
73#include "llvm/IR/Module.h"
74#include "llvm/IR/PassManager.h"
75#include "llvm/IR/PatternMatch.h"
76#include "llvm/IR/Value.h"
77#include "llvm/InitializePasses.h"
78#include "llvm/Support/Casting.h"
79#include "llvm/Support/Debug.h"
80#include "llvm/Support/DebugCounter.h"
81#include "llvm/Support/ErrorHandling.h"
82#include "llvm/Support/raw_ostream.h"
83#include "llvm/Transforms/Scalar.h"
84#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
85#include "llvm/Transforms/Utils/BuildLibCalls.h"
86#include "llvm/Transforms/Utils/Local.h"
87#include <algorithm>
88#include <cassert>
89#include <cstdint>
90#include <map>
91#include <optional>
92#include <utility>
93
94using namespace llvm;
95using namespace PatternMatch;
96
97#define DEBUG_TYPE "dse"
98
99STATISTIC(NumRemainingStores, "Number of stores remaining after DSE");
100STATISTIC(NumRedundantStores, "Number of redundant stores deleted");
101STATISTIC(NumFastStores, "Number of stores deleted");
102STATISTIC(NumFastOther, "Number of other instrs removed");
103STATISTIC(NumCompletePartials, "Number of stores dead by later partials");
104STATISTIC(NumModifiedStores, "Number of stores modified");
105STATISTIC(NumCFGChecks, "Number of stores modified");
106STATISTIC(NumCFGTries, "Number of stores modified");
107STATISTIC(NumCFGSuccess, "Number of stores modified");
108STATISTIC(NumGetDomMemoryDefPassed,
109 "Number of times a valid candidate is returned from getDomMemoryDef");
110STATISTIC(NumDomMemDefChecks,
111 "Number iterations check for reads in getDomMemoryDef");
112
113DEBUG_COUNTER(MemorySSACounter, "dse-memoryssa",
114 "Controls which MemoryDefs are eliminated.");
115
116//===----------------------------------------------------------------------===//
117// Helper functions
118//===----------------------------------------------------------------------===//
119using OverlapIntervalsTy = std::map<int64_t, int64_t>;
120using InstOverlapIntervalsTy = MapVector<Instruction *, OverlapIntervalsTy>;
121
122/// Returns true if the end of this instruction can be safely shortened in
123/// length.
124static bool isShortenableAtTheEnd(Instruction *I) {
125 // Don't shorten stores for now
126 if (isa<StoreInst>(Val: I))
127 return false;
128
129 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: I)) {
130 switch (II->getIntrinsicID()) {
131 default: return false;
132 case Intrinsic::memset:
133 case Intrinsic::memcpy:
134 case Intrinsic::memcpy_element_unordered_atomic:
135 case Intrinsic::memset_element_unordered_atomic:
136 // Do shorten memory intrinsics.
137 // FIXME: Add memmove if it's also safe to transform.
138 return true;
139 }
140 }
141
142 // Don't shorten libcalls calls for now.
143
144 return false;
145}
146
147/// Returns true if the beginning of this instruction can be safely shortened
148/// in length.
149static bool isShortenableAtTheBeginning(Instruction *I) {
150 // FIXME: Handle only memset for now. Supporting memcpy/memmove should be
151 // easily done by offsetting the source address.
152 return isa<AnyMemSetInst>(Val: I);
153}
154
155static std::optional<TypeSize> getPointerSize(const Value *V,
156 const DataLayout &DL,
157 const TargetLibraryInfo &TLI,
158 const Function *F) {
159 uint64_t Size;
160 ObjectSizeOpts Opts;
161 Opts.NullIsUnknownSize = NullPointerIsDefined(F);
162
163 if (getObjectSize(Ptr: V, Size, DL, TLI: &TLI, Opts))
164 return TypeSize::getFixed(ExactSize: Size);
165 return std::nullopt;
166}
167
168namespace {
169
170enum OverwriteResult {
171 OW_Begin,
172 OW_Complete,
173 OW_End,
174 OW_PartialEarlierWithFullLater,
175 OW_MaybePartial,
176 OW_None,
177 OW_Unknown
178};
179
180} // end anonymous namespace
181
182/// Check if two instruction are masked stores that completely
183/// overwrite one another. More specifically, \p KillingI has to
184/// overwrite \p DeadI.
185static OverwriteResult isMaskedStoreOverwrite(const Instruction *KillingI,
186 const Instruction *DeadI,
187 BatchAAResults &AA) {
188 const auto *KillingII = dyn_cast<IntrinsicInst>(Val: KillingI);
189 const auto *DeadII = dyn_cast<IntrinsicInst>(Val: DeadI);
190 if (KillingII == nullptr || DeadII == nullptr)
191 return OW_Unknown;
192 if (KillingII->getIntrinsicID() != DeadII->getIntrinsicID())
193 return OW_Unknown;
194
195 switch (KillingII->getIntrinsicID()) {
196 case Intrinsic::masked_store:
197 case Intrinsic::vp_store: {
198 const DataLayout &DL = KillingII->getDataLayout();
199 auto *KillingTy = KillingII->getArgOperand(i: 0)->getType();
200 auto *DeadTy = DeadII->getArgOperand(i: 0)->getType();
201 if (DL.getTypeSizeInBits(Ty: KillingTy) != DL.getTypeSizeInBits(Ty: DeadTy))
202 return OW_Unknown;
203 // Element count.
204 if (cast<VectorType>(Val: KillingTy)->getElementCount() !=
205 cast<VectorType>(Val: DeadTy)->getElementCount())
206 return OW_Unknown;
207 // Pointers.
208 Value *KillingPtr = KillingII->getArgOperand(i: 1);
209 Value *DeadPtr = DeadII->getArgOperand(i: 1);
210 if (KillingPtr != DeadPtr && !AA.isMustAlias(V1: KillingPtr, V2: DeadPtr))
211 return OW_Unknown;
212 if (KillingII->getIntrinsicID() == Intrinsic::masked_store) {
213 // Masks.
214 // TODO: check that KillingII's mask is a superset of the DeadII's mask.
215 if (KillingII->getArgOperand(i: 2) != DeadII->getArgOperand(i: 2))
216 return OW_Unknown;
217 } else if (KillingII->getIntrinsicID() == Intrinsic::vp_store) {
218 // Masks.
219 // TODO: check that KillingII's mask is a superset of the DeadII's mask.
220 if (KillingII->getArgOperand(i: 2) != DeadII->getArgOperand(i: 2))
221 return OW_Unknown;
222 // Lengths.
223 if (KillingII->getArgOperand(i: 3) != DeadII->getArgOperand(i: 3))
224 return OW_Unknown;
225 }
226 return OW_Complete;
227 }
228 default:
229 return OW_Unknown;
230 }
231}
232
233/// Return 'OW_Complete' if a store to the 'KillingLoc' location completely
234/// overwrites a store to the 'DeadLoc' location, 'OW_End' if the end of the
235/// 'DeadLoc' location is completely overwritten by 'KillingLoc', 'OW_Begin'
236/// if the beginning of the 'DeadLoc' location is overwritten by 'KillingLoc'.
237/// 'OW_PartialEarlierWithFullLater' means that a dead (big) store was
238/// overwritten by a killing (smaller) store which doesn't write outside the big
239/// store's memory locations. Returns 'OW_Unknown' if nothing can be determined.
240/// NOTE: This function must only be called if both \p KillingLoc and \p
241/// DeadLoc belong to the same underlying object with valid \p KillingOff and
242/// \p DeadOff.
243static OverwriteResult isPartialOverwrite(const ScalarOptions &Opts,
244 const MemoryLocation &KillingLoc,
245 const MemoryLocation &DeadLoc,
246 int64_t KillingOff, int64_t DeadOff,
247 Instruction *DeadI,
248 InstOverlapIntervalsTy &IOL) {
249 const uint64_t KillingSize = KillingLoc.Size.getValue();
250 const uint64_t DeadSize = DeadLoc.Size.getValue();
251 // We may now overlap, although the overlap is not complete. There might also
252 // be other incomplete overlaps, and together, they might cover the complete
253 // dead store.
254 // Note: The correctness of this logic depends on the fact that this function
255 // is not even called providing DepWrite when there are any intervening reads.
256 if (Opts.enable_dse_partial_overwrite_tracking &&
257 KillingOff < int64_t(DeadOff + DeadSize) &&
258 int64_t(KillingOff + KillingSize) >= DeadOff) {
259
260 // Insert our part of the overlap into the map.
261 auto &IM = IOL[DeadI];
262 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite: DeadLoc [" << DeadOff << ", "
263 << int64_t(DeadOff + DeadSize) << ") KillingLoc ["
264 << KillingOff << ", " << int64_t(KillingOff + KillingSize)
265 << ")\n");
266
267 // Make sure that we only insert non-overlapping intervals and combine
268 // adjacent intervals. The intervals are stored in the map with the ending
269 // offset as the key (in the half-open sense) and the starting offset as
270 // the value.
271 int64_t KillingIntStart = KillingOff;
272 int64_t KillingIntEnd = KillingOff + KillingSize;
273
274 // Find any intervals ending at, or after, KillingIntStart which start
275 // before KillingIntEnd.
276 auto ILI = IM.lower_bound(x: KillingIntStart);
277 if (ILI != IM.end() && ILI->second <= KillingIntEnd) {
278 // This existing interval is overlapped with the current store somewhere
279 // in [KillingIntStart, KillingIntEnd]. Merge them by erasing the existing
280 // intervals and adjusting our start and end.
281 KillingIntStart = std::min(a: KillingIntStart, b: ILI->second);
282 KillingIntEnd = std::max(a: KillingIntEnd, b: ILI->first);
283 ILI = IM.erase(position: ILI);
284
285 // Continue erasing and adjusting our end in case other previous
286 // intervals are also overlapped with the current store.
287 //
288 // |--- dead 1 ---| |--- dead 2 ---|
289 // |------- killing---------|
290 //
291 while (ILI != IM.end() && ILI->second <= KillingIntEnd) {
292 assert(ILI->second > KillingIntStart && "Unexpected interval");
293 KillingIntEnd = std::max(a: KillingIntEnd, b: ILI->first);
294 ILI = IM.erase(position: ILI);
295 }
296 }
297
298 IM[KillingIntEnd] = KillingIntStart;
299
300 ILI = IM.begin();
301 if (ILI->second <= DeadOff && ILI->first >= int64_t(DeadOff + DeadSize)) {
302 LLVM_DEBUG(dbgs() << "DSE: Full overwrite from partials: DeadLoc ["
303 << DeadOff << ", " << int64_t(DeadOff + DeadSize)
304 << ") Composite KillingLoc [" << ILI->second << ", "
305 << ILI->first << ")\n");
306 ++NumCompletePartials;
307 return OW_Complete;
308 }
309 }
310
311 // Check for a dead store which writes to all the memory locations that
312 // the killing store writes to.
313 if (Opts.enable_dse_partial_store_merging && KillingOff >= DeadOff &&
314 int64_t(DeadOff + DeadSize) > KillingOff &&
315 uint64_t(KillingOff - DeadOff) + KillingSize <= DeadSize) {
316 LLVM_DEBUG(dbgs() << "DSE: Partial overwrite a dead load [" << DeadOff
317 << ", " << int64_t(DeadOff + DeadSize)
318 << ") by a killing store [" << KillingOff << ", "
319 << int64_t(KillingOff + KillingSize) << ")\n");
320 // TODO: Maybe come up with a better name?
321 return OW_PartialEarlierWithFullLater;
322 }
323
324 // Another interesting case is if the killing store overwrites the end of the
325 // dead store.
326 //
327 // |--dead--|
328 // |-- killing --|
329 //
330 // In this case we may want to trim the size of dead store to avoid
331 // generating stores to addresses which will definitely be overwritten killing
332 // store.
333 if (!Opts.enable_dse_partial_overwrite_tracking &&
334 (KillingOff > DeadOff && KillingOff < int64_t(DeadOff + DeadSize) &&
335 int64_t(KillingOff + KillingSize) >= int64_t(DeadOff + DeadSize)))
336 return OW_End;
337
338 // Finally, we also need to check if the killing store overwrites the
339 // beginning of the dead store.
340 //
341 // |--dead--|
342 // |-- killing --|
343 //
344 // In this case we may want to move the destination address and trim the size
345 // of dead store to avoid generating stores to addresses which will definitely
346 // be overwritten killing store.
347 if (!Opts.enable_dse_partial_overwrite_tracking &&
348 (KillingOff <= DeadOff && int64_t(KillingOff + KillingSize) > DeadOff)) {
349 assert(int64_t(KillingOff + KillingSize) < int64_t(DeadOff + DeadSize) &&
350 "Expect to be handled as OW_Complete");
351 return OW_Begin;
352 }
353 // Otherwise, they don't completely overlap.
354 return OW_Unknown;
355}
356
357/// Returns true if the memory which is accessed by the second instruction is not
358/// modified between the first and the second instruction.
359/// Precondition: Second instruction must be dominated by the first
360/// instruction.
361static bool
362memoryIsNotModifiedBetween(Instruction *FirstI, Instruction *SecondI,
363 BatchAAResults &AA, const DataLayout &DL,
364 DominatorTree *DT) {
365 // Do a backwards scan through the CFG from SecondI to FirstI. Look for
366 // instructions which can modify the memory location accessed by SecondI.
367 //
368 // While doing the walk keep track of the address to check. It might be
369 // different in different basic blocks due to PHI translation.
370 using BlockAddressPair = std::pair<BasicBlock *, PHITransAddr>;
371 SmallVector<BlockAddressPair, 16> WorkList;
372 // Keep track of the address we visited each block with. Bail out if we
373 // visit a block with different addresses.
374 DenseMap<BasicBlock *, Value *> Visited;
375
376 BasicBlock::iterator FirstBBI(FirstI);
377 ++FirstBBI;
378 BasicBlock::iterator SecondBBI(SecondI);
379 BasicBlock *FirstBB = FirstI->getParent();
380 BasicBlock *SecondBB = SecondI->getParent();
381 MemoryLocation MemLoc;
382 if (auto *MemSet = dyn_cast<MemSetInst>(Val: SecondI))
383 MemLoc = MemoryLocation::getForDest(MI: MemSet);
384 else
385 MemLoc = MemoryLocation::get(Inst: SecondI);
386
387 auto *MemLocPtr = const_cast<Value *>(MemLoc.Ptr);
388
389 // Start checking the SecondBB.
390 WorkList.push_back(
391 Elt: std::make_pair(x&: SecondBB, y: PHITransAddr(MemLocPtr, DL, nullptr)));
392 bool isFirstBlock = true;
393
394 // Check all blocks going backward until we reach the FirstBB.
395 while (!WorkList.empty()) {
396 BlockAddressPair Current = WorkList.pop_back_val();
397 BasicBlock *B = Current.first;
398 PHITransAddr &Addr = Current.second;
399 Value *Ptr = Addr.getAddr();
400
401 // Ignore instructions before FirstI if this is the FirstBB.
402 BasicBlock::iterator BI = (B == FirstBB ? FirstBBI : B->begin());
403
404 BasicBlock::iterator EI;
405 if (isFirstBlock) {
406 // Ignore instructions after SecondI if this is the first visit of SecondBB.
407 assert(B == SecondBB && "first block is not the store block");
408 EI = SecondBBI;
409 isFirstBlock = false;
410 } else {
411 // It's not SecondBB or (in case of a loop) the second visit of SecondBB.
412 // In this case we also have to look at instructions after SecondI.
413 EI = B->end();
414 }
415 for (; BI != EI; ++BI) {
416 Instruction *I = &*BI;
417 if (I->mayWriteToMemory() && I != SecondI)
418 if (isModSet(MRI: AA.getModRefInfo(I, OptLoc: MemLoc.getWithNewPtr(NewPtr: Ptr))))
419 return false;
420 }
421 if (B != FirstBB) {
422 assert(B != &FirstBB->getParent()->getEntryBlock() &&
423 "Should not hit the entry block because SI must be dominated by LI");
424 for (BasicBlock *Pred : predecessors(BB: B)) {
425 PHITransAddr PredAddr = Addr;
426 if (PredAddr.needsPHITranslationFromBlock(BB: B)) {
427 if (!PredAddr.isPotentiallyPHITranslatable())
428 return false;
429 if (!PredAddr.translateValue(CurBB: B, PredBB: Pred, DT, MustDominate: false))
430 return false;
431 }
432 Value *TranslatedPtr = PredAddr.getAddr();
433 auto Inserted = Visited.insert(KV: std::make_pair(x&: Pred, y&: TranslatedPtr));
434 if (!Inserted.second) {
435 // We already visited this block before. If it was with a different
436 // address - bail out!
437 if (TranslatedPtr != Inserted.first->second)
438 return false;
439 // ... otherwise just skip it.
440 continue;
441 }
442 WorkList.push_back(Elt: std::make_pair(x&: Pred, y&: PredAddr));
443 }
444 }
445 }
446 return true;
447}
448
449static void shortenAssignment(Instruction *Inst, Value *OriginalDest,
450 uint64_t OldSizeInBits, uint64_t NewSizeInBits,
451 bool IsOverwriteEnd) {
452 const DataLayout &DL = Inst->getDataLayout();
453 uint64_t DeadSliceSizeInBits = OldSizeInBits - NewSizeInBits;
454 // The dead slice offset is relative to OriginalDest, the slice start we hand
455 // calculateFragmentIntersect. Shortening the end keeps the front of the
456 // store, so the dead bits start where the new store ends; shortening the
457 // beginning kills the bits at OriginalDest itself. Don't add OriginalDest's
458 // offset from its base object here. calculateFragmentIntersect already
459 // measures that pointer against the marker's address.
460 uint64_t DeadSliceOffsetInBits = IsOverwriteEnd ? NewSizeInBits : 0;
461 auto SetDeadFragExpr = [](auto *Assign,
462 DIExpression::FragmentInfo DeadFragment) {
463 // createFragmentExpression expects an offset relative to the existing
464 // fragment offset if there is one.
465 uint64_t RelativeOffset = DeadFragment.OffsetInBits -
466 Assign->getExpression()
467 ->getFragmentInfo()
468 .value_or(DIExpression::FragmentInfo(0, 0))
469 .OffsetInBits;
470 if (auto NewExpr = DIExpression::createFragmentExpression(
471 Expr: Assign->getExpression(), OffsetInBits: RelativeOffset, SizeInBits: DeadFragment.SizeInBits)) {
472 Assign->setExpression(*NewExpr);
473 return;
474 }
475 // Failed to create a fragment expression for this so discard the value,
476 // making this a kill location.
477 auto *Expr = *DIExpression::createFragmentExpression(
478 Expr: DIExpression::get(Context&: Assign->getContext(), Elements: {}), OffsetInBits: DeadFragment.OffsetInBits,
479 SizeInBits: DeadFragment.SizeInBits);
480 Assign->setExpression(Expr);
481 Assign->setKillLocation();
482 };
483
484 // A DIAssignID to use so that the inserted dbg.assign intrinsics do not
485 // link to any instructions. Created in the loop below (once).
486 DIAssignID *LinkToNothing = nullptr;
487 LLVMContext &Ctx = Inst->getContext();
488 auto GetDeadLink = [&Ctx, &LinkToNothing]() {
489 if (!LinkToNothing)
490 LinkToNothing = DIAssignID::getDistinct(Context&: Ctx);
491 return LinkToNothing;
492 };
493
494 // Insert an unlinked dbg.assign intrinsic for the dead fragment after each
495 // overlapping dbg.assign intrinsic.
496 for (DbgVariableRecord *Assign : at::getDVRAssignmentMarkers(Inst)) {
497 std::optional<DIExpression::FragmentInfo> NewFragment;
498 if (!at::calculateFragmentIntersect(DL, Dest: OriginalDest, SliceOffsetInBits: DeadSliceOffsetInBits,
499 SliceSizeInBits: DeadSliceSizeInBits, DVRAssign: Assign,
500 Result&: NewFragment) ||
501 !NewFragment) {
502 // Either the intersection couldn't be worked out, or it covers the
503 // entire variable region described by the record. Full coverage leaves
504 // NewFragment empty rather than making calculateFragmentIntersect fail,
505 // so unlink the whole assignment from the store in both cases.
506 Assign->setKillAddress();
507 Assign->setAssignId(GetDeadLink());
508 continue;
509 }
510 // No intersect.
511 if (NewFragment->SizeInBits == 0)
512 continue;
513
514 // Fragments overlap: insert a new dbg.assign for this dead part.
515 auto *NewAssign = static_cast<decltype(Assign)>(Assign->clone());
516 NewAssign->insertAfter(InsertAfter: Assign->getIterator());
517 NewAssign->setAssignId(GetDeadLink());
518 if (NewFragment)
519 SetDeadFragExpr(NewAssign, *NewFragment);
520 NewAssign->setKillAddress();
521 }
522}
523
524/// Update the attributes given that a memory access is updated (the
525/// dereferenced pointer could be moved forward when shortening a
526/// mem intrinsic).
527static void adjustArgAttributes(AnyMemIntrinsic *Intrinsic, unsigned ArgNo,
528 uint64_t PtrOffset) {
529 // Remember old attributes.
530 AttributeSet OldAttrs = Intrinsic->getParamAttributes(ArgNo);
531
532 // Find attributes that should be kept, and remove the rest.
533 AttributeMask AttrsToRemove;
534 for (auto &Attr : OldAttrs) {
535 if (Attr.hasKindAsEnum()) {
536 switch (Attr.getKindAsEnum()) {
537 default:
538 break;
539 case Attribute::Alignment:
540 // Only keep alignment if PtrOffset satisfy the alignment.
541 if (isAligned(Lhs: Attr.getAlignment().valueOrOne(), SizeInBytes: PtrOffset))
542 continue;
543 break;
544 case Attribute::Dereferenceable:
545 case Attribute::DereferenceableOrNull:
546 // We could reduce the size of these attributes according to
547 // PtrOffset. But we simply drop these for now.
548 break;
549 case Attribute::NonNull:
550 case Attribute::NoUndef:
551 continue;
552 }
553 }
554 AttrsToRemove.addAttribute(A: Attr);
555 }
556
557 // Remove the attributes that should be dropped.
558 Intrinsic->removeParamAttrs(ArgNo, AttrsToRemove);
559}
560
561static bool tryToShorten(Instruction *DeadI, int64_t &DeadStart,
562 uint64_t &DeadSize, int64_t KillingStart,
563 uint64_t KillingSize, bool IsOverwriteEnd) {
564 auto *DeadIntrinsic = cast<AnyMemIntrinsic>(Val: DeadI);
565 Align PrefAlign = DeadIntrinsic->getDestAlign().valueOrOne();
566
567 // We assume that memet/memcpy operates in chunks of the "largest" native
568 // type size and aligned on the same value. That means optimal start and size
569 // of memset/memcpy should be modulo of preferred alignment of that type. That
570 // is it there is no any sense in trying to reduce store size any further
571 // since any "extra" stores comes for free anyway.
572 // On the other hand, maximum alignment we can achieve is limited by alignment
573 // of initial store.
574
575 // TODO: Limit maximum alignment by preferred (or abi?) alignment of the
576 // "largest" native type.
577 // Note: What is the proper way to get that value?
578 // Should TargetTransformInfo::getRegisterBitWidth be used or anything else?
579 // PrefAlign = std::min(DL.getPrefTypeAlign(LargestType), PrefAlign);
580
581 int64_t ToRemoveStart = 0;
582 uint64_t ToRemoveSize = 0;
583 // Compute start and size of the region to remove. Make sure 'PrefAlign' is
584 // maintained on the remaining store.
585 if (IsOverwriteEnd) {
586 // Calculate required adjustment for 'KillingStart' in order to keep
587 // remaining store size aligned on 'PerfAlign'.
588 uint64_t Off =
589 offsetToAlignment(Value: uint64_t(KillingStart - DeadStart), Alignment: PrefAlign);
590 ToRemoveStart = KillingStart + Off;
591 if (DeadSize <= uint64_t(ToRemoveStart - DeadStart))
592 return false;
593 ToRemoveSize = DeadSize - uint64_t(ToRemoveStart - DeadStart);
594 } else {
595 ToRemoveStart = DeadStart;
596 assert(KillingSize >= uint64_t(DeadStart - KillingStart) &&
597 "Not overlapping accesses?");
598 ToRemoveSize = KillingSize - uint64_t(DeadStart - KillingStart);
599 // Calculate required adjustment for 'ToRemoveSize'in order to keep
600 // start of the remaining store aligned on 'PerfAlign'.
601 uint64_t Off = offsetToAlignment(Value: ToRemoveSize, Alignment: PrefAlign);
602 if (Off != 0) {
603 if (ToRemoveSize <= (PrefAlign.value() - Off))
604 return false;
605 ToRemoveSize -= PrefAlign.value() - Off;
606 }
607 assert(isAligned(PrefAlign, ToRemoveSize) &&
608 "Should preserve selected alignment");
609 }
610
611 assert(ToRemoveSize > 0 && "Shouldn't reach here if nothing to remove");
612 assert(DeadSize > ToRemoveSize && "Can't remove more than original size");
613
614 uint64_t NewSize = DeadSize - ToRemoveSize;
615 if (DeadIntrinsic->isAtomic()) {
616 // When shortening an atomic memory intrinsic, the newly shortened
617 // length must remain an integer multiple of the element size.
618 const uint32_t ElementSize = DeadIntrinsic->getElementSizeInBytes();
619 if (0 != NewSize % ElementSize)
620 return false;
621 }
622
623 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n OW "
624 << (IsOverwriteEnd ? "END" : "BEGIN") << ": " << *DeadI
625 << "\n KILLER [" << ToRemoveStart << ", "
626 << int64_t(ToRemoveStart + ToRemoveSize) << ")\n");
627
628 DeadIntrinsic->setLength(NewSize);
629 DeadIntrinsic->setDestAlignment(PrefAlign);
630
631 Value *OrigDest = DeadIntrinsic->getRawDest();
632 if (!IsOverwriteEnd) {
633 Value *Indices[1] = {
634 ConstantInt::get(Ty: DeadIntrinsic->getLength()->getType(), V: ToRemoveSize)};
635 Instruction *NewDestGEP = GetElementPtrInst::CreateInBounds(
636 PointeeType: Type::getInt8Ty(C&: DeadIntrinsic->getContext()), Ptr: OrigDest, IdxList: Indices, NameStr: "",
637 InsertBefore: DeadI->getIterator());
638 NewDestGEP->setDebugLoc(DeadIntrinsic->getDebugLoc());
639 DeadIntrinsic->setDest(NewDestGEP);
640 adjustArgAttributes(Intrinsic: DeadIntrinsic, ArgNo: 0, PtrOffset: ToRemoveSize);
641 }
642
643 // Update attached dbg.assign intrinsics. Assume 8-bit byte.
644 shortenAssignment(Inst: DeadI, OriginalDest: OrigDest, OldSizeInBits: DeadSize * 8, NewSizeInBits: NewSize * 8, IsOverwriteEnd);
645
646 // Finally update start and size of dead access.
647 if (!IsOverwriteEnd)
648 DeadStart += ToRemoveSize;
649 DeadSize = NewSize;
650
651 return true;
652}
653
654static bool tryToShortenEnd(Instruction *DeadI, OverlapIntervalsTy &IntervalMap,
655 int64_t &DeadStart, uint64_t &DeadSize) {
656 if (IntervalMap.empty() || !isShortenableAtTheEnd(I: DeadI))
657 return false;
658
659 OverlapIntervalsTy::iterator OII = --IntervalMap.end();
660 int64_t KillingStart = OII->second;
661 uint64_t KillingSize = OII->first - KillingStart;
662
663 assert(OII->first - KillingStart >= 0 && "Size expected to be positive");
664
665 if (KillingStart > DeadStart &&
666 // Note: "KillingStart - KillingStart" is known to be positive due to
667 // preceding check.
668 (uint64_t)(KillingStart - DeadStart) < DeadSize &&
669 // Note: "DeadSize - (uint64_t)(KillingStart - DeadStart)" is known to
670 // be non negative due to preceding checks.
671 KillingSize >= DeadSize - (uint64_t)(KillingStart - DeadStart)) {
672 if (tryToShorten(DeadI, DeadStart, DeadSize, KillingStart, KillingSize,
673 IsOverwriteEnd: true)) {
674 IntervalMap.erase(position: OII);
675 return true;
676 }
677 }
678 return false;
679}
680
681static bool tryToShortenBegin(Instruction *DeadI,
682 OverlapIntervalsTy &IntervalMap,
683 int64_t &DeadStart, uint64_t &DeadSize) {
684 if (IntervalMap.empty() || !isShortenableAtTheBeginning(I: DeadI))
685 return false;
686
687 OverlapIntervalsTy::iterator OII = IntervalMap.begin();
688 int64_t KillingStart = OII->second;
689 uint64_t KillingSize = OII->first - KillingStart;
690
691 assert(OII->first - KillingStart >= 0 && "Size expected to be positive");
692
693 if (KillingStart <= DeadStart &&
694 // Note: "DeadStart - KillingStart" is known to be non negative due to
695 // preceding check.
696 KillingSize > (uint64_t)(DeadStart - KillingStart)) {
697 // Note: "KillingSize - (uint64_t)(DeadStart - DeadStart)" is known to
698 // be positive due to preceding checks.
699 assert(KillingSize - (uint64_t)(DeadStart - KillingStart) < DeadSize &&
700 "Should have been handled as OW_Complete");
701 if (tryToShorten(DeadI, DeadStart, DeadSize, KillingStart, KillingSize,
702 IsOverwriteEnd: false)) {
703 IntervalMap.erase(position: OII);
704 return true;
705 }
706 }
707 return false;
708}
709
710static Constant *
711tryToMergePartialOverlappingStores(StoreInst *KillingI, StoreInst *DeadI,
712 int64_t KillingOffset, int64_t DeadOffset,
713 const DataLayout &DL, BatchAAResults &AA,
714 DominatorTree *DT) {
715 assert(KillingI);
716 assert(DeadI);
717
718 // If the store we find is:
719 // a) partially overwritten by the store to 'Loc'
720 // b) the killing store is fully contained in the dead one and
721 // c) they both have a constant value
722 // d) none of the two stores need padding
723 // Merge the two stores, replacing the dead store's value with a
724 // merge of both values.
725 //
726 // TODO: Deal with other constant types (vectors, etc), and probably
727 // some mem intrinsics (if needed)
728 if (!isa<ConstantInt>(Val: DeadI->getValueOperand()) ||
729 !DL.typeSizeEqualsStoreSize(Ty: DeadI->getValueOperand()->getType()) ||
730 !isa<ConstantInt>(Val: KillingI->getValueOperand()) ||
731 !DL.typeSizeEqualsStoreSize(Ty: KillingI->getValueOperand()->getType()) ||
732 !memoryIsNotModifiedBetween(FirstI: DeadI, SecondI: KillingI, AA, DL, DT))
733 return nullptr;
734
735 // The merge erases KillingI and writes its bytes via DeadI. For that to be
736 // safe:
737 // - KillingI must be deletable (not volatile, ordering at most unordered),
738 // - DeadI must be safe to rewrite, and
739 // - their orderings must match, so the bytes originally written by
740 // KillingI keep the same atomicity after they are folded into DeadI.
741 // This allows merging two simple stores or two unordered-atomic stores with
742 // matching ordering, while leaving volatile and ordered-atomic stores in
743 // place.
744 if (!KillingI->isUnordered() || !DeadI->isUnordered() ||
745 KillingI->getOrdering() != DeadI->getOrdering())
746 return nullptr;
747
748 APInt DeadValue = cast<ConstantInt>(Val: DeadI->getValueOperand())->getValue();
749 APInt KillingValue =
750 cast<ConstantInt>(Val: KillingI->getValueOperand())->getValue();
751 unsigned KillingBits = KillingValue.getBitWidth();
752 assert(DeadValue.getBitWidth() > KillingValue.getBitWidth());
753 KillingValue = KillingValue.zext(width: DeadValue.getBitWidth());
754
755 // Offset of the smaller store inside the larger store
756 unsigned BitOffsetDiff = (KillingOffset - DeadOffset) * 8;
757 unsigned LShiftAmount =
758 DL.isBigEndian() ? DeadValue.getBitWidth() - BitOffsetDiff - KillingBits
759 : BitOffsetDiff;
760 APInt Mask = APInt::getBitsSet(numBits: DeadValue.getBitWidth(), loBit: LShiftAmount,
761 hiBit: LShiftAmount + KillingBits);
762 // Clear the bits we'll be replacing, then OR with the smaller
763 // store, shifted appropriately.
764 APInt Merged = (DeadValue & ~Mask) | (KillingValue << LShiftAmount);
765 LLVM_DEBUG(dbgs() << "DSE: Merge Stores:\n Dead: " << *DeadI
766 << "\n Killing: " << *KillingI
767 << "\n Merged Value: " << Merged << '\n');
768 return ConstantInt::get(Ty: DeadI->getValueOperand()->getType(), V: Merged);
769}
770
771// Returns true if \p I is an intrinsic that does not read or write memory.
772static bool isNoopIntrinsic(Instruction *I) {
773 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Val: I)) {
774 switch (II->getIntrinsicID()) {
775 case Intrinsic::lifetime_start:
776 case Intrinsic::lifetime_end:
777 case Intrinsic::invariant_end:
778 case Intrinsic::launder_invariant_group:
779 case Intrinsic::assume:
780 return true;
781 default:
782 return false;
783 }
784 }
785 return false;
786}
787
788// Check if we can ignore \p D for DSE.
789static bool canSkipDef(MemoryDef *D, bool DefVisibleToCaller) {
790 Instruction *DI = D->getMemoryInst();
791 // Calls that only access inaccessible memory cannot read or write any memory
792 // locations we consider for elimination.
793 if (auto *CB = dyn_cast<CallBase>(Val: DI))
794 if (CB->onlyAccessesInaccessibleMemory())
795 return true;
796
797 // We can eliminate stores to locations not visible to the caller across
798 // throwing instructions.
799 if (DI->mayThrow() && !DefVisibleToCaller)
800 return true;
801
802 // We can remove the dead stores, irrespective of the fence and its ordering
803 // (release/acquire/seq_cst). Fences only constraints the ordering of
804 // already visible stores, it does not make a store visible to other
805 // threads. So, skipping over a fence does not change a store from being
806 // dead.
807 if (isa<FenceInst>(Val: DI))
808 return true;
809
810 // Skip intrinsics that do not really read or modify memory.
811 if (isNoopIntrinsic(I: DI))
812 return true;
813
814 return false;
815}
816
817namespace {
818
819// A memory location wrapper that represents a MemoryLocation, `MemLoc`,
820// defined by `MemDef`.
821struct MemoryLocationWrapper {
822 MemoryLocationWrapper(MemoryLocation MemLoc, MemoryDef *MemDef,
823 bool DefByInitializesAttr)
824 : MemLoc(MemLoc), MemDef(MemDef),
825 DefByInitializesAttr(DefByInitializesAttr) {
826 assert(MemLoc.Ptr && "MemLoc should be not null");
827 UnderlyingObject = getUnderlyingObject(V: MemLoc.Ptr);
828 DefInst = MemDef->getMemoryInst();
829 }
830
831 MemoryLocation MemLoc;
832 const Value *UnderlyingObject;
833 MemoryDef *MemDef;
834 Instruction *DefInst;
835 bool DefByInitializesAttr = false;
836};
837
838// A memory def wrapper that represents a MemoryDef and the MemoryLocation(s)
839// defined by this MemoryDef.
840struct MemoryDefWrapper {
841 MemoryDefWrapper(MemoryDef *MemDef,
842 ArrayRef<std::pair<MemoryLocation, bool>> MemLocations) {
843 DefInst = MemDef->getMemoryInst();
844 for (auto &[MemLoc, DefByInitializesAttr] : MemLocations)
845 DefinedLocations.push_back(
846 Elt: MemoryLocationWrapper(MemLoc, MemDef, DefByInitializesAttr));
847 }
848 Instruction *DefInst;
849 SmallVector<MemoryLocationWrapper, 1> DefinedLocations;
850};
851
852struct ArgumentInitInfo {
853 unsigned Idx;
854 bool IsDeadOrInvisibleOnUnwind;
855 ConstantRangeList Inits;
856};
857} // namespace
858
859static bool hasInitializesAttr(Instruction *I) {
860 CallBase *CB = dyn_cast<CallBase>(Val: I);
861 return CB && CB->getArgOperandWithAttribute(Kind: Attribute::Initializes);
862}
863
864// Return the intersected range list of the initializes attributes of "Args".
865// "Args" are call arguments that alias to each other.
866// If any argument in "Args" doesn't have dead_on_unwind attr and
867// "CallHasNoUnwindAttr" is false, return empty.
868static ConstantRangeList
869getIntersectedInitRangeList(ArrayRef<ArgumentInitInfo> Args,
870 bool CallHasNoUnwindAttr) {
871 if (Args.empty())
872 return {};
873
874 // To address unwind, the function should have nounwind attribute or the
875 // arguments have dead or invisible on unwind. Otherwise, return empty.
876 for (const auto &Arg : Args) {
877 if (!CallHasNoUnwindAttr && !Arg.IsDeadOrInvisibleOnUnwind)
878 return {};
879 if (Arg.Inits.empty())
880 return {};
881 }
882
883 ConstantRangeList IntersectedIntervals = Args.front().Inits;
884 for (auto &Arg : Args.drop_front())
885 IntersectedIntervals = IntersectedIntervals.intersectWith(CRL: Arg.Inits);
886
887 return IntersectedIntervals;
888}
889
890namespace {
891
892struct DSEState {
893 const ScalarOptions &Opts;
894 Function &F;
895 AliasAnalysis &AA;
896 EarliestEscapeAnalysis EA;
897
898 /// The single BatchAA instance that is used to cache AA queries. It will
899 /// not be invalidated over the whole run. This is safe, because:
900 /// 1. Only memory writes are removed, so the alias cache for memory
901 /// locations remains valid.
902 /// 2. No new instructions are added (only instructions removed), so cached
903 /// information for a deleted value cannot be accessed by a re-used new
904 /// value pointer.
905 BatchAAResults BatchAA;
906
907 MemorySSA &MSSA;
908 DominatorTree &DT;
909 PostDominatorTree &PDT;
910 const TargetLibraryInfo &TLI;
911 const DataLayout &DL;
912 const CycleInfo &CI;
913
914 // All MemoryDefs that potentially could kill other MemDefs.
915 SmallVector<MemoryDef *, 64> MemDefs;
916 // Any that should be skipped as they are already deleted
917 SmallPtrSet<MemoryAccess *, 4> SkipStores;
918 // Keep track whether a given object is captured before return or not.
919 DenseMap<const Value *, bool> CapturedBeforeReturn;
920 // Keep track of all of the objects that are invisible to the caller after
921 // the function returns.
922 DenseMap<const Value *, bool> InvisibleToCallerAfterRet;
923 DenseMap<const Value *, uint64_t> InvisibleToCallerAfterRetBounded;
924 // Keep track of blocks with throwing instructions not modeled in MemorySSA.
925 SmallPtrSet<BasicBlock *, 16> ThrowingBlocks;
926 // Post-order numbers for each basic block. Used to figure out if memory
927 // accesses are executed before another access.
928 DenseMap<BasicBlock *, unsigned> PostOrderNumbers;
929
930 /// Keep track of instructions (partly) overlapping with killing MemoryDefs per
931 /// basic block.
932 MapVector<BasicBlock *, InstOverlapIntervalsTy> IOLs;
933 // Check if there are root nodes that are terminated by UnreachableInst.
934 // Those roots pessimize post-dominance queries. If there are such roots,
935 // fall back to CFG scan starting from all non-unreachable roots.
936 bool AnyUnreachableExit;
937
938 // Whether or not we should iterate on removing dead stores at the end of the
939 // function due to removing a store causing a previously captured pointer to
940 // no longer be captured.
941 bool ShouldIterateEndOfFunctionDSE;
942
943 /// Dead instructions to be removed at the end of DSE.
944 SmallVector<Instruction *> ToRemove;
945
946 // Class contains self-reference, make sure it's not copied/moved.
947 DSEState(const ScalarOptions &Opts, Function &F, AliasAnalysis &AA,
948 MemorySSA &MSSA, DominatorTree &DT, PostDominatorTree &PDT,
949 const TargetLibraryInfo &TLI, const CycleInfo &CI);
950 DSEState(const DSEState &) = delete;
951 DSEState &operator=(const DSEState &) = delete;
952
953 LocationSize strengthenLocationSize(const Instruction *I,
954 LocationSize Size) const;
955
956 /// Return 'OW_Complete' if a store to the 'KillingLoc' location (by \p
957 /// KillingI instruction) completely overwrites a store to the 'DeadLoc'
958 /// location (by \p DeadI instruction).
959 /// Return OW_MaybePartial if \p KillingI does not completely overwrite
960 /// \p DeadI, but they both write to the same underlying object. In that
961 /// case, use isPartialOverwrite to check if \p KillingI partially overwrites
962 /// \p DeadI. Returns 'OR_None' if \p KillingI is known to not overwrite the
963 /// \p DeadI. Returns 'OW_Unknown' if nothing can be determined.
964 OverwriteResult isOverwrite(const Instruction *KillingI,
965 const Instruction *DeadI,
966 const MemoryLocation &KillingLoc,
967 const MemoryLocation &DeadLoc,
968 int64_t &KillingOff, int64_t &DeadOff);
969
970 bool isInvisibleToCallerAfterRet(const Value *V, const Value *Ptr,
971 const LocationSize StoreSize);
972
973 bool isInvisibleToCallerOnUnwind(const Value *V);
974
975 std::optional<MemoryLocation> getLocForWrite(Instruction *I) const;
976
977 // Returns a list of <MemoryLocation, bool> pairs written by I.
978 // The bool means whether the write is from Initializes attr.
979 SmallVector<std::pair<MemoryLocation, bool>, 1>
980 getLocForInst(Instruction *I, bool ConsiderInitializesAttr);
981
982 /// Assuming this instruction has a dead analyzable write, can we delete
983 /// this instruction?
984 bool isRemovable(Instruction *I);
985
986 /// Returns true if \p UseInst completely overwrites \p DefLoc
987 /// (stored by \p DefInst).
988 bool isCompleteOverwrite(const MemoryLocation &DefLoc, Instruction *DefInst,
989 Instruction *UseInst);
990
991 /// Returns true if \p Def is not read before returning from the function.
992 bool isWriteAtEndOfFunction(MemoryDef *Def, const MemoryLocation &DefLoc);
993
994 /// If \p I is a memory terminator like llvm.lifetime.end or free, return a
995 /// pair with the MemoryLocation terminated by \p I and a boolean flag
996 /// indicating whether \p I is a free-like call.
997 std::optional<std::pair<MemoryLocation, bool>>
998 getLocForTerminator(Instruction *I) const;
999
1000 /// Returns true if \p I is a memory terminator instruction like
1001 /// llvm.lifetime.end or free.
1002 bool isMemTerminatorInst(Instruction *I) const;
1003
1004 /// Returns true if \p MaybeTerm is a memory terminator for \p Loc from
1005 /// instruction \p AccessI.
1006 bool isMemTerminator(const MemoryLocation &Loc, Instruction *AccessI,
1007 Instruction *MaybeTerm);
1008
1009 // Returns true if \p Use may read from \p DefLoc.
1010 bool isReadClobber(const MemoryLocation &DefLoc, Instruction *UseInst);
1011
1012 /// Returns true if a dependency between \p Current and \p KillingDef is
1013 /// guaranteed to be loop invariant for the loops that they are in. Either
1014 /// because they are known to be in the same block, in the same loop level or
1015 /// by guaranteeing that \p CurrentLoc only references a single MemoryLocation
1016 /// during execution of the containing function.
1017 bool isGuaranteedLoopIndependent(const Instruction *Current,
1018 const Instruction *KillingDef,
1019 const MemoryLocation &CurrentLoc);
1020
1021 /// Returns true if \p Ptr is guaranteed to be loop invariant for any possible
1022 /// loop. In particular, this guarantees that it only references a single
1023 /// MemoryLocation during execution of the containing function.
1024 bool isGuaranteedLoopInvariant(const Value *Ptr);
1025
1026 // Find a MemoryDef writing to \p KillingLoc and dominating \p StartAccess,
1027 // with no read access between them or on any other path to a function exit
1028 // block if \p KillingLoc is not accessible after the function returns. If
1029 // there is no such MemoryDef, return std::nullopt. The returned value may not
1030 // (completely) overwrite \p KillingLoc. Currently we bail out when we
1031 // encounter an aliasing MemoryUse (read).
1032 std::optional<MemoryAccess *>
1033 getDomMemoryDef(MemoryDef *KillingDef, MemoryAccess *StartAccess,
1034 const MemoryLocation &KillingLoc, const Value *KillingUndObj,
1035 unsigned &ScanLimit, unsigned &WalkerStepLimit,
1036 bool IsMemTerm, unsigned &PartialLimit,
1037 bool IsInitializesAttrMemLoc);
1038
1039 /// Delete dead memory defs and recursively add their operands to ToRemove if
1040 /// they became dead.
1041 void
1042 deleteDeadInstruction(Instruction *SI,
1043 SmallPtrSetImpl<MemoryAccess *> *Deleted = nullptr);
1044
1045 // Check for any extra throws between \p KillingI and \p DeadI that block
1046 // DSE. This only checks extra maythrows (those that aren't MemoryDef's).
1047 // MemoryDef that may throw are handled during the walk from one def to the
1048 // next.
1049 bool mayThrowBetween(Instruction *KillingI, Instruction *DeadI,
1050 const Value *KillingUndObj);
1051
1052 // Check if \p DeadI acts as a DSE barrier for \p KillingI. The following
1053 // instructions act as barriers:
1054 // * A memory instruction that may throw and \p KillingI accesses a non-stack
1055 // object.
1056 // * Atomic stores stronger that monotonic.
1057 bool isDSEBarrier(const Value *KillingUndObj, Instruction *DeadI);
1058
1059 /// Eliminate writes to objects that are not visible in the caller and are not
1060 /// accessed before returning from the function.
1061 bool eliminateDeadWritesAtEndOfFunction();
1062
1063 /// If we have a zero initializing memset following a call to malloc,
1064 /// try folding it into a call to calloc.
1065 bool tryFoldIntoCalloc(MemoryDef *Def, const Value *DefUO);
1066
1067 /// \returns true if \p Def is a no-op store, either because it
1068 /// directly stores back a loaded value or stores zero to a calloced object.
1069 bool storeIsNoop(MemoryDef *Def, const Value *DefUO);
1070
1071 bool removePartiallyOverlappedStores(InstOverlapIntervalsTy &IOL);
1072
1073 /// Eliminates writes to locations where the value that is being written
1074 /// is already stored at the same location.
1075 bool eliminateRedundantStoresOfExistingValues();
1076
1077 /// If there is a dominating condition that implies the value being stored in
1078 /// a pointer, and such a condition appears in a node that dominates the
1079 /// store, then the store may be redundant if no write occurs in between.
1080 bool eliminateRedundantStoresViaDominatingConditions();
1081
1082 // Return the locations written by the initializes attribute.
1083 // Note that this function considers:
1084 // 1. Unwind edge: use "initializes" attribute only if the callee has
1085 // "nounwind" attribute, or the argument has "dead_on_unwind" attribute,
1086 // or the argument is invisible to caller on unwind. That is, we don't
1087 // perform incorrect DSE on unwind edges in the current function.
1088 // 2. Argument alias: for aliasing arguments, the "initializes" attribute is
1089 // the intersected range list of their "initializes" attributes.
1090 SmallVector<MemoryLocation, 1> getInitializesArgMemLoc(const Instruction *I);
1091
1092 // Try to eliminate dead defs that access `KillingLocWrapper.MemLoc` and are
1093 // killed by `KillingLocWrapper.MemDef`. Return whether
1094 // any changes were made, and whether `KillingLocWrapper.DefInst` was deleted.
1095 std::pair<bool, bool>
1096 eliminateDeadDefs(const MemoryLocationWrapper &KillingLocWrapper);
1097
1098 // Try to eliminate dead defs killed by `KillingDefWrapper` and return the
1099 // change state: whether make any change.
1100 bool eliminateDeadDefs(const MemoryDefWrapper &KillingDefWrapper);
1101};
1102
1103} // end anonymous namespace
1104
1105static void pushMemUses(MemoryAccess *Acc,
1106 SmallVectorImpl<MemoryAccess *> &WorkList,
1107 SmallPtrSetImpl<MemoryAccess *> &Visited) {
1108 for (Use &U : Acc->uses()) {
1109 auto *MA = cast<MemoryAccess>(Val: U.getUser());
1110 if (Visited.insert(Ptr: MA).second)
1111 WorkList.push_back(Elt: MA);
1112 }
1113}
1114
1115// Return true if "Arg" is function local and isn't captured before "CB".
1116static bool isFuncLocalAndNotCaptured(Value *Arg, const CallBase *CB,
1117 EarliestEscapeAnalysis &EA) {
1118 const Value *UnderlyingObj = getUnderlyingObject(V: Arg);
1119 return isIdentifiedFunctionLocal(V: UnderlyingObj) &&
1120 capturesNothing(CC: EA.getCapturesBefore(Object: UnderlyingObj, I: CB, /*OrAt=*/true,
1121 /*ReturnCaptures=*/false));
1122}
1123
1124DSEState::DSEState(const ScalarOptions &Opts, Function &F, AliasAnalysis &AA,
1125 MemorySSA &MSSA, DominatorTree &DT, PostDominatorTree &PDT,
1126 const TargetLibraryInfo &TLI, const CycleInfo &CI)
1127 : Opts(Opts), F(F), AA(AA), EA(DT, nullptr, &CI), BatchAA(AA, &EA),
1128 MSSA(MSSA), DT(DT), PDT(PDT), TLI(TLI), DL(F.getDataLayout()), CI(CI) {
1129 // Collect blocks with throwing instructions not modeled in MemorySSA and
1130 // alloc-like objects.
1131 unsigned PO = 0;
1132 for (BasicBlock *BB : post_order(G: &F)) {
1133 PostOrderNumbers[BB] = PO++;
1134 for (Instruction &I : *BB) {
1135 MemoryAccess *MA = MSSA.getMemoryAccess(I: &I);
1136 if (I.mayThrow() && !MA)
1137 ThrowingBlocks.insert(Ptr: I.getParent());
1138
1139 auto *MD = dyn_cast_or_null<MemoryDef>(Val: MA);
1140 if (MD && MemDefs.size() < Opts.dse_memoryssa_defs_per_block_limit &&
1141 (getLocForWrite(I: &I) || isMemTerminatorInst(I: &I) ||
1142 (Opts.enable_dse_initializes_attr_improvement &&
1143 hasInitializesAttr(I: &I))))
1144 MemDefs.push_back(Elt: MD);
1145 }
1146 }
1147
1148 // Treat byval, inalloca or dead on return arguments the same as Allocas,
1149 // stores to them are dead at the end of the function.
1150 for (Argument &AI : F.args()) {
1151 if (AI.hasPassPointeeByValueCopyAttr()) {
1152 InvisibleToCallerAfterRet.insert(KV: {&AI, true});
1153 continue;
1154 }
1155
1156 if (!AI.getType()->isPointerTy())
1157 continue;
1158
1159 const DeadOnReturnInfo &Info = AI.getDeadOnReturnInfo();
1160 if (Info.coversAllReachableMemory())
1161 InvisibleToCallerAfterRet.insert(KV: {&AI, true});
1162 else if (uint64_t DeadBytes = Info.getNumberOfDeadBytes())
1163 InvisibleToCallerAfterRetBounded.insert(KV: {&AI, DeadBytes});
1164 }
1165
1166 AnyUnreachableExit = any_of(Range: PDT.roots(), P: [](const BasicBlock *E) {
1167 return isa<UnreachableInst>(Val: E->getTerminator());
1168 });
1169}
1170
1171LocationSize DSEState::strengthenLocationSize(const Instruction *I,
1172 LocationSize Size) const {
1173 if (auto *CB = dyn_cast<CallBase>(Val: I)) {
1174 LibFunc F = TLI.getLibFunc(CB: *CB);
1175 if (TLI.has(F) && (F == LibFunc_memset_chk || F == LibFunc_memcpy_chk)) {
1176 // Use the precise location size specified by the 3rd argument
1177 // for determining KillingI overwrites DeadLoc if it is a memset_chk
1178 // instruction. memset_chk will write either the amount specified as 3rd
1179 // argument or the function will immediately abort and exit the program.
1180 // NOTE: AA may determine NoAlias if it can prove that the access size
1181 // is larger than the allocation size due to that being UB. To avoid
1182 // returning potentially invalid NoAlias results by AA, limit the use of
1183 // the precise location size to isOverwrite.
1184 if (const auto *Len = dyn_cast<ConstantInt>(Val: CB->getArgOperand(i: 2)))
1185 return LocationSize::precise(Value: Len->getZExtValue());
1186 }
1187 }
1188 return Size;
1189}
1190
1191OverwriteResult DSEState::isOverwrite(const Instruction *KillingI,
1192 const Instruction *DeadI,
1193 const MemoryLocation &KillingLoc,
1194 const MemoryLocation &DeadLoc,
1195 int64_t &KillingOff, int64_t &DeadOff) {
1196 // AliasAnalysis does not always account for loops. Limit overwrite checks
1197 // to dependencies for which we can guarantee they are independent of any
1198 // loops they are in.
1199 if (!isGuaranteedLoopIndependent(Current: DeadI, KillingDef: KillingI, CurrentLoc: DeadLoc))
1200 return OW_Unknown;
1201
1202 LocationSize KillingLocSize =
1203 strengthenLocationSize(I: KillingI, Size: KillingLoc.Size);
1204 const Value *DeadPtr = DeadLoc.Ptr->stripPointerCasts();
1205 const Value *KillingPtr = KillingLoc.Ptr->stripPointerCasts();
1206 const Value *DeadUndObj = getUnderlyingObject(V: DeadPtr);
1207 const Value *KillingUndObj = getUnderlyingObject(V: KillingPtr);
1208
1209 // Check whether the killing store overwrites the whole object, in which
1210 // case the size/offset of the dead store does not matter.
1211 if (DeadUndObj == KillingUndObj && KillingLocSize.isPrecise() &&
1212 isIdentifiedObject(V: KillingUndObj)) {
1213 std::optional<TypeSize> KillingUndObjSize =
1214 getPointerSize(V: KillingUndObj, DL, TLI, F: &F);
1215 if (KillingUndObjSize && *KillingUndObjSize == KillingLocSize.getValue())
1216 return OW_Complete;
1217 }
1218
1219 // FIXME: Vet that this works for size upper-bounds. Seems unlikely that we'll
1220 // get imprecise values here, though (except for unknown sizes).
1221 if (!KillingLocSize.isPrecise() || !DeadLoc.Size.isPrecise()) {
1222 // In case no constant size is known, try to an IR values for the number
1223 // of bytes written and check if they match.
1224 const auto *KillingMemI = dyn_cast<MemIntrinsic>(Val: KillingI);
1225 const auto *DeadMemI = dyn_cast<MemIntrinsic>(Val: DeadI);
1226 if (KillingMemI && DeadMemI) {
1227 const Value *KillingV = KillingMemI->getLength();
1228 const Value *DeadV = DeadMemI->getLength();
1229 if (KillingV == DeadV && BatchAA.isMustAlias(LocA: DeadLoc, LocB: KillingLoc))
1230 return OW_Complete;
1231 }
1232
1233 // Masked stores have imprecise locations, but we can reason about them
1234 // to some extent.
1235 return isMaskedStoreOverwrite(KillingI, DeadI, AA&: BatchAA);
1236 }
1237
1238 const TypeSize KillingSize = KillingLocSize.getValue();
1239 const TypeSize DeadSize = DeadLoc.Size.getValue();
1240 // Bail on doing Size comparison which depends on AA for now
1241 // TODO: Remove AnyScalable once Alias Analysis deal with scalable vectors
1242 const bool AnyScalable = DeadSize.isScalable() || KillingLocSize.isScalable();
1243
1244 if (AnyScalable)
1245 return OW_Unknown;
1246 // Query the alias information
1247 AliasResult AAR = BatchAA.alias(LocA: KillingLoc, LocB: DeadLoc);
1248
1249 // If the start pointers are the same, we just have to compare sizes to see if
1250 // the killing store was larger than the dead store.
1251 if (AAR == AliasResult::MustAlias) {
1252 // Make sure that the KillingSize size is >= the DeadSize size.
1253 if (KillingSize >= DeadSize)
1254 return OW_Complete;
1255 }
1256
1257 // If we hit a partial alias we may have a full overwrite
1258 if (AAR == AliasResult::PartialAlias && AAR.hasOffset()) {
1259 int32_t Off = AAR.getOffset();
1260 if (Off >= 0 && (uint64_t)Off + DeadSize <= KillingSize)
1261 return OW_Complete;
1262 }
1263
1264 // If we can't resolve the same pointers to the same object, then we can't
1265 // analyze them at all.
1266 if (DeadUndObj != KillingUndObj) {
1267 // Non aliasing stores to different objects don't overlap. Note that
1268 // if the killing store is known to overwrite whole object (out of
1269 // bounds access overwrites whole object as well) then it is assumed to
1270 // completely overwrite any store to the same object even if they don't
1271 // actually alias (see next check).
1272 if (AAR == AliasResult::NoAlias)
1273 return OW_None;
1274 return OW_Unknown;
1275 }
1276
1277 // Okay, we have stores to two completely different pointers. Try to
1278 // decompose the pointer into a "base + constant_offset" form. If the base
1279 // pointers are equal, then we can reason about the two stores.
1280 DeadOff = 0;
1281 KillingOff = 0;
1282 const Value *DeadBasePtr =
1283 GetPointerBaseWithConstantOffset(Ptr: DeadPtr, Offset&: DeadOff, DL);
1284 const Value *KillingBasePtr =
1285 GetPointerBaseWithConstantOffset(Ptr: KillingPtr, Offset&: KillingOff, DL);
1286
1287 // If the base pointers still differ, we have two completely different
1288 // stores.
1289 if (DeadBasePtr != KillingBasePtr)
1290 return OW_Unknown;
1291
1292 // The killing access completely overlaps the dead store if and only if
1293 // both start and end of the dead one is "inside" the killing one:
1294 // |<->|--dead--|<->|
1295 // |-----killing------|
1296 // Accesses may overlap if and only if start of one of them is "inside"
1297 // another one:
1298 // |<->|--dead--|<-------->|
1299 // |-------killing--------|
1300 // OR
1301 // |-------dead-------|
1302 // |<->|---killing---|<----->|
1303 //
1304 // We have to be careful here as *Off is signed while *.Size is unsigned.
1305
1306 // Check if the dead access starts "not before" the killing one.
1307 if (DeadOff >= KillingOff) {
1308 // If the dead access ends "not after" the killing access then the
1309 // dead one is completely overwritten by the killing one.
1310 if (uint64_t(DeadOff - KillingOff) + DeadSize <= KillingSize)
1311 return OW_Complete;
1312 // If start of the dead access is "before" end of the killing access
1313 // then accesses overlap.
1314 else if ((uint64_t)(DeadOff - KillingOff) < KillingSize)
1315 return OW_MaybePartial;
1316 }
1317 // If start of the killing access is "before" end of the dead access then
1318 // accesses overlap.
1319 else if ((uint64_t)(KillingOff - DeadOff) < DeadSize) {
1320 return OW_MaybePartial;
1321 }
1322
1323 // Can reach here only if accesses are known not to overlap.
1324 return OW_None;
1325}
1326
1327bool DSEState::isInvisibleToCallerAfterRet(const Value *V, const Value *Ptr,
1328 const LocationSize StoreSize) {
1329 if (isa<AllocaInst>(Val: V))
1330 return true;
1331
1332 auto IBounded = InvisibleToCallerAfterRetBounded.find(Val: V);
1333 if (IBounded != InvisibleToCallerAfterRetBounded.end()) {
1334 int64_t ValueOffset;
1335 [[maybe_unused]] const Value *BaseValue =
1336 GetPointerBaseWithConstantOffset(Ptr, Offset&: ValueOffset, DL);
1337 // If we are not able to find a constant offset from the UO, we have to
1338 // pessimistically assume that the store writes to memory out of the
1339 // dead_on_return bounds.
1340 if (BaseValue != V)
1341 return false;
1342 // This store is only invisible after return if we are in bounds of the
1343 // range marked dead.
1344 if (StoreSize.hasValue() &&
1345 ValueOffset + StoreSize.getValue() <= IBounded->second &&
1346 ValueOffset >= 0)
1347 return true;
1348 }
1349 auto I = InvisibleToCallerAfterRet.insert(KV: {V, false});
1350 if (I.second && isInvisibleToCallerOnUnwind(V) && isNoAliasCall(V))
1351 I.first->second = capturesNothing(
1352 CC: PointerMayBeCaptured(V, Mask: CaptureComponents::Provenance).WithRet);
1353 return I.first->second;
1354}
1355
1356bool DSEState::isInvisibleToCallerOnUnwind(const Value *V) {
1357 bool RequiresNoCaptureBeforeUnwind;
1358 if (!isNotVisibleOnUnwind(Object: V, RequiresNoCaptureBeforeUnwind))
1359 return false;
1360 if (!RequiresNoCaptureBeforeUnwind)
1361 return true;
1362
1363 auto I = CapturedBeforeReturn.insert(KV: {V, true});
1364 if (I.second)
1365 // NOTE: This could be made more precise by PointerMayBeCapturedBefore
1366 // with the killing MemoryDef. But we refrain from doing so for now to
1367 // limit compile-time and this does not cause any changes to the number
1368 // of stores removed on a large test set in practice.
1369 I.first->second = capturesAnything(
1370 CC: PointerMayBeCaptured(V, Mask: CaptureComponents::Provenance).WithoutRet);
1371 return !I.first->second;
1372}
1373
1374std::optional<MemoryLocation> DSEState::getLocForWrite(Instruction *I) const {
1375 if (!I->mayWriteToMemory())
1376 return std::nullopt;
1377
1378 if (auto *CB = dyn_cast<CallBase>(Val: I))
1379 return MemoryLocation::getForDest(CI: CB, TLI);
1380
1381 return MemoryLocation::getOrNone(Inst: I);
1382}
1383
1384SmallVector<std::pair<MemoryLocation, bool>, 1>
1385DSEState::getLocForInst(Instruction *I, bool ConsiderInitializesAttr) {
1386 SmallVector<std::pair<MemoryLocation, bool>, 1> Locations;
1387 if (isMemTerminatorInst(I)) {
1388 if (auto Loc = getLocForTerminator(I))
1389 Locations.push_back(Elt: std::make_pair(x&: Loc->first, y: false));
1390 return Locations;
1391 }
1392
1393 if (auto Loc = getLocForWrite(I))
1394 Locations.push_back(Elt: std::make_pair(x&: *Loc, y: false));
1395
1396 if (ConsiderInitializesAttr) {
1397 for (auto &MemLoc : getInitializesArgMemLoc(I)) {
1398 Locations.push_back(Elt: std::make_pair(x&: MemLoc, y: true));
1399 }
1400 }
1401 return Locations;
1402}
1403
1404bool DSEState::isRemovable(Instruction *I) {
1405 assert(getLocForWrite(I) && "Must have analyzable write");
1406
1407 // Don't remove volatile/atomic stores.
1408 if (StoreInst *SI = dyn_cast<StoreInst>(Val: I))
1409 return SI->isUnordered();
1410
1411 if (auto *CB = dyn_cast<CallBase>(Val: I)) {
1412 // Don't remove volatile memory intrinsics.
1413 if (auto *MI = dyn_cast<MemIntrinsic>(Val: CB))
1414 return !MI->isVolatile();
1415
1416 // Never remove dead lifetime intrinsics, e.g. because they are followed
1417 // by a free.
1418 if (CB->isLifetimeStartOrEnd())
1419 return false;
1420
1421 return CB->use_empty() && CB->willReturn() && CB->doesNotThrow() &&
1422 !CB->isTerminator();
1423 }
1424
1425 return false;
1426}
1427
1428bool DSEState::isCompleteOverwrite(const MemoryLocation &DefLoc,
1429 Instruction *DefInst, Instruction *UseInst) {
1430 // UseInst has a MemoryDef associated in MemorySSA. It's possible for a
1431 // MemoryDef to not write to memory, e.g. a volatile load is modeled as a
1432 // MemoryDef.
1433 if (!UseInst->mayWriteToMemory())
1434 return false;
1435
1436 if (auto *CB = dyn_cast<CallBase>(Val: UseInst))
1437 if (CB->onlyAccessesInaccessibleMemory())
1438 return false;
1439
1440 int64_t InstWriteOffset, DepWriteOffset;
1441 if (auto CC = getLocForWrite(I: UseInst))
1442 return isOverwrite(KillingI: UseInst, DeadI: DefInst, KillingLoc: *CC, DeadLoc: DefLoc, KillingOff&: InstWriteOffset,
1443 DeadOff&: DepWriteOffset) == OW_Complete;
1444 return false;
1445}
1446
1447bool DSEState::isWriteAtEndOfFunction(MemoryDef *Def,
1448 const MemoryLocation &DefLoc) {
1449 LLVM_DEBUG(dbgs() << " Check if def " << *Def << " ("
1450 << *Def->getMemoryInst()
1451 << ") is at the end the function \n");
1452 SmallVector<MemoryAccess *, 4> WorkList;
1453 SmallPtrSet<MemoryAccess *, 8> Visited;
1454
1455 pushMemUses(Acc: Def, WorkList, Visited);
1456 for (unsigned I = 0; I < WorkList.size(); I++) {
1457 if (WorkList.size() >= Opts.dse_memoryssa_scanlimit) {
1458 LLVM_DEBUG(dbgs() << " ... hit exploration limit.\n");
1459 return false;
1460 }
1461
1462 MemoryAccess *UseAccess = WorkList[I];
1463 if (isa<MemoryPhi>(Val: UseAccess)) {
1464 // AliasAnalysis does not account for loops. Limit elimination to
1465 // candidates for which we can guarantee they always store to the same
1466 // memory location.
1467 if (!isGuaranteedLoopInvariant(Ptr: DefLoc.Ptr))
1468 return false;
1469
1470 pushMemUses(Acc: cast<MemoryPhi>(Val: UseAccess), WorkList, Visited);
1471 continue;
1472 }
1473 // TODO: Checking for aliasing is expensive. Consider reducing the amount
1474 // of times this is called and/or caching it.
1475 Instruction *UseInst = cast<MemoryUseOrDef>(Val: UseAccess)->getMemoryInst();
1476 if (isReadClobber(DefLoc, UseInst)) {
1477 LLVM_DEBUG(dbgs() << " ... hit read clobber " << *UseInst << ".\n");
1478 return false;
1479 }
1480
1481 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(Val: UseAccess))
1482 pushMemUses(Acc: UseDef, WorkList, Visited);
1483 }
1484 return true;
1485}
1486
1487std::optional<std::pair<MemoryLocation, bool>>
1488DSEState::getLocForTerminator(Instruction *I) const {
1489 if (auto *CB = dyn_cast<CallBase>(Val: I)) {
1490 if (CB->getIntrinsicID() == Intrinsic::lifetime_end)
1491 return {
1492 std::make_pair(x: MemoryLocation::getForArgument(Call: CB, ArgIdx: 0, TLI: &TLI), y: false)};
1493 if (Value *FreedOp = getFreedOperand(CB, TLI: &TLI))
1494 return {std::make_pair(x: MemoryLocation::getAfter(Ptr: FreedOp), y: true)};
1495 }
1496
1497 return std::nullopt;
1498}
1499
1500bool DSEState::isMemTerminatorInst(Instruction *I) const {
1501 auto *CB = dyn_cast<CallBase>(Val: I);
1502 return CB && (CB->getIntrinsicID() == Intrinsic::lifetime_end ||
1503 getFreedOperand(CB, TLI: &TLI) != nullptr);
1504}
1505
1506bool DSEState::isMemTerminator(const MemoryLocation &Loc, Instruction *AccessI,
1507 Instruction *MaybeTerm) {
1508 std::optional<std::pair<MemoryLocation, bool>> MaybeTermLoc =
1509 getLocForTerminator(I: MaybeTerm);
1510
1511 if (!MaybeTermLoc)
1512 return false;
1513
1514 // If the terminator is a free-like call, all accesses to the underlying
1515 // object can be considered terminated.
1516 if (getUnderlyingObject(V: Loc.Ptr) !=
1517 getUnderlyingObject(V: MaybeTermLoc->first.Ptr))
1518 return false;
1519
1520 auto TermLoc = MaybeTermLoc->first;
1521 if (MaybeTermLoc->second) {
1522 const Value *LocUO = getUnderlyingObject(V: Loc.Ptr);
1523 return BatchAA.isMustAlias(V1: TermLoc.Ptr, V2: LocUO);
1524 }
1525 int64_t InstWriteOffset = 0;
1526 int64_t DepWriteOffset = 0;
1527 return isOverwrite(KillingI: MaybeTerm, DeadI: AccessI, KillingLoc: TermLoc, DeadLoc: Loc, KillingOff&: InstWriteOffset,
1528 DeadOff&: DepWriteOffset) == OW_Complete;
1529}
1530
1531bool DSEState::isReadClobber(const MemoryLocation &DefLoc,
1532 Instruction *UseInst) {
1533 if (isNoopIntrinsic(I: UseInst))
1534 return false;
1535
1536 // Monotonic or weaker atomic stores can be re-ordered and do not need to be
1537 // treated as read clobber.
1538 if (auto SI = dyn_cast<StoreInst>(Val: UseInst))
1539 return isStrongerThan(AO: SI->getOrdering(), Other: AtomicOrdering::Monotonic);
1540
1541 if (!UseInst->mayReadFromMemory())
1542 return false;
1543
1544 if (auto *CB = dyn_cast<CallBase>(Val: UseInst))
1545 if (CB->onlyAccessesInaccessibleMemory())
1546 return false;
1547
1548 return isRefSet(MRI: BatchAA.getModRefInfo(I: UseInst, OptLoc: DefLoc));
1549}
1550
1551bool DSEState::isGuaranteedLoopIndependent(const Instruction *Current,
1552 const Instruction *KillingDef,
1553 const MemoryLocation &CurrentLoc) {
1554 // If the dependency is within the same block or loop level (being careful
1555 // of irreducible loops), we know that AA will return a valid result for the
1556 // memory dependency. (Both at the function level, outside of any loop,
1557 // would also be valid but we currently disable that to limit compile time).
1558 if (Current->getParent() == KillingDef->getParent())
1559 return true;
1560 CycleRef CurrentC = CI.getCycle(Block: Current->getParent());
1561 if (CurrentC && CurrentC == CI.getCycle(Block: KillingDef->getParent()))
1562 return true;
1563 // Otherwise check the memory location is invariant to any loops.
1564 return isGuaranteedLoopInvariant(Ptr: CurrentLoc.Ptr);
1565}
1566
1567bool DSEState::isGuaranteedLoopInvariant(const Value *Ptr) {
1568 Ptr = Ptr->stripPointerCasts();
1569 if (auto *GEP = dyn_cast<GEPOperator>(Val: Ptr))
1570 if (GEP->hasAllConstantIndices())
1571 Ptr = GEP->getPointerOperand()->stripPointerCasts();
1572
1573 if (auto *I = dyn_cast<Instruction>(Val: Ptr)) {
1574 return I->getParent()->isEntryBlock() || !CI.getCycle(Block: I->getParent());
1575 }
1576 return true;
1577}
1578
1579std::optional<MemoryAccess *> DSEState::getDomMemoryDef(
1580 MemoryDef *KillingDef, MemoryAccess *StartAccess,
1581 const MemoryLocation &KillingLoc, const Value *KillingUndObj,
1582 unsigned &ScanLimit, unsigned &WalkerStepLimit, bool IsMemTerm,
1583 unsigned &PartialLimit, bool IsInitializesAttrMemLoc) {
1584 if (ScanLimit == 0 || WalkerStepLimit == 0) {
1585 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n");
1586 return std::nullopt;
1587 }
1588
1589 MemoryAccess *Current = StartAccess;
1590 Instruction *KillingI = KillingDef->getMemoryInst();
1591 LLVM_DEBUG(dbgs() << " trying to get dominating access\n");
1592
1593 // Only optimize defining access of KillingDef when directly starting at its
1594 // defining access. The defining access also must only access KillingLoc. At
1595 // the moment we only support instructions with a single write location, so
1596 // it should be sufficient to disable optimizations for instructions that
1597 // also read from memory.
1598 bool CanOptimize = Opts.dse_optimize_memoryssa &&
1599 KillingDef->getDefiningAccess() == StartAccess &&
1600 !KillingI->mayReadFromMemory();
1601
1602 // Find the next clobbering Mod access for DefLoc, starting at StartAccess.
1603 std::optional<MemoryLocation> CurrentLoc;
1604 for (;; Current = cast<MemoryDef>(Val: Current)->getDefiningAccess()) {
1605 LLVM_DEBUG({
1606 dbgs() << " visiting " << *Current;
1607 if (!MSSA.isLiveOnEntryDef(Current) && isa<MemoryUseOrDef>(Current))
1608 dbgs() << " (" << *cast<MemoryUseOrDef>(Current)->getMemoryInst()
1609 << ")";
1610 dbgs() << "\n";
1611 });
1612
1613 // Reached TOP.
1614 if (MSSA.isLiveOnEntryDef(MA: Current)) {
1615 LLVM_DEBUG(dbgs() << " ... found LiveOnEntryDef\n");
1616 if (CanOptimize && Current != KillingDef->getDefiningAccess())
1617 // The first clobbering def is... none.
1618 KillingDef->setOptimized(Current);
1619 return std::nullopt;
1620 }
1621
1622 // Cost of a step. Accesses in the same block are more likely to be valid
1623 // candidates for elimination, hence consider them cheaper.
1624 unsigned StepCost = KillingDef->getBlock() == Current->getBlock()
1625 ? Opts.dse_memoryssa_samebb_cost
1626 : Opts.dse_memoryssa_otherbb_cost;
1627 if (WalkerStepLimit <= StepCost) {
1628 LLVM_DEBUG(dbgs() << " ... hit walker step limit\n");
1629 return std::nullopt;
1630 }
1631 WalkerStepLimit -= StepCost;
1632
1633 // Return for MemoryPhis. They cannot be eliminated directly and the
1634 // caller is responsible for traversing them.
1635 if (isa<MemoryPhi>(Val: Current)) {
1636 LLVM_DEBUG(dbgs() << " ... found MemoryPhi\n");
1637 return Current;
1638 }
1639
1640 // Below, check if CurrentDef is a valid candidate to be eliminated by
1641 // KillingDef. If it is not, check the next candidate.
1642 MemoryDef *CurrentDef = cast<MemoryDef>(Val: Current);
1643 Instruction *CurrentI = CurrentDef->getMemoryInst();
1644
1645 if (canSkipDef(D: CurrentDef, DefVisibleToCaller: !isInvisibleToCallerOnUnwind(V: KillingUndObj))) {
1646 CanOptimize = false;
1647 continue;
1648 }
1649
1650 // Before we try to remove anything, check for any extra throwing
1651 // instructions that block us from DSEing
1652 if (mayThrowBetween(KillingI, DeadI: CurrentI, KillingUndObj)) {
1653 LLVM_DEBUG(dbgs() << " ... skip, may throw!\n");
1654 return std::nullopt;
1655 }
1656
1657 // Check for anything that looks like it will be a barrier to further
1658 // removal
1659 if (isDSEBarrier(KillingUndObj, DeadI: CurrentI)) {
1660 LLVM_DEBUG(dbgs() << " ... skip, barrier\n");
1661 return std::nullopt;
1662 }
1663
1664 // If Current is known to be on path that reads DefLoc or is a read
1665 // clobber, bail out, as the path is not profitable. We skip this check
1666 // for intrinsic calls, because the code knows how to handle memcpy
1667 // intrinsics.
1668 if (!isa<IntrinsicInst>(Val: CurrentI) && isReadClobber(DefLoc: KillingLoc, UseInst: CurrentI))
1669 return std::nullopt;
1670
1671 // Quick check if there are direct uses that are read-clobbers.
1672 if (any_of(Range: Current->uses(), P: [this, &KillingLoc, StartAccess](Use &U) {
1673 if (auto *UseOrDef = dyn_cast<MemoryUseOrDef>(Val: U.getUser()))
1674 return !MSSA.dominates(A: StartAccess, B: UseOrDef) &&
1675 isReadClobber(DefLoc: KillingLoc, UseInst: UseOrDef->getMemoryInst());
1676 return false;
1677 })) {
1678 LLVM_DEBUG(dbgs() << " ... found a read clobber\n");
1679 return std::nullopt;
1680 }
1681
1682 // If Current does not have an analyzable write location or is not
1683 // removable, skip it.
1684 CurrentLoc = getLocForWrite(I: CurrentI);
1685 if (!CurrentLoc || !isRemovable(I: CurrentI)) {
1686 CanOptimize = false;
1687 continue;
1688 }
1689
1690 // AliasAnalysis does not account for loops. Limit elimination to
1691 // candidates for which we can guarantee they always store to the same
1692 // memory location and not located in different loops.
1693 if (!isGuaranteedLoopIndependent(Current: CurrentI, KillingDef: KillingI, CurrentLoc: *CurrentLoc)) {
1694 LLVM_DEBUG(dbgs() << " ... not guaranteed loop independent\n");
1695 CanOptimize = false;
1696 continue;
1697 }
1698
1699 if (IsMemTerm) {
1700 // If the killing def is a memory terminator (e.g. lifetime.end), check
1701 // the next candidate if the current Current does not write the same
1702 // underlying object as the terminator.
1703 if (!isMemTerminator(Loc: *CurrentLoc, AccessI: CurrentI, MaybeTerm: KillingI)) {
1704 CanOptimize = false;
1705 continue;
1706 }
1707 } else {
1708 int64_t KillingOffset = 0;
1709 int64_t DeadOffset = 0;
1710 auto OR = isOverwrite(KillingI, DeadI: CurrentI, KillingLoc, DeadLoc: *CurrentLoc,
1711 KillingOff&: KillingOffset, DeadOff&: DeadOffset);
1712 if (CanOptimize) {
1713 // CurrentDef is the earliest write clobber of KillingDef. Use it as
1714 // optimized access. Do not optimize if CurrentDef is already the
1715 // defining access of KillingDef.
1716 if (CurrentDef != KillingDef->getDefiningAccess() &&
1717 (OR == OW_Complete || OR == OW_MaybePartial))
1718 KillingDef->setOptimized(CurrentDef);
1719
1720 // Once a may-aliasing def is encountered do not set an optimized
1721 // access.
1722 if (OR != OW_None)
1723 CanOptimize = false;
1724 }
1725
1726 // If Current does not write to the same object as KillingDef, check
1727 // the next candidate.
1728 if (OR == OW_Unknown || OR == OW_None)
1729 continue;
1730 else if (OR == OW_MaybePartial) {
1731 // If KillingDef only partially overwrites Current, check the next
1732 // candidate if the partial step limit is exceeded. This aggressively
1733 // limits the number of candidates for partial store elimination,
1734 // which are less likely to be removable in the end.
1735 if (PartialLimit <= 1) {
1736 WalkerStepLimit -= 1;
1737 LLVM_DEBUG(dbgs() << " ... reached partial limit ... continue with "
1738 "next access\n");
1739 continue;
1740 }
1741 PartialLimit -= 1;
1742 }
1743 }
1744 break;
1745 };
1746
1747 // Accesses to objects accessible after the function returns can only be
1748 // eliminated if the access is dead along all paths to the exit. Collect
1749 // the blocks with killing (=completely overwriting MemoryDefs) and check if
1750 // they cover all paths from MaybeDeadAccess to any function exit.
1751 SmallPtrSet<Instruction *, 16> KillingDefs;
1752 KillingDefs.insert(Ptr: KillingDef->getMemoryInst());
1753 MemoryAccess *MaybeDeadAccess = Current;
1754 MemoryLocation MaybeDeadLoc = *CurrentLoc;
1755 Instruction *MaybeDeadI = cast<MemoryDef>(Val: MaybeDeadAccess)->getMemoryInst();
1756 LLVM_DEBUG(dbgs() << " Checking for reads of " << *MaybeDeadAccess << " ("
1757 << *MaybeDeadI << ")\n");
1758
1759 SmallVector<MemoryAccess *, 32> WorkList;
1760 SmallPtrSet<MemoryAccess *, 32> Visited;
1761 pushMemUses(Acc: MaybeDeadAccess, WorkList, Visited);
1762
1763 // Check if DeadDef may be read.
1764 for (unsigned I = 0; I < WorkList.size(); I++) {
1765 MemoryAccess *UseAccess = WorkList[I];
1766
1767 LLVM_DEBUG(dbgs() << " " << *UseAccess);
1768 // Bail out if the number of accesses to check exceeds the scan limit.
1769 if (ScanLimit < (WorkList.size() - I)) {
1770 LLVM_DEBUG(dbgs() << "\n ... hit scan limit\n");
1771 return std::nullopt;
1772 }
1773 --ScanLimit;
1774 NumDomMemDefChecks++;
1775
1776 if (isa<MemoryPhi>(Val: UseAccess)) {
1777 if (any_of(Range&: KillingDefs, P: [this, UseAccess](Instruction *KI) {
1778 return DT.properlyDominates(A: KI->getParent(), B: UseAccess->getBlock());
1779 })) {
1780 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing block\n");
1781 continue;
1782 }
1783 LLVM_DEBUG(dbgs() << "\n ... adding PHI uses\n");
1784 pushMemUses(Acc: UseAccess, WorkList, Visited);
1785 continue;
1786 }
1787
1788 Instruction *UseInst = cast<MemoryUseOrDef>(Val: UseAccess)->getMemoryInst();
1789 LLVM_DEBUG(dbgs() << " (" << *UseInst << ")\n");
1790
1791 if (any_of(Range&: KillingDefs, P: [this, UseInst](Instruction *KI) {
1792 return DT.dominates(Def: KI, User: UseInst);
1793 })) {
1794 LLVM_DEBUG(dbgs() << " ... skipping, dominated by killing def\n");
1795 continue;
1796 }
1797
1798 // A memory terminator kills all preceeding MemoryDefs and all succeeding
1799 // MemoryAccesses. We do not have to check it's users.
1800 if (isMemTerminator(Loc: MaybeDeadLoc, AccessI: MaybeDeadI, MaybeTerm: UseInst)) {
1801 LLVM_DEBUG(
1802 dbgs()
1803 << " ... skipping, memterminator invalidates following accesses\n");
1804 continue;
1805 }
1806
1807 if (isNoopIntrinsic(I: cast<MemoryUseOrDef>(Val: UseAccess)->getMemoryInst())) {
1808 LLVM_DEBUG(dbgs() << " ... adding uses of intrinsic\n");
1809 pushMemUses(Acc: UseAccess, WorkList, Visited);
1810 continue;
1811 }
1812
1813 if (UseInst->mayThrow() && !isInvisibleToCallerOnUnwind(V: KillingUndObj)) {
1814 LLVM_DEBUG(dbgs() << " ... found throwing instruction\n");
1815 return std::nullopt;
1816 }
1817
1818 // Uses which may read the original MemoryDef mean we cannot eliminate the
1819 // original MD. Stop walk.
1820 // If KillingDef is a CallInst with "initializes" attribute, the reads in
1821 // the callee would be dominated by initializations, so it should be safe.
1822 bool IsKillingDefFromInitAttr = false;
1823 if (IsInitializesAttrMemLoc) {
1824 if (KillingI == UseInst &&
1825 KillingUndObj == getUnderlyingObject(V: MaybeDeadLoc.Ptr))
1826 IsKillingDefFromInitAttr = true;
1827 }
1828
1829 if (isReadClobber(DefLoc: MaybeDeadLoc, UseInst) && !IsKillingDefFromInitAttr) {
1830 LLVM_DEBUG(dbgs() << " ... found read clobber\n");
1831 return std::nullopt;
1832 }
1833
1834 // If this worklist walks back to the original memory access (and the
1835 // pointer is not guarenteed loop invariant) then we cannot assume that a
1836 // store kills itself.
1837 if (MaybeDeadAccess == UseAccess &&
1838 !isGuaranteedLoopInvariant(Ptr: MaybeDeadLoc.Ptr)) {
1839 LLVM_DEBUG(dbgs() << " ... found not loop invariant self access\n");
1840 return std::nullopt;
1841 }
1842 // Otherwise, for the KillingDef and MaybeDeadAccess we only have to check
1843 // if it reads the memory location.
1844 // TODO: It would probably be better to check for self-reads before
1845 // calling the function.
1846 if (KillingDef == UseAccess || MaybeDeadAccess == UseAccess) {
1847 LLVM_DEBUG(dbgs() << " ... skipping killing def/dom access\n");
1848 continue;
1849 }
1850
1851 // Check all uses for MemoryDefs, except for defs completely overwriting
1852 // the original location. Otherwise we have to check uses of *all*
1853 // MemoryDefs we discover, including non-aliasing ones. Otherwise we might
1854 // miss cases like the following
1855 // 1 = Def(LoE) ; <----- DeadDef stores [0,1]
1856 // 2 = Def(1) ; (2, 1) = NoAlias, stores [2,3]
1857 // Use(2) ; MayAlias 2 *and* 1, loads [0, 3].
1858 // (The Use points to the *first* Def it may alias)
1859 // 3 = Def(1) ; <---- Current (3, 2) = NoAlias, (3,1) = MayAlias,
1860 // stores [0,1]
1861 if (MemoryDef *UseDef = dyn_cast<MemoryDef>(Val: UseAccess)) {
1862 if (isCompleteOverwrite(DefLoc: MaybeDeadLoc, DefInst: MaybeDeadI, UseInst)) {
1863 BasicBlock *MaybeKillingBlock = UseInst->getParent();
1864 if (PostOrderNumbers.find(Val: MaybeKillingBlock)->second <
1865 PostOrderNumbers.find(Val: MaybeDeadAccess->getBlock())->second) {
1866 if (!isInvisibleToCallerAfterRet(V: KillingUndObj, Ptr: KillingLoc.Ptr,
1867 StoreSize: KillingLoc.Size)) {
1868 LLVM_DEBUG(dbgs()
1869 << " ... found killing def " << *UseInst << "\n");
1870 KillingDefs.insert(Ptr: UseInst);
1871 }
1872 } else {
1873 LLVM_DEBUG(dbgs()
1874 << " ... found preceeding def " << *UseInst << "\n");
1875 return std::nullopt;
1876 }
1877 } else
1878 pushMemUses(Acc: UseDef, WorkList, Visited);
1879 }
1880 }
1881
1882 // For accesses to locations visible after the function returns, make sure
1883 // that the location is dead (=overwritten) along all paths from
1884 // MaybeDeadAccess to the exit.
1885 if (!isInvisibleToCallerAfterRet(V: KillingUndObj, Ptr: KillingLoc.Ptr,
1886 StoreSize: KillingLoc.Size)) {
1887 SmallPtrSet<BasicBlock *, 16> KillingBlocks;
1888 for (Instruction *KD : KillingDefs)
1889 KillingBlocks.insert(Ptr: KD->getParent());
1890 assert(!KillingBlocks.empty() &&
1891 "Expected at least a single killing block");
1892
1893 // Find the common post-dominator of all killing blocks.
1894 BasicBlock *CommonPred = *KillingBlocks.begin();
1895 for (BasicBlock *BB : llvm::drop_begin(RangeOrContainer&: KillingBlocks)) {
1896 if (!CommonPred)
1897 break;
1898 CommonPred = PDT.findNearestCommonDominator(A: CommonPred, B: BB);
1899 }
1900
1901 // If the common post-dominator does not post-dominate MaybeDeadAccess,
1902 // there is a path from MaybeDeadAccess to an exit not going through a
1903 // killing block.
1904 if (!PDT.dominates(A: CommonPred, B: MaybeDeadAccess->getBlock())) {
1905 if (!AnyUnreachableExit)
1906 return std::nullopt;
1907
1908 // Fall back to CFG scan starting at all non-unreachable roots if not
1909 // all paths to the exit go through CommonPred.
1910 CommonPred = nullptr;
1911 }
1912
1913 // If CommonPred itself is in the set of killing blocks, we're done.
1914 if (KillingBlocks.count(Ptr: CommonPred))
1915 return {MaybeDeadAccess};
1916
1917 SetVector<BasicBlock *> WorkList;
1918 // If CommonPred is null, there are multiple exits from the function.
1919 // They all have to be added to the worklist.
1920 if (CommonPred)
1921 WorkList.insert(X: CommonPred);
1922 else
1923 for (BasicBlock *R : PDT.roots()) {
1924 if (!isa<UnreachableInst>(Val: R->getTerminator()))
1925 WorkList.insert(X: R);
1926 }
1927
1928 NumCFGTries++;
1929 // Check if all paths starting from an exit node go through one of the
1930 // killing blocks before reaching MaybeDeadAccess.
1931 for (unsigned I = 0; I < WorkList.size(); I++) {
1932 NumCFGChecks++;
1933 BasicBlock *Current = WorkList[I];
1934 if (KillingBlocks.count(Ptr: Current))
1935 continue;
1936 if (Current == MaybeDeadAccess->getBlock())
1937 return std::nullopt;
1938
1939 // MaybeDeadAccess is reachable from the entry, so we don't have to
1940 // explore unreachable blocks further.
1941 if (!DT.isReachableFromEntry(A: Current))
1942 continue;
1943
1944 WorkList.insert_range(R: predecessors(BB: Current));
1945
1946 if (WorkList.size() >= Opts.dse_memoryssa_path_check_limit)
1947 return std::nullopt;
1948 }
1949 NumCFGSuccess++;
1950 }
1951
1952 // No aliasing MemoryUses of MaybeDeadAccess found, MaybeDeadAccess is
1953 // potentially dead.
1954 return {MaybeDeadAccess};
1955}
1956
1957void DSEState::deleteDeadInstruction(Instruction *SI,
1958 SmallPtrSetImpl<MemoryAccess *> *Deleted) {
1959 MemorySSAUpdater Updater(&MSSA);
1960 SmallVector<Instruction *, 32> NowDeadInsts;
1961 NowDeadInsts.push_back(Elt: SI);
1962 --NumFastOther;
1963
1964 while (!NowDeadInsts.empty()) {
1965 Instruction *DeadInst = NowDeadInsts.pop_back_val();
1966 ++NumFastOther;
1967
1968 // Try to preserve debug information attached to the dead instruction.
1969 salvageDebugInfo(I&: *DeadInst);
1970 salvageKnowledge(I: DeadInst);
1971
1972 // Remove the Instruction from MSSA.
1973 MemoryAccess *MA = MSSA.getMemoryAccess(I: DeadInst);
1974 bool IsMemDef = MA && isa<MemoryDef>(Val: MA);
1975 if (MA) {
1976 if (IsMemDef) {
1977 auto *MD = cast<MemoryDef>(Val: MA);
1978 SkipStores.insert(Ptr: MD);
1979 if (Deleted)
1980 Deleted->insert(Ptr: MD);
1981 if (auto *SI = dyn_cast<StoreInst>(Val: MD->getMemoryInst())) {
1982 if (SI->getValueOperand()->getType()->isPointerTy()) {
1983 const Value *UO = getUnderlyingObject(V: SI->getValueOperand());
1984 if (CapturedBeforeReturn.erase(Val: UO))
1985 ShouldIterateEndOfFunctionDSE = true;
1986 InvisibleToCallerAfterRet.erase(Val: UO);
1987 InvisibleToCallerAfterRetBounded.erase(Val: UO);
1988 }
1989 }
1990 }
1991
1992 Updater.removeMemoryAccess(MA);
1993 }
1994
1995 auto I = IOLs.find(Key: DeadInst->getParent());
1996 if (I != IOLs.end())
1997 I->second.erase(Key: DeadInst);
1998 // Remove its operands
1999 for (Use &O : DeadInst->operands())
2000 if (Instruction *OpI = dyn_cast<Instruction>(Val&: O)) {
2001 O.set(PoisonValue::get(T: O->getType()));
2002 if (isInstructionTriviallyDead(I: OpI, TLI: &TLI))
2003 NowDeadInsts.push_back(Elt: OpI);
2004 }
2005
2006 EA.removeInstruction(I: DeadInst);
2007 // Remove memory defs directly if they don't produce results, but only
2008 // queue other dead instructions for later removal. They may have been
2009 // used as memory locations that have been cached by BatchAA. Removing
2010 // them here may lead to newly created instructions to be allocated at the
2011 // same address, yielding stale cache entries.
2012 if (IsMemDef && DeadInst->getType()->isVoidTy())
2013 DeadInst->eraseFromParent();
2014 else
2015 ToRemove.push_back(Elt: DeadInst);
2016 }
2017}
2018
2019bool DSEState::mayThrowBetween(Instruction *KillingI, Instruction *DeadI,
2020 const Value *KillingUndObj) {
2021 // First see if we can ignore it by using the fact that KillingI is an
2022 // alloca/alloca like object that is not visible to the caller during
2023 // execution of the function.
2024 if (KillingUndObj && isInvisibleToCallerOnUnwind(V: KillingUndObj))
2025 return false;
2026
2027 if (KillingI->getParent() == DeadI->getParent())
2028 return ThrowingBlocks.count(Ptr: KillingI->getParent());
2029 return !ThrowingBlocks.empty();
2030}
2031
2032bool DSEState::isDSEBarrier(const Value *KillingUndObj, Instruction *DeadI) {
2033 // If DeadI may throw it acts as a barrier, unless we are to an
2034 // alloca/alloca like object that does not escape.
2035 if (DeadI->mayThrow() && !isInvisibleToCallerOnUnwind(V: KillingUndObj))
2036 return true;
2037
2038 // If DeadI is an atomic load/store stronger than monotonic, do not try to
2039 // eliminate/reorder it.
2040 if (DeadI->isAtomic()) {
2041 if (auto *LI = dyn_cast<LoadInst>(Val: DeadI))
2042 return isStrongerThanMonotonic(AO: LI->getOrdering());
2043 if (auto *SI = dyn_cast<StoreInst>(Val: DeadI))
2044 return isStrongerThanMonotonic(AO: SI->getOrdering());
2045 if (auto *ARMW = dyn_cast<AtomicRMWInst>(Val: DeadI))
2046 return isStrongerThanMonotonic(AO: ARMW->getOrdering());
2047 if (auto *CmpXchg = dyn_cast<AtomicCmpXchgInst>(Val: DeadI))
2048 return isStrongerThanMonotonic(AO: CmpXchg->getSuccessOrdering()) ||
2049 isStrongerThanMonotonic(AO: CmpXchg->getFailureOrdering());
2050 llvm_unreachable("other instructions should be skipped in MemorySSA");
2051 }
2052 return false;
2053}
2054
2055bool DSEState::eliminateDeadWritesAtEndOfFunction() {
2056 bool MadeChange = false;
2057 LLVM_DEBUG(
2058 dbgs() << "Trying to eliminate MemoryDefs at the end of the function\n");
2059 do {
2060 ShouldIterateEndOfFunctionDSE = false;
2061 for (MemoryDef *Def : llvm::reverse(C&: MemDefs)) {
2062 if (SkipStores.contains(Ptr: Def))
2063 continue;
2064
2065 Instruction *DefI = Def->getMemoryInst();
2066 auto DefLoc = getLocForWrite(I: DefI);
2067 if (!DefLoc || !isRemovable(I: DefI)) {
2068 LLVM_DEBUG(dbgs() << " ... could not get location for write or "
2069 "instruction not removable.\n");
2070 continue;
2071 }
2072
2073 // NOTE: Currently eliminating writes at the end of a function is
2074 // limited to MemoryDefs with a single underlying object, to save
2075 // compile-time. In practice it appears the case with multiple
2076 // underlying objects is very uncommon. If it turns out to be important,
2077 // we can use getUnderlyingObjects here instead.
2078 const Value *UO = getUnderlyingObject(V: DefLoc->Ptr);
2079 if (!isInvisibleToCallerAfterRet(V: UO, Ptr: DefLoc->Ptr, StoreSize: DefLoc->Size))
2080 continue;
2081
2082 if (isWriteAtEndOfFunction(Def, DefLoc: *DefLoc)) {
2083 // See through pointer-to-pointer bitcasts
2084 LLVM_DEBUG(dbgs() << " ... MemoryDef is not accessed until the end "
2085 "of the function\n");
2086 deleteDeadInstruction(SI: DefI);
2087 ++NumFastStores;
2088 MadeChange = true;
2089 }
2090 }
2091 } while (ShouldIterateEndOfFunctionDSE);
2092 return MadeChange;
2093}
2094
2095bool DSEState::eliminateRedundantStoresViaDominatingConditions() {
2096 bool MadeChange = false;
2097 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs whose value being "
2098 "written is implied by a dominating condition\n");
2099
2100 using ConditionInfo = std::pair<Value *, Value *>;
2101 using ScopedHTType = ScopedHashTable<ConditionInfo, Instruction *>;
2102
2103 // We maintain a scoped hash table of the active dominating conditions for a
2104 // given node.
2105 ScopedHTType ActiveConditions;
2106 auto GetDominatingCondition = [&](BasicBlock *BB)
2107 -> std::optional<std::tuple<ConditionInfo, Instruction *, BasicBlock *>> {
2108 auto *BI = dyn_cast<CondBrInst>(Val: BB->getTerminator());
2109 if (!BI)
2110 return std::nullopt;
2111
2112 // In case both blocks are the same, it is not possible to determine
2113 // if optimization is possible. (We would not want to optimize a store
2114 // in the FalseBB if condition is true and vice versa.)
2115 if (BI->getSuccessor(i: 0) == BI->getSuccessor(i: 1))
2116 return std::nullopt;
2117
2118 Instruction *ICmpL;
2119 CmpPredicate Pred;
2120 Value *StorePtr, *StoreVal;
2121 if (!match(V: BI->getCondition(),
2122 P: m_c_ICmp(Pred, L: m_Instruction(I&: ICmpL, P: m_Load(Op: m_Value(V&: StorePtr))),
2123 R: m_Value(V&: StoreVal))) ||
2124 !ICmpInst::isEquality(P: Pred))
2125 return std::nullopt;
2126
2127 // Ensure the replacement is allowed when comparing pointers, as
2128 // the equality compares addresses only, not pointers' provenance.
2129 if (StoreVal->getType()->isPointerTy() &&
2130 !canReplacePointersIfEqual(From: StoreVal, To: ICmpL, DL))
2131 return std::nullopt;
2132
2133 unsigned ImpliedSuccIdx = Pred == ICmpInst::ICMP_EQ ? 0 : 1;
2134 BasicBlock *ImpliedSucc = BI->getSuccessor(i: ImpliedSuccIdx);
2135 return {{ConditionInfo(StorePtr, StoreVal), ICmpL, ImpliedSucc}};
2136 };
2137
2138 auto VisitNode = [&](DomTreeNode *Node, unsigned Depth, auto &Self) -> void {
2139 if (Depth > Opts.dse_max_dom_cond_depth)
2140 return;
2141
2142 BasicBlock *BB = Node->getBlock();
2143 // Check for redundant stores against active known conditions.
2144 if (auto *Accesses = MSSA.getBlockDefs(BB)) {
2145 for (MemoryDef &Def :
2146 make_early_inc_range(Range: make_isa_range<MemoryDef>(Range&: *Accesses))) {
2147 auto *SI = dyn_cast<StoreInst>(Val: Def.getMemoryInst());
2148 if (!SI || !SI->isUnordered())
2149 continue;
2150
2151 Instruction *LI = ActiveConditions.lookup(
2152 Key: {SI->getPointerOperand(), SI->getValueOperand()});
2153 if (!LI)
2154 continue;
2155
2156 // Found a dominating condition that may imply the value being stored.
2157 // Make sure there does not exist any clobbering access between the
2158 // load and the potential redundant store.
2159 MemoryAccess *LoadAccess = MSSA.getMemoryAccess(I: LI);
2160 MemoryAccess *ClobberingAccess =
2161 MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(&Def, AA&: BatchAA);
2162 if (MSSA.dominates(A: ClobberingAccess, B: LoadAccess)) {
2163 LLVM_DEBUG(dbgs()
2164 << "Removing No-Op Store:\n DEAD: " << *SI << '\n');
2165 deleteDeadInstruction(SI);
2166 NumRedundantStores++;
2167 MadeChange = true;
2168 }
2169 }
2170 }
2171
2172 // See whether this basic block establishes a dominating condition.
2173 auto MaybeCondition = GetDominatingCondition(BB);
2174
2175 for (DomTreeNode *Child : Node->children()) {
2176 // RAII scope for the active conditions.
2177 ScopedHTType::ScopeTy Scope(ActiveConditions);
2178 if (MaybeCondition) {
2179 const auto &[Cond, LI, ImpliedSucc] = *MaybeCondition;
2180 if (DT.dominates(BBE: BasicBlockEdge(BB, ImpliedSucc), BB: Child->getBlock())) {
2181 // Found a condition that holds for this child, dominated by the
2182 // current node via the equality edge. Propagate the condition to
2183 // the children by pushing it onto the table.
2184 ActiveConditions.insert(Key: Cond, Val: LI);
2185 }
2186 }
2187
2188 // Recursively visit the children of this node. Upon destruction, the no
2189 // longer active condition before visiting any sibling nodes is popped
2190 // from the active scope.
2191 Self(Child, Depth + 1, Self);
2192 }
2193 };
2194
2195 // Do a DFS walk of the dom-tree.
2196 VisitNode(DT.getRootNode(), 0, VisitNode);
2197
2198 return MadeChange;
2199}
2200
2201bool DSEState::tryFoldIntoCalloc(MemoryDef *Def, const Value *DefUO) {
2202 Instruction *DefI = Def->getMemoryInst();
2203 MemSetInst *MemSet = dyn_cast<MemSetInst>(Val: DefI);
2204 if (!MemSet)
2205 // TODO: Could handle zero store to small allocation as well.
2206 return false;
2207 Constant *StoredConstant = dyn_cast<Constant>(Val: MemSet->getValue());
2208 if (!StoredConstant || !StoredConstant->isNullValue())
2209 return false;
2210
2211 if (!isRemovable(I: DefI))
2212 // The memset might be volatile..
2213 return false;
2214
2215 if (F.hasFnAttribute(Kind: Attribute::SanitizeMemory) ||
2216 F.hasFnAttribute(Kind: Attribute::SanitizeAddress) ||
2217 F.hasFnAttribute(Kind: Attribute::SanitizeHWAddress) || F.getName() == "calloc")
2218 return false;
2219 auto *Malloc = const_cast<CallInst *>(dyn_cast<CallInst>(Val: DefUO));
2220 if (!Malloc)
2221 return false;
2222 auto *InnerCallee = Malloc->getCalledFunction();
2223 if (!InnerCallee)
2224 return false;
2225 LibFunc Func = TLI.getLibFunc(FDecl: *InnerCallee);
2226 StringRef ZeroedVariantName;
2227 if (Func != LibFunc_malloc || !TLI.has(F: Func)) {
2228 Attribute Attr = Malloc->getFnAttr(Kind: "alloc-variant-zeroed");
2229 if (!Attr.isValid())
2230 return false;
2231 ZeroedVariantName = Attr.getValueAsString();
2232 if (ZeroedVariantName.empty())
2233 return false;
2234 }
2235
2236 // Gracefully handle malloc with unexpected memory attributes.
2237 auto *MallocDef = dyn_cast_or_null<MemoryDef>(Val: MSSA.getMemoryAccess(I: Malloc));
2238 if (!MallocDef)
2239 return false;
2240
2241 auto shouldCreateCalloc = [](CallInst *Malloc, CallInst *Memset) {
2242 // Check for br(icmp ptr, null), truebb, falsebb) pattern at the end
2243 // of malloc block
2244 auto *MallocBB = Malloc->getParent(), *MemsetBB = Memset->getParent();
2245 if (MallocBB == MemsetBB)
2246 return true;
2247 auto *Ptr = Memset->getArgOperand(i: 0);
2248 auto *TI = MallocBB->getTerminator();
2249 BasicBlock *TrueBB, *FalseBB;
2250 if (!match(V: TI, P: m_Br(C: m_SpecificICmp(MatchPred: ICmpInst::ICMP_EQ, L: m_Specific(V: Ptr),
2251 R: m_Zero()),
2252 T&: TrueBB, F&: FalseBB)))
2253 return false;
2254 if (MemsetBB != FalseBB)
2255 return false;
2256 return true;
2257 };
2258
2259 if (Malloc->getOperand(i_nocapture: 0) != MemSet->getLength())
2260 return false;
2261 if (!shouldCreateCalloc(Malloc, MemSet) || !DT.dominates(Def: Malloc, User: MemSet) ||
2262 !memoryIsNotModifiedBetween(FirstI: Malloc, SecondI: MemSet, AA&: BatchAA, DL, DT: &DT))
2263 return false;
2264 IRBuilder<> IRB(Malloc);
2265 assert(Func == LibFunc_malloc || !ZeroedVariantName.empty());
2266 Value *Calloc = nullptr;
2267 if (!ZeroedVariantName.empty()) {
2268 LLVMContext &Ctx = Malloc->getContext();
2269 AttributeList Attrs = InnerCallee->getAttributes();
2270 AllocFnKind AllocKind =
2271 Attrs.getFnAttr(Kind: Attribute::AllocKind).getAllocKind() |
2272 AllocFnKind::Zeroed;
2273 AllocKind &= ~AllocFnKind::Uninitialized;
2274 Attrs =
2275 Attrs.addFnAttribute(C&: Ctx, Attr: Attribute::getWithAllocKind(Context&: Ctx, Kind: AllocKind))
2276 .removeFnAttribute(C&: Ctx, Kind: "alloc-variant-zeroed");
2277 FunctionCallee ZeroedVariant = Malloc->getModule()->getOrInsertFunction(
2278 Name: ZeroedVariantName, T: InnerCallee->getFunctionType(), AttributeList: Attrs);
2279 cast<Function>(Val: ZeroedVariant.getCallee())
2280 ->setCallingConv(Malloc->getCallingConv());
2281 SmallVector<Value *, 3> Args;
2282 Args.append(in_start: Malloc->arg_begin(), in_end: Malloc->arg_end());
2283 CallInst *CI = IRB.CreateCall(Callee: ZeroedVariant, Args, Name: ZeroedVariantName);
2284 CI->setCallingConv(Malloc->getCallingConv());
2285 Calloc = CI;
2286 } else {
2287 Type *SizeTTy = Malloc->getArgOperand(i: 0)->getType();
2288 Calloc = emitCalloc(Num: ConstantInt::get(Ty: SizeTTy, V: 1), Size: Malloc->getArgOperand(i: 0),
2289 B&: IRB, TLI, AddrSpace: Malloc->getType()->getPointerAddressSpace());
2290 }
2291 if (!Calloc)
2292 return false;
2293
2294 if (MDNode *MD = Malloc->getMetadata(KindID: LLVMContext::MD_alloc_token))
2295 cast<Instruction>(Val: Calloc)->setMetadata(KindID: LLVMContext::MD_alloc_token, Node: MD);
2296
2297 MemorySSAUpdater Updater(&MSSA);
2298 auto *NewAccess = Updater.createMemoryAccessAfter(I: cast<Instruction>(Val: Calloc),
2299 Definition: nullptr, InsertPt: MallocDef);
2300 auto *NewAccessMD = cast<MemoryDef>(Val: NewAccess);
2301 Updater.insertDef(Def: NewAccessMD, /*RenameUses=*/true);
2302 Malloc->replaceAllUsesWith(V: Calloc);
2303 deleteDeadInstruction(SI: Malloc);
2304 return true;
2305}
2306
2307bool DSEState::storeIsNoop(MemoryDef *Def, const Value *DefUO) {
2308 Instruction *DefI = Def->getMemoryInst();
2309 StoreInst *Store = dyn_cast<StoreInst>(Val: DefI);
2310 MemSetInst *MemSet = dyn_cast<MemSetInst>(Val: DefI);
2311 Constant *StoredConstant = nullptr;
2312 if (Store)
2313 StoredConstant = dyn_cast<Constant>(Val: Store->getOperand(i_nocapture: 0));
2314 else if (MemSet)
2315 StoredConstant = dyn_cast<Constant>(Val: MemSet->getValue());
2316 else
2317 return false;
2318
2319 if (!isRemovable(I: DefI))
2320 return false;
2321
2322 if (StoredConstant) {
2323 Constant *InitC =
2324 getInitialValueOfAllocation(V: DefUO, TLI: &TLI, Ty: StoredConstant->getType());
2325 // If the clobbering access is LiveOnEntry, no instructions between them
2326 // can modify the memory location.
2327 if (InitC && InitC == StoredConstant)
2328 return MSSA.isLiveOnEntryDef(
2329 MA: MSSA.getSkipSelfWalker()->getClobberingMemoryAccess(Def, AA&: BatchAA));
2330 }
2331
2332 if (!Store)
2333 return false;
2334
2335 if (auto *LoadI = dyn_cast<LoadInst>(Val: Store->getOperand(i_nocapture: 0))) {
2336 if (LoadI->getPointerOperand() == Store->getOperand(i_nocapture: 1)) {
2337 // Get the defining access for the load.
2338 auto *LoadAccess = MSSA.getMemoryAccess(I: LoadI)->getDefiningAccess();
2339 // Fast path: the defining accesses are the same.
2340 if (LoadAccess == Def->getDefiningAccess())
2341 return true;
2342
2343 // Look through phi accesses. Recursively scan all phi accesses by
2344 // adding them to a worklist. Bail when we run into a memory def that
2345 // does not match LoadAccess.
2346 SetVector<MemoryAccess *> ToCheck;
2347 MemoryAccess *Current =
2348 MSSA.getWalker()->getClobberingMemoryAccess(Def, AA&: BatchAA);
2349 // We don't want to bail when we run into the store memory def. But,
2350 // the phi access may point to it. So, pretend like we've already
2351 // checked it.
2352 ToCheck.insert(X: Def);
2353 ToCheck.insert(X: Current);
2354 // Start at current (1) to simulate already having checked Def.
2355 for (unsigned I = 1; I < ToCheck.size(); ++I) {
2356 Current = ToCheck[I];
2357 if (auto PhiAccess = dyn_cast<MemoryPhi>(Val: Current)) {
2358 // Check all the operands.
2359 for (auto &Use : PhiAccess->incoming_values())
2360 ToCheck.insert(X: cast<MemoryAccess>(Val: &Use));
2361 continue;
2362 }
2363
2364 // If we found a memory def, bail. This happens when we have an
2365 // unrelated write in between an otherwise noop store.
2366 assert(isa<MemoryDef>(Current) && "Only MemoryDefs should reach here.");
2367 // TODO: Skip no alias MemoryDefs that have no aliasing reads.
2368 // We are searching for the definition of the store's destination.
2369 // So, if that is the same definition as the load, then this is a
2370 // noop. Otherwise, fail.
2371 if (LoadAccess != Current)
2372 return false;
2373 }
2374 return true;
2375 }
2376 }
2377
2378 return false;
2379}
2380
2381bool DSEState::removePartiallyOverlappedStores(InstOverlapIntervalsTy &IOL) {
2382 bool Changed = false;
2383 for (auto OI : IOL) {
2384 Instruction *DeadI = OI.first;
2385 MemoryLocation Loc = *getLocForWrite(I: DeadI);
2386 assert(isRemovable(DeadI) && "Expect only removable instruction");
2387
2388 const Value *Ptr = Loc.Ptr->stripPointerCasts();
2389 int64_t DeadStart = 0;
2390 uint64_t DeadSize = Loc.Size.getValue();
2391 GetPointerBaseWithConstantOffset(Ptr, Offset&: DeadStart, DL);
2392 OverlapIntervalsTy &IntervalMap = OI.second;
2393 Changed |= tryToShortenEnd(DeadI, IntervalMap, DeadStart, DeadSize);
2394 if (IntervalMap.empty())
2395 continue;
2396 Changed |= tryToShortenBegin(DeadI, IntervalMap, DeadStart, DeadSize);
2397 }
2398 return Changed;
2399}
2400
2401bool DSEState::eliminateRedundantStoresOfExistingValues() {
2402 bool MadeChange = false;
2403 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs that write the "
2404 "already existing value\n");
2405 for (auto *Def : MemDefs) {
2406 if (SkipStores.contains(Ptr: Def) || MSSA.isLiveOnEntryDef(MA: Def))
2407 continue;
2408
2409 Instruction *DefInst = Def->getMemoryInst();
2410 auto MaybeDefLoc = getLocForWrite(I: DefInst);
2411 if (!MaybeDefLoc || !isRemovable(I: DefInst))
2412 continue;
2413
2414 MemoryDef *UpperDef;
2415 // To conserve compile-time, we avoid walking to the next clobbering def.
2416 // Instead, we just try to get the optimized access, if it exists. DSE
2417 // will try to optimize defs during the earlier traversal.
2418 if (Def->isOptimized())
2419 UpperDef = dyn_cast<MemoryDef>(Val: Def->getOptimized());
2420 else
2421 UpperDef = dyn_cast<MemoryDef>(Val: Def->getDefiningAccess());
2422 if (!UpperDef || MSSA.isLiveOnEntryDef(MA: UpperDef))
2423 continue;
2424
2425 Instruction *UpperInst = UpperDef->getMemoryInst();
2426 auto IsRedundantStore = [&]() {
2427 // We don't care about differences in call attributes here.
2428 if (DefInst->isIdenticalToWhenDefined(I: UpperInst,
2429 /*IntersectAttrs=*/true))
2430 return true;
2431 if (auto *MemSetI = dyn_cast<MemSetInst>(Val: UpperInst)) {
2432 if (auto *SI = dyn_cast<StoreInst>(Val: DefInst)) {
2433 // MemSetInst must have a write location.
2434 auto UpperLoc = getLocForWrite(I: UpperInst);
2435 if (!UpperLoc)
2436 return false;
2437 int64_t InstWriteOffset = 0;
2438 int64_t DepWriteOffset = 0;
2439 auto OR = isOverwrite(KillingI: UpperInst, DeadI: DefInst, KillingLoc: *UpperLoc, DeadLoc: *MaybeDefLoc,
2440 KillingOff&: InstWriteOffset, DeadOff&: DepWriteOffset);
2441 Value *StoredByte = isBytewiseValue(V: SI->getValueOperand(), DL);
2442 return StoredByte && StoredByte == MemSetI->getOperand(i_nocapture: 1) &&
2443 OR == OW_Complete;
2444 }
2445 }
2446 return false;
2447 };
2448
2449 if (!IsRedundantStore() || isReadClobber(DefLoc: *MaybeDefLoc, UseInst: DefInst))
2450 continue;
2451 LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n DEAD: " << *DefInst
2452 << '\n');
2453 deleteDeadInstruction(SI: DefInst);
2454 NumRedundantStores++;
2455 MadeChange = true;
2456 }
2457 return MadeChange;
2458}
2459
2460SmallVector<MemoryLocation, 1>
2461DSEState::getInitializesArgMemLoc(const Instruction *I) {
2462 const CallBase *CB = dyn_cast<CallBase>(Val: I);
2463 if (!CB)
2464 return {};
2465
2466 // Collect aliasing arguments and their initializes ranges.
2467 SmallMapVector<Value *, SmallVector<ArgumentInitInfo, 2>, 2> Arguments;
2468 for (unsigned Idx = 0, Count = CB->arg_size(); Idx < Count; ++Idx) {
2469 Value *CurArg = CB->getArgOperand(i: Idx);
2470 if (!CurArg->getType()->isPointerTy())
2471 continue;
2472
2473 ConstantRangeList Inits;
2474 Attribute InitializesAttr = CB->getParamAttr(ArgNo: Idx, Kind: Attribute::Initializes);
2475 // initializes on byval arguments refers to the callee copy, not the
2476 // original memory the caller passed in.
2477 if (InitializesAttr.isValid() && !CB->isByValArgument(ArgNo: Idx))
2478 Inits = InitializesAttr.getValueAsConstantRangeList();
2479
2480 // Check whether "CurArg" could alias with global variables. We require
2481 // either it's function local and isn't captured before or the "CB" only
2482 // accesses arg or inaccessible mem.
2483 if (!Inits.empty() && !CB->onlyAccessesInaccessibleMemOrArgMem() &&
2484 !isFuncLocalAndNotCaptured(Arg: CurArg, CB, EA))
2485 Inits = ConstantRangeList();
2486
2487 // We don't perform incorrect DSE on unwind edges in the current function,
2488 // and use the "initializes" attribute to kill dead stores if:
2489 // - The call does not throw exceptions, "CB->doesNotThrow()".
2490 // - Or the callee parameter has "dead_on_unwind" attribute.
2491 // - Or the argument is invisible to caller on unwind, and there are no
2492 // unwind edges from this call in the current function (e.g. `CallInst`).
2493 bool IsDeadOrInvisibleOnUnwind =
2494 CB->paramHasAttr(ArgNo: Idx, Kind: Attribute::DeadOnUnwind) ||
2495 (isa<CallInst>(Val: CB) && isInvisibleToCallerOnUnwind(V: CurArg));
2496 ArgumentInitInfo InitInfo{.Idx: Idx, .IsDeadOrInvisibleOnUnwind: IsDeadOrInvisibleOnUnwind, .Inits: Inits};
2497 bool FoundAliasing = false;
2498 for (auto &[Arg, AliasList] : Arguments) {
2499 auto AAR = BatchAA.alias(LocA: MemoryLocation::getBeforeOrAfter(Ptr: Arg),
2500 LocB: MemoryLocation::getBeforeOrAfter(Ptr: CurArg));
2501 if (AAR == AliasResult::NoAlias) {
2502 continue;
2503 } else if (AAR == AliasResult::MustAlias) {
2504 FoundAliasing = true;
2505 AliasList.push_back(Elt: InitInfo);
2506 } else {
2507 // For PartialAlias and MayAlias, there is an offset or may be an
2508 // unknown offset between the arguments and we insert an empty init
2509 // range to discard the entire initializes info while intersecting.
2510 FoundAliasing = true;
2511 AliasList.push_back(Elt: ArgumentInitInfo{.Idx: Idx, .IsDeadOrInvisibleOnUnwind: IsDeadOrInvisibleOnUnwind,
2512 .Inits: ConstantRangeList()});
2513 }
2514 }
2515 if (!FoundAliasing)
2516 Arguments[CurArg] = {InitInfo};
2517 }
2518
2519 SmallVector<MemoryLocation, 1> Locations;
2520 for (const auto &[_, Args] : Arguments) {
2521 auto IntersectedRanges =
2522 getIntersectedInitRangeList(Args, CallHasNoUnwindAttr: CB->doesNotThrow());
2523 if (IntersectedRanges.empty())
2524 continue;
2525
2526 for (const auto &Arg : Args) {
2527 for (const auto &Range : IntersectedRanges) {
2528 int64_t Start = Range.getLower().getSExtValue();
2529 int64_t End = Range.getUpper().getSExtValue();
2530 // For now, we only handle locations starting at offset 0.
2531 if (Start == 0)
2532 Locations.push_back(Elt: MemoryLocation(CB->getArgOperand(i: Arg.Idx),
2533 LocationSize::precise(Value: End - Start),
2534 CB->getAAMetadata()));
2535 }
2536 }
2537 }
2538 return Locations;
2539}
2540
2541std::pair<bool, bool>
2542DSEState::eliminateDeadDefs(const MemoryLocationWrapper &KillingLocWrapper) {
2543 bool Changed = false;
2544 bool DeletedKillingLoc = false;
2545 unsigned ScanLimit = Opts.dse_memoryssa_scanlimit;
2546 unsigned WalkerStepLimit = Opts.dse_memoryssa_walklimit;
2547 unsigned PartialLimit = Opts.dse_memoryssa_partial_store_limit;
2548 // Worklist of MemoryAccesses that may be killed by
2549 // "KillingLocWrapper.MemDef".
2550 SmallSetVector<MemoryAccess *, 8> ToCheck;
2551 // Track MemoryAccesses that have been deleted in the loop below, so we can
2552 // skip them. Don't use SkipStores for this, which may contain reused
2553 // MemoryAccess addresses.
2554 SmallPtrSet<MemoryAccess *, 8> Deleted;
2555 [[maybe_unused]] unsigned OrigNumSkipStores = SkipStores.size();
2556 ToCheck.insert(X: KillingLocWrapper.MemDef->getDefiningAccess());
2557
2558 // Check if MemoryAccesses in the worklist are killed by
2559 // "KillingLocWrapper.MemDef".
2560 for (unsigned I = 0; I < ToCheck.size(); I++) {
2561 MemoryAccess *Current = ToCheck[I];
2562 if (Deleted.contains(Ptr: Current))
2563 continue;
2564 std::optional<MemoryAccess *> MaybeDeadAccess = getDomMemoryDef(
2565 KillingDef: KillingLocWrapper.MemDef, StartAccess: Current, KillingLoc: KillingLocWrapper.MemLoc,
2566 KillingUndObj: KillingLocWrapper.UnderlyingObject, ScanLimit, WalkerStepLimit,
2567 IsMemTerm: isMemTerminatorInst(I: KillingLocWrapper.DefInst), PartialLimit,
2568 IsInitializesAttrMemLoc: KillingLocWrapper.DefByInitializesAttr);
2569
2570 if (!MaybeDeadAccess) {
2571 LLVM_DEBUG(dbgs() << " finished walk\n");
2572 continue;
2573 }
2574 MemoryAccess *DeadAccess = *MaybeDeadAccess;
2575 LLVM_DEBUG(dbgs() << " Checking if we can kill " << *DeadAccess);
2576 if (isa<MemoryPhi>(Val: DeadAccess)) {
2577 LLVM_DEBUG(dbgs() << "\n ... adding incoming values to worklist\n");
2578 for (Value *V : cast<MemoryPhi>(Val: DeadAccess)->incoming_values()) {
2579 MemoryAccess *IncomingAccess = cast<MemoryAccess>(Val: V);
2580 BasicBlock *IncomingBlock = IncomingAccess->getBlock();
2581 BasicBlock *PhiBlock = DeadAccess->getBlock();
2582
2583 // We only consider incoming MemoryAccesses that come before the
2584 // MemoryPhi. Otherwise we could discover candidates that do not
2585 // strictly dominate our starting def.
2586 if (PostOrderNumbers[IncomingBlock] > PostOrderNumbers[PhiBlock])
2587 ToCheck.insert(X: IncomingAccess);
2588 }
2589 continue;
2590 }
2591 // We cannot apply the initializes attribute to DeadAccess/DeadDef.
2592 // It would incorrectly consider a call instruction as redundant store
2593 // and remove this call instruction.
2594 // TODO: this conflates the existence of a MemoryLocation with being able
2595 // to delete the instruction. Fix isRemovable() to consider calls with
2596 // side effects that cannot be removed, e.g. calls with the initializes
2597 // attribute, and remove getLocForInst(ConsiderInitializesAttr = false).
2598 MemoryDefWrapper DeadDefWrapper(
2599 cast<MemoryDef>(Val: DeadAccess),
2600 getLocForInst(I: cast<MemoryDef>(Val: DeadAccess)->getMemoryInst(),
2601 /*ConsiderInitializesAttr=*/false));
2602 assert(DeadDefWrapper.DefinedLocations.size() == 1);
2603 MemoryLocationWrapper &DeadLocWrapper =
2604 DeadDefWrapper.DefinedLocations.front();
2605 LLVM_DEBUG(dbgs() << " (" << *DeadLocWrapper.DefInst << ")\n");
2606 ToCheck.insert(X: DeadLocWrapper.MemDef->getDefiningAccess());
2607 NumGetDomMemoryDefPassed++;
2608
2609 if (!DebugCounter::shouldExecute(Counter&: MemorySSACounter))
2610 continue;
2611 if (isMemTerminatorInst(I: KillingLocWrapper.DefInst)) {
2612 if (KillingLocWrapper.UnderlyingObject != DeadLocWrapper.UnderlyingObject)
2613 continue;
2614 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
2615 << *DeadLocWrapper.DefInst << "\n KILLER: "
2616 << *KillingLocWrapper.DefInst << '\n');
2617 deleteDeadInstruction(SI: DeadLocWrapper.DefInst, Deleted: &Deleted);
2618 ++NumFastStores;
2619 Changed = true;
2620 } else {
2621 // Check if DeadI overwrites KillingI.
2622 int64_t KillingOffset = 0;
2623 int64_t DeadOffset = 0;
2624 OverwriteResult OR =
2625 isOverwrite(KillingI: KillingLocWrapper.DefInst, DeadI: DeadLocWrapper.DefInst,
2626 KillingLoc: KillingLocWrapper.MemLoc, DeadLoc: DeadLocWrapper.MemLoc,
2627 KillingOff&: KillingOffset, DeadOff&: DeadOffset);
2628 if (OR == OW_MaybePartial) {
2629 auto &IOL = IOLs[DeadLocWrapper.DefInst->getParent()];
2630 OR = isPartialOverwrite(Opts, KillingLoc: KillingLocWrapper.MemLoc,
2631 DeadLoc: DeadLocWrapper.MemLoc, KillingOff: KillingOffset,
2632 DeadOff: DeadOffset, DeadI: DeadLocWrapper.DefInst, IOL);
2633 }
2634 if (Opts.enable_dse_partial_store_merging &&
2635 OR == OW_PartialEarlierWithFullLater) {
2636 auto *DeadSI = dyn_cast<StoreInst>(Val: DeadLocWrapper.DefInst);
2637 auto *KillingSI = dyn_cast<StoreInst>(Val: KillingLocWrapper.DefInst);
2638 // We are re-using tryToMergePartialOverlappingStores, which requires
2639 // DeadSI to dominate KillingSI.
2640 // TODO: implement tryToMergeParialOverlappingStores using MemorySSA.
2641 if (DeadSI && KillingSI && DT.dominates(Def: DeadSI, User: KillingSI)) {
2642 if (Constant *Merged = tryToMergePartialOverlappingStores(
2643 KillingI: KillingSI, DeadI: DeadSI, KillingOffset, DeadOffset, DL, AA&: BatchAA,
2644 DT: &DT)) {
2645
2646 // Update stored value of earlier store to merged constant.
2647 DeadSI->setOperand(i_nocapture: 0, Val_nocapture: Merged);
2648 ++NumModifiedStores;
2649 Changed = true;
2650 DeletedKillingLoc = true;
2651
2652 // Remove killing store and remove any outstanding overlap
2653 // intervals for the updated store.
2654 deleteDeadInstruction(SI: KillingSI, Deleted: &Deleted);
2655 auto I = IOLs.find(Key: DeadSI->getParent());
2656 if (I != IOLs.end())
2657 I->second.erase(Key: DeadSI);
2658 break;
2659 }
2660 }
2661 }
2662 if (OR == OW_Complete) {
2663 LLVM_DEBUG(dbgs() << "DSE: Remove Dead Store:\n DEAD: "
2664 << *DeadLocWrapper.DefInst << "\n KILLER: "
2665 << *KillingLocWrapper.DefInst << '\n');
2666 deleteDeadInstruction(SI: DeadLocWrapper.DefInst, Deleted: &Deleted);
2667 ++NumFastStores;
2668 Changed = true;
2669 }
2670 }
2671 }
2672
2673 assert(SkipStores.size() - OrigNumSkipStores == Deleted.size() &&
2674 "SkipStores and Deleted out of sync?");
2675
2676 return {Changed, DeletedKillingLoc};
2677}
2678
2679bool DSEState::eliminateDeadDefs(const MemoryDefWrapper &KillingDefWrapper) {
2680 if (KillingDefWrapper.DefinedLocations.empty()) {
2681 LLVM_DEBUG(dbgs() << "Failed to find analyzable write location for "
2682 << *KillingDefWrapper.DefInst << "\n");
2683 return false;
2684 }
2685
2686 bool MadeChange = false;
2687 for (auto &KillingLocWrapper : KillingDefWrapper.DefinedLocations) {
2688 LLVM_DEBUG(dbgs() << "Trying to eliminate MemoryDefs killed by "
2689 << *KillingLocWrapper.MemDef << " ("
2690 << *KillingLocWrapper.DefInst << ")\n");
2691 auto [Changed, DeletedKillingLoc] = eliminateDeadDefs(KillingLocWrapper);
2692 MadeChange |= Changed;
2693
2694 // Check if the store is a no-op.
2695 if (!DeletedKillingLoc && storeIsNoop(Def: KillingLocWrapper.MemDef,
2696 DefUO: KillingLocWrapper.UnderlyingObject)) {
2697 LLVM_DEBUG(dbgs() << "DSE: Remove No-Op Store:\n DEAD: "
2698 << *KillingLocWrapper.DefInst << '\n');
2699 deleteDeadInstruction(SI: KillingLocWrapper.DefInst);
2700 NumRedundantStores++;
2701 MadeChange = true;
2702 continue;
2703 }
2704 // Can we form a calloc from a memset/malloc pair?
2705 if (!DeletedKillingLoc &&
2706 tryFoldIntoCalloc(Def: KillingLocWrapper.MemDef,
2707 DefUO: KillingLocWrapper.UnderlyingObject)) {
2708 LLVM_DEBUG(dbgs() << "DSE: Remove memset after forming calloc:\n"
2709 << " DEAD: " << *KillingLocWrapper.DefInst << '\n');
2710 deleteDeadInstruction(SI: KillingLocWrapper.DefInst);
2711 MadeChange = true;
2712 continue;
2713 }
2714 }
2715 return MadeChange;
2716}
2717
2718static bool eliminateDeadStores(Function &F, AliasAnalysis &AA, MemorySSA &MSSA,
2719 DominatorTree &DT, PostDominatorTree &PDT,
2720 const TargetLibraryInfo &TLI,
2721 const CycleInfo &CI) {
2722 const ScalarOptions &Opts =
2723 F.getContext().getLibraryOptions().get<ScalarOptions>();
2724 bool MadeChange = false;
2725 DSEState State(Opts, F, AA, MSSA, DT, PDT, TLI, CI);
2726 // For each store:
2727 for (unsigned I = 0; I < State.MemDefs.size(); I++) {
2728 MemoryDef *KillingDef = State.MemDefs[I];
2729 if (State.SkipStores.count(Ptr: KillingDef))
2730 continue;
2731
2732 MemoryDefWrapper KillingDefWrapper(
2733 KillingDef,
2734 State.getLocForInst(I: KillingDef->getMemoryInst(),
2735 ConsiderInitializesAttr: Opts.enable_dse_initializes_attr_improvement));
2736 MadeChange |= State.eliminateDeadDefs(KillingDefWrapper);
2737 }
2738
2739 if (Opts.enable_dse_partial_overwrite_tracking)
2740 for (auto &KV : State.IOLs)
2741 MadeChange |= State.removePartiallyOverlappedStores(IOL&: KV.second);
2742
2743 MadeChange |= State.eliminateRedundantStoresOfExistingValues();
2744 MadeChange |= State.eliminateDeadWritesAtEndOfFunction();
2745 MadeChange |= State.eliminateRedundantStoresViaDominatingConditions();
2746
2747 while (!State.ToRemove.empty()) {
2748 Instruction *DeadInst = State.ToRemove.pop_back_val();
2749 DeadInst->eraseFromParent();
2750 }
2751
2752 return MadeChange;
2753}
2754
2755//===----------------------------------------------------------------------===//
2756// DSE Pass
2757//===----------------------------------------------------------------------===//
2758PreservedAnalyses DSEPass::run(Function &F, FunctionAnalysisManager &AM) {
2759 AliasAnalysis &AA = AM.getResult<AAManager>(IR&: F);
2760 const TargetLibraryInfo &TLI = AM.getResult<TargetLibraryAnalysis>(IR&: F);
2761 DominatorTree &DT = AM.getResult<DominatorTreeAnalysis>(IR&: F);
2762 MemorySSA &MSSA = AM.getResult<MemorySSAAnalysis>(IR&: F).getMSSA();
2763 PostDominatorTree &PDT = AM.getResult<PostDominatorTreeAnalysis>(IR&: F);
2764 CycleInfo &CI = AM.getResult<CycleAnalysis>(IR&: F);
2765
2766 bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, CI);
2767
2768#ifdef LLVM_ENABLE_STATS
2769 if (AreStatisticsEnabled())
2770 for (auto &I : instructions(F))
2771 NumRemainingStores += isa<StoreInst>(Val: &I);
2772#endif
2773
2774 if (!Changed)
2775 return PreservedAnalyses::all();
2776
2777 PreservedAnalyses PA;
2778 PA.preserveSet<CFGAnalyses>();
2779 PA.preserve<MemorySSAAnalysis>();
2780 return PA;
2781}
2782
2783namespace {
2784
2785/// A legacy pass for the legacy pass manager that wraps \c DSEPass.
2786class DSELegacyPass : public FunctionPass {
2787public:
2788 static char ID; // Pass identification, replacement for typeid
2789
2790 DSELegacyPass() : FunctionPass(ID) {
2791 initializeDSELegacyPassPass(*PassRegistry::getPassRegistry());
2792 }
2793
2794 bool runOnFunction(Function &F) override {
2795 if (skipFunction(F))
2796 return false;
2797
2798 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2799 DominatorTree &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2800 const TargetLibraryInfo &TLI =
2801 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
2802 MemorySSA &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2803 PostDominatorTree &PDT =
2804 getAnalysis<PostDominatorTreeWrapperPass>().getPostDomTree();
2805 CycleInfo &CI = getAnalysis<CycleInfoWrapperPass>().getResult();
2806
2807 bool Changed = eliminateDeadStores(F, AA, MSSA, DT, PDT, TLI, CI);
2808
2809#ifdef LLVM_ENABLE_STATS
2810 if (AreStatisticsEnabled())
2811 for (auto &I : instructions(F))
2812 NumRemainingStores += isa<StoreInst>(Val: &I);
2813#endif
2814
2815 return Changed;
2816 }
2817
2818 void getAnalysisUsage(AnalysisUsage &AU) const override {
2819 AU.setPreservesCFG();
2820 AU.addRequired<AAResultsWrapperPass>();
2821 AU.addRequired<TargetLibraryInfoWrapperPass>();
2822 AU.addPreserved<GlobalsAAWrapperPass>();
2823 AU.addRequired<DominatorTreeWrapperPass>();
2824 AU.addRequired<PostDominatorTreeWrapperPass>();
2825 AU.addRequired<MemorySSAWrapperPass>();
2826 AU.addPreserved<MemorySSAWrapperPass>();
2827 AU.addRequired<CycleInfoWrapperPass>();
2828 AU.addRequired<AssumptionCacheTracker>();
2829 }
2830};
2831
2832} // end anonymous namespace
2833
2834char DSELegacyPass::ID = 0;
2835
2836INITIALIZE_PASS_BEGIN(DSELegacyPass, "dse", "Dead Store Elimination", false,
2837 false)
2838INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
2839INITIALIZE_PASS_DEPENDENCY(PostDominatorTreeWrapperPass)
2840INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
2841INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
2842INITIALIZE_PASS_DEPENDENCY(MemorySSAWrapperPass)
2843INITIALIZE_PASS_DEPENDENCY(MemoryDependenceWrapperPass)
2844INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
2845INITIALIZE_PASS_DEPENDENCY(CycleInfoWrapperPass)
2846INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
2847INITIALIZE_PASS_END(DSELegacyPass, "dse", "Dead Store Elimination", false,
2848 false)
2849
2850LLVM_ABI FunctionPass *llvm::createDeadStoreEliminationPass() {
2851 return new DSELegacyPass();
2852}
2853