1 //===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===//
3 // This pass is used to promote memory references to be register references. A
4 // simple example of the transformation performed by this pass is:
7 // %X = alloca int, uint 1 ret int 42
8 // store int 42, int *%X
12 // To do this transformation, a simple analysis is done to ensure it is safe.
13 // Currently this just loops over all alloca instructions, looking for
14 // instructions that are only used in simple load and stores.
16 // After this, the code is transformed by...something magical :)
18 //===----------------------------------------------------------------------===//
20 #include "llvm/Transforms/Scalar/PromoteMemoryToRegister.h"
21 #include "llvm/Analysis/Dominators.h"
22 #include "llvm/iMemory.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iTerminators.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Function.h"
27 #include "llvm/BasicBlock.h"
28 #include "llvm/ConstantVals.h"
33 using cfg::DominanceFrontier;
37 //instance of the promoter -- to keep all the local function data.
38 // gets re-created for each function processed
42 vector<AllocaInst*> Allocas; // the alloca instruction..
43 map<Instruction *, int> AllocaLookup; //reverse mapping of above
45 vector<vector<BasicBlock *> > WriteSets; // index corresponds to Allocas
46 vector<vector<BasicBlock *> > PhiNodes; // index corresponds to Allocas
47 vector<vector<Value *> > CurrentValue; //the current value stack
49 //list of instructions to remove at end of pass :)
50 vector<Instruction *> killlist;
52 set<BasicBlock *> visited; //the basic blocks we've already visited
53 map<BasicBlock *, vector<PHINode *> > new_phinodes; //the phinodes we're adding
56 void traverse(BasicBlock *f, BasicBlock * predecessor);
57 bool PromoteFunction(Function *F, DominanceFrontier &DF);
58 bool queuePhiNode(BasicBlock *bb, int alloca_index);
59 void findSafeAllocas(Function *M);
62 // I do this so that I can force the deconstruction of the local variables
63 PromoteInstance(Function *F, DominanceFrontier &DF)
65 didchange=PromoteFunction(F, DF);
67 //This returns whether the pass changes anything
68 operator bool () { return didchange; }
71 } // end of anonymous namespace
73 // findSafeAllocas - Find allocas that are safe to promote
75 void PromoteInstance::findSafeAllocas(Function *F)
77 BasicBlock *BB = F->getEntryNode(); // Get the entry node for the function
79 // Look at all instructions in the entry node
80 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
81 if (AllocaInst *AI = dyn_cast<AllocaInst>(*I)) // Is it an alloca?
82 if (!AI->isArrayAllocation()) {
84 for (Value::use_iterator UI = AI->use_begin(), UE = AI->use_end();
85 UI != UE; ++UI) { // Loop over all of the uses of the alloca
87 // Only allow nonindexed memory access instructions...
88 if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(*UI)) {
89 if (MAI->hasIndices()) { // indexed?
90 // Allow the access if there is only one index and the index is zero.
91 if (*MAI->idx_begin() != ConstantUInt::get(Type::UIntTy, 0) ||
92 MAI->idx_begin()+1 != MAI->idx_end()) {
93 isSafe = false; break;
97 isSafe = false; break; // Not a load or store?
100 if (isSafe) // If all checks pass, add alloca to safe list
102 AllocaLookup[AI]=Allocas.size();
103 Allocas.push_back(AI);
110 bool PromoteInstance::PromoteFunction(Function *F, DominanceFrontier & DF) {
111 // Calculate the set of safe allocas
114 // Add each alloca to the killlist
115 // note: killlist is destroyed MOST recently added to least recently.
116 killlist.assign(Allocas.begin(), Allocas.end());
118 // Calculate the set of write-locations for each alloca.
119 // this is analogous to counting the number of 'redefinitions' of each variable.
120 for (unsigned i = 0; i<Allocas.size(); ++i)
122 AllocaInst * AI = Allocas[i];
123 WriteSets.push_back(std::vector<BasicBlock *>()); //add a new set
124 for (Value::use_iterator U = AI->use_begin();U!=AI->use_end();++U)
126 if (MemAccessInst *MAI = dyn_cast<StoreInst>(*U)) {
127 WriteSets[i].push_back(MAI->getParent()); // jot down the basic-block it came from
132 // Compute the locations where PhiNodes need to be inserted
133 // look at the dominance frontier of EACH basic-block we have a write in
134 PhiNodes.resize(Allocas.size());
135 for (unsigned i = 0; i<Allocas.size(); ++i)
137 for (unsigned j = 0; j<WriteSets[i].size(); j++)
139 //look up the DF for this write, add it to PhiNodes
140 DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]);
141 DominanceFrontier::DomSetType s = (*it).second;
142 for (DominanceFrontier::DomSetType::iterator p = s.begin();p!=s.end(); ++p)
144 if (queuePhiNode(*p, i))
145 PhiNodes[i].push_back(*p);
148 // perform iterative step
149 for (unsigned k = 0; k<PhiNodes[i].size(); k++)
151 DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]);
152 DominanceFrontier::DomSetType s = it->second;
153 for (DominanceFrontier::DomSetType::iterator p = s.begin(); p!=s.end(); ++p)
155 if (queuePhiNode(*p,i))
156 PhiNodes[i].push_back(*p);
161 // Walks all basic blocks in the function
162 // performing the SSA rename algorithm
163 // and inserting the phi nodes we marked as necessary
164 BasicBlock * f = F->front(); //get root basic-block
166 CurrentValue.push_back(vector<Value *>(Allocas.size()));
168 traverse(f, NULL); // there is no predecessor of the root node
171 // ** REMOVE EVERYTHING IN THE KILL-LIST **
172 // we need to kill 'uses' before root values
173 // so we should probably run through in reverse
174 for (vector<Instruction *>::reverse_iterator i = killlist.rbegin(); i!=killlist.rend(); ++i)
176 Instruction * r = *i;
177 BasicBlock * o = r->getParent();
180 BasicBlock::InstListType & l = o->getInstList();
181 o->getInstList().remove(r);
185 return !Allocas.empty();
190 void PromoteInstance::traverse(BasicBlock *f, BasicBlock * predecessor)
192 vector<Value *> * tos = &CurrentValue.back(); //look at top-
194 //if this is a BB needing a phi node, lookup/create the phinode for
195 // each variable we need phinodes for.
196 map<BasicBlock *, vector<PHINode *> >::iterator nd = new_phinodes.find(f);
197 if (nd!=new_phinodes.end())
199 for (unsigned k = 0; k!=nd->second.size(); ++k)
202 //at this point we can assume that the array has phi nodes.. let's
203 // add the incoming data
205 nd->second[k]->addIncoming((*tos)[k],predecessor);
206 //also note that the active variable IS designated by the phi node
207 (*tos)[k] = nd->second[k];
211 //don't revisit nodes
212 if (visited.find(f)!=visited.end())
217 BasicBlock::iterator i = f->begin();
218 //keep track of the value of each variable we're watching.. how?
221 Instruction * inst = *i; //get the instruction
222 //is this a write/read?
223 if (LoadInst * LI = dyn_cast<LoadInst>(inst))
225 // This is a bit weird...
226 Value * ptr = LI->getPointerOperand(); //of type value
227 if (AllocaInst * srcinstr = dyn_cast<AllocaInst>(ptr))
229 map<Instruction *, int>::iterator ai = AllocaLookup.find(srcinstr);
230 if (ai!=AllocaLookup.end())
232 if (Value *r = (*tos)[ai->second])
234 //walk the use list of this load and replace
236 LI->replaceAllUsesWith(r);
237 //now delete the instruction.. somehow..
238 killlist.push_back((Instruction *)LI);
243 else if (StoreInst * SI = dyn_cast<StoreInst>(inst))
245 // delete this instruction and mark the name as the
246 // current holder of the value
247 Value * ptr = SI->getPointerOperand(); //of type value
248 if (Instruction * srcinstr = dyn_cast<Instruction>(ptr))
250 map<Instruction *, int>::iterator ai = AllocaLookup.find(srcinstr);
251 if (ai!=AllocaLookup.end())
253 //what value were we writing?
254 Value * writeval = SI->getOperand(0);
256 (*tos)[ai->second] = writeval;
257 //now delete it.. somehow?
258 killlist.push_back((Instruction *)SI);
263 else if (TerminatorInst * TI = dyn_cast<TerminatorInst>(inst))
265 // Recurse across our sucessors
266 for (unsigned i = 0; i!=TI->getNumSuccessors(); i++)
268 CurrentValue.push_back(CurrentValue.back());
269 traverse(TI->getSuccessor(i),f); //this node IS the predecessor
270 CurrentValue.pop_back();
277 // queues a phi-node to be added to a basic-block for a specific Alloca
278 // returns true if there wasn't already a phi-node for that variable
281 bool PromoteInstance::queuePhiNode(BasicBlock *bb, int i /*the alloca*/)
283 map<BasicBlock *, vector<PHINode *> >::iterator nd;
284 //look up the basic-block in question
285 nd = new_phinodes.find(bb);
286 //if the basic-block has no phi-nodes added, or at least none
287 //for the i'th alloca. then add.
288 if (nd==new_phinodes.end() || nd->second[i]==NULL)
290 //we're not added any phi nodes to this basicblock yet
291 // create the phi-node array.
292 if (nd==new_phinodes.end())
294 new_phinodes[bb] = vector<PHINode *>(Allocas.size());
295 nd = new_phinodes.find(bb);
298 //find the type the alloca returns
299 const PointerType * pt = Allocas[i]->getType();
300 //create a phi-node using the DEREFERENCED type
301 PHINode * ph = new PHINode(pt->getElementType(), Allocas[i]->getName()+".mem2reg");
303 //add the phi-node to the basic-block
304 bb->getInstList().push_front(ph);
312 struct PromotePass : public FunctionPass {
314 // runOnFunction - To run this pass, first we calculate the alloca
315 // instructions that are safe for promotion, then we promote each one.
317 virtual bool runOnFunction(Function *F) {
318 return (bool)PromoteInstance(F, getAnalysis<DominanceFrontier>());
322 // getAnalysisUsage - We need dominance frontiers
324 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
325 AU.addRequired(DominanceFrontier::ID);
331 // createPromoteMemoryToRegister - Provide an entry point to create this pass.
333 Pass *createPromoteMemoryToRegister() {
334 return new PromotePass();