+
+ // At this point, the renamer has added entries to PHI nodes for all reachable
+ // code. Unfortunately, there may be blocks which are not reachable, which
+ // the renamer hasn't traversed. If this is the case, the PHI nodes may not
+ // have incoming values for all predecessors. Loop over all PHI nodes we have
+ // created, inserting null constants if they are missing any incoming values.
+ //
+ for (std::map<BasicBlock*, std::vector<PHINode *> >::iterator I =
+ NewPhiNodes.begin(), E = NewPhiNodes.end(); I != E; ++I) {
+
+ std::vector<BasicBlock*> Preds(pred_begin(I->first), pred_end(I->first));
+ std::vector<PHINode*> &PNs = I->second;
+ assert(!PNs.empty() && "Empty PHI node list??");
+
+ // Only do work here if there the PHI nodes are missing incoming values. We
+ // know that all PHI nodes that were inserted in a block will have the same
+ // number of incoming values, so we can just check any PHI node.
+ PHINode *FirstPHI = PNs[0];
+ if (Preds.size() != FirstPHI->getNumIncomingValues()) {
+ // Ok, now we know that all of the PHI nodes are missing entries for some
+ // basic blocks. Start by sorting the incoming predecessors for efficient
+ // access.
+ std::sort(Preds.begin(), Preds.end());
+
+ // Now we loop through all BB's which have entries in FirstPHI and remove
+ // them from the Preds list.
+ for (unsigned i = 0, e = FirstPHI->getNumIncomingValues(); i != e; ++i) {
+ // Do a log(n) search of teh Preds list for the entry we want.
+ std::vector<BasicBlock*>::iterator EntIt =
+ std::lower_bound(Preds.begin(), Preds.end(),
+ FirstPHI->getIncomingBlock(i));
+ assert(EntIt != Preds.end() && *EntIt == FirstPHI->getIncomingBlock(i)&&
+ "PHI node has entry for a block which is not a predecessor!");
+
+ // Remove the entry
+ Preds.erase(EntIt);
+ }
+
+ // At this point, the blocks left in the preds list must have dummy
+ // entries inserted into every PHI nodes for the block.
+ for (unsigned i = 0, e = PNs.size(); i != e; ++i) {
+ PHINode *PN = PNs[i];
+ Value *NullVal = Constant::getNullValue(PN->getType());
+ for (unsigned pred = 0, e = Preds.size(); pred != e; ++pred)
+ PN->addIncoming(NullVal, Preds[pred]);
+ }
+ }
+ }