Superfluous Stack and Status Setting
Last time we looked at every one of the whopping 70 bytes of extra code that had accreted around our tiny little 6 byte program. Now we are going to start figuring out what we can get rid of.
We saw this in the block of initialization code added at the beginning of our program…
2c: 1f be out 0x3f, r1 ; 63
…which is setting the Status Register (0x3f) to zero. I wasn’t sure why you would need that, and it turns out that you don’t. The data sheet for this chip explicitly states that this register will always be initialized to zero on reset (page 10). I looked at a few others (including the ATMEGA328 used in the Ardunio), and these chips also make the same guarantee.
As long as the chip is coming out of a rest, the Status Register will already be zero when we hit this line, and the only way I can see that we could end up here is via a reset, so this code is redundant. (The one exception is the Bad Interrupt Vector we saw last time, but that needs to go also!)
Next lets look at the code that initializes the Stack Pointer again…
2e: cf e5 ldi r28, 0x5F ; 95 30: d1 e0 ldi r29, 0x01 ; 1 32: de bf out 0x3e, r29 ; 62 34: cd bf out 0x3d, r28 ; 61
Again, according to the chip specifications this code also appears to be redundant. The Stack Pointer (0x3e) is guaranteed to be initialized to point to the top of SRAM after any reset. I even tested this on an actual chip (harder than it sounds!), and it really does get automatically set no matter how I reset the chip (power, WatchDog, reset pin).
The code that sets the other register (0x3d) is just plain wrong for this processor. The spec shows this location as “reserved” (page 255) and “reserved I/O memory addresses should never be written” (page 256).
So here are 10 bytes of unnecessary code that we can remove safely remove from any and every ATTINY4313 program (any many others) complied by avr-gcc. Think of the millions and millions of AVRs all around the world saddled with these extra 5 cycles of effort every time they reset!
How does something like this happen? The avg-gcc is a massive software project that supports dozens of processors. It is a huge amount of work to create and maintain something like this and the people who work on it do an amazing job. Besides taking up a tiny bit of extra space and time, these superfluous bytes do not make any working programs crash, so finding and fixing stuff like this is very, very low on the the priority list.
But to those of us (me?) obsessed with maximal minimalism, even 1 extra byte is too much to swallow.
Tune in next time to see how these bytes – and more -are banished in search of the smallest program. We still have 54 more bytes to loose!