How to generate high frequency clock with high stability from a microcontroller?
Your GPIO pins aren't able to change between low and high signal fast enough.

At 40 Mhz the period of a single cycle is 25 ns. Here is the definition of the slew rate of GPIO pins from document http://www.ti.com/lit/ds/spms376e/spms376e.pdf:



For a single cycle you need at one raising and one falling edge. 

As seen in the chart above in the best case that'll add up to 16.7ns (8-mA drive with slew rate control disabled). So in this case your pins will spend most of the time of the period slewing the signal up or down. And that's more or less what we're seeing on your oscilloscope picture as well.