Gradient Guidance for Diffusion Models: An Optimization Perspective