Re-apply r175688, with the changes suggested by Jakob in PR15320.