I'm using MPLAB X and XC8 to compile a simple project for the PIC16F886. To manipulate the GPIOs, what I'm doing is
#define gpio_ra1(b) (b ? porta |= 0x02 : (porta &= ~(0x02))) and then letting the compiler do its constant propagation and whatever so that the expressions gpio_ra1(true) and gpio_ra1(false) can be compiled to a single bcf or bsf instruction. Works great on SDCC, but, at least in the case where b evaluates to false, such as in the statement gpio_ra1(0), XC8 produces the following buffoonery:
movlw 253 ; the relevant bit is now 0 movwf ??random_local_variable ; why is the compiler keeping a copy of this? movf ??random_local_variable,w ; why is the compiler reloading the value it just saved? bcf 3,5 ; banksel the gpio ports andwf 6,f ; now bring the gpio pin low I'm not sure what the XC8 compiler is doing with random_local_variable; this variable is never used outside of sequences like this, meaning it's never meaningful to read this variable. But my biggest concerns with the generated code are basically
is the write actually atomic? When I use this on port B it interferes with the in-circuit debugger
the whole sequence of instructions can just be replaced with
bcf 6,1.does XC8 actually provide an intrinsic you're "supposed to" use?
x=gpio_ra1(true)- and then the expectation would be thatxwill receive the value of the evaluated expression (that isporta |= 0x02). For that reason the compiler wants to "keep" this value. And looks like it is not optimizing well enough to understand you don't need this value. I suggest to replace the macro withstatic inline voidfunction (withif/elseconstruct) \$\endgroup\$