Reputation: 3975
Is there a way to tell g++
more about a type, function, or specific variable (other than attributes) that I might know is safe to preform.
Example:
TurnLedOn();
TurnLedOn();
Only the first function actually turns the LED on the second function does not actually do anything....so would it be possible to tell g++
more about the function so that it gets rid of a second call if it knows that the LED is on (because it knows that a corresponding TurnLedOff()
function has not been called)....
The reason I do not want to use g++
attributes is because I want to arbitrarily define optimizations, which is really not possible with attributes (and I believe the optimization I am trying here is not actually possible to begin with using attributes)
Upvotes: 0
Views: 69
Reputation:
Contrary to your thinking, the answer by @immibis is what you were expecting.
This way to describe the complex behavior of the function TurnLedOn
(i.e. needn't be called twice in a row unless unlocked by some other action) is indeed how you tell the compiler to perform this "optimization".
Could you imagine other annotations such as
#pragma call_once_toggle_pair(TurnLEDOn, TurnLEDOff)
with innumerable variants describing all your vagaries ?
The C++ language has enough provisions to let you express arbitrarily complex situations, please don't add yet a layer of complexity on top of that.
Upvotes: 0
Reputation: 27577
These are optimisations you need to code. Such as:
class LedSwitch {
bool isOn{false};
public:
inline void turnLedOn(){
if (!isOn) {
isOn = true;
// ...
}
}
// ...
}
// ...
If the code inlines then the compiler might then notice the bool negated in the second hardcoded sequential call, but why do that in the first place?
Maybe you should revisit design if things like this are slowing down your code.
Upvotes: 4
Reputation: 58888
One possibility is to make it so that the second TurnLedOn
call does nothing, and make it inline and declare it in a header file so the compiler can see the definition in any source file:
extern bool isLedOn; // defined somewhere else
inline void TurnLedOn()
{
if(!isLedOn)
{
ActuallyTurnLedOn();
isLedOn = true;
}
}
Then the compiler might be able to figure out by itself that calling TurnLedOn
twice does nothing useful. Of course, as with any optimization, you have no guarantees.
Upvotes: 2