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