Products > Programming

Efficient C Code for ARM Devices

<< < (3/3)

Yes, but if the compiler can't see the arguments it has to generate code for the if statement.


--- Quote from: kamtar on October 09, 2019, 03:53:28 pm ---maybe a stupid question but wouldn't this allow the compiler to do the same optimization?  ???

--- Code: ---void f(int *x, int n)
    if (((n > 0) && ((n&7)==0)) != true)

    int i;
    for (i = 0; i < n; i++)  {
--- End code ---

--- End quote ---

Maybe you haven't read the whole thread, because this is exactly what some of us have said (I being first when saying "if you actually actively CHECK for a condition, the compiler will not only generate code to check it's true, but will also have all hints it needs to optimize the code when it is".

And most of us agree that the ARM optimization hint is a VERY slippery thing.

Now, to be fair, many of us have already encountered the case when you had to write a function that should be very efficient, and in which you didn't want to check for extra conditions each time it's executed, due to the extra overhead (in that case, you'd make sure the conditions always hold true when calling the function). In that case, if again you chose NOT TO actively check parameters, giving the compiler an opportunity  to better optimize the code can be interesting, which this "assume" directive is for. It's always risky, but I'd venture many, if not most of us, have done that at least once (silently assuming parameter values are in a given range).

If you do that correctly, the calling code should still include ways of checking the parameters from a higher level, or at least only generate parameters that meet the expected ranges. There again, the compiler WILL have the info if it's not too dumb. Of course, for that to work properly, you should usually put said function in the same source file as where it's called. If it can be called externally, then the compiler will usually not do any kind of cross-file static analysis AFAIK. So my rule and advice here is that if you ever need to write such a function that doesn't check parameters at run-time for optimization reasons, only do that with local functions (local to one source file, declared static).

We're in a world where we try to keep as much little bug inducing things away from the programmer. And you come around with this  :P
Oh well, I'm sure someone has a need for this.
I always try to avoid tricks like this unless it's highly streamlined stuff that yields you something and isn't portable anyway. (eg: kernels, drivers)


[0] Message Index

[*] Previous page

There was an error while thanking
Go to full version