1 //===- PromoteMemoryToRegister.cpp - Convert allocas to registers ---------===//
3 // This file promote memory references to be register references. It promotes
4 // alloca instructions which only have loads and stores as uses. An alloca is
5 // transformed by using dominator frontiers to place PHI nodes, then traversing
6 // the function in depth-first order to rewrite loads and stores as appropriate.
7 // This is just the standard SSA construction algorithm to construct "pruned"
10 //===----------------------------------------------------------------------===//
12 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
13 #include "llvm/Analysis/Dominators.h"
14 #include "llvm/iMemory.h"
15 #include "llvm/iPHINode.h"
16 #include "llvm/Function.h"
17 #include "llvm/Constant.h"
18 #include "llvm/Support/CFG.h"
19 #include "Support/StringExtras.h"
21 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
22 /// This is true if there are only loads and stores to the alloca...
24 bool isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
25 // FIXME: If the memory unit is of pointer or integer type, we can permit
26 // assignments to subsections of the memory unit.
28 // Only allow direct loads and stores...
29 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
30 UI != UE; ++UI) // Loop over all of the uses of the alloca
31 if (!isa<LoadInst>(*UI))
32 if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
33 if (SI->getOperand(0) == AI)
34 return false; // Don't allow a store of the AI, only INTO the AI.
36 return false; // Not a load or store?
43 struct PromoteMem2Reg {
44 // Allocas - The alloca instructions being promoted
45 std::vector<AllocaInst*> Allocas;
47 DominanceFrontier &DF;
50 // AllocaLookup - Reverse mapping of Allocas
51 std::map<AllocaInst*, unsigned> AllocaLookup;
53 // NewPhiNodes - The PhiNodes we're adding.
54 std::map<BasicBlock*, std::vector<PHINode*> > NewPhiNodes;
56 // Visited - The set of basic blocks the renamer has already visited.
57 std::set<BasicBlock*> Visited;
60 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominatorTree &dt,
61 DominanceFrontier &df, const TargetData &td)
62 : Allocas(A), DT(dt), DF(df), TD(td) {}
67 void MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
68 std::set<PHINode*> &DeadPHINodes);
69 void PromoteLocallyUsedAlloca(AllocaInst *AI);
71 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
72 std::vector<Value*> &IncVals);
73 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx, unsigned &Version,
74 std::set<PHINode*> &InsertedPHINodes);
76 } // end of anonymous namespace
78 void PromoteMem2Reg::run() {
79 Function &F = *DF.getRoot()->getParent();
81 for (unsigned AllocaNum = 0; AllocaNum != Allocas.size(); ++AllocaNum) {
82 AllocaInst *AI = Allocas[AllocaNum];
84 assert(isAllocaPromotable(AI, TD) &&
85 "Cannot promote non-promotable alloca!");
86 assert(AI->getParent()->getParent() == &F &&
87 "All allocas should be in the same function, which is same as DF!");
89 if (AI->use_empty()) {
90 // If there are no uses of the alloca, just delete it now.
91 AI->getParent()->getInstList().erase(AI);
93 // Remove the alloca from the Allocas list, since it has been processed
94 Allocas[AllocaNum] = Allocas.back();
100 // Calculate the set of read and write-locations for each alloca. This is
101 // analogous to counting the number of 'uses' and 'definitions' of each
103 std::vector<BasicBlock*> DefiningBlocks;
104 std::vector<BasicBlock*> UsingBlocks;
106 BasicBlock *OnlyBlock = 0;
107 bool OnlyUsedInOneBlock = true;
109 // As we scan the uses of the alloca instruction, keep track of stores, and
110 // decide whether all of the loads and stores to the alloca are within the
112 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E;++U){
113 Instruction *User = cast<Instruction>(*U);
114 if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
115 // Remember the basic blocks which define new values for the alloca
116 DefiningBlocks.push_back(SI->getParent());
118 // Otherwise it must be a load instruction, keep track of variable reads
119 UsingBlocks.push_back(cast<LoadInst>(User)->getParent());
122 if (OnlyUsedInOneBlock) {
124 OnlyBlock = User->getParent();
125 else if (OnlyBlock != User->getParent())
126 OnlyUsedInOneBlock = false;
130 // If the alloca is only read and written in one basic block, just perform a
131 // linear sweep over the block to eliminate it.
132 if (OnlyUsedInOneBlock) {
133 PromoteLocallyUsedAlloca(AI);
135 // Remove the alloca from the Allocas list, since it has been processed
136 Allocas[AllocaNum] = Allocas.back();
142 // Compute the locations where PhiNodes need to be inserted. Look at the
143 // dominance frontier of EACH basic-block we have a write in.
145 unsigned CurrentVersion = 0;
146 std::set<PHINode*> InsertedPHINodes;
147 while (!DefiningBlocks.empty()) {
148 BasicBlock *BB = DefiningBlocks.back();
149 DefiningBlocks.pop_back();
151 // Look up the DF for this write, add it to PhiNodes
152 DominanceFrontier::const_iterator it = DF.find(BB);
153 if (it != DF.end()) {
154 const DominanceFrontier::DomSetType &S = it->second;
155 for (DominanceFrontier::DomSetType::iterator P = S.begin(),PE = S.end();
157 if (QueuePhiNode(*P, AllocaNum, CurrentVersion, InsertedPHINodes))
158 DefiningBlocks.push_back(*P);
162 // Now that we have inserted PHI nodes along the Iterated Dominance Frontier
163 // of the writes to the variable, scan through the reads of the variable,
164 // marking PHI nodes which are actually necessary as alive (by removing them
165 // from the InsertedPHINodes set). This is not perfect: there may PHI
166 // marked alive because of loads which are dominated by stores, but there
167 // will be no unmarked PHI nodes which are actually used.
169 for (unsigned i = 0, e = UsingBlocks.size(); i != e; ++i)
170 MarkDominatingPHILive(UsingBlocks[i], AllocaNum, InsertedPHINodes);
173 // If there are any PHI nodes which are now known to be dead, remove them!
174 for (std::set<PHINode*>::iterator I = InsertedPHINodes.begin(),
175 E = InsertedPHINodes.end(); I != E; ++I) {
177 std::vector<PHINode*> &BBPNs = NewPhiNodes[PN->getParent()];
178 BBPNs[AllocaNum] = 0;
180 // Check to see if we just removed the last inserted PHI node from this
181 // basic block. If so, remove the entry for the basic block.
182 bool HasOtherPHIs = false;
183 for (unsigned i = 0, e = BBPNs.size(); i != e; ++i)
189 NewPhiNodes.erase(PN->getParent());
191 PN->getParent()->getInstList().erase(PN);
194 // Keep the reverse mapping of the 'Allocas' array.
195 AllocaLookup[Allocas[AllocaNum]] = AllocaNum;
199 return; // All of the allocas must have been trivial!
201 // Set the incoming values for the basic block to be null values for all of
202 // the alloca's. We do this in case there is a load of a value that has not
203 // been stored yet. In this case, it will get this null value.
205 std::vector<Value *> Values(Allocas.size());
206 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
207 Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
209 // Walks all basic blocks in the function performing the SSA rename algorithm
210 // and inserting the phi nodes we marked as necessary
212 RenamePass(F.begin(), 0, Values);
214 // The renamer uses the Visited set to avoid infinite loops. Clear it now.
217 // Remove the allocas themselves from the function...
218 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
219 Instruction *A = Allocas[i];
221 // If there are any uses of the alloca instructions left, they must be in
222 // sections of dead code that were not processed on the dominance frontier.
223 // Just delete the users now.
226 A->replaceAllUsesWith(Constant::getNullValue(A->getType()));
227 A->getParent()->getInstList().erase(A);
230 // At this point, the renamer has added entries to PHI nodes for all reachable
231 // code. Unfortunately, there may be blocks which are not reachable, which
232 // the renamer hasn't traversed. If this is the case, the PHI nodes may not
233 // have incoming values for all predecessors. Loop over all PHI nodes we have
234 // created, inserting null constants if they are missing any incoming values.
236 for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I =
237 NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
239 std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
240 std::vector<PHINode*> &PNs = I->second;
241 assert(!PNs.empty() && "Empty PHI node list??");
243 // Only do work here if there the PHI nodes are missing incoming values. We
244 // know that all PHI nodes that were inserted in a block will have the same
245 // number of incoming values, so we can just check any PHI node.
247 for (unsigned i = 0; (FirstPHI = PNs[i]) == 0; ++i)
250 if (Preds.size() != FirstPHI->getNumIncomingValues()) {
251 // Ok, now we know that all of the PHI nodes are missing entries for some
252 // basic blocks. Start by sorting the incoming predecessors for efficient
254 std::sort(Preds.begin(), Preds.end());
256 // Now we loop through all BB's which have entries in FirstPHI and remove
257 // them from the Preds list.
258 for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
259 // Do a log(n) search of the Preds list for the entry we want.
260 std::vector<BasicBlock*>::iterator EntIt =
261 std::lower_bound(Preds.begin(), Preds.end(),
262 FirstPHI->getIncomingBlock(i));
263 assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
264 "PHI node has entry for a block which is not a predecessor!");
270 // At this point, the blocks left in the preds list must have dummy
271 // entries inserted into every PHI nodes for the block.
272 for (unsigned i = 0, e = PNs.size(); i != e; ++i) {
273 PHINode *PN = PNs[i];
274 Value *NullVal = Constant::getNullValue(PN->getType());
275 for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
276 PN->addIncoming(NullVal, Preds[pred]);
282 // MarkDominatingPHILive - Mem2Reg wants to construct "pruned" SSA form, not
283 // "minimal" SSA form. To do this, it inserts all of the PHI nodes on the IDF
284 // as usual (inserting the PHI nodes in the DeadPHINodes set), then processes
285 // each read of the variable. For each block that reads the variable, this
286 // function is called, which removes used PHI nodes from the DeadPHINodes set.
287 // After all of the reads have been processed, any PHI nodes left in the
288 // DeadPHINodes set are removed.
290 void PromoteMem2Reg::MarkDominatingPHILive(BasicBlock *BB, unsigned AllocaNum,
291 std::set<PHINode*> &DeadPHINodes) {
292 // Scan the immediate dominators of this block looking for a block which has a
293 // PHI node for Alloca num. If we find it, mark the PHI node as being alive!
294 for (DominatorTree::Node *N = DT[BB]; N; N = N->getIDom()) {
295 BasicBlock *DomBB = N->getBlock();
296 std::map<BasicBlock*, std::vector<PHINode*> >::iterator
297 I = NewPhiNodes.find(DomBB);
298 if (I != NewPhiNodes.end() && I->second[AllocaNum]) {
299 // Ok, we found an inserted PHI node which dominates this value.
300 PHINode *DominatingPHI = I->second[AllocaNum];
302 // Find out if we previously thought it was dead.
303 std::set<PHINode*>::iterator DPNI = DeadPHINodes.find(DominatingPHI);
304 if (DPNI != DeadPHINodes.end()) {
305 // Ok, until now, we thought this PHI node was dead. Mark it as being
307 DeadPHINodes.erase(DPNI);
309 // Now that we have marked the PHI node alive, also mark any PHI nodes
310 // which it might use as being alive as well.
311 for (pred_iterator PI = pred_begin(DomBB), PE = pred_end(DomBB);
313 MarkDominatingPHILive(*PI, AllocaNum, DeadPHINodes);
319 // PromoteLocallyUsedAlloca - Many allocas are only used within a single basic
320 // block. If this is the case, avoid traversing the CFG and inserting a lot of
321 // potentially useless PHI nodes by just performing a single linear pass over
322 // the basic block using the Alloca.
324 void PromoteMem2Reg::PromoteLocallyUsedAlloca(AllocaInst *AI) {
325 assert(!AI->use_empty() && "There are no uses of the alloca!");
327 // Uses of the uninitialized memory location shall get zero...
328 Value *CurVal = Constant::getNullValue(AI->getAllocatedType());
330 BasicBlock *BB = cast<Instruction>(AI->use_back())->getParent();
332 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
333 Instruction *Inst = I++;
334 if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
335 if (LI->getOperand(0) == AI) {
336 // Loads just return the "current value"...
337 LI->replaceAllUsesWith(CurVal);
338 BB->getInstList().erase(LI);
340 } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
341 if (SI->getOperand(1) == AI) {
342 // Loads just update the "current value"...
343 CurVal = SI->getOperand(0);
344 BB->getInstList().erase(SI);
349 // After traversing the basic block, there should be no more uses of the
350 // alloca, remove it now.
351 assert(AI->use_empty() && "Uses of alloca from more than one BB??");
352 AI->getParent()->getInstList().erase(AI);
355 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
356 // Alloca returns true if there wasn't already a phi-node for that variable
358 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo,
360 std::set<PHINode*> &InsertedPHINodes) {
361 // Look up the basic-block in question
362 std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
363 if (BBPNs.empty()) BBPNs.resize(Allocas.size());
365 // If the BB already has a phi node added for the i'th alloca then we're done!
366 if (BBPNs[AllocaNo]) return false;
368 // Create a PhiNode using the dereferenced type... and add the phi-node to the
370 BBPNs[AllocaNo] = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
371 Allocas[AllocaNo]->getName() + "." +
372 utostr(Version++), BB->begin());
373 InsertedPHINodes.insert(BBPNs[AllocaNo]);
378 // RenamePass - Recursively traverse the CFG of the function, renaming loads and
379 // stores to the allocas which we are promoting. IncomingVals indicates what
380 // value each Alloca contains on exit from the predecessor block Pred.
382 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
383 std::vector<Value*> &IncomingVals) {
385 // If this BB needs a PHI node, update the PHI node for each variable we need
387 std::map<BasicBlock*, std::vector<PHINode *> >::iterator
388 BBPNI = NewPhiNodes.find(BB);
389 if (BBPNI != NewPhiNodes.end()) {
390 std::vector<PHINode *> &BBPNs = BBPNI->second;
391 for (unsigned k = 0; k != BBPNs.size(); ++k)
392 if (PHINode *PN = BBPNs[k]) {
393 // Add this incoming value to the PHI node.
394 PN->addIncoming(IncomingVals[k], Pred);
396 // The currently active variable for this block is now the PHI.
397 IncomingVals[k] = PN;
401 // don't revisit nodes
402 if (Visited.count(BB)) return;
407 for (BasicBlock::iterator II = BB->begin(); !isa<TerminatorInst>(II); ) {
408 Instruction *I = II++; // get the instruction, increment iterator
410 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
411 if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
412 std::map<AllocaInst*, unsigned>::iterator AI = AllocaLookup.find(Src);
413 if (AI != AllocaLookup.end()) {
414 Value *V = IncomingVals[AI->second];
416 // walk the use list of this load and replace all uses with r
417 LI->replaceAllUsesWith(V);
418 BB->getInstList().erase(LI);
421 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
422 // Delete this instruction and mark the name as the current holder of the
424 if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
425 std::map<AllocaInst *, unsigned>::iterator ai = AllocaLookup.find(Dest);
426 if (ai != AllocaLookup.end()) {
427 // what value were we writing?
428 IncomingVals[ai->second] = SI->getOperand(0);
429 BB->getInstList().erase(SI);
435 // Recurse to our successors.
436 TerminatorInst *TI = BB->getTerminator();
437 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
438 std::vector<Value*> OutgoingVals(IncomingVals);
439 RenamePass(TI->getSuccessor(i), BB, OutgoingVals);
443 /// PromoteMemToReg - Promote the specified list of alloca instructions into
444 /// scalar registers, inserting PHI nodes as appropriate. This function makes
445 /// use of DominanceFrontier information. This function does not modify the CFG
446 /// of the function at all. All allocas must be from the same function.
448 void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
449 DominatorTree &DT, DominanceFrontier &DF,
450 const TargetData &TD) {
451 // If there is nothing to do, bail out...
452 if (Allocas.empty()) return;
453 PromoteMem2Reg(Allocas, DT, DF, TD).run();