1 //===- LoopInstSimplify.cpp - Loop Instruction Simplification Pass --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass performs lightweight instruction simplification on loop bodies.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
15 #include "llvm/ADT/PointerIntPair.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallPtrSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/AssumptionCache.h"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/Analysis/LoopInfo.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/TargetLibraryInfo.h"
25 #include "llvm/IR/BasicBlock.h"
26 #include "llvm/IR/CFG.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/PassManager.h"
33 #include "llvm/IR/User.h"
34 #include "llvm/Pass.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Utils/Local.h"
38 #include "llvm/Transforms/Utils/LoopUtils.h"
44 #define DEBUG_TYPE "loop-instsimplify"
46 STATISTIC(NumSimplified, "Number of redundant instructions simplified");
48 static bool SimplifyLoopInst(Loop *L, DominatorTree *DT, LoopInfo *LI,
50 const TargetLibraryInfo *TLI) {
51 SmallVector<BasicBlock *, 8> ExitBlocks;
52 L->getUniqueExitBlocks(ExitBlocks);
53 array_pod_sort(ExitBlocks.begin(), ExitBlocks.end());
55 SmallPtrSet<const Instruction *, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
57 // The bit we are stealing from the pointer represents whether this basic
58 // block is the header of a subloop, in which case we only process its phis.
59 using WorklistItem = PointerIntPair<BasicBlock *, 1>;
60 SmallVector<WorklistItem, 16> VisitStack;
61 SmallPtrSet<BasicBlock *, 32> Visited;
71 VisitStack.push_back(WorklistItem(L->getHeader(), false));
73 while (!VisitStack.empty()) {
74 WorklistItem Item = VisitStack.pop_back_val();
75 BasicBlock *BB = Item.getPointer();
76 bool IsSubloopHeader = Item.getInt();
77 const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
79 // Simplify instructions in the current basic block.
80 for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
81 Instruction *I = &*BI++;
83 // The first time through the loop ToSimplify is empty and we try to
84 // simplify all instructions. On later iterations ToSimplify is not
85 // empty and we only bother simplifying instructions that are in it.
86 if (!ToSimplify->empty() && !ToSimplify->count(I))
89 // Don't bother simplifying unused instructions.
90 if (!I->use_empty()) {
91 Value *V = SimplifyInstruction(I, {DL, TLI, DT, AC});
92 if (V && LI->replacementPreservesLCSSAForm(I, V)) {
93 // Mark all uses for resimplification next time round the loop.
94 for (User *U : I->users())
95 Next->insert(cast<Instruction>(U));
97 I->replaceAllUsesWith(V);
102 if (RecursivelyDeleteTriviallyDeadInstructions(I, TLI)) {
103 // RecursivelyDeleteTriviallyDeadInstruction can remove more than one
104 // instruction, so simply incrementing the iterator does not work.
105 // When instructions get deleted re-iterate instead.
111 if (IsSubloopHeader && !isa<PHINode>(I))
115 // Add all successors to the worklist, except for loop exit blocks and the
116 // bodies of subloops. We visit the headers of loops so that we can
118 // their phis, but we contract the rest of the subloop body and only
120 // edges leading back to the original loop.
121 for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
123 BasicBlock *SuccBB = *SI;
124 if (!Visited.insert(SuccBB).second)
127 const Loop *SuccLoop = LI->getLoopFor(SuccBB);
128 if (SuccLoop && SuccLoop->getHeader() == SuccBB &&
129 L->contains(SuccLoop)) {
130 VisitStack.push_back(WorklistItem(SuccBB, true));
132 SmallVector<BasicBlock *, 8> SubLoopExitBlocks;
133 SuccLoop->getExitBlocks(SubLoopExitBlocks);
135 for (unsigned i = 0; i < SubLoopExitBlocks.size(); ++i) {
136 BasicBlock *ExitBB = SubLoopExitBlocks[i];
137 if (LI->getLoopFor(ExitBB) == L && Visited.insert(ExitBB).second)
138 VisitStack.push_back(WorklistItem(ExitBB, false));
145 std::binary_search(ExitBlocks.begin(), ExitBlocks.end(), SuccBB);
149 VisitStack.push_back(WorklistItem(SuccBB, false));
153 // Place the list of instructions to simplify on the next loop iteration
155 std::swap(ToSimplify, Next);
158 Changed |= LocalChanged;
159 } while (LocalChanged);
166 class LoopInstSimplifyLegacyPass : public LoopPass {
168 static char ID; // Pass ID, replacement for typeid
170 LoopInstSimplifyLegacyPass() : LoopPass(ID) {
171 initializeLoopInstSimplifyLegacyPassPass(*PassRegistry::getPassRegistry());
174 bool runOnLoop(Loop *L, LPPassManager &LPM) override {
177 DominatorTreeWrapperPass *DTWP =
178 getAnalysisIfAvailable<DominatorTreeWrapperPass>();
179 DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
180 LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
181 AssumptionCache *AC =
182 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
183 *L->getHeader()->getParent());
184 const TargetLibraryInfo *TLI =
185 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
187 return SimplifyLoopInst(L, DT, LI, AC, TLI);
190 void getAnalysisUsage(AnalysisUsage &AU) const override {
191 AU.addRequired<AssumptionCacheTracker>();
192 AU.addRequired<TargetLibraryInfoWrapperPass>();
193 AU.setPreservesCFG();
194 getLoopAnalysisUsage(AU);
198 } // end anonymous namespace
200 PreservedAnalyses LoopInstSimplifyPass::run(Loop &L, LoopAnalysisManager &AM,
201 LoopStandardAnalysisResults &AR,
203 if (!SimplifyLoopInst(&L, &AR.DT, &AR.LI, &AR.AC, &AR.TLI))
204 return PreservedAnalyses::all();
206 auto PA = getLoopPassPreservedAnalyses();
207 PA.preserveSet<CFGAnalyses>();
211 char LoopInstSimplifyLegacyPass::ID = 0;
213 INITIALIZE_PASS_BEGIN(LoopInstSimplifyLegacyPass, "loop-instsimplify",
214 "Simplify instructions in loops", false, false)
215 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
216 INITIALIZE_PASS_DEPENDENCY(LoopPass)
217 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
218 INITIALIZE_PASS_END(LoopInstSimplifyLegacyPass, "loop-instsimplify",
219 "Simplify instructions in loops", false, false)
221 Pass *llvm::createLoopInstSimplifyPass() {
222 return new LoopInstSimplifyLegacyPass();