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