Another surprisingly simple optimization missed.


Some surprising compiler stuff with a weird solution:
Here the "disassembly" of an intialization routine. It just assigns values to elements of two arrays.

It's not obvious but the first variables, enable_moon, reverse_modes etc are actually macro aliases to elements in a single array, OPT_ARRAYs. You can see the first LDI to R30 and R31 (Z) loads the array address. the R24 loads the value to set. Then the value is saved to Z+N, where N is different for each array element. That's basically ok... (for anyone looking carefully, R1 always contains 0, which is what most of those are being set to).


00000095 e2.e6 LDI R30,0x62 Load immediate
00000096 f0.e0 LDI R31,0x00 Load immediate
00000097 85.e5 LDI R24,0x55 Load immediate
00000098 80.87 STD Z+8,R24 Store indirect with displacement
567: enable_moon = INIT_ENABLE_MOON;
00000099 13.82 STD Z+3,R1 Store indirect with displacement
574: reverse_modes = INIT_REVERSE_MODES;
0000009A 14.82 STD Z+4,R1 Store indirect with displacement
579: memory = INIT_MEMORY;
0000009B 12.82 STD Z+2,R1 Store indirect with displacement
582: offtim3 = INIT_OFFTIM3;
0000009C 16.82 STD Z+6,R1 Store indirect with displacement
589: muggle_mode = INIT_MUGGLE_MODE;
0000009D 11.82 STD Z+1,R1 Store indirect with displacement
603: overrides[5]=GROUP_SELECT_MODE;
0000009E ad.e6 LDI R26,0x6D Load immediate
0000009F b0.e0 LDI R27,0x00 Load immediate
000000A0 8e.ef LDI R24,0xFE Load immediate
000000A1 15.96 ADIW R26,0x05 Add immediate to word
000000A2 8c.93 ST X,R24 Store indirect
000000A3 15.97 SBIW R26,0x05 Subtract immediate from word
605: overrides[7]=TEMP_CAL_MODE;
000000A4 8d.ef LDI R24,0xFD Load immediate
000000A5 17.96 ADIW R26,0x07 Add immediate to word
000000A6 8c.93 ST X,R24 Store indirect
614: modegroup = INIT_MODEGROUP;
000000A7 11.86 STD Z+9,R1 Store indirect with displacement
616: maxtemp = INIT_MAXTEMP; // temperature step-down threshold, each number is roughly equal to 4c degrees
000000A8 88.e5 LDI R24,0x58 Load immediate
000000A9 82.87 STD Z+10,R24 Store indirect with displacement
618: mode_idx=0; // initial mode
000000AA 61.2c MOV R6,R1 Copy register
1542: eepos=0;
000000AB 71.2c MOV R7,R1 Copy register

The Z register (R30 and R31) can store to an address (array pointer) plus a displacement (array offset), those instructions like Z+8.

.

Z is in use already and will be used again, so isn't used for the overrides array, which uses X instead. X cannot do store with displacement. So it loads the 0 position, and then it loads the offset for each element, and then it adds them together. And then it stores. But the zero and offsets are compile time constants, so why doesn't the compiler just compute the address of each element and load that instead of loading two different offsets and performing a sum? This is pretty surprising.


Worse, after adding 5 to write the 5th (ok 6th) element it subtracts 5 back off to reset the array pointer, and then adds 7. Really? The compiler couldn't at least figure out to just add 2 instead? I guess after the first error there's no reason to expect better.

But, assuming there's some good reason for all this, why doesn't it at least just move the overrrides initialization to the end where it can be done with Z? I mean these optimizing compilers re-arrange our code whenever we don't want them to. It's amazing how many discussions there are about getting interrupts to turn on and off when you want them to, and basically no guarantees they will, but it doesn't reorder this?

So I did exactly that. I moved those lines to the end. And then it did use Z, and saved 10 bytes! Whoohoo. (but this is just one thing I happened to notice). This makes the code organization a little uglier though.

Sometimes I'm amazed at what the optimizations can do. Sometimes I'm irritated, and sometimes like this I'm just very unimpressed.

Another place I just noticed to save a few bytes:

If you build up a register like

DDRB=0x00;

#ifdef PWN1_PIN

DDRBB |=(1<< PWM1_PIN);

#endif

#ifdef PEM2_PIN

DDRBB |=(1<<PWM2_PIN):

#endif

...

The optimizer cannot combine the writes. It shouldn't. Those are volatile registers.

What you can do is :

t_DDRB=0x00;

#ifdef PWN1_PIN

t_DDRB |=(1<< PWM1_PIN);

#endif

