Remove unnecesary &*'s
[oota-llvm.git] / lib / Transforms / Utils / SimplifyCFG.cpp
1 //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
2 //
3 // Peephole optimize the CFG.
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "llvm/Transforms/Utils/Local.h"
8 #include "llvm/Constant.h"
9 #include "llvm/iPHINode.h"
10 #include "llvm/Support/CFG.h"
11 #include <algorithm>
12 #include <functional>
13
14 // PropagatePredecessors - This gets "Succ" ready to have the predecessors from
15 // "BB".  This is a little tricky because "Succ" has PHI nodes, which need to
16 // have extra slots added to them to hold the merge edges from BB's
17 // predecessors, and BB itself might have had PHI nodes in it.  This function
18 // returns true (failure) if the Succ BB already has a predecessor that is a
19 // predecessor of BB and incoming PHI arguments would not be discernable.
20 //
21 // Assumption: Succ is the single successor for BB.
22 //
23 static bool PropagatePredecessorsForPHIs(BasicBlock *BB, BasicBlock *Succ) {
24   assert(*succ_begin(BB) == Succ && "Succ is not successor of BB!");
25
26   if (!isa<PHINode>(Succ->front()))
27     return false;  // We can make the transformation, no problem.
28
29   // If there is more than one predecessor, and there are PHI nodes in
30   // the successor, then we need to add incoming edges for the PHI nodes
31   //
32   const std::vector<BasicBlock*> BBPreds(pred_begin(BB), pred_end(BB));
33
34   // Check to see if one of the predecessors of BB is already a predecessor of
35   // Succ.  If so, we cannot do the transformation if there are any PHI nodes
36   // with incompatible values coming in from the two edges!
37   //
38   for (pred_iterator PI = pred_begin(Succ), PE = pred_end(Succ); PI != PE; ++PI)
39     if (find(BBPreds.begin(), BBPreds.end(), *PI) != BBPreds.end()) {
40       // Loop over all of the PHI nodes checking to see if there are
41       // incompatible values coming in.
42       for (BasicBlock::iterator I = Succ->begin();
43            PHINode *PN = dyn_cast<PHINode>(I); ++I) {
44         // Loop up the entries in the PHI node for BB and for *PI if the values
45         // coming in are non-equal, we cannot merge these two blocks (instead we
46         // should insert a conditional move or something, then merge the
47         // blocks).
48         int Idx1 = PN->getBasicBlockIndex(BB);
49         int Idx2 = PN->getBasicBlockIndex(*PI);
50         assert(Idx1 != -1 && Idx2 != -1 &&
51                "Didn't have entries for my predecessors??");
52         if (PN->getIncomingValue(Idx1) != PN->getIncomingValue(Idx2))
53           return true;  // Values are not equal...
54       }
55     }
56
57   // Loop over all of the PHI nodes in the successor BB
58   for (BasicBlock::iterator I = Succ->begin();
59        PHINode *PN = dyn_cast<PHINode>(I); ++I) {
60     Value *OldVal = PN->removeIncomingValue(BB, false);
61     assert(OldVal && "No entry in PHI for Pred BB!");
62
63     // If this incoming value is one of the PHI nodes in BB...
64     if (isa<PHINode>(OldVal) && cast<PHINode>(OldVal)->getParent() == BB) {
65       PHINode *OldValPN = cast<PHINode>(OldVal);
66       for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), 
67              End = BBPreds.end(); PredI != End; ++PredI) {
68         PN->addIncoming(OldValPN->getIncomingValueForBlock(*PredI), *PredI);
69       }
70     } else {
71       for (std::vector<BasicBlock*>::const_iterator PredI = BBPreds.begin(), 
72              End = BBPreds.end(); PredI != End; ++PredI) {
73         // Add an incoming value for each of the new incoming values...
74         PN->addIncoming(OldVal, *PredI);
75       }
76     }
77   }
78   return false;
79 }
80
81
82 // SimplifyCFG - This function is used to do simplification of a CFG.  For
83 // example, it adjusts branches to branches to eliminate the extra hop, it
84 // eliminates unreachable basic blocks, and does other "peephole" optimization
85 // of the CFG.  It returns true if a modification was made.
86 //
87 // WARNING:  The entry node of a function may not be simplified.
88 //
89 bool SimplifyCFG(BasicBlock *BB) {
90   Function *M = BB->getParent();
91
92   assert(BB && BB->getParent() && "Block not embedded in function!");
93   assert(BB->getTerminator() && "Degenerate basic block encountered!");
94   assert(&BB->getParent()->front() != BB && "Can't Simplify entry block!");
95
96   // Remove basic blocks that have no predecessors... which are unreachable.
97   if (pred_begin(BB) == pred_end(BB) &&
98       !BB->hasConstantReferences()) {
99     //cerr << "Removing BB: \n" << BB;
100
101     // Loop through all of our successors and make sure they know that one
102     // of their predecessors is going away.
103     for_each(succ_begin(BB), succ_end(BB),
104              std::bind2nd(std::mem_fun(&BasicBlock::removePredecessor), BB));
105
106     while (!BB->empty()) {
107       Instruction &I = BB->back();
108       // If this instruction is used, replace uses with an arbitrary
109       // constant value.  Because control flow can't get here, we don't care
110       // what we replace the value with.  Note that since this block is 
111       // unreachable, and all values contained within it must dominate their
112       // uses, that all uses will eventually be removed.
113       if (!I.use_empty()) 
114         // Make all users of this instruction reference the constant instead
115         I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
116       
117       // Remove the instruction from the basic block
118       BB->getInstList().pop_back();
119     }
120     M->getBasicBlockList().erase(BB);
121     return true;
122   }
123
124   // Check to see if this block has no non-phi instructions and only a single
125   // successor.  If so, replace references to this basic block with references
126   // to the successor.
127   succ_iterator SI(succ_begin(BB));
128   if (SI != succ_end(BB) && ++SI == succ_end(BB)) {  // One succ?
129
130     BasicBlock::iterator BBI = BB->begin();  // Skip over phi nodes...
131     while (isa<PHINode>(*BBI)) ++BBI;
132
133     if (BBI->isTerminator()) {   // Terminator is the only non-phi instruction!
134       BasicBlock *Succ = *succ_begin(BB); // There is exactly one successor
135      
136       if (Succ != BB) {   // Arg, don't hurt infinite loops!
137         // If our successor has PHI nodes, then we need to update them to
138         // include entries for BB's predecessors, not for BB itself.
139         // Be careful though, if this transformation fails (returns true) then
140         // we cannot do this transformation!
141         //
142         if (!PropagatePredecessorsForPHIs(BB, Succ)) {
143           //cerr << "Killing Trivial BB: \n" << BB;
144           std::string OldName = BB->getName();
145
146           std::vector<BasicBlock*>
147             OldSuccPreds(pred_begin(Succ), pred_end(Succ));
148
149           // Move all PHI nodes in BB to Succ if they are alive, otherwise
150           // delete them.
151           while (PHINode *PN = dyn_cast<PHINode>(&BB->front()))
152             if (PN->use_empty())
153               BB->getInstList().erase(BB->begin());  // Nuke instruction...
154             else {
155               // The instruction is alive, so this means that Succ must have
156               // *ONLY* had BB as a predecessor, and the PHI node is still valid
157               // now.  Simply move it into Succ, because we know that BB
158               // strictly dominated Succ.
159               BB->getInstList().remove(BB->begin());
160               Succ->getInstList().push_front(PN);
161
162               // We need to add new entries for the PHI node to account for
163               // predecessors of Succ that the PHI node does not take into
164               // account.  At this point, since we know that BB dominated succ,
165               // this means that we should any newly added incoming edges should
166               // use the PHI node as the value for these edges, because they are
167               // loop back edges.
168               
169               for (unsigned i = 0, e = OldSuccPreds.size(); i != e; ++i)
170                 if (OldSuccPreds[i] != BB)
171                   PN->addIncoming(PN, OldSuccPreds[i]);
172             }
173
174           // Everything that jumped to BB now goes to Succ...
175           BB->replaceAllUsesWith(Succ);
176
177           // Delete the old basic block...
178           M->getBasicBlockList().erase(BB);
179         
180           if (!OldName.empty() && !Succ->hasName())  // Transfer name if we can
181             Succ->setName(OldName);
182           
183           //cerr << "Function after removal: \n" << M;
184           return true;
185         }
186       }
187     }
188   }
189
190   // Merge basic blocks into their predecessor if there is only one distinct
191   // pred, and if there is only one distinct successor of the predecessor, and
192   // if there are no PHI nodes.
193   //
194   if (!BB->hasConstantReferences()) {
195     pred_iterator PI(pred_begin(BB)), PE(pred_end(BB));
196     BasicBlock *OnlyPred = *PI++;
197     for (; PI != PE; ++PI)  // Search all predecessors, see if they are all same
198       if (*PI != OnlyPred) {
199         OnlyPred = 0;       // There are multiple different predecessors...
200         break;
201       }
202   
203     BasicBlock *OnlySucc = 0;
204     if (OnlyPred && OnlyPred != BB) {   // Don't break self loops
205       // Check to see if there is only one distinct successor...
206       succ_iterator SI(succ_begin(OnlyPred)), SE(succ_end(OnlyPred));
207       OnlySucc = BB;
208       for (; SI != SE; ++SI)
209         if (*SI != OnlySucc) {
210           OnlySucc = 0;     // There are multiple distinct successors!
211           break;
212         }
213     }
214
215     if (OnlySucc) {
216       //cerr << "Merging: " << BB << "into: " << OnlyPred;
217       TerminatorInst *Term = OnlyPred->getTerminator();
218
219       // Resolve any PHI nodes at the start of the block.  They are all
220       // guaranteed to have exactly one entry if they exist, unless there are
221       // multiple duplicate (but guaranteed to be equal) entries for the
222       // incoming edges.  This occurs when there are multiple edges from
223       // OnlyPred to OnlySucc.
224       //
225       while (PHINode *PN = dyn_cast<PHINode>(&BB->front())) {
226         PN->replaceAllUsesWith(PN->getIncomingValue(0));
227         BB->getInstList().pop_front();  // Delete the phi node...
228       }
229
230       // Delete the unconditional branch from the predecessor...
231       OnlyPred->getInstList().pop_back();
232       
233       // Move all definitions in the succecessor to the predecessor...
234       OnlyPred->getInstList().splice(OnlyPred->end(), BB->getInstList());
235                                      
236       // Make all PHI nodes that refered to BB now refer to Pred as their
237       // source...
238       BB->replaceAllUsesWith(OnlyPred);
239
240       std::string OldName = BB->getName();
241
242       // Erase basic block from the function... 
243       M->getBasicBlockList().erase(BB);
244
245       // Inherit predecessors name if it exists...
246       if (!OldName.empty() && !OnlyPred->hasName())
247         OnlyPred->setName(OldName);
248       
249       return true;
250     }
251   }
252   
253   return false;
254 }