Reputation: 155
How I can say to the compiler how to optimize something or what some call to function.
I mean like create allocate method and let the compiler optimize it as it optimize it with malloc
or new
.
Or like if somewhere in the code the function X is called and it's return value is not used then delete this call. (Function from .lib that the compiler don't know a piece about it)
There are options for this?
For example:
auto val=X(); //Use the return value
X(); //Don't use
auto t=allocate<T>(); //Allocate on heap
t->Show(val); //Run single function and don't use it's pointer somewhere (Save it after the function is exit)
And optimize it to:
X(); //First line, just call it
T().Show(val); //Combines third and fourth lines, Allocate on stack and run the single function
If you asking 'why you need this?' I am creating programming language with my own GC and heap. (And lot of things too)
It translates to C++ then I don't want to optimize the code while translate it. (It's gonna be a pain) Because I can call functions randomly in places. (I can't detect if their values are used or not)
Upvotes: 1
Views: 213
Reputation: 34563
Optimization is compiler-specific, so you'll need to look in your compiler's documentation to see what optimization "hints" it allows you to put in code. For example, here are some of GCC's function attributes:
malloc
attribute tells the compiler that if the function returns a non-null pointer, it's always a "new" area of memory, not another pointer to something that's already been allocated. You'd probably want to use this on a function that wraps the real malloc()
.const
attribute (different from the ordinary const
keyword) says that the function's return value depends solely on its arguments and has no side effects, so it's safe for the compiler to eliminate duplicate calls with the same arguments.noreturn
attribute tells the compiler that a function never returns; you'd use this on functions that terminate the program, like C's exit()
.Attributes go on the declaration of a function, typically in a header file, so you can use them even if the function's implementation is in a compiled library that'll be linked in later. But remember that function attributes are promises from you to the compiler: if you declare a function with the noreturn
attribute, for example, and then implement it with code that actually can return, strange things may happen at runtime when it does.
You can also use function attributes to help with correctness checking:
nonnull
attribute tells the compiler that certain (pointer) arguments aren't supposed to be null, so it can issue warnings if it detects that they might be.format
argument tells the compiler that the function takes a format string like C's printf()
, so it can check that the types of the variadic arguments match the corresponding format codes in the format string. (For example, you shouldn't write "%s
" in the format string but then pass an integer as its value.)Upvotes: 5