#ifdef PEM2_PIN

t_DDRB |=(1<<PWM2_PIN):

#endif

DDRB=t_DDRB;

And the compiler is free to calculate t_DDRB and then optimize it out, and produce one assign to DDRB as you only asked for one. I haven't tested yet, but it certainly should do this and is usually pretty aggressive about this type of optimization.

Great work, Flintrock! It’s good having you around!

No one could argue with your thoughts here David. :beer:

Thanks guys, not sure anyone cares, but who knows little things someone might find interesting or useful sometime.

The |= thing ends up saving a bunch of bytes, about 50 on bistro HD for about two or three sets of cases like that (all cases caused by me in the first place, so just improving on my own issues here)

I'm a bit surprised actually. Those I/O registers are bitwise accessible, so those should not have been read/modify/writes, but just a bit set. The assembly now looks great, but I didn't look before I did it, and now I wonder if it was doing something else wrong. There was a little more to it on one or two cases, so who knows. I probably won't undo it just to see.

Anyway, lesson is it pays to use local temp variables for intermediate calculations on volatile registers (or volatile anything). (usually) For asynchronous (interrupt) stuff, this is probably the right way to do things anyway. You want a deliberate commit point for your communication variables.

I'm just going to update this post with a couple more, they were already things I was using, but

inline: (basic)

This one is fairly well known, but details can be surprising to people new to it. Declaring a function inline prevents the call to it and the register protection steps within the prelogue and prologue. However, if the function is used many times, the code gets repeated so that's wasteful. It's best used for functions only used once.

The compiler is supposed to consider inline as a hint and make intelligent choices about when to inline. However it seems very bad at making this determination. So going through and compiling with each function inlined and not, can find a few bytes. In reality you'd probably need to try every combination since as soon as you inline one function you're using registers that potentially affect the optimization of inlining another. Generally though just trying each one is pretty good, and can save a few bytes.

This unfortunately restricts code organization because inline functions must be included or in the same file, not in separate compilation units.

Register variables: (intermediate, dangerous if you don't read the fine print here)

register uint8_t mode_idx asm("r6");

You can attach a global variable to a working register like that. In that case register 6. This prevents the need to move the variable in and out of memory, saving instructions. However it uses up valuable working registers. Generally on attiny you can use any register from R2 through R7 as any subroutine or pre-compiled library that uses these registers is required by the compiler convention to save and restore these. Try this on a FEW very highly used variables, and try different registers. It might save 20 bytes. This is pretty safe so long as you don't use these variables in interrupts.

That said, if you're going to access these in an interrupt, you need to make sure your included libraries aren't using them since their values may be different during those library calls and an interrupt may hit during those calls. Using a global register in an interrupt should be considered advanced and dangerous, and could be argued to be a bad idea for future development since inclusion of new libraries could unexpectedly break the code. But this is embedded code and hacks to make things possible are sometimes the reality.

Naked interrupts: (advanced but can be very safe if done right)

Normally an interrupt has no idea when it will occur, so it must save all working registers to the stack and restore them at the end. A smart compiler at least only saves the ones actually used in the interrupt, but gcc has a minimal template for this that is always applied and isn't always needed. The best is if you can make your interrupts not touch any registers. Then you declare them naked. However you have to know how the C translates to ASM and how the asm instructions affect registers, all documented in the instruction set manual. You also need to include your own "reti" instruction in asm since naked functions don't even include a return statement at the end (and a C return statement is incorrect for interrupts).

In particular bit sets on memory below 32 can be done without storing the value in a register before moving it out. SBI and CBI asm commands. The GPIOR registers are unused registers in that address space and you can allocate single bits to variable names to get more use of these limited bits.

So your interrupt can hit, read or set a status bit, use that to maybe decide to change a pin state (also SBI) and exit without touching a register. Then you get to declare it naked. See the PWM4 interrupt in bistro-HD for an example and look for the bit variable definition for how to setup the bitfield variable. This is pretty safe so long as you know what the assembly commands are doing. It that case it's written in inline assembly to guarantee this is controlled.

One thing to be careful of is the status register. This is changed after many commands and is used for example for comparissons. It may be necessary to at "in, push" and "pop, out" the status register if any of the commands used change it... and then also the temp register used to do that. It can be diminishing returns quickly. However this a great thing about the sbi cbi trick. They so not modify the status register.

Another way to pass data to the interrupt without clobbering registers is to use a global register as described above, but note the dangers mentioned there. Because it is an interrupt, you must be sure that register isn't being used by any linked library that might be interrupted.

I may flesh this out with some detail later and possibly more tricks.