A general version of the Morse-Sard theorem