1 //===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===//
3 // This file is used to promote memory references to be register references. A
4 // simple example of the transformation performed by this function is:
7 // %X = alloca int, uint 1 ret int 42
8 // store int 42, int *%X
12 // The code is transformed by looping over all of the alloca instruction,
13 // calculating dominator frontiers, then inserting phi-nodes following the usual
14 // SSA construction algorithm. This code does not modify the CFG of the
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iPHINode.h"
23 #include "llvm/iTerminators.h"
24 #include "llvm/Function.h"
25 #include "llvm/Constant.h"
26 #include "llvm/Type.h"
28 /// isAllocaPromotable - Return true if this alloca is legal for promotion.
29 /// This is true if there are only loads and stores to the alloca...
31 bool isAllocaPromotable(const AllocaInst *AI, const TargetData &TD) {
32 // FIXME: If the memory unit is of pointer or integer type, we can permit
33 // assignments to subsections of the memory unit.
35 // Only allow direct loads and stores...
36 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end();
37 UI != UE; ++UI) // Loop over all of the uses of the alloca
38 if (!isa<LoadInst>(*UI))
39 if (const StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
40 if (SI->getOperand(0) == AI)
41 return false; // Don't allow a store of the AI, only INTO the AI.
43 return false; // Not a load or store?
51 struct PromoteMem2Reg {
52 const std::vector<AllocaInst*> &Allocas; // the alloca instructions..
53 DominanceFrontier &DF;
56 std::map<Instruction*, unsigned> AllocaLookup; // reverse mapping of above
58 std::vector<std::vector<BasicBlock*> > PhiNodes;// Idx corresponds 2 Allocas
60 // List of instructions to remove at end of pass
61 std::vector<Instruction *> KillList;
64 std::vector<PHINode*> > NewPhiNodes; // the PhiNodes we're adding
67 PromoteMem2Reg(const std::vector<AllocaInst*> &A, DominanceFrontier &df,
69 : Allocas(A), DF(df), TD(td) {}
74 void RenamePass(BasicBlock *BB, BasicBlock *Pred,
75 std::vector<Value*> &IncVals,
76 std::set<BasicBlock*> &Visited);
77 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx);
79 } // end of anonymous namespace
82 void PromoteMem2Reg::run() {
83 // If there is nothing to do, bail out...
84 if (Allocas.empty()) return;
86 Function &F = *DF.getRoot()->getParent();
88 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) {
89 assert(isAllocaPromotable(Allocas[i], TD) &&
90 "Cannot promote non-promotable alloca!");
91 assert(Allocas[i]->getParent()->getParent() == &F &&
92 "All allocas should be in the same function, which is same as DF!");
93 AllocaLookup[Allocas[i]] = i;
97 // Add each alloca to the KillList. Note: KillList is destroyed MOST recently
98 // added to least recently.
99 KillList.assign(Allocas.begin(), Allocas.end());
101 // Calculate the set of write-locations for each alloca. This is analogous to
102 // counting the number of 'redefinitions' of each variable.
103 std::vector<std::vector<BasicBlock*> > WriteSets;// Idx corresponds to Allocas
104 WriteSets.resize(Allocas.size());
105 for (unsigned i = 0; i != Allocas.size(); ++i) {
106 AllocaInst *AI = Allocas[i];
107 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U)
108 if (StoreInst *SI = dyn_cast<StoreInst>(*U))
109 // jot down the basic-block it came from
110 WriteSets[i].push_back(SI->getParent());
113 // Compute the locations where PhiNodes need to be inserted. Look at the
114 // dominance frontier of EACH basic-block we have a write in
116 PhiNodes.resize(Allocas.size());
117 for (unsigned i = 0; i != Allocas.size(); ++i) {
118 for (unsigned j = 0; j != WriteSets[i].size(); j++) {
119 // Look up the DF for this write, add it to PhiNodes
120 DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]);
121 DominanceFrontier::DomSetType S = it->second;
122 for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end();
127 // Perform iterative step
128 for (unsigned k = 0; k != PhiNodes[i].size(); k++) {
129 DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]);
130 DominanceFrontier::DomSetType S = it->second;
131 for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end();
137 // Set the incoming values for the basic block to be null values for all of
138 // the alloca's. We do this in case there is a load of a value that has not
139 // been stored yet. In this case, it will get this null value.
141 std::vector<Value *> Values(Allocas.size());
142 for (unsigned i = 0, e = Allocas.size(); i != e; ++i)
143 Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType());
145 // Walks all basic blocks in the function performing the SSA rename algorithm
146 // and inserting the phi nodes we marked as necessary
148 std::set<BasicBlock*> Visited; // The basic blocks we've already visited
149 RenamePass(F.begin(), 0, Values, Visited);
151 // Remove all instructions marked by being placed in the KillList...
153 while (!KillList.empty()) {
154 Instruction *I = KillList.back();
157 I->getParent()->getInstList().erase(I);
162 // QueuePhiNode - queues a phi-node to be added to a basic-block for a specific
163 // Alloca returns true if there wasn't already a phi-node for that variable
165 bool PromoteMem2Reg::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) {
166 // Look up the basic-block in question
167 std::vector<PHINode*> &BBPNs = NewPhiNodes[BB];
168 if (BBPNs.empty()) BBPNs.resize(Allocas.size());
170 // If the BB already has a phi node added for the i'th alloca then we're done!
171 if (BBPNs[AllocaNo]) return false;
173 // Create a PhiNode using the dereferenced type... and add the phi-node to the
175 PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(),
176 Allocas[AllocaNo]->getName()+".mem2reg",
178 BBPNs[AllocaNo] = PN;
179 PhiNodes[AllocaNo].push_back(BB);
183 void PromoteMem2Reg::RenamePass(BasicBlock *BB, BasicBlock *Pred,
184 std::vector<Value*> &IncomingVals,
185 std::set<BasicBlock*> &Visited) {
186 // If this is a BB needing a phi node, lookup/create the phinode for each
187 // variable we need phinodes for.
188 std::vector<PHINode *> &BBPNs = NewPhiNodes[BB];
189 for (unsigned k = 0; k != BBPNs.size(); ++k)
190 if (PHINode *PN = BBPNs[k]) {
191 // at this point we can assume that the array has phi nodes.. let's add
193 PN->addIncoming(IncomingVals[k], Pred);
195 // also note that the active variable IS designated by the phi node
196 IncomingVals[k] = PN;
199 // don't revisit nodes
200 if (Visited.count(BB)) return;
205 // keep track of the value of each variable we're watching.. how?
206 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II) {
207 Instruction *I = II; // get the instruction
209 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
210 if (AllocaInst *Src = dyn_cast<AllocaInst>(LI->getPointerOperand())) {
211 std::map<Instruction*, unsigned>::iterator AI = AllocaLookup.find(Src);
212 if (AI != AllocaLookup.end()) {
213 Value *V = IncomingVals[AI->second];
215 // walk the use list of this load and replace all uses with r
216 LI->replaceAllUsesWith(V);
217 KillList.push_back(LI); // Mark the load to be deleted
220 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
221 // Delete this instruction and mark the name as the current holder of the
223 if (AllocaInst *Dest = dyn_cast<AllocaInst>(SI->getPointerOperand())) {
224 std::map<Instruction *, unsigned>::iterator ai =AllocaLookup.find(Dest);
225 if (ai != AllocaLookup.end()) {
226 // what value were we writing?
227 IncomingVals[ai->second] = SI->getOperand(0);
228 KillList.push_back(SI); // Mark the store to be deleted
232 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) {
233 // Recurse across our successors
234 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) {
235 std::vector<Value*> OutgoingVals(IncomingVals);
236 RenamePass(TI->getSuccessor(i), BB, OutgoingVals, Visited);
242 /// PromoteMemToReg - Promote the specified list of alloca instructions into
243 /// scalar registers, inserting PHI nodes as appropriate. This function makes
244 /// use of DominanceFrontier information. This function does not modify the CFG
245 /// of the function at all. All allocas must be from the same function.
247 void PromoteMemToReg(const std::vector<AllocaInst*> &Allocas,
248 DominanceFrontier &DF, const TargetData &TD) {
249 PromoteMem2Reg(Allocas, DF, TD).run();