e0d2c2475fcc5b322f73376a4ab9b42db56abde3
[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/Constant.h"
29
30 using std::vector;
31 using std::map;
32 using std::set;
33
34 namespace {
35   struct PromotePass : public FunctionPass {
36     vector<AllocaInst*>          Allocas;      // the alloca instruction..
37     map<Instruction*, unsigned>  AllocaLookup; // reverse mapping of above
38     
39     vector<vector<BasicBlock*> > PhiNodes;     // index corresponds to Allocas
40     
41     // List of instructions to remove at end of pass
42     vector<Instruction *>        KillList;
43     
44     map<BasicBlock*,vector<PHINode*> > NewPhiNodes; // the PhiNodes we're adding
45
46   public:
47     // runOnFunction - To run this pass, first we calculate the alloca
48     // instructions that are safe for promotion, then we promote each one.
49     //
50     virtual bool runOnFunction(Function *F);
51
52     // getAnalysisUsage - We need dominance frontiers
53     //
54     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
55       AU.addRequired(DominanceFrontier::ID);
56       AU.preservesCFG();
57     }
58
59   private:
60     void Traverse(BasicBlock *BB, BasicBlock *Pred, vector<Value*> &IncVals,
61                   set<BasicBlock*> &Visited);
62     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx);
63     void FindSafeAllocas(Function *F);
64   };
65
66 }  // end of anonymous namespace
67
68
69 // isSafeAlloca - This predicate controls what types of alloca instructions are
70 // allowed to be promoted...
71 //
72 static inline bool isSafeAlloca(const AllocaInst *AI) {
73   if (AI->isArrayAllocation()) return false;
74
75   for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
76        UI != UE; ++UI) {   // Loop over all of the uses of the alloca
77
78     // Only allow nonindexed memory access instructions...
79     if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(*UI)) {
80       if (MAI->hasIndices()) {  // indexed?
81         // Allow the access if there is only one index and the index is
82         // zero.
83         if (*MAI->idx_begin() != Constant::getNullValue(Type::UIntTy) ||
84             MAI->idx_begin()+1 != MAI->idx_end())
85           return false;
86       }
87     } else {
88       return false;   // Not a load or store?
89     }
90   }
91   
92   return true;
93 }
94
95 // FindSafeAllocas - Find allocas that are safe to promote
96 //
97 void PromotePass::FindSafeAllocas(Function *F) {
98   BasicBlock *BB = F->getEntryNode();  // Get the entry node for the function
99
100   // Look at all instructions in the entry node
101   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
102     if (AllocaInst *AI = dyn_cast<AllocaInst>(*I))       // Is it an alloca?
103       if (isSafeAlloca(AI)) {   // If safe alloca, add alloca to safe list
104         AllocaLookup[AI] = Allocas.size();  // Keep reverse mapping
105         Allocas.push_back(AI);
106       }
107 }
108
109
110
111 bool PromotePass::runOnFunction(Function *F) {
112   // Calculate the set of safe allocas
113   FindSafeAllocas(F);
114
115   // If there is nothing to do, bail out...
116   if (Allocas.empty()) return false;
117
118   // Add each alloca to the KillList.  Note: KillList is destroyed MOST recently
119   // added to least recently.
120   KillList.assign(Allocas.begin(), Allocas.end());
121
122   // Calculate the set of write-locations for each alloca.  This is analogous to
123   // counting the number of 'redefinitions' of each variable.
124   vector<vector<BasicBlock*> > WriteSets;    // index corresponds to Allocas
125   WriteSets.resize(Allocas.size());
126   for (unsigned i = 0; i != Allocas.size(); ++i) {
127     AllocaInst *AI = Allocas[i];
128     for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
129       if (StoreInst *SI = dyn_cast<StoreInst>(*U))
130         // jot down the basic-block it came from
131         WriteSets[i].push_back(SI->getParent());
132   }
133
134   // Get dominance frontier information...
135   DominanceFrontier &DF = getAnalysis<DominanceFrontier>();
136
137   // Compute the locations where PhiNodes need to be inserted.  Look at the
138   // dominance frontier of EACH basic-block we have a write in
139   //
140   PhiNodes.resize(Allocas.size());
141   for (unsigned i = 0; i != Allocas.size(); ++i) {
142     for (unsigned j = 0; j != WriteSets[i].size(); j++) {
143       // Look up the DF for this write, add it to PhiNodes
144       DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]);
145       DominanceFrontier::DomSetType     S = it->second;
146       for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end();
147            P != PE; ++P)
148         QueuePhiNode(*P, i);
149     }
150     
151     // Perform iterative step
152     for (unsigned k = 0; k != PhiNodes[i].size(); k++) {
153       DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]);
154       DominanceFrontier::DomSetType     S = it->second;
155       for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end();
156            P != PE; ++P)
157         QueuePhiNode(*P, i);
158     }
159   }
160
161   // Set the incoming values for the basic block to be null values for all of
162   // the alloca's.  We do this in case there is a load of a value that has not
163   // been stored yet.  In this case, it will get this null value.
164   //
165   vector<Value *> Values(Allocas.size());
166   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
167     Values[i] = Constant::getNullValue(Allocas[i]->getType()->getElementType());
168
169   // Walks all basic blocks in the function performing the SSA rename algorithm
170   // and inserting the phi nodes we marked as necessary
171   //
172   set<BasicBlock*> Visited;         // The basic blocks we've already visited
173   Traverse(F->front(), 0, Values, Visited);
174
175   // Remove all instructions marked by being placed in the KillList...
176   //
177   while (!KillList.empty()) {
178     Instruction *I = KillList.back();
179     KillList.pop_back();
180
181     I->getParent()->getInstList().remove(I);
182     delete I;
183   }
184
185   // Purge data structurse so they are available the next iteration...
186   Allocas.clear();
187   AllocaLookup.clear();
188   PhiNodes.clear();
189   NewPhiNodes.clear();
190   return true;
191 }
192
193
194 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
195 // Alloca returns true if there wasn't already a phi-node for that variable
196 //
197 bool PromotePass::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) {
198   // Look up the basic-block in question
199   vector<PHINode*> &BBPNs = NewPhiNodes[BB];
200   if (BBPNs.empty()) BBPNs.resize(Allocas.size());
201
202   // If the BB already has a phi node added for the i'th alloca then we're done!
203   if (BBPNs[AllocaNo]) return false;
204
205   // Create a PhiNode using the dereferenced type...
206   PHINode *PN = new PHINode(Allocas[AllocaNo]->getType()->getElementType(),
207                             Allocas[AllocaNo]->getName()+".mem2reg");
208   BBPNs[AllocaNo] = PN;
209
210   // Add the phi-node to the basic-block
211   BB->getInstList().push_front(PN);
212
213   PhiNodes[AllocaNo].push_back(BB);
214   return true;
215 }
216
217 void PromotePass::Traverse(BasicBlock *BB, BasicBlock *Pred,
218                            vector<Value*> &IncomingVals,
219                            set<BasicBlock*> &Visited) {
220   // If this is a BB needing a phi node, lookup/create the phinode for each
221   // variable we need phinodes for.
222   vector<PHINode *> &BBPNs = NewPhiNodes[BB];
223   for (unsigned k = 0; k != BBPNs.size(); ++k)
224     if (PHINode *PN = BBPNs[k]) {
225       // at this point we can assume that the array has phi nodes.. let's add
226       // the incoming data
227       PN->addIncoming(IncomingVals[k], Pred);
228
229       // also note that the active variable IS designated by the phi node
230       IncomingVals[k] = PN;
231     }
232
233   // don't revisit nodes
234   if (Visited.count(BB)) return;
235   
236   // mark as visited
237   Visited.insert(BB);
238
239   // keep track of the value of each variable we're watching.. how?
240   for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II) {
241     Instruction *I = *II; //get the instruction
242
243     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
244       Value *Ptr = LI->getPointerOperand();
245
246       if (AllocaInst *Src = dyn_cast<AllocaInst>(Ptr)) {
247         map<Instruction*, unsigned>::iterator AI = AllocaLookup.find(Src);
248         if (AI != AllocaLookup.end()) {
249           Value *V = IncomingVals[AI->second];
250
251           // walk the use list of this load and replace all uses with r
252           LI->replaceAllUsesWith(V);
253           KillList.push_back(LI); // Mark the load to be deleted
254         }
255       }
256     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
257       // delete this instruction and mark the name as the current holder of the
258       // value
259       Value *Ptr = SI->getPointerOperand();
260       if (AllocaInst *Dest = dyn_cast<AllocaInst>(Ptr)) {
261         map<Instruction *, unsigned>::iterator ai = AllocaLookup.find(Dest);
262         if (ai != AllocaLookup.end()) {
263           // what value were we writing?
264           IncomingVals[ai->second] = SI->getOperand(0);
265           KillList.push_back(SI);  // Mark the store to be deleted
266         }
267       }
268       
269     } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) {
270       // Recurse across our successors
271       for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
272         vector<Value*> OutgoingVals(IncomingVals);
273         Traverse(TI->getSuccessor(i), BB, OutgoingVals, Visited);
274       }
275     }
276   }
277 }
278
279
280 // createPromoteMemoryToRegister - Provide an entry point to create this pass.
281 //
282 Pass *createPromoteMemoryToRegister() {
283   return new PromotePass();
284 }