Various cleanups and efficiency improvements
[oota-llvm.git] / lib / Transforms / Utils / DemoteRegToStack.cpp
1 //===- DemoteRegToStack.cpp - Move a virtual register to the stack --------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 // 
10 // This file provide the function DemoteRegToStack().  This function takes a
11 // virtual register computed by an Instruction& X and replaces it with a slot in
12 // the stack frame, allocated via alloca. It returns the pointer to the
13 // AllocaInst inserted.
14 //
15 //===----------------------------------------------------------------------===//
16
17 #include "llvm/Transforms/Utils/DemoteRegToStack.h"
18 #include "llvm/Function.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iPHINode.h"
21 #include "llvm/iTerminators.h"
22 #include "llvm/Type.h"
23 #include "Support/hash_set"
24
25 typedef hash_set<PHINode*>           PhiSet;
26 typedef hash_set<PHINode*>::iterator PhiSetIterator;
27
28 // Helper function to push a phi *and* all its operands to the worklist!
29 // Do not push an instruction if it is already in the result set of Phis to go.
30 inline void PushOperandsOnWorkList(std::vector<Instruction*>& workList,
31                                    PhiSet& phisToGo, PHINode* phiN) {
32   for (User::op_iterator OI = phiN->op_begin(), OE = phiN->op_end();
33        OI != OE; ++OI) {
34     Instruction* opI = cast<Instruction>(OI);
35     if (!isa<PHINode>(opI) || !phisToGo.count(cast<PHINode>(opI)))
36       workList.push_back(opI);
37   }
38 }
39
40 static void FindPhis(Instruction& X, PhiSet& phisToGo) {
41   std::vector<Instruction*> workList;
42   workList.push_back(&X);
43
44   // Handle the case that X itself is a Phi!
45   if (PHINode* phiX = dyn_cast<PHINode>(&X)) {
46     phisToGo.insert(phiX);
47     PushOperandsOnWorkList(workList, phisToGo, phiX);
48   }
49
50   // Now use a worklist to find all phis reachable from X, and
51   // (recursively) all phis reachable from operands of such phis.
52   while (!workList.empty()) {
53     Instruction *I = workList.back();
54     workList.pop_back();
55     for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); UI!=E; ++UI)
56       if (PHINode* phiN = dyn_cast<PHINode>(*UI))
57         if (phisToGo.find(phiN) == phisToGo.end()) {
58           // Seeing this phi for the first time: it must go!
59           phisToGo.insert(phiN);
60           workList.push_back(phiN);
61           PushOperandsOnWorkList(workList, phisToGo, phiN);
62         }
63   }
64 }
65
66
67 // Insert loads before all uses of I, except uses in Phis
68 // since all such Phis *must* be deleted.
69 static void LoadBeforeUses(Instruction* def, AllocaInst* XSlot) {
70   for (unsigned nPhis = 0; def->use_size() - nPhis > 0; ) {
71       Instruction* useI = cast<Instruction>(def->use_back());
72       if (!isa<PHINode>(useI)) {
73         LoadInst* loadI =
74           new LoadInst(XSlot, std::string("Load")+XSlot->getName(), useI);
75         useI->replaceUsesOfWith(def, loadI);
76       } else
77         ++nPhis;
78   }
79 }
80
81 static void AddLoadsAndStores(AllocaInst* XSlot, Instruction& X,
82                               PhiSet& phisToGo) {
83   for (PhiSetIterator PI=phisToGo.begin(), PE=phisToGo.end(); PI != PE; ++PI) {
84     PHINode* pn = *PI;
85
86     // First, insert loads before all uses except uses in Phis.
87     // Do this first because new stores will appear as uses also!
88     LoadBeforeUses(pn, XSlot);
89
90     // For every incoming operand of the Phi, insert a store either
91     // just after the instruction defining the value or just before the
92     // predecessor of the Phi if the value is a formal, not an instruction.
93     // 
94     for (unsigned i=0, N=pn->getNumIncomingValues(); i < N; ++i) {
95       Value* phiOp = pn->getIncomingValue(i);
96       if (phiOp != &X &&
97           (!isa<PHINode>(phiOp) || !phisToGo.count(cast<PHINode>(phiOp)))) {
98         // This operand is not a phi that will be deleted: need to store.
99         assert(!isa<TerminatorInst>(phiOp));
100
101         Instruction* storeBefore;
102         if (Instruction* I = dyn_cast<Instruction>(phiOp)) {
103           // phiOp is an instruction, store its result right after it.
104           assert(I->getNext() && "Non-terminator without successor?");
105           storeBefore = I->getNext();
106         } else {
107           // If not, it must be a formal: store it at the end of the
108           // predecessor block of the Phi (*not* at function entry!).
109           storeBefore = pn->getIncomingBlock(i)->getTerminator();
110         }
111               
112         // Create instr. to store the value of phiOp before `insertBefore'
113         StoreInst* storeI = new StoreInst(phiOp, XSlot, storeBefore);
114       }
115     }
116   }
117 }
118
119 //---------------------------------------------------------------------------- 
120 // function DemoteRegToStack()
121 // 
122 // This function takes a virtual register computed by an
123 // Instruction& X and replaces it with a slot in the stack frame,
124 // allocated via alloca.  It has to:
125 // (1) Identify all Phi operations that have X as an operand and
126 //     transitively other Phis that use such Phis; 
127 // (2) Store all values merged with X via Phi operations to the stack slot;
128 // (3) Load the value from the stack slot just before any use of X or any
129 //     of the Phis that were eliminated; and
130 // (4) Delete all the Phis, which should all now be dead.
131 //
132 // Returns the pointer to the alloca inserted to create a stack slot for X.
133 //
134 AllocaInst* DemoteRegToStack(Instruction& X) {
135   if (X.getType() == Type::VoidTy)
136     return 0;                             // nothing to do!
137
138   // Find all Phis involving X or recursively using such Phis or Phis
139   // involving operands of such Phis (essentially all Phis in the "web" of X)
140   PhiSet phisToGo;
141   FindPhis(X, phisToGo);
142
143   // Create a stack slot to hold X
144   Function* parentFunc = X.getParent()->getParent();
145   AllocaInst *XSlot = new AllocaInst(X.getType(), 0, X.getName(),
146                                      parentFunc->getEntryBlock().begin());
147
148
149   // Insert loads before all uses of X and (*only then*) insert store after X
150   assert(X.getNext() && "Non-terminator (since non-void) with no successor?");
151   LoadBeforeUses(&X, XSlot);
152   StoreInst* storeI = new StoreInst(&X, XSlot, X.getNext());
153
154   // Do the same for all the phis that will be deleted
155   AddLoadsAndStores(XSlot, X, phisToGo);
156
157   // Delete the phis and return the alloca instruction
158   for (PhiSetIterator PI = phisToGo.begin(), E = phisToGo.end(); PI != E; ++PI)
159     (*PI)->getParent()->getInstList().erase(*PI);
160
161   return XSlot;
162 }