4bfc4e041a0651d1150028d996fdc2447f14dc10
[oota-llvm.git] / lib / Transforms / Utils / PromoteMemoryToRegister.cpp
1 //===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===//
2 //
3 // This file is used to promote memory references to be register references.  A
4 // simple example of the transformation performed by this function 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 // The code is transformed by looping over all of the alloca instruction,
13 // calculating dominator frontiers, then inserting phi-nodes following the usual
14 // SSA construction algorithm.  This code does not modify the CFG of the
15 // function.
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/iTerminators.h"
24 #include "llvm/Function.h"
25 #include "llvm/Constant.h"
26 #include "llvm/Type.h"
27 #include "llvm/Support/CFG.h"
28 #include "Support/StringExtras.h"
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
52 namespace {
53   struct PromoteMem2Reg {
54     // Allocas - The alloca instructions being promoted
55     const std::vector<AllocaInst*> &Allocas;
56     DominanceFrontier &DF;
57     const TargetData &TD;
58
59     // AllocaLookup - Reverse mapping of Allocas
60     std::map<AllocaInst*, unsigned>  AllocaLookup;
61
62     // VersionNumbers - Current version counters for each alloca
63     std::vector<unsigned> VersionNumbers;
64     
65     // NewPhiNodes - The PhiNodes we're adding.
66     std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
67
68     // Visited - The set of basic blocks the renamer has already visited.
69     std::set<BasicBlock*> Visited;
70
71   public:
72     PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominanceFrontier &df,
73                    const TargetData &td) : Allocas(A), DF(df), TD(td) {}
74
75     void run();
76
77   private:
78     void RenamePass(BasicBlock *BB, BasicBlock *Pred,
79                     std::vector<Value*> &IncVals);
80     bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx);
81   };
82 }  // end of anonymous namespace
83
84 void PromoteMem2Reg::run() {
85   Function &F = *DF.getRoot()->getParent();
86
87   VersionNumbers.resize(Allocas.size());
88
89   for (unsigned i = 0; i != Allocas.size(); ++i) {
90     AllocaInst *AI = Allocas[i];
91
92     assert(isAllocaPromotable(AI, TD) &&
93            "Cannot promote non-promotable alloca!");
94     assert(Allocas[i]->getParent()->getParent() == &F &&
95            "All allocas should be in the same function, which is same as DF!");
96
97     // Calculate the set of write-locations for each alloca.  This is analogous
98     // to counting the number of 'redefinitions' of each variable.
99     std::vector<BasicBlock*> DefiningBlocks;
100     for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
101       if (StoreInst *SI = dyn_cast<StoreInst>(cast<Instruction>(*U)))
102         // jot down the basic-block it came from
103         DefiningBlocks.push_back(SI->getParent());
104
105     AllocaLookup[Allocas[i]] = i;
106     
107     // PhiNodeBlocks - A list of blocks that phi nodes have been inserted for
108     // this alloca.
109     std::vector<BasicBlock*> PhiNodeBlocks;
110
111     // Compute the locations where PhiNodes need to be inserted.  Look at the
112     // dominance frontier of EACH basic-block we have a write in.
113     //
114     while (!DefiningBlocks.empty()) {
115       BasicBlock *BB = DefiningBlocks.back();
116       DefiningBlocks.pop_back();
117
118       // Look up the DF for this write, add it to PhiNodes
119       DominanceFrontier::const_iterator it = DF.find(BB);
120       if (it != DF.end()) {
121         const DominanceFrontier::DomSetType &S = it->second;
122         for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
123              P != PE; ++P)
124           if (QueuePhiNode(*P, i))
125             DefiningBlocks.push_back(*P);
126       }
127     }
128   }
129
130   // Set the incoming values for the basic block to be null values for all of
131   // the alloca's.  We do this in case there is a load of a value that has not
132   // been stored yet.  In this case, it will get this null value.
133   //
134   std::vector<Value *> Values(Allocas.size());
135   for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
136     Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
137
138   // Walks all basic blocks in the function performing the SSA rename algorithm
139   // and inserting the phi nodes we marked as necessary
140   //
141   RenamePass(F.begin(), 0, Values);
142   Visited.clear();
143
144   // Remove the allocas themselves from the function...
145   for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
146     Instruction *A = Allocas[i];
147
148     // If there are any uses of the alloca instructions left, they must be in
149     // sections of dead code that were not processed on the dominance frontier.
150     // Just delete the users now.
151     //
152     if (!A->use_empty())
153       A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
154     A->getParent()->getInstList().erase(A);
155   }
156 }
157
158
159 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
160 // Alloca returns true if there wasn't already a phi-node for that variable
161 //
162 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) {
163   // Look up the basic-block in question
164   std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
165   if (BBPNs.empty()) BBPNs.resize(Allocas.size());
166
167   // If the BB already has a phi node added for the i'th alloca then we're done!
168   if (BBPNs[AllocaNo]) return false;
169
170   // Create a PhiNode using the dereferenced type... and add the phi-node to the
171   // BasicBlock.
172   PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
173                             Allocas[AllocaNo]->getName() + "." +
174                                       utostr(VersionNumbers[AllocaNo]++),
175                             BB->begin());
176
177   // Add null incoming values for all predecessors.  This ensures that if one of
178   // the predecessors is not found in the depth-first traversal of the CFG (ie,
179   // because it is an unreachable predecessor), that all PHI nodes will have the
180   // correct number of entries for their predecessors.
181   Value *NullVal = Constant::getNullValue(PN->getType());
182
183   // This is necessary because adding incoming values to the PHI node adds uses
184   // to the basic blocks being used, which can invalidate the predecessor
185   // iterator!
186   std::vector<BasicBlock*> Preds(pred_begin(BB), pred_end(BB));
187   for (unsigned i = 0, e = Preds.size(); i != e; ++i)
188     PN->addIncoming(NullVal, Preds[i]);
189
190   BBPNs[AllocaNo] = PN;
191   return true;
192 }
193
194 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
195                                 std::vector<Value*> &IncomingVals) {
196   // If this BB needs a PHI node, update the PHI node for each variable we need
197   // PHI nodes for.
198   std::map<BasicBlock*, std::vector<PHINode *> >::iterator
199     BBPNI = NewPhiNodes.find(BB);
200   if (BBPNI != NewPhiNodes.end()) {
201     std::vector<PHINode *> &BBPNs = BBPNI->second;
202     for (unsigned k = 0; k != BBPNs.size(); ++k)
203       if (PHINode *PN = BBPNs[k]) {
204         // The PHI node may have multiple entries for this predecessor.  We must
205         // make sure we update all of them.
206         for (unsigned i = 0, e = PN->getNumOperands(); i != e; i += 2) {
207           if (PN->getOperand(i+1) == Pred)
208             // At this point we can assume that the array has phi nodes.. let's
209             // update the incoming data.
210             PN->setOperand(i, IncomingVals[k]);
211         }
212         // also note that the active variable IS designated by the phi node
213         IncomingVals[k] = PN;
214       }
215   }
216
217   // don't revisit nodes
218   if (Visited.count(BB)) return;
219   
220   // mark as visited
221   Visited.insert(BB);
222
223   BasicBlock::iterator II = BB->begin();
224   while (1) {
225     Instruction *I = II++; // get the instruction, increment iterator
226
227     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
228       if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
229         std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
230         if (AI != AllocaLookup.end()) {
231           Value *V = IncomingVals[AI->second];
232
233           // walk the use list of this load and replace all uses with r
234           LI->replaceAllUsesWith(V);
235           BB->getInstList().erase(LI);
236         }
237       }
238     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
239       // Delete this instruction and mark the name as the current holder of the
240       // value
241       if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
242         std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
243         if (ai != AllocaLookup.end()) {
244           // what value were we writing?
245           IncomingVals[ai->second] = SI->getOperand(0);
246           BB->getInstList().erase(SI);
247         }
248       }
249       
250     } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) {
251       // Recurse across our successors
252       for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
253         std::vector<Value*> OutgoingVals(IncomingVals);
254         RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
255       }
256       break;
257     }
258   }
259 }
260
261 /// PromoteMemToReg - Promote the specified list of alloca instructions into
262 /// scalar registers, inserting PHI nodes as appropriate.  This function makes
263 /// use of DominanceFrontier information.  This function does not modify the CFG
264 /// of the function at all.  All allocas must be from the same function.
265 ///
266 void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
267                      DominanceFrontier &DF, const TargetData &TD) {
268   // If there is nothing to do, bail out...
269   if (Allocas.empty()) return;
270   PromoteMem2Reg(Allocas, DF, TD).run();
271 }