1 //===- DemoteRegToStack.cpp - Move a virtual reg. to stack ----------------===//
3 // This file provide the function DemoteRegToStack(). This function takes a
4 // virtual register computed by an Instruction& X and replaces it with a slot in
5 // the stack frame, allocated via alloca. It returns the pointer to the
6 // AllocaInst inserted.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Transforms/Utils/DemoteRegToStack.h"
11 #include "llvm/Function.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iPHINode.h"
14 #include "llvm/iTerminators.h"
15 #include "llvm/Type.h"
16 #include "Support/hash_set"
19 typedef hash_set<PHINode*> PhiSet;
20 typedef hash_set<PHINode*>::iterator PhiSetIterator;
22 // Helper function to push a phi *and* all its operands to the worklist!
23 // Do not push an instruction if it is already in the result set of Phis to go.
24 inline void PushOperandsOnWorkList(std::stack<Instruction*>& workList,
25 PhiSet& phisToGo, PHINode* phiN) {
26 for (User::op_iterator OI = phiN->op_begin(), OE = phiN->op_end();
28 if (Instruction* opI = dyn_cast<Instruction>(OI))
29 if (!isa<PHINode>(opI) ||
30 phisToGo.find(cast<PHINode>(opI)) == phisToGo.end())
34 static void FindPhis(Instruction& X, PhiSet& phisToGo) {
35 std::stack<Instruction*> workList;
38 // Handle the case that X itself is a Phi!
39 if (PHINode* phiX = dyn_cast<PHINode>(&X)) {
40 phisToGo.insert(phiX);
41 PushOperandsOnWorkList(workList, phisToGo, phiX);
44 // Now use a worklist to find all phis reachable from X, and
45 // (recursively) all phis reachable from operands of such phis.
46 for (Instruction* workI; !workList.empty(); workList.pop()) {
47 workI = workList.top();
48 for (Value::use_iterator UI=workI->use_begin(), UE=workI->use_end();
50 if (PHINode* phiN = dyn_cast<PHINode>(*UI))
51 if (phisToGo.find(phiN) == phisToGo.end()) {
52 // Seeing this phi for the first time: it must go!
53 phisToGo.insert(phiN);
55 PushOperandsOnWorkList(workList, phisToGo, phiN);
61 // Create the Alloca for X
62 static AllocaInst* CreateAllocaForX(Instruction& X) {
63 Function* parentFunc = X.getParent()->getParent();
64 Instruction* entryInst = parentFunc->getEntryBlock().begin();
65 return new AllocaInst(X.getType(), /*arraySize*/ NULL,
66 X.hasName()? X.getName()+std::string("OnStack")
71 // Insert loads before all uses of I, except uses in Phis
72 // since all such Phis *must* be deleted.
73 static void LoadBeforeUses(Instruction* def, AllocaInst* XSlot) {
74 for (unsigned nPhis = 0; def->use_size() - nPhis > 0; ) {
75 Instruction* useI = cast<Instruction>(def->use_back());
76 if (!isa<PHINode>(useI)) {
78 new LoadInst(XSlot, std::string("Load")+XSlot->getName(), useI);
79 useI->replaceUsesOfWith(def, loadI);
85 static void AddLoadsAndStores(AllocaInst* XSlot, Instruction& X,
87 for (PhiSetIterator PI=phisToGo.begin(), PE=phisToGo.end(); PI != PE; ++PI) {
90 // First, insert loads before all uses except uses in Phis.
91 // Do this first because new stores will appear as uses also!
92 LoadBeforeUses(pn, XSlot);
94 // For every incoming operand of the Phi, insert a store either
95 // just after the instruction defining the value or just before the
96 // predecessor of the Phi if the value is a formal, not an instruction.
98 for (unsigned i=0, N=pn->getNumIncomingValues(); i < N; ++i) {
99 Value* phiOp = pn->getIncomingValue(i);
101 (!isa<PHINode>(phiOp) ||
102 phisToGo.find(cast<PHINode>(phiOp)) == phisToGo.end())) {
103 // This operand is not a phi that will be deleted: need to store.
104 assert(!isa<TerminatorInst>(phiOp));
106 Instruction* storeBefore;
107 if (Instruction* I = dyn_cast<Instruction>(phiOp)) {
108 // phiOp is an instruction, store its result right after it.
109 assert(I->getNext() && "Non-terminator without successor?");
110 storeBefore = I->getNext();
112 // If not, it must be a formal: store it at the end of the
113 // predecessor block of the Phi (*not* at function entry!).
114 storeBefore = pn->getIncomingBlock(i)->getTerminator();
117 // Create instr. to store the value of phiOp before `insertBefore'
118 StoreInst* storeI = new StoreInst(phiOp, XSlot, storeBefore);
124 static void DeletePhis(PhiSet& phisToGo) {
125 for (PhiSetIterator PI=phisToGo.begin(), PE=phisToGo.end(); PI != PE; ++PI) {
126 assert((*PI)->use_size() == 0 && "This PHI should be DEAD!");
127 (*PI)->getParent()->getInstList().remove(*PI);
133 //----------------------------------------------------------------------------
134 // function DemoteRegToStack()
136 // This function takes a virtual register computed by an
137 // Instruction& X and replaces it with a slot in the stack frame,
138 // allocated via alloca. It has to:
139 // (1) Identify all Phi operations that have X as an operand and
140 // transitively other Phis that use such Phis;
141 // (2) Store all values merged with X via Phi operations to the stack slot;
142 // (3) Load the value from the stack slot just before any use of X or any
143 // of the Phis that were eliminated; and
144 // (4) Delete all the Phis, which should all now be dead.
146 // Returns the pointer to the alloca inserted to create a stack slot for X.
147 //----------------------------------------------------------------------------
149 AllocaInst* DemoteRegToStack(Instruction& X) {
150 if (X.getType() == Type::VoidTy)
151 return NULL; // nothing to do!
153 // Find all Phis involving X or recursively using such Phis or Phis
154 // involving operands of such Phis (essentially all Phis in the "web" of X)
156 FindPhis(X, phisToGo);
158 // Create a stack slot to hold X
159 AllocaInst* XSlot = CreateAllocaForX(X);
161 // Insert loads before all uses of X and (*only then*) insert store after X
162 assert(X.getNext() && "Non-terminator (since non-void) with no successor?");
163 LoadBeforeUses(&X, XSlot);
164 StoreInst* storeI = new StoreInst(&X, XSlot, X.getNext());
166 // Do the same for all the phis that will be deleted
167 AddLoadsAndStores(XSlot, X, phisToGo);
169 // Delete the phis and return the alloca instruction
170 DeletePhis(phisToGo);