Index: llvm/lib/Transforms/Utils/DemoteRegToStack.cpp =================================================================== --- llvm/lib/Transforms/Utils/DemoteRegToStack.cpp +++ llvm/lib/Transforms/Utils/DemoteRegToStack.cpp @@ -92,8 +92,19 @@ BasicBlock::iterator InsertPt; if (!I.isTerminator()) { InsertPt = ++I.getIterator(); + // Don't insert before PHI nodes or landingpad instrs. for (; isa(InsertPt) || InsertPt->isEHPad(); ++InsertPt) - /* empty */; // Don't insert before PHI nodes or landingpad instrs. + if (isa(InsertPt)) + break; + if (CatchSwitchInst *CSI = dyn_cast(InsertPt)) { + for (BasicBlock *Handler : CSI->handlers()) { + new StoreInst(&I, Slot, &*Handler->getFirstInsertionPt()); + } + if (CSI->hasUnwindDest()) { + new StoreInst(&I, Slot, &*CSI->getUnwindDest()->getFirstInsertionPt()); + } + return Slot; + } } else { InvokeInst &II = cast(I); InsertPt = II.getNormalDest()->getFirstInsertionPt(); @@ -138,14 +149,27 @@ // Insert a load in place of the PHI and replace all uses. BasicBlock::iterator InsertPt = P->getIterator(); - + // Don't insert before PHI nodes or landingpad instrs. for (; isa(InsertPt) || InsertPt->isEHPad(); ++InsertPt) - /* empty */; // Don't insert before PHI nodes or landingpad instrs. - - Value *V = - new LoadInst(P->getType(), Slot, P->getName() + ".reload", &*InsertPt); - P->replaceAllUsesWith(V); - + if (isa(InsertPt)) + break; + if (CatchSwitchInst *CSI = dyn_cast(InsertPt)) { + // We need a separate load before each actual use of the PHI + SmallVector users; + for (User *U : P->users()) { + Instruction *User = cast(U); + users.push_back(User); + } + for (Instruction *User : users) { + Value *V = + new LoadInst(P->getType(), Slot, P->getName() + ".reload", User); + User->replaceUsesOfWith(P, V); + } + } else { + Value *V = + new LoadInst(P->getType(), Slot, P->getName() + ".reload", &*InsertPt); + P->replaceAllUsesWith(V); + } // Delete PHI. P->eraseFromParent(); return Slot;