1cf099d11SDimitry Andric //===- LoopInstSimplify.cpp - Loop Instruction Simplification Pass --------===//
2cf099d11SDimitry Andric //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6cf099d11SDimitry Andric //
7cf099d11SDimitry Andric //===----------------------------------------------------------------------===//
8cf099d11SDimitry Andric //
9cf099d11SDimitry Andric // This pass performs lightweight instruction simplification on loop bodies.
10cf099d11SDimitry Andric //
11cf099d11SDimitry Andric //===----------------------------------------------------------------------===//
12cf099d11SDimitry Andric
1301095a5dSDimitry Andric #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
144a16efa3SDimitry Andric #include "llvm/ADT/STLExtras.h"
15044eb2f6SDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
16044eb2f6SDimitry Andric #include "llvm/ADT/SmallVector.h"
175ca98fd9SDimitry Andric #include "llvm/ADT/Statistic.h"
1867c32a98SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
19cf099d11SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
20cf099d11SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
21eb11fae6SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
22cf099d11SDimitry Andric #include "llvm/Analysis/LoopPass.h"
23d8e91e46SDimitry Andric #include "llvm/Analysis/MemorySSA.h"
24d8e91e46SDimitry Andric #include "llvm/Analysis/MemorySSAUpdater.h"
2501095a5dSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
26044eb2f6SDimitry Andric #include "llvm/IR/BasicBlock.h"
275ca98fd9SDimitry Andric #include "llvm/IR/Dominators.h"
28044eb2f6SDimitry Andric #include "llvm/IR/Instruction.h"
294a16efa3SDimitry Andric #include "llvm/IR/Instructions.h"
30044eb2f6SDimitry Andric #include "llvm/IR/Module.h"
31044eb2f6SDimitry Andric #include "llvm/IR/PassManager.h"
32044eb2f6SDimitry Andric #include "llvm/Support/Casting.h"
3301095a5dSDimitry Andric #include "llvm/Transforms/Scalar.h"
34d8e91e46SDimitry Andric #include "llvm/Transforms/Utils/Local.h"
3501095a5dSDimitry Andric #include "llvm/Transforms/Utils/LoopUtils.h"
36e3b55780SDimitry Andric #include <optional>
37044eb2f6SDimitry Andric #include <utility>
38044eb2f6SDimitry Andric
39cf099d11SDimitry Andric using namespace llvm;
40cf099d11SDimitry Andric
415ca98fd9SDimitry Andric #define DEBUG_TYPE "loop-instsimplify"
425ca98fd9SDimitry Andric
43cf099d11SDimitry Andric STATISTIC(NumSimplified, "Number of redundant instructions simplified");
44cf099d11SDimitry Andric
simplifyLoopInst(Loop & L,DominatorTree & DT,LoopInfo & LI,AssumptionCache & AC,const TargetLibraryInfo & TLI,MemorySSAUpdater * MSSAU)45eb11fae6SDimitry Andric static bool simplifyLoopInst(Loop &L, DominatorTree &DT, LoopInfo &LI,
46d8e91e46SDimitry Andric AssumptionCache &AC, const TargetLibraryInfo &TLI,
47d8e91e46SDimitry Andric MemorySSAUpdater *MSSAU) {
48ac9a064cSDimitry Andric const DataLayout &DL = L.getHeader()->getDataLayout();
49eb11fae6SDimitry Andric SimplifyQuery SQ(DL, &TLI, &DT, &AC);
50cf099d11SDimitry Andric
51eb11fae6SDimitry Andric // On the first pass over the loop body we try to simplify every instruction.
52eb11fae6SDimitry Andric // On subsequent passes, we can restrict this to only simplifying instructions
53eb11fae6SDimitry Andric // where the inputs have been updated. We end up needing two sets: one
54eb11fae6SDimitry Andric // containing the instructions we are simplifying in *this* pass, and one for
55eb11fae6SDimitry Andric // the instructions we will want to simplify in the *next* pass. We use
56eb11fae6SDimitry Andric // pointers so we can swap between two stably allocated sets.
57cf099d11SDimitry Andric SmallPtrSet<const Instruction *, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
58cf099d11SDimitry Andric
59eb11fae6SDimitry Andric // Track the PHI nodes that have already been visited during each iteration so
60eb11fae6SDimitry Andric // that we can identify when it is necessary to iterate.
61eb11fae6SDimitry Andric SmallPtrSet<PHINode *, 4> VisitedPHIs;
62eb11fae6SDimitry Andric
63eb11fae6SDimitry Andric // While simplifying we may discover dead code or cause code to become dead.
64eb11fae6SDimitry Andric // Keep track of all such instructions and we will delete them at the end.
65cfca06d7SDimitry Andric SmallVector<WeakTrackingVH, 8> DeadInsts;
66eb11fae6SDimitry Andric
67eb11fae6SDimitry Andric // First we want to create an RPO traversal of the loop body. By processing in
68eb11fae6SDimitry Andric // RPO we can ensure that definitions are processed prior to uses (for non PHI
69eb11fae6SDimitry Andric // uses) in all cases. This ensures we maximize the simplifications in each
70eb11fae6SDimitry Andric // iteration over the loop and minimizes the possible causes for continuing to
71eb11fae6SDimitry Andric // iterate.
72eb11fae6SDimitry Andric LoopBlocksRPO RPOT(&L);
73eb11fae6SDimitry Andric RPOT.perform(&LI);
74d8e91e46SDimitry Andric MemorySSA *MSSA = MSSAU ? MSSAU->getMemorySSA() : nullptr;
75cf099d11SDimitry Andric
76cf099d11SDimitry Andric bool Changed = false;
77eb11fae6SDimitry Andric for (;;) {
78d8e91e46SDimitry Andric if (MSSAU && VerifyMemorySSA)
79d8e91e46SDimitry Andric MSSA->verifyMemorySSA();
80eb11fae6SDimitry Andric for (BasicBlock *BB : RPOT) {
81eb11fae6SDimitry Andric for (Instruction &I : *BB) {
82eb11fae6SDimitry Andric if (auto *PI = dyn_cast<PHINode>(&I))
83eb11fae6SDimitry Andric VisitedPHIs.insert(PI);
84cf099d11SDimitry Andric
85eb11fae6SDimitry Andric if (I.use_empty()) {
86eb11fae6SDimitry Andric if (isInstructionTriviallyDead(&I, &TLI))
87eb11fae6SDimitry Andric DeadInsts.push_back(&I);
88eb11fae6SDimitry Andric continue;
89eb11fae6SDimitry Andric }
90cf099d11SDimitry Andric
91eb11fae6SDimitry Andric // We special case the first iteration which we can detect due to the
92eb11fae6SDimitry Andric // empty `ToSimplify` set.
93eb11fae6SDimitry Andric bool IsFirstIteration = ToSimplify->empty();
94cf099d11SDimitry Andric
95eb11fae6SDimitry Andric if (!IsFirstIteration && !ToSimplify->count(&I))
96cf099d11SDimitry Andric continue;
97cf099d11SDimitry Andric
98145449b1SDimitry Andric Value *V = simplifyInstruction(&I, SQ.getWithInstruction(&I));
99eb11fae6SDimitry Andric if (!V || !LI.replacementPreservesLCSSAForm(&I, V))
100eb11fae6SDimitry Andric continue;
101cf099d11SDimitry Andric
102c0981da4SDimitry Andric for (Use &U : llvm::make_early_inc_range(I.uses())) {
103eb11fae6SDimitry Andric auto *UserI = cast<Instruction>(U.getUser());
104eb11fae6SDimitry Andric U.set(V);
105eb11fae6SDimitry Andric
106145449b1SDimitry Andric // Do not bother dealing with unreachable code.
107145449b1SDimitry Andric if (!DT.isReachableFromEntry(UserI->getParent()))
108145449b1SDimitry Andric continue;
109145449b1SDimitry Andric
110eb11fae6SDimitry Andric // If the instruction is used by a PHI node we have already processed
111eb11fae6SDimitry Andric // we'll need to iterate on the loop body to converge, so add it to
112eb11fae6SDimitry Andric // the next set.
113eb11fae6SDimitry Andric if (auto *UserPI = dyn_cast<PHINode>(UserI))
114eb11fae6SDimitry Andric if (VisitedPHIs.count(UserPI)) {
115eb11fae6SDimitry Andric Next->insert(UserPI);
116eb11fae6SDimitry Andric continue;
117eb11fae6SDimitry Andric }
118eb11fae6SDimitry Andric
119eb11fae6SDimitry Andric // If we are only simplifying targeted instructions and the user is an
120eb11fae6SDimitry Andric // instruction in the loop body, add it to our set of targeted
121eb11fae6SDimitry Andric // instructions. Because we process defs before uses (outside of PHIs)
122eb11fae6SDimitry Andric // we won't have visited it yet.
123eb11fae6SDimitry Andric //
124eb11fae6SDimitry Andric // We also skip any uses outside of the loop being simplified. Those
125eb11fae6SDimitry Andric // should always be PHI nodes due to LCSSA form, and we don't want to
126eb11fae6SDimitry Andric // try to simplify those away.
127eb11fae6SDimitry Andric assert((L.contains(UserI) || isa<PHINode>(UserI)) &&
128eb11fae6SDimitry Andric "Uses outside the loop should be PHI nodes due to LCSSA!");
129eb11fae6SDimitry Andric if (!IsFirstIteration && L.contains(UserI))
130eb11fae6SDimitry Andric ToSimplify->insert(UserI);
131eb11fae6SDimitry Andric }
132eb11fae6SDimitry Andric
133d8e91e46SDimitry Andric if (MSSAU)
134d8e91e46SDimitry Andric if (Instruction *SimpleI = dyn_cast_or_null<Instruction>(V))
135d8e91e46SDimitry Andric if (MemoryAccess *MA = MSSA->getMemoryAccess(&I))
136d8e91e46SDimitry Andric if (MemoryAccess *ReplacementMA = MSSA->getMemoryAccess(SimpleI))
137d8e91e46SDimitry Andric MA->replaceAllUsesWith(ReplacementMA);
138d8e91e46SDimitry Andric
139eb11fae6SDimitry Andric assert(I.use_empty() && "Should always have replaced all uses!");
140eb11fae6SDimitry Andric if (isInstructionTriviallyDead(&I, &TLI))
141eb11fae6SDimitry Andric DeadInsts.push_back(&I);
142cf099d11SDimitry Andric ++NumSimplified;
143eb11fae6SDimitry Andric Changed = true;
144cf099d11SDimitry Andric }
145cf099d11SDimitry Andric }
146cf099d11SDimitry Andric
147eb11fae6SDimitry Andric // Delete any dead instructions found thus far now that we've finished an
148eb11fae6SDimitry Andric // iteration over all instructions in all the loop blocks.
149eb11fae6SDimitry Andric if (!DeadInsts.empty()) {
150eb11fae6SDimitry Andric Changed = true;
151d8e91e46SDimitry Andric RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, &TLI, MSSAU);
152eb11fae6SDimitry Andric }
153eb11fae6SDimitry Andric
154d8e91e46SDimitry Andric if (MSSAU && VerifyMemorySSA)
155d8e91e46SDimitry Andric MSSA->verifyMemorySSA();
156d8e91e46SDimitry Andric
157eb11fae6SDimitry Andric // If we never found a PHI that needs to be simplified in the next
158eb11fae6SDimitry Andric // iteration, we're done.
159eb11fae6SDimitry Andric if (Next->empty())
160cf099d11SDimitry Andric break;
161cf099d11SDimitry Andric
162eb11fae6SDimitry Andric // Otherwise, put the next set in place for the next iteration and reset it
163eb11fae6SDimitry Andric // and the visited PHIs for that iteration.
164eb11fae6SDimitry Andric std::swap(Next, ToSimplify);
165cf099d11SDimitry Andric Next->clear();
166eb11fae6SDimitry Andric VisitedPHIs.clear();
167eb11fae6SDimitry Andric DeadInsts.clear();
168eb11fae6SDimitry Andric }
169cf099d11SDimitry Andric
170cf099d11SDimitry Andric return Changed;
171cf099d11SDimitry Andric }
17201095a5dSDimitry Andric
run(Loop & L,LoopAnalysisManager & AM,LoopStandardAnalysisResults & AR,LPMUpdater &)173581a6d85SDimitry Andric PreservedAnalyses LoopInstSimplifyPass::run(Loop &L, LoopAnalysisManager &AM,
174581a6d85SDimitry Andric LoopStandardAnalysisResults &AR,
175581a6d85SDimitry Andric LPMUpdater &) {
176e3b55780SDimitry Andric std::optional<MemorySSAUpdater> MSSAU;
177d8e91e46SDimitry Andric if (AR.MSSA) {
178d8e91e46SDimitry Andric MSSAU = MemorySSAUpdater(AR.MSSA);
179706b4fc4SDimitry Andric if (VerifyMemorySSA)
180d8e91e46SDimitry Andric AR.MSSA->verifyMemorySSA();
181d8e91e46SDimitry Andric }
182d8e91e46SDimitry Andric if (!simplifyLoopInst(L, AR.DT, AR.LI, AR.AC, AR.TLI,
183e3b55780SDimitry Andric MSSAU ? &*MSSAU : nullptr))
18401095a5dSDimitry Andric return PreservedAnalyses::all();
18501095a5dSDimitry Andric
18671d5a254SDimitry Andric auto PA = getLoopPassPreservedAnalyses();
18771d5a254SDimitry Andric PA.preserveSet<CFGAnalyses>();
1881d5ae102SDimitry Andric if (AR.MSSA)
189e6d15924SDimitry Andric PA.preserve<MemorySSAAnalysis>();
19071d5a254SDimitry Andric return PA;
19101095a5dSDimitry Andric }
192