Will inline function avoid external condition? - c++

I want to confirm if a certain kind optimization that came to my mind is possible.
// test.h
class Test
{
public:
static void Main();
private:
__forceinline static bool func1()
{
return ((externalCond1 && externalCond2) ? true : false);
}
}
// test.cpp
#include "test.h"
void Test::Main()
{
if(func1() == true)
{
//Do something
}
}
Would the condition at Main be optimized away thanks to the inlined func1, and prevent it from actually being tested? (resulting in only testing the conditions within func1).
This is only an example code. But, since my real inlined function is about that short anyways, I would simply copy the conditions within func1 to all places that wanted to call this function, if it turns out that this optimization is impossible.
Finally, I would like to know (only if the optimization is possible) whether it would simply be a case of the "Return Value Optimization" paradigm.

If the __forceinline attribute is honored, your code is equivalent to
void Test::Main()
{
if (((externalCond1 && externalCond2) ? true : false) == true)
{
//Do something
}
}
If your conditions are external in the sense of being variables external to this compilation unit, then they cannot be optimized away as their values are unknown at compile-time.

Related

Is it possible to detect if a function is called at compile time

I'm developing a C++ library, there are two functions: func1 and func2.
I want to generate an compile-time error if developer forgets to call func1 before calling func2:
This will be OK:
func1();
func2(); // OK
But this would fail:
func2(); // ERROR, you forget to call func1()
Of course, it's very easy to generate a runtime error but I would like to generate a compile-time error.
I've tried as below but it's not working because I can't modify a constexpr variable:
static constexpr bool b {false};
void func1() {
b = true; // ERROR!
}
typename<std::enable_if_t<b == true>* = nullptr>
void func2() {}
I'm not very good at metaprogramming. I want to know if it's possible to generate a compile-time error in this case.
Make temporal coupling explicit:
make func1 return a type which should be consumed by func2:
struct func1_result {
// Possibly constructors private, and friendship to `func1`.
//...
};
func1_result func1();
void func2(const func1_result&);
So you cannot call func2 without creating first func1_result (returned by func1).
It is not possible at least in corner cases. Look at the following code (headers and test for scanf return value omitted for brievety):
int main() {
int code;
printf("Enter code value: ");
scanf("%d", &code);
if (code > 0) func1();
func2(); // has func1 be called ?
return 0;
}
Here, even the best static analysis tool will be unable to state whether func1 is called before func2 because it depends on a value which will only be known at runtime. Ok, this is a rather stupid example, but real world programs often read their config data at run time and that config can change even part of their initialization.

C/C++ optimizing away checks to see if a function has already been run before

