- // If we decided we need a spill, do it.
- // FIXME: Spilling this way is overkill, as it forces all uses of
- // the value to be reloaded from the stack slot, even those that aren't
- // in the unwind blocks. We should be more selective.
- if (NeedsSpill) {
- DemoteRegToStack(*Inst, true);
- ++NumSpilled;
- }
+ // Now go through the instructions which were spilled and replace their uses
+ // after a crossed invoke with a reload instruction.
+ for (SmallVectorImpl<std::pair<Instruction*, Instruction*> >::iterator
+ I = ReloadUsers.begin(), E = ReloadUsers.end(); I != E; ++I) {
+ Instruction *User = I->second;
+ AllocaInst *Slot = AllocaMap[*I];
+ assert(Slot && "A spill slot hasn't been allocated yet!");
+
+ if (PHINode *PN = dyn_cast<PHINode>(User)) {
+ // If this is a PHI node, we can't insert a load of the value before the
+ // use. Instead insert the load in the predecessor block corresponding to
+ // the incoming value.
+ //
+ // Note that if there are multiple edges from a basic block to this PHI
+ // node that we cannot have multiple loads. The problem is that the
+ // resulting PHI node will have multiple values (from each load) coming in
+ // from the same block, which is illegal SSA form. For this reason, we
+ // keep track of and reuse loads we insert.
+ DenseMap<BasicBlock*, Value*> Loads;
+ for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
+ if (PN->getIncomingValue(i) == I->first) {
+ Value *&V = Loads[PN->getIncomingBlock(i)];
+ if (V == 0)
+ // Insert the load into the predecessor block
+ V = new LoadInst(Slot, I->first->getName() + ".reload", true,
+ PN->getIncomingBlock(i)->getTerminator());
+
+ PN->setIncomingValue(i, V);
+ }
+ } else {
+ LoadInst *Reload = new LoadInst(Slot, Slot->getName() + ".reload", User);
+ User->replaceUsesOfWith(I->first, Reload);