Post-growth annealing and electron beam irradiation during cathodoluminescence were used to determine the chemical origin of the main optical emission lines in moderately and heavily Mg-doped GaN. The 3.27 eV donor-acceptor pair (DAP) emission line that dominates the emission spectrum in moderately Mg-doped (p-type) GaN was found to be strongly reduced by electron irradiation and of different chemical origin than the DAP at a similar energetic position in Si-doped (n-type) GaN. These results suggest that the acceptor responsible for the 3.27 eV DAP emission in Mg-doped GaN is Mg,and that the donor (20-30 meV) is hydrogen-related, possibly a (V-N-H) complex. This complex is dissociated either by electron irradiation or thermal annealing in N-2 or O-2 atmosphere. We found that upon electron irradiation, a deeper emission line (centered at 3.14 eV) emerged, which was assigned to a DAP consisting of the same Mg acceptor level and a deeper donor (100-200 meV) with a similar capture cross section as the donor in the 3.27 eV emission. Moreover, two different deep donor levels at 350+/-30 and 440+/-40 meV were identified as being responsible for,the blue band (2.8-3.0 eV) in heavily Mg-doped GaN. The donor level at 350+/-30 meV was strongly affected by electron irradiation and attributed to a H-related defect.