The VersionNumbers vector is only used during PHI placement. Turn it into an argumen...
[oota-llvm.git] / lib / Transforms / Utils / PromoteMemoryToRegister.cpp
1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2 //
3 // This file promote memory references to be register references.  It promotes
4 // alloca instructions which only have loads and stores as uses.  An alloca is
5 // transformed by using dominator frontiers to place PHI nodes, then traversing
6 // the function in depth-first order to rewrite loads and stores as appropriate.
7 // This is just the standard SSA construction algorithm.
8 //
9 //===----------------------------------------------------------------------===//
10
11 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
12 #include "llvm/Analysis/Dominators.h"
13 #include "llvm/iMemory.h"
14 #include "llvm/iPHINode.h"
15 #include "llvm/Function.h"
16 #include "llvm/Constant.h"
17 #include "llvm/Support/CFG.h"
18 #include "Support/StringExtras.h"
19
20 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
21 /// This is true if there are only loads and stores to the alloca...
22 ///
23 bool isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
24   // FIXME: If the memory unit is of pointer or integer type, we can permit
25   // assignments to subsections of the memory unit.
26
27   // Only allow direct loads and stores...
28   for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
29        UI != UE; ++UI)     // Loop over all of the uses of the alloca
30     if (!isa<LoadInst>(*UI))
31       if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
32         if (SI->getOperand(0) == AI)
33           return false;   // Don't allow a store of the AI, only INTO the AI.
34       } else {
35         return false;   // Not a load or store?
36       }
37   
38   return true;
39 }
40
41
42 namespace {
43   struct PromoteMem2Reg {
44     // Allocas - The alloca instructions being promoted
45     const std::vector<AllocaInst*> &Allocas;
46     DominanceFrontier &DF;
47     const TargetData &TD;
48
49     // AllocaLookup - Reverse mapping of Allocas
50     std::map<AllocaInst*, unsigned>  AllocaLookup;
51
52     // NewPhiNodes - The PhiNodes we're adding.
53     std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
54
55     // Visited - The set of basic blocks the renamer has already visited.
56     std::set<BasicBlock*> Visited;
57
58   public:
59     PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominanceFrontier &df,
60                    const TargetData &td) : Allocas(A), DF(df), TD(td) {}
61
62     void run();
63
64   private:
65     void RenamePass(BasicBlock *BB, BasicBlock *Pred,
66                     std::vector<Value*> &IncVals);
67     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version);
68   };
69 }  // end of anonymous namespace
70
71 void PromoteMem2Reg::run() {
72   Function &F = *DF.getRoot()->getParent();
73
74   for (unsigned i = 0; i != Allocas.size(); ++i) {
75     AllocaInst *AI = Allocas[i];
76
77     assert(isAllocaPromotable(AI, TD) &&
78            "Cannot promote non-promotable alloca!");
79     assert(Allocas[i]->getParent()->getParent() == &F &&
80            "All allocas should be in the same function, which is same as DF!");
81
82     // Calculate the set of write-locations for each alloca.  This is analogous
83     // to counting the number of 'redefinitions' of each variable.
84     std::vector<BasicBlock*> DefiningBlocks;
85     for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
86       if (StoreInst *SI = dyn_cast<StoreInst>(cast<Instruction>(*U)))
87         // jot down the basic-block it came from
88         DefiningBlocks.push_back(SI->getParent());
89
90     AllocaLookup[Allocas[i]] = i;
91     
92     // PhiNodeBlocks - A list of blocks that phi nodes have been inserted for
93     // this alloca.
94     std::vector<BasicBlock*> PhiNodeBlocks;
95
96     // Compute the locations where PhiNodes need to be inserted.  Look at the
97     // dominance frontier of EACH basic-block we have a write in.
98     //
99     unsigned CurrentVersion = 0;
100     while (!DefiningBlocks.empty()) {
101       BasicBlock *BB = DefiningBlocks.back();
102       DefiningBlocks.pop_back();
103
104       // Look up the DF for this write, add it to PhiNodes
105       DominanceFrontier::const_iterator it = DF.find(BB);
106       if (it != DF.end()) {
107         const DominanceFrontier::DomSetType &S = it->second;
108         for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
109              P != PE; ++P)
110           if (QueuePhiNode(*P, i, CurrentVersion))
111             DefiningBlocks.push_back(*P);
112       }
113     }
114   }
115
116   // Set the incoming values for the basic block to be null values for all of
117   // the alloca's.  We do this in case there is a load of a value that has not
118   // been stored yet.  In this case, it will get this null value.
119   //
120   std::vector<Value *> Values(Allocas.size());
121   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
122     Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
123
124   // Walks all basic blocks in the function performing the SSA rename algorithm
125   // and inserting the phi nodes we marked as necessary
126   //
127   RenamePass(F.begin(), 0, Values);
128
129   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
130   Visited.clear();
131
132   // Remove the allocas themselves from the function...
133   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
134     Instruction *A = Allocas[i];
135
136     // If there are any uses of the alloca instructions left, they must be in
137     // sections of dead code that were not processed on the dominance frontier.
138     // Just delete the users now.
139     //
140     if (!A->use_empty())
141       A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
142     A->getParent()->getInstList().erase(A);
143   }
144
145   // At this point, the renamer has added entries to PHI nodes for all reachable
146   // code.  Unfortunately, there may be blocks which are not reachable, which
147   // the renamer hasn't traversed.  If this is the case, the PHI nodes may not
148   // have incoming values for all predecessors.  Loop over all PHI nodes we have
149   // created, inserting null constants if they are missing any incoming values.
150   //
151   for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I = 
152          NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
153
154     std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
155     std::vector<PHINode*> &PNs = I->second;
156     assert(!PNs.empty() && "Empty PHI node list??");
157
158     // Only do work here if there the PHI nodes are missing incoming values.  We
159     // know that all PHI nodes that were inserted in a block will have the same
160     // number of incoming values, so we can just check any PHI node.
161     PHINode *FirstPHI = PNs[0];
162     if (Preds.size() != FirstPHI->getNumIncomingValues()) {
163       // Ok, now we know that all of the PHI nodes are missing entries for some
164       // basic blocks.  Start by sorting the incoming predecessors for efficient
165       // access.
166       std::sort(Preds.begin(), Preds.end());
167
168       // Now we loop through all BB's which have entries in FirstPHI and remove
169       // them from the Preds list.
170       for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
171         // Do a log(n) search of teh Preds list for the entry we want.
172         std::vector<BasicBlock*>::iterator EntIt =
173           std::lower_bound(Preds.begin(), Preds.end(),
174                            FirstPHI->getIncomingBlock(i));
175         assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
176                "PHI node has entry for a block which is not a predecessor!");
177
178         // Remove the entry
179         Preds.erase(EntIt);
180       }
181
182       // At this point, the blocks left in the preds list must have dummy
183       // entries inserted into every PHI nodes for the block.
184       for (unsigned i = 0, e = PNs.size(); i != e; ++i) {
185         PHINode *PN = PNs[i];
186         Value *NullVal = Constant::getNullValue(PN->getType());
187         for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
188           PN->addIncoming(NullVal, Preds[pred]);
189       }
190     }
191   }
192 }
193
194
195 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
196 // Alloca returns true if there wasn't already a phi-node for that variable
197 //
198 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
199                                   unsigned &Version) {
200   // Look up the basic-block in question
201   std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
202   if (BBPNs.empty()) BBPNs.resize(Allocas.size());
203
204   // If the BB already has a phi node added for the i'th alloca then we're done!
205   if (BBPNs[AllocaNo]) return false;
206
207   // Create a PhiNode using the dereferenced type... and add the phi-node to the
208   // BasicBlock.
209   BBPNs[AllocaNo] = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
210                                 Allocas[AllocaNo]->getName() + "." +
211                                         utostr(Version++), BB->begin());
212   return true;
213 }
214
215 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
216                                 std::vector<Value*> &IncomingVals) {
217
218   // If this BB needs a PHI node, update the PHI node for each variable we need
219   // PHI nodes for.
220   std::map<BasicBlock*, std::vector<PHINode *> >::iterator
221     BBPNI = NewPhiNodes.find(BB);
222   if (BBPNI != NewPhiNodes.end()) {
223     std::vector<PHINode *> &BBPNs = BBPNI->second;
224     for (unsigned k = 0; k != BBPNs.size(); ++k)
225       if (PHINode *PN = BBPNs[k]) {
226         // Add this incoming value to the PHI node.
227         PN->addIncoming(IncomingVals[k], Pred);
228
229         // The currently active variable for this block is now the PHI.
230         IncomingVals[k] = PN;
231       }
232   }
233
234   // don't revisit nodes
235   if (Visited.count(BB)) return;
236   
237   // mark as visited
238   Visited.insert(BB);
239
240   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
241     Instruction *I = II++; // get the instruction, increment iterator
242
243     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
244       if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
245         std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
246         if (AI != AllocaLookup.end()) {
247           Value *V = IncomingVals[AI->second];
248
249           // walk the use list of this load and replace all uses with r
250           LI->replaceAllUsesWith(V);
251           BB->getInstList().erase(LI);
252         }
253       }
254     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
255       // Delete this instruction and mark the name as the current holder of the
256       // value
257       if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
258         std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
259         if (ai != AllocaLookup.end()) {
260           // what value were we writing?
261           IncomingVals[ai->second] = SI->getOperand(0);
262           BB->getInstList().erase(SI);
263         }
264       }
265     }
266   }
267
268   // Recurse to our successors
269   TerminatorInst *TI = BB->getTerminator();
270   for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
271     std::vector<Value*> OutgoingVals(IncomingVals);
272     RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
273   }
274 }
275
276 /// PromoteMemToReg - Promote the specified list of alloca instructions into
277 /// scalar registers, inserting PHI nodes as appropriate.  This function makes
278 /// use of DominanceFrontier information.  This function does not modify the CFG
279 /// of the function at all.  All allocas must be from the same function.
280 ///
281 void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
282                      DominanceFrontier &DF, const TargetData &TD) {
283   // If there is nothing to do, bail out...
284   if (Allocas.empty()) return;
285   PromoteMem2Reg(Allocas, DF, TD).run();
286 }