Add some statistics to SSI so we can see what it's up to.
[oota-llvm.git] / lib / Transforms / Utils / SSI.cpp
1 //===------------------- SSI.cpp - Creates SSI Representation -------------===//
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 converts a list of variables to the Static Single Information
11 // form. This is a program representation described by Scott Ananian in his
12 // Master Thesis: "The Static Single Information Form (1999)".
13 // We are building an on-demand representation, that is, we do not convert
14 // every single variable in the target function to SSI form. Rather, we receive
15 // a list of target variables that must be converted. We also do not
16 // completely convert a target variable to the SSI format. Instead, we only
17 // change the variable in the points where new information can be attached
18 // to its live range, that is, at branch points.
19 //
20 //===----------------------------------------------------------------------===//
21
22 #define DEBUG_TYPE "ssi"
23
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Transforms/Utils/SSI.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/Dominators.h"
28
29 using namespace llvm;
30
31 static const std::string SSI_PHI = "SSI_phi";
32 static const std::string SSI_SIG = "SSI_sigma";
33
34 static const unsigned UNSIGNED_INFINITE = ~0U;
35
36 STATISTIC(NumSigmaInserted, "Number of sigma functions inserted");
37 STATISTIC(NumPhiInserted, "Number of phi functions inserted");
38
39 void SSI::getAnalysisUsage(AnalysisUsage &AU) const {
40   AU.addRequired<DominanceFrontier>();
41   AU.addRequired<DominatorTree>();
42   AU.setPreservesAll();
43 }
44
45 bool SSI::runOnFunction(Function &F) {
46   DT_ = &getAnalysis<DominatorTree>();
47   return false;
48 }
49
50 /// This methods creates the SSI representation for the list of values
51 /// received. It will only create SSI representation if a value is used
52 /// in a to decide a branch. Repeated values are created only once.
53 ///
54 void SSI::createSSI(SmallVectorImpl<Instruction *> &value) {
55   init(value);
56
57   for (unsigned i = 0; i < num_values; ++i) {
58     if (created.insert(value[i])) {
59       needConstruction[i] = true;
60     }
61   }
62   insertSigmaFunctions(value);
63
64   // Test if there is a need to transform to SSI
65   if (needConstruction.any()) {
66     insertPhiFunctions(value);
67     renameInit(value);
68     rename(DT_->getRoot());
69     fixPhis();
70   }
71
72   clean();
73 }
74
75 /// Insert sigma functions (a sigma function is a phi function with one
76 /// operator)
77 ///
78 void SSI::insertSigmaFunctions(SmallVectorImpl<Instruction *> &value) {
79   for (unsigned i = 0; i < num_values; ++i) {
80     if (!needConstruction[i])
81       continue;
82
83     bool need = false;
84     for (Value::use_iterator begin = value[i]->use_begin(), end =
85          value[i]->use_end(); begin != end; ++begin) {
86       // Test if the Use of the Value is in a comparator
87       CmpInst *CI = dyn_cast<CmpInst>(begin);
88       if (CI && isUsedInTerminator(CI)) {
89         // Basic Block of the Instruction
90         BasicBlock *BB = CI->getParent();
91         // Last Instruction of the Basic Block
92         const TerminatorInst *TI = BB->getTerminator();
93
94         for (unsigned j = 0, e = TI->getNumSuccessors(); j < e; ++j) {
95           // Next Basic Block
96           BasicBlock *BB_next = TI->getSuccessor(j);
97           if (BB_next != BB &&
98               BB_next->getUniquePredecessor() != NULL &&
99               dominateAny(BB_next, value[i])) {
100             PHINode *PN = PHINode::Create(
101                 value[i]->getType(), SSI_SIG, BB_next->begin());
102             PN->addIncoming(value[i], BB);
103             sigmas.insert(std::make_pair(PN, i));
104             created.insert(PN);
105             need = true;
106             defsites[i].push_back(BB_next);
107             ++NumSigmaInserted;
108           }
109         }
110       }
111     }
112     needConstruction[i] = need;
113   }
114 }
115
116 /// Insert phi functions when necessary
117 ///
118 void SSI::insertPhiFunctions(SmallVectorImpl<Instruction *> &value) {
119   DominanceFrontier *DF = &getAnalysis<DominanceFrontier>();
120   for (unsigned i = 0; i < num_values; ++i) {
121     // Test if there were any sigmas for this variable
122     if (needConstruction[i]) {
123
124       SmallPtrSet<BasicBlock *, 1> BB_visited;
125
126       // Insert phi functions if there is any sigma function
127       while (!defsites[i].empty()) {
128
129         BasicBlock *BB = defsites[i].back();
130
131         defsites[i].pop_back();
132         DominanceFrontier::iterator DF_BB = DF->find(BB);
133
134         // Iterates through all the dominance frontier of BB
135         for (std::set<BasicBlock *>::iterator DF_BB_begin =
136              DF_BB->second.begin(), DF_BB_end = DF_BB->second.end();
137              DF_BB_begin != DF_BB_end; ++DF_BB_begin) {
138           BasicBlock *BB_dominated = *DF_BB_begin;
139
140           // Test if has not yet visited this node and if the
141           // original definition dominates this node
142           if (BB_visited.insert(BB_dominated) &&
143               DT_->properlyDominates(value_original[i], BB_dominated) &&
144               dominateAny(BB_dominated, value[i])) {
145             PHINode *PN = PHINode::Create(
146                 value[i]->getType(), SSI_PHI, BB_dominated->begin());
147             phis.insert(std::make_pair(PN, i));
148             created.insert(PN);
149
150             defsites[i].push_back(BB_dominated);
151             ++NumPhiInserted;
152           }
153         }
154       }
155       BB_visited.clear();
156     }
157   }
158 }
159
160 /// Some initialization for the rename part
161 ///
162 void SSI::renameInit(SmallVectorImpl<Instruction *> &value) {
163   value_stack.resize(num_values);
164   for (unsigned i = 0; i < num_values; ++i) {
165     value_stack[i].push_back(value[i]);
166   }
167 }
168
169 /// Renames all variables in the specified BasicBlock.
170 /// Only variables that need to be rename will be.
171 ///
172 void SSI::rename(BasicBlock *BB) {
173   BitVector *defined = new BitVector(num_values, false);
174
175   // Iterate through instructions and make appropriate renaming.
176   // For SSI_PHI (b = PHI()), store b at value_stack as a new
177   // definition of the variable it represents.
178   // For SSI_SIG (b = PHI(a)), substitute a with the current
179   // value of a, present in the value_stack.
180   // Then store bin the value_stack as the new definition of a.
181   // For all other instructions (b = OP(a, c, d, ...)), we need to substitute
182   // all operands with its current value, present in value_stack.
183   for (BasicBlock::iterator begin = BB->begin(), end = BB->end();
184        begin != end; ++begin) {
185     Instruction *I = begin;
186     if (PHINode *PN = dyn_cast<PHINode>(I)) { // Treat PHI functions
187       int position;
188
189       // Treat SSI_PHI
190       if ((position = getPositionPhi(PN)) != -1) {
191         value_stack[position].push_back(PN);
192         (*defined)[position] = true;
193       }
194
195       // Treat SSI_SIG
196       else if ((position = getPositionSigma(PN)) != -1) {
197         substituteUse(I);
198         value_stack[position].push_back(PN);
199         (*defined)[position] = true;
200       }
201
202       // Treat all other PHI functions
203       else {
204         substituteUse(I);
205       }
206     }
207
208     // Treat all other functions
209     else {
210       substituteUse(I);
211     }
212   }
213
214   // This loop iterates in all BasicBlocks that are successors of the current
215   // BasicBlock. For each SSI_PHI instruction found, insert an operand.
216   // This operand is the current operand in value_stack for the variable
217   // in "position". And the BasicBlock this operand represents is the current
218   // BasicBlock.
219   for (succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) {
220     BasicBlock *BB_succ = *SI;
221
222     for (BasicBlock::iterator begin = BB_succ->begin(),
223          notPhi = BB_succ->getFirstNonPHI(); begin != *notPhi; ++begin) {
224       Instruction *I = begin;
225       PHINode *PN;
226       int position;
227       if ((PN = dyn_cast<PHINode>(I)) && ((position
228           = getPositionPhi(PN)) != -1)) {
229         PN->addIncoming(value_stack[position].back(), BB);
230       }
231     }
232   }
233
234   // This loop calls rename on all children from this block. This time children
235   // refers to a successor block in the dominance tree.
236   DomTreeNode *DTN = DT_->getNode(BB);
237   for (DomTreeNode::iterator begin = DTN->begin(), end = DTN->end();
238        begin != end; ++begin) {
239     DomTreeNodeBase<BasicBlock> *DTN_children = *begin;
240     BasicBlock *BB_children = DTN_children->getBlock();
241     rename(BB_children);
242   }
243
244   // Now we remove all inserted definitions of a variable from the top of
245   // the stack leaving the previous one as the top.
246   if (defined->any()) {
247     for (unsigned i = 0; i < num_values; ++i) {
248       if ((*defined)[i]) {
249         value_stack[i].pop_back();
250       }
251     }
252   }
253 }
254
255 /// Substitute any use in this instruction for the last definition of
256 /// the variable
257 ///
258 void SSI::substituteUse(Instruction *I) {
259   for (unsigned i = 0, e = I->getNumOperands(); i < e; ++i) {
260     Value *operand = I->getOperand(i);
261     for (unsigned j = 0; j < num_values; ++j) {
262       if (operand == value_stack[j].front() &&
263           I != value_stack[j].back()) {
264         PHINode *PN_I = dyn_cast<PHINode>(I);
265         PHINode *PN_vs = dyn_cast<PHINode>(value_stack[j].back());
266
267         // If a phi created in a BasicBlock is used as an operand of another
268         // created in the same BasicBlock, this step marks this second phi,
269         // to fix this issue later. It cannot be fixed now, because the
270         // operands of the first phi are not final yet.
271         if (PN_I && PN_vs &&
272             value_stack[j].back()->getParent() == I->getParent()) {
273
274           phisToFix.insert(PN_I);
275         }
276
277         I->setOperand(i, value_stack[j].back());
278         break;
279       }
280     }
281   }
282 }
283
284 /// Test if the BasicBlock BB dominates any use or definition of value.
285 ///
286 bool SSI::dominateAny(BasicBlock *BB, Instruction *value) {
287   for (Value::use_iterator begin = value->use_begin(),
288        end = value->use_end(); begin != end; ++begin) {
289     Instruction *I = cast<Instruction>(*begin);
290     BasicBlock *BB_father = I->getParent();
291     if (DT_->dominates(BB, BB_father)) {
292       return true;
293     }
294   }
295   return false;
296 }
297
298 /// When there is a phi node that is created in a BasicBlock and it is used
299 /// as an operand of another phi function used in the same BasicBlock,
300 /// LLVM looks this as an error. So on the second phi, the first phi is called
301 /// P and the BasicBlock it incomes is B. This P will be replaced by the value
302 /// it has for BasicBlock B.
303 ///
304 void SSI::fixPhis() {
305   for (SmallPtrSet<PHINode *, 1>::iterator begin = phisToFix.begin(),
306        end = phisToFix.end(); begin != end; ++begin) {
307     PHINode *PN = *begin;
308     for (unsigned i = 0, e = PN->getNumIncomingValues(); i < e; ++i) {
309       PHINode *PN_father;
310       if ((PN_father = dyn_cast<PHINode>(PN->getIncomingValue(i))) &&
311           PN->getParent() == PN_father->getParent()) {
312         BasicBlock *BB = PN->getIncomingBlock(i);
313         int pos = PN_father->getBasicBlockIndex(BB);
314         PN->setIncomingValue(i, PN_father->getIncomingValue(pos));
315       }
316     }
317   }
318 }
319
320 /// Return which variable (position on the vector of variables) this phi
321 /// represents on the phis list.
322 ///
323 unsigned SSI::getPositionPhi(PHINode *PN) {
324   DenseMap<PHINode *, unsigned>::iterator val = phis.find(PN);
325   if (val == phis.end())
326     return UNSIGNED_INFINITE;
327   else
328     return val->second;
329 }
330
331 /// Return which variable (position on the vector of variables) this phi
332 /// represents on the sigmas list.
333 ///
334 unsigned SSI::getPositionSigma(PHINode *PN) {
335   DenseMap<PHINode *, unsigned>::iterator val = sigmas.find(PN);
336   if (val == sigmas.end())
337     return UNSIGNED_INFINITE;
338   else
339     return val->second;
340 }
341
342 /// Return true if the the Comparison Instruction is an operator
343 /// of the Terminator instruction of its Basic Block.
344 ///
345 unsigned SSI::isUsedInTerminator(CmpInst *CI) {
346   TerminatorInst *TI = CI->getParent()->getTerminator();
347   if (TI->getNumOperands() == 0) {
348     return false;
349   } else if (CI == TI->getOperand(0)) {
350     return true;
351   } else {
352     return false;
353   }
354 }
355
356 /// Initializes
357 ///
358 void SSI::init(SmallVectorImpl<Instruction *> &value) {
359   num_values = value.size();
360   needConstruction.resize(num_values, false);
361
362   value_original.resize(num_values);
363   defsites.resize(num_values);
364
365   for (unsigned i = 0; i < num_values; ++i) {
366     value_original[i] = value[i]->getParent();
367     defsites[i].push_back(value_original[i]);
368   }
369 }
370
371 /// Clean all used resources in this creation of SSI
372 ///
373 void SSI::clean() {
374   for (unsigned i = 0; i < num_values; ++i) {
375     defsites[i].clear();
376     if (i < value_stack.size())
377       value_stack[i].clear();
378   }
379
380   phis.clear();
381   sigmas.clear();
382   phisToFix.clear();
383
384   defsites.clear();
385   value_stack.clear();
386   value_original.clear();
387   needConstruction.clear();
388 }
389
390 /// createSSIPass - The public interface to this file...
391 ///
392 FunctionPass *llvm::createSSIPass() { return new SSI(); }
393
394 char SSI::ID = 0;
395 static RegisterPass<SSI> X("ssi", "Static Single Information Construction");
396
397 /// SSIEverything - A pass that runs createSSI on every non-void variable,
398 /// intended for debugging.
399 namespace {
400   struct VISIBILITY_HIDDEN SSIEverything : public FunctionPass {
401     static char ID; // Pass identification, replacement for typeid
402     SSIEverything() : FunctionPass((intptr_t)&ID) {}
403
404     bool runOnFunction(Function &F);
405
406     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
407       AU.addRequired<SSI>();
408     }
409   };
410 }
411
412 bool SSIEverything::runOnFunction(Function &F) {
413   SmallVector<Instruction *, 16> Insts;
414   SSI &ssi = getAnalysis<SSI>();
415
416   if (F.isDeclaration() || F.isIntrinsic()) return false;
417
418   for (Function::iterator B = F.begin(), BE = F.end(); B != BE; ++B)
419     for (BasicBlock::iterator I = B->begin(), E = B->end(); I != E; ++I)
420       if (I->getType() != Type::VoidTy)
421         Insts.push_back(I);
422
423   ssi.createSSI(Insts);
424   return true;
425 }
426
427 /// createSSIEverythingPass - The public interface to this file...
428 ///
429 FunctionPass *llvm::createSSIEverythingPass() { return new SSIEverything(); }
430
431 char SSIEverything::ID = 0;
432 static RegisterPass<SSIEverything>
433 Y("ssi-everything", "Static Single Information Construction");