1 //===- llvm/Transforms/HoistPHIConstants.h - Normalize PHI nodes ------------=//
3 // HoistPHIConstants - Remove literal constants that are arguments of PHI nodes
4 // by inserting cast instructions in the preceeding basic blocks, and changing
5 // constant references into references of the casted value.
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Transforms/HoistPHIConstants.h"
10 #include "llvm/iPHINode.h"
11 #include "llvm/iOther.h"
12 #include "llvm/BasicBlock.h"
13 #include "llvm/Method.h"
17 typedef pair<BasicBlock *, Value*> BBConstTy;
18 typedef map<BBConstTy, CastInst *> CachedCopyMap;
20 static Value *NormalizePhiOperand(PHINode *PN, Value *CPV,
21 BasicBlock *Pred, CachedCopyMap &CopyCache) {
23 /* NOTE: CahedCopyMap was disabled to insert phi elimination code
24 for all phi args -- Ruchira
28 // Check if we've already inserted a copy for this constant in Pred
29 // Note that `copyCache[Pred]' will create an empty vector the first time
31 CachedCopyMap::iterator CCI = CopyCache.find(BBConstTy(Pred, CPV));
32 if (CCI != CopyCache.end()) return CCI->second;
34 // Create a copy instruction and add it to the cache...
35 CastInst *Inst = new CastInst(CPV, CPV->getType());
36 CopyCache.insert(make_pair(BBConstTy(Pred, CPV), Inst));
38 // Insert the copy just before the terminator inst of the predecessor BB
39 assert(Pred->getTerminator() && "Degenerate BB encountered!");
40 Pred->getInstList().insert(Pred->getInstList().end()-1, Inst);
46 //---------------------------------------------------------------------------
47 // Entry point for normalizing constant args in PHIs
48 //---------------------------------------------------------------------------
50 bool HoistPHIConstants::doHoistPHIConstants(Method *M) {
54 for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI) {
55 vector<PHINode*> phis; // normalizing invalidates BB iterator
57 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II) {
58 if (PHINode *PN = dyn_cast<PHINode>(*II))
61 break; // All PHIs occur at top of BB!
64 for (vector<PHINode*>::iterator PI=phis.begin(); PI != phis.end(); ++PI)
65 for (unsigned i = 0; i < (*PI)->getNumIncomingValues(); ++i) {
66 Value *Op = (*PI)->getIncomingValue(i);
68 if (isa<Constant>(Op)) {
69 (*PI)->setIncomingValue(i,
70 NormalizePhiOperand((*PI),
71 (*PI)->getIncomingValue(i),
72 (*PI)->getIncomingBlock(i), Cache));