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