Heavy-quark production in gluon fusion at two loops in QCD