PromoteMemoryToRegister.cpp revision 7e70829632f82de15db187845666aaca6e04b792
1//===- PromoteMemoryToRegister.cpp - Convert memory refs to regs ----------===// 2// 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: 5// 6// FROM CODE TO CODE 7// %X = alloca int, uint 1 ret int 42 8// store int 42, int *%X 9// %Y = load int* %X 10// ret int %Y 11// 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. 15// 16// After this, the code is transformed by...something magical :) 17// 18//===----------------------------------------------------------------------===// 19 20#include "llvm/Transforms/Scalar.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/Function.h" 26#include "llvm/BasicBlock.h" 27#include "llvm/Constant.h" 28#include "llvm/Type.h" 29#include "Support/StatisticReporter.h" 30 31static Statistic<> NumPromoted("mem2reg\t\t- Number of alloca's promoted"); 32 33using std::vector; 34using std::map; 35using std::set; 36 37namespace { 38 struct PromotePass : public FunctionPass { 39 vector<AllocaInst*> Allocas; // the alloca instruction.. 40 map<Instruction*, unsigned> AllocaLookup; // reverse mapping of above 41 42 vector<vector<BasicBlock*> > PhiNodes; // index corresponds to Allocas 43 44 // List of instructions to remove at end of pass 45 vector<Instruction *> KillList; 46 47 map<BasicBlock*,vector<PHINode*> > NewPhiNodes; // the PhiNodes we're adding 48 49 public: 50 const char *getPassName() const { return "Promote Memory to Register"; } 51 52 // runOnFunction - To run this pass, first we calculate the alloca 53 // instructions that are safe for promotion, then we promote each one. 54 // 55 virtual bool runOnFunction(Function &F); 56 57 // getAnalysisUsage - We need dominance frontiers 58 // 59 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 60 AU.addRequired(DominanceFrontier::ID); 61 AU.preservesCFG(); 62 } 63 64 private: 65 void Traverse(BasicBlock *BB, BasicBlock *Pred, vector<Value*> &IncVals, 66 set<BasicBlock*> &Visited); 67 bool QueuePhiNode(BasicBlock *BB, unsigned AllocaIdx); 68 void FindSafeAllocas(Function &F); 69 }; 70 71} // end of anonymous namespace 72 73 74// isSafeAlloca - This predicate controls what types of alloca instructions are 75// allowed to be promoted... 76// 77static inline bool isSafeAlloca(const AllocaInst *AI) { 78 if (AI->isArrayAllocation()) return false; 79 80 for (Value::use_const_iterator UI = AI->use_begin(), UE = AI->use_end(); 81 UI != UE; ++UI) { // Loop over all of the uses of the alloca 82 83 // Only allow nonindexed memory access instructions... 84 if (MemAccessInst *MAI = dyn_cast<MemAccessInst>(*UI)) { 85 if (MAI->getPointerOperand() != (Value*)AI) 86 return false; // Reject stores of alloca pointer into some other loc. 87 88 if (MAI->hasIndices()) { // indexed? 89 // Allow the access if there is only one index and the index is 90 // zero. 91 if (*MAI->idx_begin() != Constant::getNullValue(Type::UIntTy) || 92 MAI->idx_begin()+1 != MAI->idx_end()) 93 return false; 94 } 95 } else { 96 return false; // Not a load or store? 97 } 98 } 99 100 return true; 101} 102 103// FindSafeAllocas - Find allocas that are safe to promote 104// 105void PromotePass::FindSafeAllocas(Function &F) { 106 BasicBlock &BB = F.getEntryNode(); // Get the entry node for the function 107 108 // Look at all instructions in the entry node 109 for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I) 110 if (AllocaInst *AI = dyn_cast<AllocaInst>(&*I)) // Is it an alloca? 111 if (isSafeAlloca(AI)) { // If safe alloca, add alloca to safe list 112 AllocaLookup[AI] = Allocas.size(); // Keep reverse mapping 113 Allocas.push_back(AI); 114 } 115} 116 117 118 119bool PromotePass::runOnFunction(Function &F) { 120 // Calculate the set of safe allocas 121 FindSafeAllocas(F); 122 123 // If there is nothing to do, bail out... 124 if (Allocas.empty()) return false; 125 126 // Add each alloca to the KillList. Note: KillList is destroyed MOST recently 127 // added to least recently. 128 KillList.assign(Allocas.begin(), Allocas.end()); 129 130 // Calculate the set of write-locations for each alloca. This is analogous to 131 // counting the number of 'redefinitions' of each variable. 132 vector<vector<BasicBlock*> > WriteSets; // index corresponds to Allocas 133 WriteSets.resize(Allocas.size()); 134 for (unsigned i = 0; i != Allocas.size(); ++i) { 135 AllocaInst *AI = Allocas[i]; 136 for (Value::use_iterator U =AI->use_begin(), E = AI->use_end(); U != E; ++U) 137 if (StoreInst *SI = dyn_cast<StoreInst>(*U)) 138 // jot down the basic-block it came from 139 WriteSets[i].push_back(SI->getParent()); 140 } 141 142 // Get dominance frontier information... 143 DominanceFrontier &DF = getAnalysis<DominanceFrontier>(); 144 145 // Compute the locations where PhiNodes need to be inserted. Look at the 146 // dominance frontier of EACH basic-block we have a write in 147 // 148 PhiNodes.resize(Allocas.size()); 149 for (unsigned i = 0; i != Allocas.size(); ++i) { 150 for (unsigned j = 0; j != WriteSets[i].size(); j++) { 151 // Look up the DF for this write, add it to PhiNodes 152 DominanceFrontier::const_iterator it = DF.find(WriteSets[i][j]); 153 DominanceFrontier::DomSetType S = it->second; 154 for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end(); 155 P != PE; ++P) 156 QueuePhiNode(*P, i); 157 } 158 159 // Perform iterative step 160 for (unsigned k = 0; k != PhiNodes[i].size(); k++) { 161 DominanceFrontier::const_iterator it = DF.find(PhiNodes[i][k]); 162 DominanceFrontier::DomSetType S = it->second; 163 for (DominanceFrontier::DomSetType::iterator P = S.begin(), PE = S.end(); 164 P != PE; ++P) 165 QueuePhiNode(*P, i); 166 } 167 } 168 169 // Set the incoming values for the basic block to be null values for all of 170 // the alloca's. We do this in case there is a load of a value that has not 171 // been stored yet. In this case, it will get this null value. 172 // 173 vector<Value *> Values(Allocas.size()); 174 for (unsigned i = 0, e = Allocas.size(); i != e; ++i) 175 Values[i] = Constant::getNullValue(Allocas[i]->getAllocatedType()); 176 177 // Walks all basic blocks in the function performing the SSA rename algorithm 178 // and inserting the phi nodes we marked as necessary 179 // 180 set<BasicBlock*> Visited; // The basic blocks we've already visited 181 Traverse(F.begin(), 0, Values, Visited); 182 183 // Remove all instructions marked by being placed in the KillList... 184 // 185 while (!KillList.empty()) { 186 Instruction *I = KillList.back(); 187 KillList.pop_back(); 188 189 I->getParent()->getInstList().erase(I); 190 } 191 192 NumPromoted += Allocas.size(); 193 194 // Purge data structurse so they are available the next iteration... 195 Allocas.clear(); 196 AllocaLookup.clear(); 197 PhiNodes.clear(); 198 NewPhiNodes.clear(); 199 return true; 200} 201 202 203// QueuePhiNode - queues a phi-node to be added to a basic-block for a specific 204// Alloca returns true if there wasn't already a phi-node for that variable 205// 206bool PromotePass::QueuePhiNode(BasicBlock *BB, unsigned AllocaNo) { 207 // Look up the basic-block in question 208 vector<PHINode*> &BBPNs = NewPhiNodes[BB]; 209 if (BBPNs.empty()) BBPNs.resize(Allocas.size()); 210 211 // If the BB already has a phi node added for the i'th alloca then we're done! 212 if (BBPNs[AllocaNo]) return false; 213 214 // Create a PhiNode using the dereferenced type... 215 PHINode *PN = new PHINode(Allocas[AllocaNo]->getAllocatedType(), 216 Allocas[AllocaNo]->getName()+".mem2reg"); 217 BBPNs[AllocaNo] = PN; 218 219 // Add the phi-node to the basic-block 220 BB->getInstList().push_front(PN); 221 222 PhiNodes[AllocaNo].push_back(BB); 223 return true; 224} 225 226void PromotePass::Traverse(BasicBlock *BB, BasicBlock *Pred, 227 vector<Value*> &IncomingVals, 228 set<BasicBlock*> &Visited) { 229 // If this is a BB needing a phi node, lookup/create the phinode for each 230 // variable we need phinodes for. 231 vector<PHINode *> &BBPNs = NewPhiNodes[BB]; 232 for (unsigned k = 0; k != BBPNs.size(); ++k) 233 if (PHINode *PN = BBPNs[k]) { 234 // at this point we can assume that the array has phi nodes.. let's add 235 // the incoming data 236 PN->addIncoming(IncomingVals[k], Pred); 237 238 // also note that the active variable IS designated by the phi node 239 IncomingVals[k] = PN; 240 } 241 242 // don't revisit nodes 243 if (Visited.count(BB)) return; 244 245 // mark as visited 246 Visited.insert(BB); 247 248 // keep track of the value of each variable we're watching.. how? 249 for (BasicBlock::iterator II = BB->begin(); II != BB->end(); ++II) { 250 Instruction *I = II; // get the instruction 251 252 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 253 Value *Ptr = LI->getPointerOperand(); 254 255 if (AllocaInst *Src = dyn_cast<AllocaInst>(Ptr)) { 256 map<Instruction*, unsigned>::iterator AI = AllocaLookup.find(Src); 257 if (AI != AllocaLookup.end()) { 258 Value *V = IncomingVals[AI->second]; 259 260 // walk the use list of this load and replace all uses with r 261 LI->replaceAllUsesWith(V); 262 KillList.push_back(LI); // Mark the load to be deleted 263 } 264 } 265 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 266 // delete this instruction and mark the name as the current holder of the 267 // value 268 Value *Ptr = SI->getPointerOperand(); 269 if (AllocaInst *Dest = dyn_cast<AllocaInst>(Ptr)) { 270 map<Instruction *, unsigned>::iterator ai = AllocaLookup.find(Dest); 271 if (ai != AllocaLookup.end()) { 272 // what value were we writing? 273 IncomingVals[ai->second] = SI->getOperand(0); 274 KillList.push_back(SI); // Mark the store to be deleted 275 } 276 } 277 278 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) { 279 // Recurse across our successors 280 for (unsigned i = 0; i != TI->getNumSuccessors(); i++) { 281 vector<Value*> OutgoingVals(IncomingVals); 282 Traverse(TI->getSuccessor(i), BB, OutgoingVals, Visited); 283 } 284 } 285 } 286} 287 288 289// createPromoteMemoryToRegister - Provide an entry point to create this pass. 290// 291Pass *createPromoteMemoryToRegister() { 292 return new PromotePass(); 293} 294