Eliminate the cfg namespace, moving LoopInfo, Dominators, Interval* classes
[oota-llvm.git] / lib / Transforms / Utils / PromoteMemoryToRegister.cpp
1 //===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===//
2 //
3 // This pass is used to promote memory references to be register references.  A
4 // simple example of the transformation performed by this pass is:
5 //
6 //        FROM CODE                           TO CODE
7 //   %X = alloca int, uint 1                 ret int 42
8 //   store int 42, int *%X
9 //   %Y = load int* %X
10 //   ret int %Y
11 //
12 // To do this transformation, a simple analysis is done to ensure it is safe.
13 // Currently this just loops over all alloca instructions, looking for
14 // instructions that are only used in simple load and stores.
15 //
16 // After this, the code is transformed by...something magical :)
17 //
18 //===----------------------------------------------------------------------===//
19
20 #include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iTerminators.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Function.h"
27 #include "llvm/BasicBlock.h"
28 #include "llvm/ConstantVals.h"
29
30 using namespace std;
31
32 namespace {
33
34 //instance of the promoter -- to keep all the local function data.
35 // gets re-created for each function processed
36 class PromoteInstance
37 {
38         protected:
39         vector<AllocaInst*>                     Allocas;   // the alloca instruction..
40         map<Instruction *, int>                 AllocaLookup; //reverse mapping of above
41
42         vector<vector<BasicBlock *> >           WriteSets; // index corresponds to Allocas
43         vector<vector<BasicBlock *> >           PhiNodes;  // index corresponds to Allocas
44         vector<vector<Value *> >                CurrentValue; //the current value stack
45
46         //list of instructions to remove at end of pass :)
47         vector<Instruction *> killlist;
48
49         set<BasicBlock *>                       visited;        //the basic blocks we've already visited
50         map<BasicBlock *, vector<PHINode *> >   new_phinodes;   //the phinodes we're adding
51
52
53         void traverse(BasicBlock *f, BasicBlock * predecessor);
54         bool PromoteFunction(Function *F, DominanceFrontier &DF);
55         bool queuePhiNode(BasicBlock *bb, int alloca_index);
56         void findSafeAllocas(Function *M);
57         bool didchange;
58         public:
59         // I do this so that I can force the deconstruction of the local variables
60         PromoteInstance(Function *F, DominanceFrontier &DF)
61         {
62                 didchange=PromoteFunction(F, DF);
63         }
64         //This returns whether the pass changes anything
65         operator bool () { return didchange; }
66 };
67
68 }  // end of anonymous namespace
69
70 // findSafeAllocas - Find allocas that are safe to promote
71 //
72 void PromoteInstance::findSafeAllocas(Function *F)  
73 {
74   BasicBlock *BB = F->getEntryNode();  // Get the entry node for the function
75
76   // Look at all instructions in the entry node
77   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
78     if (AllocaInst *AI = dyn_cast<AllocaInst>(*I))       // Is it an alloca?
79       if (!AI->isArrayAllocation()) {
80         bool isSafe = true;
81         for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
82              UI != UE; ++UI) {   // Loop over all of the uses of the alloca
83
84           // Only allow nonindexed memory access instructions...
85           if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(*UI)) {
86             if (MAI->hasIndices()) {  // indexed?
87               // Allow the access if there is only one index and the index is zero.
88               if (*MAI->idx_begin() != ConstantUInt::get(Type::UIntTy, 0) ||
89                   MAI->idx_begin()+1 != MAI->idx_end()) {
90                 isSafe = false; break;
91               }
92             }
93           } else {
94             isSafe = false; break;   // Not a load or store?
95           }
96         }
97         if (isSafe)              // If all checks pass, add alloca to safe list
98           {
99             AllocaLookup[AI]=Allocas.size();
100             Allocas.push_back(AI);
101           }
102       }
103 }
104
105
106
107 bool PromoteInstance::PromoteFunction(Function *F, DominanceFrontier & DF) {
108         // Calculate the set of safe allocas
109         findSafeAllocas(F);
110
111         // Add each alloca to the killlist
112         // note: killlist is destroyed MOST recently added to least recently.
113         killlist.assign(Allocas.begin(), Allocas.end());
114
115         // Calculate the set of write-locations for each alloca.
116         // this is analogous to counting the number of 'redefinitions' of each variable.
117         for (unsigned i = 0; i<Allocas.size(); ++i)
118         {
119                 AllocaInst * AI = Allocas[i];
120                 WriteSets.push_back(std::vector<BasicBlock *>()); //add a new set
121                 for (Value::use_iterator U = AI->use_begin();U!=AI->use_end();++U)
122                 {
123                         if (MemAccessInst *MAI = dyn_cast<StoreInst>(*U)) {
124                                 WriteSets[i].push_back(MAI->getParent()); // jot down the basic-block it came from
125                         }
126                 }
127         }
128
129         // Compute the locations where PhiNodes need to be inserted
130         // look at the dominance frontier of EACH basic-block we have a write in
131         PhiNodes.resize(Allocas.size());
132         for (unsigned i = 0; i<Allocas.size(); ++i)
133         {
134                 for (unsigned j = 0; j<WriteSets[i].size(); j++)
135                 {
136                         //look up the DF for this write, add it to PhiNodes
137                         DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]);
138                         DominanceFrontier::DomSetType     s = (*it).second;
139                         for (DominanceFrontier::DomSetType::iterator p = s.begin();p!=s.end(); ++p)
140                         {
141                                 if (queuePhiNode(*p, i))
142                                   PhiNodes[i].push_back(*p);
143                         }
144                 }
145                 // perform iterative step
146                 for (unsigned k = 0; k<PhiNodes[i].size(); k++)
147                 {
148                         DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]);
149                         DominanceFrontier::DomSetType     s = it->second;
150                         for (DominanceFrontier::DomSetType::iterator p = s.begin(); p!=s.end(); ++p)
151                         {
152                                 if (queuePhiNode(*p,i))
153                                 PhiNodes[i].push_back(*p);
154                         }
155                 }
156         }
157
158         // Walks all basic blocks in the function
159         // performing the SSA rename algorithm
160         // and inserting the phi nodes we marked as necessary
161         BasicBlock * f = F->front(); //get root basic-block
162
163         CurrentValue.push_back(vector<Value *>(Allocas.size()));
164
165         traverse(f, NULL);  // there is no predecessor of the root node
166
167
168         // ** REMOVE EVERYTHING IN THE KILL-LIST **
169         // we need to kill 'uses' before root values
170         // so we should probably run through in reverse
171         for (vector<Instruction *>::reverse_iterator i = killlist.rbegin(); i!=killlist.rend(); ++i)
172         {
173                 Instruction * r = *i;
174                 BasicBlock * o = r->getParent();
175                 //now go find..
176
177                 BasicBlock::InstListType & l = o->getInstList();
178                 o->getInstList().remove(r);
179                 delete r;
180         }
181
182         return !Allocas.empty();
183 }
184
185
186
187 void PromoteInstance::traverse(BasicBlock *f, BasicBlock * predecessor)
188 {
189         vector<Value *> * tos = &CurrentValue.back(); //look at top-
190
191         //if this is a BB needing a phi node, lookup/create the phinode for
192         // each variable we need phinodes for.
193         map<BasicBlock *, vector<PHINode *> >::iterator nd = new_phinodes.find(f);
194         if (nd!=new_phinodes.end())
195         {
196                 for (unsigned k = 0; k!=nd->second.size(); ++k)
197                 if (nd->second[k])
198                 {
199                         //at this point we can assume that the array has phi nodes.. let's
200                         // add the incoming data
201                         if ((*tos)[k])
202                         nd->second[k]->addIncoming((*tos)[k],predecessor);
203                         //also note that the active variable IS designated by the phi node
204                         (*tos)[k] = nd->second[k];
205                 }
206         }
207
208         //don't revisit nodes
209         if (visited.find(f)!=visited.end())
210         return;
211         //mark as visited
212         visited.insert(f);
213
214         BasicBlock::iterator i = f->begin();
215         //keep track of the value of each variable we're watching.. how?
216         while(i!=f->end())
217         {
218                 Instruction * inst = *i; //get the instruction
219                 //is this a write/read?
220                 if (LoadInst * LI = dyn_cast<LoadInst>(inst))
221                 {
222                         // This is a bit weird...
223                         Value * ptr = LI->getPointerOperand(); //of type value
224                         if (AllocaInst * srcinstr = dyn_cast<AllocaInst>(ptr))
225                         {
226                                 map<Instruction *, int>::iterator ai = AllocaLookup.find(srcinstr);
227                                 if (ai!=AllocaLookup.end())
228                                 {
229                                         if (Value *r = (*tos)[ai->second])
230                                         {
231                                                 //walk the use list of this load and replace
232                                                 // all uses with r
233                                                 LI->replaceAllUsesWith(r);
234                                                 //now delete the instruction.. somehow..
235                                                 killlist.push_back((Instruction *)LI);
236                                         }
237                                 }
238                         }
239                 }
240                 else if (StoreInst * SI = dyn_cast<StoreInst>(inst))
241                 {
242                         // delete this instruction and mark the name as the
243                         // current holder of the value
244                         Value * ptr =  SI->getPointerOperand(); //of type value
245                         if (Instruction * srcinstr = dyn_cast<Instruction>(ptr))
246                         {
247                                 map<Instruction *, int>::iterator ai = AllocaLookup.find(srcinstr);
248                                 if (ai!=AllocaLookup.end())
249                                 {
250                                         //what value were we writing?
251                                         Value * writeval = SI->getOperand(0);
252                                         //write down...
253                                         (*tos)[ai->second] = writeval;
254                                         //now delete it.. somehow?
255                                         killlist.push_back((Instruction *)SI);
256                                 }
257                         }
258
259                 }
260                 else if (TerminatorInst * TI = dyn_cast<TerminatorInst>(inst))
261                 {
262                         // Recurse across our sucessors
263                         for (unsigned i = 0; i!=TI->getNumSuccessors(); i++)
264                         {
265                                 CurrentValue.push_back(CurrentValue.back());
266                                 traverse(TI->getSuccessor(i),f); //this node IS the predecessor
267                                 CurrentValue.pop_back();
268                         }
269                 }
270                 i++;
271         }
272 }
273
274 // queues a phi-node to be added to a basic-block for a specific Alloca
275 // returns true  if there wasn't already a phi-node for that variable
276
277
278 bool PromoteInstance::queuePhiNode(BasicBlock *bb, int i /*the alloca*/)
279 {
280         map<BasicBlock *, vector<PHINode *> >::iterator nd;
281         //look up the basic-block in question
282         nd = new_phinodes.find(bb);
283         //if the basic-block has no phi-nodes added, or at least none
284         //for the i'th alloca. then add.
285         if (nd==new_phinodes.end() || nd->second[i]==NULL)
286         {
287                 //we're not added any phi nodes to this basicblock yet
288                 // create the phi-node array.
289                 if (nd==new_phinodes.end())
290                 {
291                         new_phinodes[bb] = vector<PHINode *>(Allocas.size());
292                         nd = new_phinodes.find(bb);
293                 }
294
295                 //find the type the alloca returns
296                 const PointerType * pt = Allocas[i]->getType();
297                 //create a phi-node using the DEREFERENCED type
298                 PHINode * ph = new PHINode(pt->getElementType(), Allocas[i]->getName()+".mem2reg");
299                 nd->second[i] = ph;
300                 //add the phi-node to the basic-block
301                 bb->getInstList().push_front(ph);
302                 return true;
303         }
304         return false;
305 }
306
307
308 namespace {
309   struct PromotePass : public FunctionPass {
310
311     // runOnFunction - To run this pass, first we calculate the alloca
312     // instructions that are safe for promotion, then we promote each one.
313     //
314     virtual bool runOnFunction(Function *F) {
315       return (bool)PromoteInstance(F, getAnalysis<DominanceFrontier>());
316     }
317     
318
319     // getAnalysisUsage - We need dominance frontiers
320     //
321     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
322       AU.addRequired(DominanceFrontier::ID);
323     }
324   };
325 }
326   
327
328 // createPromoteMemoryToRegister - Provide an entry point to create this pass.
329 //
330 Pass *createPromoteMemoryToRegister() {
331         return new PromotePass();
332 }
333
334