Let's say you have a function in C/C++, that behaves a certain way the first time it runs. And then, all other times it behaves another way (see below for example). After it runs the first time, the if statement becomes redundant and could be optimized away if speed is important. Is there any way to make this optimization?
bool val = true;
void function1() {
if (val == true) {
// do something
val = false;
}
else {
// do other stuff, val is never set to true again
}
}
gcc has a builtin function that let you inform the implementation about branch prediction:
__builtin_expect
http://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
For example in your case:
bool val = true;
void function1()
{
if (__builtin_expect(val, 0)) {
// do something
val = false;
}
else {
// do other stuff, val is never set to true again
}
}
You should only make the change if you're certain that it truly is a bottleneck. With branch-prediction, the if statement is probably instant, since it's a very predictable pattern.
That said, you can use callbacks:
#include <iostream>
using namespace std;
typedef void (*FunPtr) (void);
FunPtr method;
void subsequentRun()
{
std::cout << "subsequent call" << std::endl;
}
void firstRun()
{
std::cout << "first run" << std::endl;
method = subsequentRun;
}
int main()
{
method = firstRun;
method();
method();
method();
}
produces the output:
first run subsequent call subsequent call
You could use a function pointer but then it will require an indirect call in any case:
void (*yourFunction)(void) = &firstCall;
void firstCall() {
..
yourFunction = &otherCalls;
}
void otherCalls() {
..
}
void main()
{
yourFunction();
}
One possible method is to compile two different versions of the function (this can be done from a single function in the source with templates), and use a function pointer or object to decide at runtime. However, the pointer overhead will likely outweigh any potential gains unless your function is really expensive.
You could use a static member variable instead of a global variable..
Or, if the code you're running the first time changes something for all future uses (eg, opening a file?), you could use that change as a check to determine whether or not to run the code (ie, check if the file is open). This would save you the extra variable. Also, it might help with error checking - if for some reason the initial change is be unchanged by another operation (eg, the file is on removable media that is removed improperly), your check could try to re-do the change.
A compiler can only optimize what is known at compile time.
In your case, the value of val is only known at runtime, so it can't be optimized.
The if test is very quick, you shouldn't worry about optimizing it.
If you'd like to make the code a little bit cleaner you could make the variable local to the function using static:
void function() {
static bool firstRun = true;
if (firstRun) {
firstRun = false;
...
}
else {
...
}
}
On entering the function for the first time, firstRun would be true, and it would persist so each time the function is called, the firstRun variable will be the same instance as the ones before it (and will be false each subsequent time).
This could be used well with #ouah's solution.
Compilers like g++ (and I'm sure msvc) support generating profile data upon a first run, then using that data to better guess what branches are most likely to be followed, and optimizing accordingly. If you're using gcc, look at the -fprofile-generate option.
The expected behavior is that the compiler will optimize that if statement such that the else will be ordered first, thus avoiding the jmp operation on all your subsequent calls, making it pretty much as fast as if it wern't there, especially if you return somewhere in that else (thus avoiding having to jump past the 'if' statements)
One way to make this optimization is to split the function in two. Instead of:
void function1()
{
if (val == true) {
// do something
val = false;
} else {
// do other stuff
}
}
Do this:
void function1()
{
// do something
}
void function2()
{
// do other stuff
}
One thing you can do is put the logic into the constructor of an object, which is then defined static. If such a static object occurs in a block scope, the constructor is run the fist time that an execution of that scope takes place. The once-only check is emitted by the compiler.
You can also put static objects at file scope, and then they are initialized before main is called.
I'm giving this answer because perhaps you're not making effective use of C++ classes.
(Regarding C/C++, there is no such language. There is C and there is C++. Are you working in C that has to also compile as C++ (sometimes called, unofficially, "Clean C"), or are you really working in C++?)
What is "Clean C" and how does it differ from standard C?
To remain compiler INDEPENDENT you can code the parts of if() in one function and else{} in another. almost all compilers optimize the if() else{} - so, once the most LIKELY being the else{} - hence code the occasional executable code in if() and the rest in a separate function that's called in else

how to know if a function was called from an specific function c++

I was wondering if is there a way to know if a function was called from other specific function.
doc(){
foo();
}
bar() {
doc();
}
foo() {
if (bar in the callStack ) { /* do this */}
}
Thanks!!
You can't do that without using many platform-specific hacks. A debugger will give you that info, but in general, you can't access the stack without using ASM hackery in C++.
If you have to do that, you're doing something wrong with your design. What are you trying to do so we can help?
Not that it's a good idea or good design, but of course you could use another global flag, like:
doc(){
foo();
}
int inBar = 0;
bar() {
inBar = 1;
doc();
inBar = 0;
}
foo() {
if (inBar) { /* do this */}
}
You should use a library that suits your compiler.
For GCC, you can think of Backtraces. This one is based on GCC builtins c/c++: call stack v.2.
For Visual C I heard about StackWalk64, but never used it myself.
You can also, of course, make your own "traces", but I think it is not what you want.
You can modify bar() to set a global bool to true on entry and false on exit.
Testing the bool in foo() will tell you if you in the bar() call stack.
namespace {
bool test_bar = false;
}
void bar( ) {
test_bar = true;
// do stuff
test_bar = false;
}
If you need the above to work in a multi_threaded environment, then the global bool will have to be thread local (using something like boost::thread_specific_ptr)
This sort of construct should only be used for tracing race conditions that are hard to catch in a debugger, it's a quick and dirty tool, other uses indicate a poor design.
how to know if a function was called from an specific function c++
You can't do that. However, you can add boolean argument to the function
foo(bool calledFromBar = false) {
if (calledFromBar) { /* do this */}
}
And set this flag from bar. However, this will cause another problem - nothing will stop any other function from setting the flag.
I think this (additional problem) can be fixed this way:
class BarFlag{
private:
bool flag;
protected:
friend void doc();
BarFlag(bool flag_)
:flag(flag_){
}
public:
inline operator bool() const{
return flag;
}
BarFlag()
:flag(false){
}
}
void foo(BarFlag flag = BarFlag()){
if (flag){/*do it*/}
}
//somewhere else
void doc(){
foo(BarFlag(true));
}

How to make sure a function is only called once

Suppose I have a function named caller, which will call a function named callee:
void caller()
{
callee();
}
Now caller might be called many times in the application, and you want to make sure callee is only called once. (kind of lazy initialization), you could implement it use a flag:
void caller()
{
static bool bFirst = true;
if(bFirst)
{
callee();
bFirst = false;
}
}
My opinion for this is it needs more code, and it needs one more check in every call of function caller.
A better solution to me is as follow: (suppose callee returns int)
void caller()
{
static int ret = callee();
}
But this can't handle the case if callee returns void, my solution is using the comma expression:
void caller()
{
static int ret = (callee(), 1);
}
But the problem with this is that comma expression is not popular used and people may get confused when see this line of code, thus cause problems for maintainance.
Do you have any good idea to make sure a function is only called once?
You could use this:
void caller()
{
static class Once { public: Once(){callee();}} Once_;
}
Thread-safe:
static boost::once_flag flag = BOOST_ONCE_INIT;
boost::call_once([]{callee();}, flag);
You could hide the function through a function pointer.
static void real_function()
{
//do stuff
function = noop_function;
}
static void noop_function()
{
}
int (*function)(void) = real_function;
Callers just call the function which will do the work the first time, and do nothing on any subsequent calls.
Your first variant with a boolean flag bFirst is nothing else that an explict manual implementatuion of what the compiler will do for you implictly in your other variants.
In other words, in a typical implementation in all of the variants you pesented so far there will be an additional check for a boolean flag in the generated machine code. The perfromance of all these variants will be the same (if that's your concern). The extra code in the first variant might look less elegant, but that doesn't seem to be a big deal to me. (Wrap it.)
Anyway, what you have as your first variant is basically how it is normally done (until you start dealing with such issues as multithreading etc.)
Inspired by some people, I think just use a macro to wrap comma expression would also make the intention clear:
#define CALL_ONCE(func) do {static bool dummy = (func, true);} while(0)

What are these c++ statements doing

void useproxynum ( ) { bUseProxy = true; return; };
void useacctnum ( ) { bUseProxy = false; return; };
Can anyone give me some insight into what these c++ statements are doing? There are in a header file.
bUseProxy is defined above
bool bUseProxy;
I'm trying to figure out what useproxynum is (method call?) and I'm also trying to figure out how to find the code behind it.
This is in Visual Studio 6.
They are inline method definitions. The return statements are extremely unnecessary.
If it were me, i'd replace that with this:
void useNum(bool proxy) { bUseProxy = proxy; }
Those are not statements. Those are 2 methods (seems to be inline). One of them just sets true to bUseProxy variable the other sets false. Thats it.
They are both methods. The lines between the { } are the code. These are inlined methods and don't have a separate implementation in a .cpp file.
You can call useproxynum() in your code, and it will cause the bUseProxy value to be set to true.
Or, you can call useacctnum() in your code and it will cause bUseProxy to be false.
This bUseProxy is probably used somewhere else.
void doSomething(int id) {
if(bUseProxy) {
lookupWithProxy(id);
}
else {
lookupWithAccNum(id);
}
}
It's worth noting that the return; statements are kind of silly - reaching the end of the function block will cause the function to return all by itself.
"Trying to figure out the code behind it" ... no no, the code is in front of it =)
they are inline methods.
when called, they set the value of the boolean, then return.