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 //===----------------------------------------------------------------------===//
12 #include "llvm/Transforms/HoistPHIConstants.h"
13 #include "llvm/iOther.h"
14 #include "llvm/BasicBlock.h"
15 #include "llvm/Method.h"
19 typedef pair<BasicBlock *, Value*> BBConstTy;
20 typedef map<BBConstTy, CastInst *> CachedCopyMap;
22 static Value *NormalizePhiOperand(PHINode *PN, Value *CPV,
23 BasicBlock *Pred, CachedCopyMap &CopyCache) {
25 /* NOTE: CahedCopyMap was disabled to insert phi elimination code
26 for all phi args -- Ruchira
30 // Check if we've already inserted a copy for this constant in Pred
31 // Note that `copyCache[Pred]' will create an empty vector the first time
33 CachedCopyMap::iterator CCI = CopyCache.find(BBConstTy(Pred, CPV));
34 if (CCI != CopyCache.end()) return CCI->second;
36 // Create a copy instruction and add it to the cache...
37 CastInst *Inst = new CastInst(CPV, CPV->getType());
38 CopyCache.insert(make_pair(BBConstTy(Pred, CPV), Inst));
40 // Insert the copy just before the terminator inst of the predecessor BB
41 assert(Pred->getTerminator() && "Degenerate BB encountered!");
42 Pred->getInstList().insert(Pred->getInstList().end()-1, Inst);
48 //---------------------------------------------------------------------------
49 // Entry point for normalizing constant args in PHIs
50 //---------------------------------------------------------------------------
52 bool HoistPHIConstants::doHoistPHIConstants(Method *M) {
56 for (Method::iterator BI = M->begin(), BE = M->end(); BI != BE; ++BI)
58 vector<PHINode*> phis; // normalizing invalidates BB iterator
60 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
62 if (PHINode *PN = dyn_cast<PHINode>(*II))
65 break; // All PHIs occur at top of BB!
68 for (vector<PHINode*>::iterator PI=phis.begin(); PI != phis.end(); ++PI)
69 for (unsigned i = 0; i < (*PI)->getNumIncomingValues(); ++i)
71 Value *Op = (*PI)->getIncomingValue(i);
73 if (isa<ConstPoolVal>(Op)) {
74 (*PI)->setIncomingValue(i,
75 NormalizePhiOperand((*PI),
76 (*PI)->getIncomingValue(i),
77 (*PI)->getIncomingBlock(i), Cache));