blob: 268290634ead9310b8ffeada8936652344de6f0d [file] [log] [blame]
Owen Andersonf3dd3e22006-05-26 21:11:53 +00001//===-- LCSSA.cpp - Convert loops into loop-closed SSA form ---------------===//
Owen Anderson8eca8912006-05-26 13:58:26 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Owen Anderson and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This pass transforms loops by placing phi nodes at the end of the loops for
11// all values that are live across the loop boundary. For example, it turns
12// the left into the right code:
13//
14// for (...) for (...)
15// if (c) if(c)
16// X1 = ... X1 = ...
17// else else
18// X2 = ... X2 = ...
19// X3 = phi(X1, X2) X3 = phi(X1, X2)
20// ... = X3 + 4 X4 = phi(X3)
21// ... = X4 + 4
22//
23// This is still valid LLVM; the extra phi nodes are purely redundant, and will
24// be trivially eliminated by InstCombine. The major benefit of this
25// transformation is that it makes many other loop optimizations, such as
26// LoopUnswitching, simpler.
27//
28//===----------------------------------------------------------------------===//
29
Owen Andersonf3dd3e22006-05-26 21:11:53 +000030#include "llvm/Transforms/Scalar.h"
Owen Anderson8eca8912006-05-26 13:58:26 +000031#include "llvm/Pass.h"
32#include "llvm/Function.h"
33#include "llvm/Instructions.h"
Owen Andersonb4e16992006-05-27 00:31:37 +000034#include "llvm/ADT/Statistic.h"
Owen Andersonf3dd3e22006-05-26 21:11:53 +000035#include "llvm/Analysis/Dominators.h"
Owen Anderson8eca8912006-05-26 13:58:26 +000036#include "llvm/Analysis/LoopInfo.h"
37#include "llvm/Support/CFG.h"
Owen Andersonf3dd3e22006-05-26 21:11:53 +000038#include <algorithm>
Owen Andersondad8c572006-05-31 20:55:06 +000039#include <iostream>
Owen Anderson1310e422006-05-27 18:47:11 +000040#include <map>
Owen Anderson8eca8912006-05-26 13:58:26 +000041#include <vector>
42
43using namespace llvm;
44
45namespace {
Owen Anderson152d0632006-05-28 19:33:28 +000046 static Statistic<> NumLCSSA("lcssa",
47 "Number of live out of a loop variables");
Owen Andersonb4e16992006-05-27 00:31:37 +000048
Owen Anderson8eca8912006-05-26 13:58:26 +000049 class LCSSA : public FunctionPass {
50 public:
Owen Andersonb4e16992006-05-27 00:31:37 +000051
52
Owen Anderson8eca8912006-05-26 13:58:26 +000053 LoopInfo *LI; // Loop information
Owen Andersonf3dd3e22006-05-26 21:11:53 +000054 DominatorTree *DT; // Dominator Tree for the current Loop...
55 DominanceFrontier *DF; // Current Dominance Frontier
Owen Anderson8eca8912006-05-26 13:58:26 +000056
57 virtual bool runOnFunction(Function &F);
Owen Anderson6e047ab2006-05-26 21:19:17 +000058 bool visitSubloop(Loop* L);
Owen Andersondad8c572006-05-31 20:55:06 +000059 void processInstruction(Instruction* Instr,
60 const std::vector<BasicBlock*>& LoopBlocks,
61 const std::vector<BasicBlock*>& exitBlocks);
Owen Anderson8eca8912006-05-26 13:58:26 +000062
63 /// This transformation requires natural loop information & requires that
Owen Andersonb4e16992006-05-27 00:31:37 +000064 /// loop preheaders be inserted into the CFG. It maintains both of these,
65 /// as well as the CFG. It also requires dominator information.
Owen Anderson8eca8912006-05-26 13:58:26 +000066 ///
67 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersonf3dd3e22006-05-26 21:11:53 +000068 AU.setPreservesCFG();
Owen Anderson8eca8912006-05-26 13:58:26 +000069 AU.addRequiredID(LoopSimplifyID);
70 AU.addPreservedID(LoopSimplifyID);
71 AU.addRequired<LoopInfo>();
72 AU.addPreserved<LoopInfo>();
Owen Anderson1310e422006-05-27 18:47:11 +000073 AU.addRequired<DominatorTree>();
Owen Andersonf3dd3e22006-05-26 21:11:53 +000074 AU.addRequired<DominanceFrontier>();
Owen Anderson8eca8912006-05-26 13:58:26 +000075 }
76 private:
Owen Andersonf3dd3e22006-05-26 21:11:53 +000077 std::set<Instruction*> getLoopValuesUsedOutsideLoop(Loop *L,
Owen Andersondad8c572006-05-31 20:55:06 +000078 const std::vector<BasicBlock*>& LoopBlocks);
79 Instruction *getValueDominatingBlock(BasicBlock *BB,
80 std::map<BasicBlock*, Instruction*> PotDoms);
Owen Anderson8eca8912006-05-26 13:58:26 +000081 };
82
83 RegisterOpt<LCSSA> X("lcssa", "Loop-Closed SSA Form Pass");
84}
85
86FunctionPass *llvm::createLCSSAPass() { return new LCSSA(); }
87
88bool LCSSA::runOnFunction(Function &F) {
89 bool changed = false;
90 LI = &getAnalysis<LoopInfo>();
Owen Andersonf3dd3e22006-05-26 21:11:53 +000091 DF = &getAnalysis<DominanceFrontier>();
92 DT = &getAnalysis<DominatorTree>();
Owen Anderson8eca8912006-05-26 13:58:26 +000093
94 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I) {
Owen Andersonf3dd3e22006-05-26 21:11:53 +000095 changed |= visitSubloop(*I);
Owen Anderson8eca8912006-05-26 13:58:26 +000096 }
97
98 return changed;
99}
100
Owen Andersonf3dd3e22006-05-26 21:11:53 +0000101bool LCSSA::visitSubloop(Loop* L) {
102 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
103 visitSubloop(*I);
104
105 // Speed up queries by creating a sorted list of blocks
106 std::vector<BasicBlock*> LoopBlocks(L->block_begin(), L->block_end());
107 std::sort(LoopBlocks.begin(), LoopBlocks.end());
108
109 std::set<Instruction*> AffectedValues = getLoopValuesUsedOutsideLoop(L,
110 LoopBlocks);
Owen Anderson8eca8912006-05-26 13:58:26 +0000111
Owen Andersondad8c572006-05-31 20:55:06 +0000112 // If no values are affected, we can save a lot of work, since we know that
113 // nothing will be changed.
114 if (AffectedValues.empty())
115 return false;
116
Owen Anderson8eca8912006-05-26 13:58:26 +0000117 std::vector<BasicBlock*> exitBlocks;
118 L->getExitBlocks(exitBlocks);
119
Owen Anderson1310e422006-05-27 18:47:11 +0000120
121 // Iterate over all affected values for this loop and insert Phi nodes
122 // for them in the appropriate exit blocks
Owen Andersondad8c572006-05-31 20:55:06 +0000123
Owen Andersonf3dd3e22006-05-26 21:11:53 +0000124 for (std::set<Instruction*>::iterator I = AffectedValues.begin(),
125 E = AffectedValues.end(); I != E; ++I) {
Owen Andersondad8c572006-05-31 20:55:06 +0000126 processInstruction(*I, LoopBlocks, exitBlocks);
Owen Anderson1310e422006-05-27 18:47:11 +0000127 }
Owen Anderson8a8f2782006-05-29 01:00:00 +0000128
Owen Andersonf3dd3e22006-05-26 21:11:53 +0000129 return true; // FIXME: Should be more intelligent in our return value.
Owen Anderson8eca8912006-05-26 13:58:26 +0000130}
131
Owen Andersondad8c572006-05-31 20:55:06 +0000132/// processInstruction -
133void LCSSA::processInstruction(Instruction* Instr,
134 const std::vector<BasicBlock*>& LoopBlocks,
135 const std::vector<BasicBlock*>& exitBlocks)
136{
137 ++NumLCSSA; // We are applying the transformation
138
139 std::map<BasicBlock*, Instruction*> Phis;
140 Phis[Instr->getParent()] = Instr;
141
142 // Phi nodes that need to be IDF-processed
143 std::vector<PHINode*> workList;
144
145 for (std::vector<BasicBlock*>::const_iterator BBI = exitBlocks.begin(),
146 BBE = exitBlocks.end(); BBI != BBE; ++BBI) {
147 PHINode *phi = new PHINode(Instr->getType(), "lcssa", (*BBI)->begin());
148 workList.push_back(phi);
149 Phis[*BBI] = phi;
150
151 // Since LoopSimplify has been run, we know that all of these predecessors
152 // are in the loop, so just hook them up in the obvious manner.
153 //for (pred_iterator PI = pred_begin(*BBI), PE = pred_end(*BBI); PI != PE;
154 // ++PI)
155 // phi->addIncoming(Instr, *PI);
156 }
157
158 // Calculate the IDF of these LCSSA Phi nodes, inserting new Phi's where
159 // necessary. Keep track of these new Phi's in Phis.
160 while (!workList.empty()) {
161 PHINode *CurPHI = workList.back();
162 workList.pop_back();
163
164 // Get the current Phi's DF, and insert Phi nodes. Add these new
165 // nodes to our worklist.
166 DominanceFrontier::const_iterator it = DF->find(CurPHI->getParent());
167 if (it != DF->end()) {
168 const DominanceFrontier::DomSetType &S = it->second;
169 for (DominanceFrontier::DomSetType::const_iterator P = S.begin(),
170 PE = S.end(); P != PE; ++P) {
171 if (Phis[*P] == 0) {
172 // Still doesn't have operands...
173 PHINode *phi = new PHINode(Instr->getType(), "lcssa");
174 (*P)->getInstList().insert((*P)->front(), phi);
175 Phis[*P] = phi;
176
177 workList.push_back(phi);
178 }
179 }
180 }
181
182 // Get the predecessor blocks of the current Phi, and use them to hook up
183 // the operands of the current Phi to any members of DFPhis that dominate
184 // it. This is a nop for the Phis inserted directly in the exit blocks,
185 // since they are not dominated by any members of DFPhis.
186 for (pred_iterator PI = pred_begin(CurPHI->getParent()),
187 E = pred_end(CurPHI->getParent()); PI != E; ++PI)
188 CurPHI->addIncoming(getValueDominatingBlock(*PI, Phis),
189 *PI);
190 }
191
192 // Find all uses of the affected value, and replace them with the
193 // appropriate Phi.
194 std::vector<Instruction*> Uses;
195 for (Instruction::use_iterator UI = Instr->use_begin(), UE = Instr->use_end();
196 UI != UE; ++UI) {
197 Instruction* use = cast<Instruction>(*UI);
198 // Don't need to update uses within the loop body
199 if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(),
200 use->getParent()) &&
201 !(std::binary_search(exitBlocks.begin(), exitBlocks.end(),
202 use->getParent()) && isa<PHINode>(use)))
203 Uses.push_back(use);
204 }
205
206 // Deliberately remove the initial instruction from Phis set.
207 Phis.erase(Instr->getParent());
208
209 for (std::vector<Instruction*>::iterator II = Uses.begin(), IE = Uses.end();
210 II != IE; ++II) {
211 (*II)->replaceUsesOfWith(Instr, getValueDominatingBlock((*II)->getParent(),
212 Phis));
213 }
214}
215
Owen Andersonf3dd3e22006-05-26 21:11:53 +0000216/// getLoopValuesUsedOutsideLoop - Return any values defined in the loop that
217/// are used by instructions outside of it.
218std::set<Instruction*> LCSSA::getLoopValuesUsedOutsideLoop(Loop *L,
Owen Andersondad8c572006-05-31 20:55:06 +0000219 const std::vector<BasicBlock*>& LoopBlocks) {
220
221 // FIXME: For large loops, we may be able to avoid a lot of use-scanning
222 // by using dominance information. In particular, if a block does not
223 // dominate any of the loop exits, then none of the values defined in the
224 // block could be used outside the loop.
225
Owen Andersonf3dd3e22006-05-26 21:11:53 +0000226 std::set<Instruction*> AffectedValues;
Owen Anderson8eca8912006-05-26 13:58:26 +0000227 for (Loop::block_iterator BB = L->block_begin(), E = L->block_end();
228 BB != E; ++BB) {
229 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); I != E; ++I)
230 for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI != E;
231 ++UI) {
232 BasicBlock *UserBB = cast<Instruction>(*UI)->getParent();
Owen Andersondad8c572006-05-31 20:55:06 +0000233 if (!std::binary_search(LoopBlocks.begin(), LoopBlocks.end(), UserBB)) {
Owen Anderson8eca8912006-05-26 13:58:26 +0000234 AffectedValues.insert(I);
Owen Andersondad8c572006-05-31 20:55:06 +0000235 break;
236 }
Owen Anderson8eca8912006-05-26 13:58:26 +0000237 }
238 }
239 return AffectedValues;
Owen Andersonf3dd3e22006-05-26 21:11:53 +0000240}
Owen Andersondad8c572006-05-31 20:55:06 +0000241
242Instruction *LCSSA::getValueDominatingBlock(BasicBlock *BB,
243 std::map<BasicBlock*, Instruction*> PotDoms) {
244 for (std::map<BasicBlock*, Instruction*>::iterator MI = PotDoms.begin(),
245 ME = PotDoms.end(); MI != ME; ++MI)
246 if (DT->getNode((*MI).first)->dominates(DT->getNode(BB)))
247 return (*MI).second;
248
249 // FIXME: Should assert false
250
251 return 0;
252}