7c29b8cc07e82809b78c167d049e8e181a0410cf
[oota-llvm.git] / lib / Transforms / Scalar / LoopInstSimplify.cpp
1 //===- LoopInstSimplify.cpp - Loop Instruction Simplification Pass --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass performs lightweight instruction simplification on loop bodies.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/AssumptionTracker.h"
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/Dominators.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Target/TargetLibraryInfo.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 using namespace llvm;
28
29 #define DEBUG_TYPE "loop-instsimplify"
30
31 STATISTIC(NumSimplified, "Number of redundant instructions simplified");
32
33 namespace {
34   class LoopInstSimplify : public LoopPass {
35   public:
36     static char ID; // Pass ID, replacement for typeid
37     LoopInstSimplify() : LoopPass(ID) {
38       initializeLoopInstSimplifyPass(*PassRegistry::getPassRegistry());
39     }
40
41     bool runOnLoop(Loop*, LPPassManager&) override;
42
43     void getAnalysisUsage(AnalysisUsage &AU) const override {
44       AU.setPreservesCFG();
45       AU.addRequired<AssumptionTracker>();
46       AU.addRequired<LoopInfo>();
47       AU.addRequiredID(LoopSimplifyID);
48       AU.addPreservedID(LoopSimplifyID);
49       AU.addPreservedID(LCSSAID);
50       AU.addPreserved("scalar-evolution");
51       AU.addRequired<TargetLibraryInfo>();
52     }
53   };
54 }
55
56 char LoopInstSimplify::ID = 0;
57 INITIALIZE_PASS_BEGIN(LoopInstSimplify, "loop-instsimplify",
58                 "Simplify instructions in loops", false, false)
59 INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
60 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
61 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
62 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
63 INITIALIZE_PASS_DEPENDENCY(LCSSA)
64 INITIALIZE_PASS_END(LoopInstSimplify, "loop-instsimplify",
65                 "Simplify instructions in loops", false, false)
66
67 Pass *llvm::createLoopInstSimplifyPass() {
68   return new LoopInstSimplify();
69 }
70
71 bool LoopInstSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
72   if (skipOptnoneFunction(L))
73     return false;
74
75   DominatorTreeWrapperPass *DTWP =
76       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
77   DominatorTree *DT = DTWP ? &DTWP->getDomTree() : nullptr;
78   LoopInfo *LI = &getAnalysis<LoopInfo>();
79   DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
80   const DataLayout *DL = DLP ? &DLP->getDataLayout() : nullptr;
81   const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
82   AssumptionTracker *AT = &getAnalysis<AssumptionTracker>();
83
84   SmallVector<BasicBlock*, 8> ExitBlocks;
85   L->getUniqueExitBlocks(ExitBlocks);
86   array_pod_sort(ExitBlocks.begin(), ExitBlocks.end());
87
88   SmallPtrSet<const Instruction*, 8> S1, S2, *ToSimplify = &S1, *Next = &S2;
89
90   // The bit we are stealing from the pointer represents whether this basic
91   // block is the header of a subloop, in which case we only process its phis.
92   typedef PointerIntPair<BasicBlock*, 1> WorklistItem;
93   SmallVector<WorklistItem, 16> VisitStack;
94   SmallPtrSet<BasicBlock*, 32> Visited;
95
96   bool Changed = false;
97   bool LocalChanged;
98   do {
99     LocalChanged = false;
100
101     VisitStack.clear();
102     Visited.clear();
103
104     VisitStack.push_back(WorklistItem(L->getHeader(), false));
105
106     while (!VisitStack.empty()) {
107       WorklistItem Item = VisitStack.pop_back_val();
108       BasicBlock *BB = Item.getPointer();
109       bool IsSubloopHeader = Item.getInt();
110
111       // Simplify instructions in the current basic block.
112       for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
113         Instruction *I = BI++;
114
115         // The first time through the loop ToSimplify is empty and we try to
116         // simplify all instructions. On later iterations ToSimplify is not
117         // empty and we only bother simplifying instructions that are in it.
118         if (!ToSimplify->empty() && !ToSimplify->count(I))
119           continue;
120
121         // Don't bother simplifying unused instructions.
122         if (!I->use_empty()) {
123           Value *V = SimplifyInstruction(I, DL, TLI, DT, AT);
124           if (V && LI->replacementPreservesLCSSAForm(I, V)) {
125             // Mark all uses for resimplification next time round the loop.
126             for (User *U : I->users())
127               Next->insert(cast<Instruction>(U));
128
129             I->replaceAllUsesWith(V);
130             LocalChanged = true;
131             ++NumSimplified;
132           }
133         }
134         bool res = RecursivelyDeleteTriviallyDeadInstructions(I, TLI);
135         if (res) {
136           // RecursivelyDeleteTriviallyDeadInstruction can remove
137           // more than one instruction, so simply incrementing the
138           // iterator does not work. When instructions get deleted
139           // re-iterate instead.
140           BI = BB->begin(); BE = BB->end();
141           LocalChanged |= res;
142         }
143
144         if (IsSubloopHeader && !isa<PHINode>(I))
145           break;
146       }
147
148       // Add all successors to the worklist, except for loop exit blocks and the
149       // bodies of subloops. We visit the headers of loops so that we can process
150       // their phis, but we contract the rest of the subloop body and only follow
151       // edges leading back to the original loop.
152       for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE;
153            ++SI) {
154         BasicBlock *SuccBB = *SI;
155         if (!Visited.insert(SuccBB))
156           continue;
157
158         const Loop *SuccLoop = LI->getLoopFor(SuccBB);
159         if (SuccLoop && SuccLoop->getHeader() == SuccBB
160                      && L->contains(SuccLoop)) {
161           VisitStack.push_back(WorklistItem(SuccBB, true));
162
163           SmallVector<BasicBlock*, 8> SubLoopExitBlocks;
164           SuccLoop->getExitBlocks(SubLoopExitBlocks);
165
166           for (unsigned i = 0; i < SubLoopExitBlocks.size(); ++i) {
167             BasicBlock *ExitBB = SubLoopExitBlocks[i];
168             if (LI->getLoopFor(ExitBB) == L && Visited.insert(ExitBB))
169               VisitStack.push_back(WorklistItem(ExitBB, false));
170           }
171
172           continue;
173         }
174
175         bool IsExitBlock = std::binary_search(ExitBlocks.begin(),
176                                               ExitBlocks.end(), SuccBB);
177         if (IsExitBlock)
178           continue;
179
180         VisitStack.push_back(WorklistItem(SuccBB, false));
181       }
182     }
183
184     // Place the list of instructions to simplify on the next loop iteration
185     // into ToSimplify.
186     std::swap(ToSimplify, Next);
187     Next->clear();
188
189     Changed |= LocalChanged;
190   } while (LocalChanged);
191
192   return Changed;
193 }