Provably Correct Automatic Sub-Differentiation for Qualified Programs