Delete dead line
[oota-llvm.git] / lib / Transforms / Utils / PromoteMemoryToRegister.cpp
1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file promote memory references to be register references.  It promotes
11 // alloca instructions which only have loads and stores as uses.  An alloca is
12 // transformed by using dominator frontiers to place PHI nodes, then traversing
13 // the function in depth-first order to rewrite loads and stores as appropriate.
14 // This is just the standard SSA construction algorithm to construct "pruned"
15 // SSA form.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iPHINode.h"
23 #include "llvm/Function.h"
24 #include "llvm/Constant.h"
25 #include "llvm/Support/CFG.h"
26 #include "Support/StringExtras.h"
27
28 namespace llvm {
29
30 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
31 /// This is true if there are only loads and stores to the alloca...
32 ///
33 bool isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
34   // FIXME: If the memory unit is of pointer or integer type, we can permit
35   // assignments to subsections of the memory unit.
36
37   // Only allow direct loads and stores...
38   for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
39        UI != UE; ++UI)     // Loop over all of the uses of the alloca
40     if (!isa<LoadInst>(*UI))
41       if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
42         if (SI->getOperand(0) == AI)
43           return false;   // Don't allow a store of the AI, only INTO the AI.
44       } else {
45         return false;   // Not a load or store?
46       }
47   
48   return true;
49 }
50
51 namespace {
52   struct PromoteMem2Reg {
53     // Allocas - The alloca instructions being promoted
54     std::vector<AllocaInst*> Allocas;
55     DominatorTree &DT;
56     DominanceFrontier &DF;
57     const TargetData &TD;
58
59     // AllocaLookup - Reverse mapping of Allocas
60     std::map<AllocaInst*, unsigned>  AllocaLookup;
61
62     // NewPhiNodes - The PhiNodes we're adding.
63     std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
64
65     // Visited - The set of basic blocks the renamer has already visited.
66     std::set<BasicBlock*> Visited;
67
68   public:
69     PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
70                    DominanceFrontier &df, const TargetData &td)
71       : Allocas(A), DT(dt), DF(df), TD(td) {}
72
73     void run();
74
75   private:
76     void MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
77                                std::set<PHINode*> &DeadPHINodes);
78     void PromoteLocallyUsedAlloca(AllocaInst *AI);
79
80     void RenamePass(BasicBlock *BB, BasicBlock *Pred,
81                     std::vector<Value*> &IncVals);
82     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
83                       std::set<PHINode*> &InsertedPHINodes);
84   };
85 }  // end of anonymous namespace
86
87 void PromoteMem2Reg::run() {
88   Function &F = *DF.getRoot()->getParent();
89
90   for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
91     AllocaInst *AI = Allocas[AllocaNum];
92
93     assert(isAllocaPromotable(AI, TD) &&
94            "Cannot promote non-promotable alloca!");
95     assert(AI->getParent()->getParent() == &F &&
96            "All allocas should be in the same function, which is same as DF!");
97
98     if (AI->use_empty()) {
99       // If there are no uses of the alloca, just delete it now.
100       AI->getParent()->getInstList().erase(AI);
101
102       // Remove the alloca from the Allocas list, since it has been processed
103       Allocas[AllocaNum] = Allocas.back();
104       Allocas.pop_back();
105       --AllocaNum;
106       continue;
107     }
108
109     // Calculate the set of read and write-locations for each alloca.  This is
110     // analogous to counting the number of 'uses' and 'definitions' of each
111     // variable.
112     std::vector<BasicBlock*> DefiningBlocks;
113     std::vector<BasicBlock*> UsingBlocks;
114
115     BasicBlock *OnlyBlock = 0;
116     bool OnlyUsedInOneBlock = true;
117
118     // As we scan the uses of the alloca instruction, keep track of stores, and
119     // decide whether all of the loads and stores to the alloca are within the
120     // same basic block.
121     for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E;++U){
122       Instruction *User = cast<Instruction>(*U);
123       if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
124         // Remember the basic blocks which define new values for the alloca
125         DefiningBlocks.push_back(SI->getParent());
126       } else {
127         // Otherwise it must be a load instruction, keep track of variable reads
128         UsingBlocks.push_back(cast<LoadInst>(User)->getParent());
129       }
130
131       if (OnlyUsedInOneBlock) {
132         if (OnlyBlock == 0)
133           OnlyBlock = User->getParent();
134         else if (OnlyBlock != User->getParent())
135           OnlyUsedInOneBlock = false;
136       }
137     }
138
139     // If the alloca is only read and written in one basic block, just perform a
140     // linear sweep over the block to eliminate it.
141     if (OnlyUsedInOneBlock) {
142       PromoteLocallyUsedAlloca(AI);
143
144       // Remove the alloca from the Allocas list, since it has been processed
145       Allocas[AllocaNum] = Allocas.back();
146       Allocas.pop_back();
147       --AllocaNum;
148       continue;
149     }
150
151     // Compute the locations where PhiNodes need to be inserted.  Look at the
152     // dominance frontier of EACH basic-block we have a write in.
153     //
154     unsigned CurrentVersion = 0;
155     std::set<PHINode*> InsertedPHINodes;
156     while (!DefiningBlocks.empty()) {
157       BasicBlock *BB = DefiningBlocks.back();
158       DefiningBlocks.pop_back();
159
160       // Look up the DF for this write, add it to PhiNodes
161       DominanceFrontier::const_iterator it = DF.find(BB);
162       if (it != DF.end()) {
163         const DominanceFrontier::DomSetType &S = it->second;
164         for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
165              P != PE; ++P)
166           if (QueuePhiNode(*P, AllocaNum, CurrentVersion, InsertedPHINodes))
167             DefiningBlocks.push_back(*P);
168       }
169     }
170
171     // Now that we have inserted PHI nodes along the Iterated Dominance Frontier
172     // of the writes to the variable, scan through the reads of the variable,
173     // marking PHI nodes which are actually necessary as alive (by removing them
174     // from the InsertedPHINodes set).  This is not perfect: there may PHI
175     // marked alive because of loads which are dominated by stores, but there
176     // will be no unmarked PHI nodes which are actually used.
177     //
178     for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
179       MarkDominatingPHILive(UsingBlocks[i], AllocaNum, InsertedPHINodes);
180     UsingBlocks.clear();
181
182     // If there are any PHI nodes which are now known to be dead, remove them!
183     for (std::set<PHINode*>::iterator I = InsertedPHINodes.begin(),
184            E = InsertedPHINodes.end(); I != E; ++I) {
185       PHINode *PN = *I;
186       std::vector<PHINode*> &BBPNs = NewPhiNodes[PN->getParent()];
187       BBPNs[AllocaNum] = 0;
188
189       // Check to see if we just removed the last inserted PHI node from this
190       // basic block.  If so, remove the entry for the basic block.
191       bool HasOtherPHIs = false;
192       for (unsigned i = 0, e = BBPNs.size(); i != e; ++i)
193         if (BBPNs[i]) {
194           HasOtherPHIs = true;
195           break;
196         }
197       if (!HasOtherPHIs)
198         NewPhiNodes.erase(PN->getParent());
199
200       PN->getParent()->getInstList().erase(PN);      
201     }
202
203     // Keep the reverse mapping of the 'Allocas' array. 
204     AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
205   }
206   
207   if (Allocas.empty())
208     return; // All of the allocas must have been trivial!
209
210   // Set the incoming values for the basic block to be null values for all of
211   // the alloca's.  We do this in case there is a load of a value that has not
212   // been stored yet.  In this case, it will get this null value.
213   //
214   std::vector<Value *> Values(Allocas.size());
215   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
216     Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
217
218   // Walks all basic blocks in the function performing the SSA rename algorithm
219   // and inserting the phi nodes we marked as necessary
220   //
221   RenamePass(F.begin(), 0, Values);
222
223   // The renamer uses the Visited set to avoid infinite loops.  Clear it now.
224   Visited.clear();
225
226   // Remove the allocas themselves from the function...
227   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
228     Instruction *A = Allocas[i];
229
230     // If there are any uses of the alloca instructions left, they must be in
231     // sections of dead code that were not processed on the dominance frontier.
232     // Just delete the users now.
233     //
234     if (!A->use_empty())
235       A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
236     A->getParent()->getInstList().erase(A);
237   }
238
239   // At this point, the renamer has added entries to PHI nodes for all reachable
240   // code.  Unfortunately, there may be blocks which are not reachable, which
241   // the renamer hasn't traversed.  If this is the case, the PHI nodes may not
242   // have incoming values for all predecessors.  Loop over all PHI nodes we have
243   // created, inserting null constants if they are missing any incoming values.
244   //
245   for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I = 
246          NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
247
248     std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
249     std::vector<PHINode*> &PNs = I->second;
250     assert(!PNs.empty() && "Empty PHI node list??");
251
252     // Only do work here if there the PHI nodes are missing incoming values.  We
253     // know that all PHI nodes that were inserted in a block will have the same
254     // number of incoming values, so we can just check any PHI node.
255     PHINode *FirstPHI;
256     for (unsigned i = 0; (FirstPHI = PNs[i]) == 0; ++i)
257       /*empty*/;
258
259     if (Preds.size() != FirstPHI->getNumIncomingValues()) {
260       // Ok, now we know that all of the PHI nodes are missing entries for some
261       // basic blocks.  Start by sorting the incoming predecessors for efficient
262       // access.
263       std::sort(Preds.begin(), Preds.end());
264
265       // Now we loop through all BB's which have entries in FirstPHI and remove
266       // them from the Preds list.
267       for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
268         // Do a log(n) search of the Preds list for the entry we want.
269         std::vector<BasicBlock*>::iterator EntIt =
270           std::lower_bound(Preds.begin(), Preds.end(),
271                            FirstPHI->getIncomingBlock(i));
272         assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
273                "PHI node has entry for a block which is not a predecessor!");
274
275         // Remove the entry
276         Preds.erase(EntIt);
277       }
278
279       // At this point, the blocks left in the preds list must have dummy
280       // entries inserted into every PHI nodes for the block.
281       for (unsigned i = 0, e = PNs.size(); i != e; ++i)
282         if (PHINode *PN = PNs[i]) {
283           Value *NullVal = Constant::getNullValue(PN->getType());
284           for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
285             PN->addIncoming(NullVal, Preds[pred]);
286         }
287     }
288   }
289 }
290
291 // MarkDominatingPHILive - Mem2Reg wants to construct "pruned" SSA form, not
292 // "minimal" SSA form.  To do this, it inserts all of the PHI nodes on the IDF
293 // as usual (inserting the PHI nodes in the DeadPHINodes set), then processes
294 // each read of the variable.  For each block that reads the variable, this
295 // function is called, which removes used PHI nodes from the DeadPHINodes set.
296 // After all of the reads have been processed, any PHI nodes left in the
297 // DeadPHINodes set are removed.
298 //
299 void PromoteMem2Reg::MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
300                                            std::set<PHINode*> &DeadPHINodes) {
301   // Scan the immediate dominators of this block looking for a block which has a
302   // PHI node for Alloca num.  If we find it, mark the PHI node as being alive!
303   for (DominatorTree::Node *N = DT[BB]; N; N = N->getIDom()) {
304     BasicBlock *DomBB = N->getBlock();
305     std::map<BasicBlock*, std::vector<PHINode*> >::iterator
306       I = NewPhiNodes.find(DomBB);
307     if (I != NewPhiNodes.end() && I->second[AllocaNum]) {
308       // Ok, we found an inserted PHI node which dominates this value.
309       PHINode *DominatingPHI = I->second[AllocaNum];
310
311       // Find out if we previously thought it was dead.
312       std::set<PHINode*>::iterator DPNI = DeadPHINodes.find(DominatingPHI);
313       if (DPNI != DeadPHINodes.end()) {
314         // Ok, until now, we thought this PHI node was dead.  Mark it as being
315         // alive/needed.
316         DeadPHINodes.erase(DPNI);
317
318         // Now that we have marked the PHI node alive, also mark any PHI nodes
319         // which it might use as being alive as well.
320         for (pred_iterator PI = pred_begin(DomBB), PE = pred_end(DomBB);
321              PI != PE; ++PI)
322           MarkDominatingPHILive(*PI, AllocaNum, DeadPHINodes);
323       }
324     }
325   }
326 }
327
328 // PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
329 // block.  If this is the case, avoid traversing the CFG and inserting a lot of
330 // potentially useless PHI nodes by just performing a single linear pass over
331 // the basic block using the Alloca.
332 //
333 void PromoteMem2Reg::PromoteLocallyUsedAlloca(AllocaInst *AI) {
334   assert(!AI->use_empty() && "There are no uses of the alloca!");
335
336   // Uses of the uninitialized memory location shall get zero...
337   Value *CurVal = Constant::getNullValue(AI->getAllocatedType());
338   
339   BasicBlock *BB = cast<Instruction>(AI->use_back())->getParent();
340
341   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
342     Instruction *Inst = I++;
343     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
344       if (LI->getOperand(0) == AI) {
345         // Loads just return the "current value"...
346         LI->replaceAllUsesWith(CurVal);
347         BB->getInstList().erase(LI);
348       }
349     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
350       if (SI->getOperand(1) == AI) {
351         // Loads just update the "current value"...
352         CurVal = SI->getOperand(0);
353         BB->getInstList().erase(SI);
354       }
355     }
356   }
357
358   // After traversing the basic block, there should be no more uses of the
359   // alloca, remove it now.
360   assert(AI->use_empty() && "Uses of alloca from more than one BB??");
361   AI->getParent()->getInstList().erase(AI);
362 }
363
364 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
365 // Alloca returns true if there wasn't already a phi-node for that variable
366 //
367 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
368                                   unsigned &Version,
369                                   std::set<PHINode*> &InsertedPHINodes) {
370   // Look up the basic-block in question
371   std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
372   if (BBPNs.empty()) BBPNs.resize(Allocas.size());
373
374   // If the BB already has a phi node added for the i'th alloca then we're done!
375   if (BBPNs[AllocaNo]) return false;
376
377   // Create a PhiNode using the dereferenced type... and add the phi-node to the
378   // BasicBlock.
379   BBPNs[AllocaNo] = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
380                                 Allocas[AllocaNo]->getName() + "." +
381                                         utostr(Version++), BB->begin());
382   InsertedPHINodes.insert(BBPNs[AllocaNo]);
383   return true;
384 }
385
386
387 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
388 // stores to the allocas which we are promoting.  IncomingVals indicates what
389 // value each Alloca contains on exit from the predecessor block Pred.
390 //
391 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
392                                 std::vector<Value*> &IncomingVals) {
393
394   // If this BB needs a PHI node, update the PHI node for each variable we need
395   // PHI nodes for.
396   std::map<BasicBlock*, std::vector<PHINode *> >::iterator
397     BBPNI = NewPhiNodes.find(BB);
398   if (BBPNI != NewPhiNodes.end()) {
399     std::vector<PHINode *> &BBPNs = BBPNI->second;
400     for (unsigned k = 0; k != BBPNs.size(); ++k)
401       if (PHINode *PN = BBPNs[k]) {
402         // Add this incoming value to the PHI node.
403         PN->addIncoming(IncomingVals[k], Pred);
404
405         // The currently active variable for this block is now the PHI.
406         IncomingVals[k] = PN;
407       }
408   }
409
410   // don't revisit nodes
411   if (Visited.count(BB)) return;
412   
413   // mark as visited
414   Visited.insert(BB);
415
416   for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
417     Instruction *I = II++; // get the instruction, increment iterator
418
419     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
420       if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
421         std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
422         if (AI != AllocaLookup.end()) {
423           Value *V = IncomingVals[AI->second];
424
425           // walk the use list of this load and replace all uses with r
426           LI->replaceAllUsesWith(V);
427           BB->getInstList().erase(LI);
428         }
429       }
430     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
431       // Delete this instruction and mark the name as the current holder of the
432       // value
433       if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
434         std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
435         if (ai != AllocaLookup.end()) {
436           // what value were we writing?
437           IncomingVals[ai->second] = SI->getOperand(0);
438           BB->getInstList().erase(SI);
439         }
440       }
441     }
442   }
443
444   // Recurse to our successors.
445   TerminatorInst *TI = BB->getTerminator();
446   for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
447     std::vector<Value*> OutgoingVals(IncomingVals);
448     RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
449   }
450 }
451
452 /// PromoteMemToReg - Promote the specified list of alloca instructions into
453 /// scalar registers, inserting PHI nodes as appropriate.  This function makes
454 /// use of DominanceFrontier information.  This function does not modify the CFG
455 /// of the function at all.  All allocas must be from the same function.
456 ///
457 void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
458                      DominatorTree &DT, DominanceFrontier &DF,
459                      const TargetData &TD) {
460   // If there is nothing to do, bail out...
461   if (Allocas.empty()) return;
462   PromoteMem2Reg(Allocas, DT, DF, TD).run();
463 }
464
465 } // End llvm namespace