How to generate programs with loops unrolled? [duplicate] - c++

This question already has an answer here:
Loop unrolling behaviour in GCC
(1 answer)
Closed 4 years ago.
I am trying to generate multiple programs from a given C/C++ program with loops unrolled. For example, I would like to convert something like this:
i = 0;
while (i < 5) {
printf("Hello");
i++;
}
to this:
i = 0;
printf("Hello");
i++;
while (i < 5) {
printf("Hello");
i++;
}
In the above example, I'd like to generate 5 programs each with a different number of loops unrolled. The compiler flags that I have looked at so far don't seem to generate a program but just optimize it. Is there any straightforward automated way of doing this?
Edit: I don't understand why this is being downvoted. The question linked as being a duplicate isn't relevant.

Is there any straightforward automated way of doing this?
This is an unusual requirement, as such I think you will have a really difficult time to find a tool that does this.
Without knowing what you are trying to achieve, what problem you are trying to resolve we can't give you a solution, other than manual unroll:
printf("Hello");
printf("Hello");
printf("Hello");
printf("Hello");
printf("Hello");

If the programs you want to change are all written by yourself and you know they're structure is simple, you may get along witha little magic of regular expressions.
For modifying arbitrary programs reliably, you must use a proper parser, detect constant for loops in the abstract syntax tree and then write back the modified syntax tree.

Related

Counter at Compile TIme [duplicate]

This question already has answers here:
Does C++ support compile-time counters?
(11 answers)
Closed 8 years ago.
I know this is a weird question, but I'm trying to find a way to analyze the code written by the user and collect some useful information that may be included in both "if" & "else" part.
Suppose I have an if-else statement,
counter = 0;
if( true )
++counter;
else
++counter;
is it possible that I can "enforce ++counter" to work and get "counter = 2" at compiler time? Template? Macro? Any other solution? Thanks in advance!
First of all, `counter' will never be 2. It will always be 1.
I'd say about 90% of current C++ compilers (running in "Release" mode") will recognize the invariant, and generate object code as if you had written:
counter = 0;
++counter;
Most will also go as far as
counter = 1;
However, such optimizations are not required by the Standard, so there is no way to "Force" a compiler to do them.
NOTE: The specifications for Java & C# do require compilers for those languages to recognize the invariant to do elide the if())

Late return value in C++

Today I did a funny mistake in my C++ code. I have a function with two arguments of type std::vector<int>::iterator& (i and j). Iterators should point to same vector. Function should return sum of two numbers in the vector, and move both iterators forward to j+1th position of vector:
int exp_func_add::evaluate(vector<int>::iterator& i, vector<int>::iterator& j) {
int result = *i + *j;
++j;
i = j;
return result;
}
First I wrote this code:
int exp_func_add::evaluate(vector<int>::iterator& i, vector<int>::iterator& j) {
++j;
i = j;
return (*i+*j); // <====== Oops !
}
We know that return statement returns control to caller. My question is why C++ standard does not define a late value return semantics? Let's call it late_return keyword:
int exp_func_add::evaluate(vector<int>::iterator& i, vector<int>::iterator& j) {
late_return *i+*j; // Hold return value but don't go back
// to the caller until leaving scope
++j;
i = j;
}
This question may get hundreds of downvotes (not constructive, blah blah). Though I would like to ask some questions:
Is there a way to simulate this behavior using macros or any other tricks?
Do this deserve an implementation or to be considered as a feature in next c++ standard?
Are there programming languages implementing similar feature?
Is there a way to simulate this behavior using macros or any other tricks?
Not really, though your first code sample is fairly idiomatic C or C++ code.The "assign a value to "result", and then have 'return result' as the last statement of the function is avery common pattern.
Do this deserve an implementation or to be considered as a feature in next c++ standard?
No, because it adds complexity without any clear benefit over the existing idiom. It'd add a whole bunch of edge cases to the language, too. Functions can have more than one return statement, so how so you handle multiple late_return statements? First one wins? Last one wins? Throw an exception? What about a code path that includes late_return and return?
Are there programming languages implementing similar feature?
The closest thing I can think of is constraints languages or logic languages like Prolog, where the "result" is produced as soon as all of the data necessary to produce it has been provided.
Is there a way to simulate this behavior using macros or any other tricks?
Yes, and you said it yourself: define a variable called ret and return it at the end. That's only one line more and it's a lot more clear what is going on when you get to the end of the function.
If I understand the question correctly you are essentially looking to do something like this:
return *i + *(++j, i=j, j-1);
The problem with this is that i may already be changed by the time we get to it. It will not necessarily (won't?) evaluate this statement left-to-right.
As other posters have mentioned this really doesn't provide any added benefit to the language, except maybe to save a line or two of code. That being said, it sounds to me like you want something like a reverse comma operator.
It doesn't exist, but the idea has been brought up here and here.
All in all, I think it adds significant complexity in a situation where it really is not needed. I don't see this as a bad question because it is always good to try and better understand how/why things work. I just don't think this particular use case warrants it.

How to store parsed function expressions for plugging-in many times?

As the topic indicates, my program needs to read several function expressions and plug-in different variables many times. Parsing the whole expression again every time I need to plug-in a new value is definitely way too ugly, so I need a way to store parsed expression.
The expression may look like 2x + sin(tan(5x)) + x^2. Oh, and the very important point -- I'm using C++.
Currently I have three ideas on it, but all not very elegant:
Storing the S-expression as a tree; evaluate it by recurring. It may
be the old-school way to handle this, but it's ugly, and I would
have to handle with different number of parameters (like + vs. sin).
Composing anonymous functions with boost::lambda. It may work nice,
but personally I don't like boost.
Writing a small python/lisp script, use its native lambda
expression and call it with IPC... Well, this is crazy.
So, any ideas?
UPDATE:
I did not try to implement support for parenthesis and functions with only one parameter, like sin().
I tried the second way first; but I did not use boost::lambda, but a feature of gcc which could be used to create (fake) anonymous functions I found from here. The resulting code has 340 lines, and not working correctly because of scoping and a subtle issue with stack.
Using lambda could not make it better; and I don't know if it could handle with scoping correctly. So sorry for not testing boost::lambda.
Storing the parsed string as S-expressions would definitely work, but the implementation would be even longer -- maybe ~500 lines? My project is not that kind of gigantic projects with tens of thousands lines of code, so devoting so much energy on maintaining that kind of twisted code which would not be used very often seems not a nice idea.
So finally I tried the third method -- it's awesome! The Python script has only 50 lines, pretty neat and easy to read. But, on the other hand, it would also make python a prerequisite of my program. It's not that bad on *nix machines, but on windows... I guess it would be very painful for the non-programmers to install Python. So is lisp.
However, my final solution is opening bc as a subprocess. Maybe it's a bad choice for most situations, however, it fits me well.
On the other hand, for projects work only under *nix or already have python as a prerequisite, personally I recommend the third way if the expression is simple enough to be parsed with hand-written parser. If it's very complicated, like Hurkyl said, you could consider creating a mini-language.
Why not use a scripting language designed for exactly this kind of purpose? There are several such languages floating around, but my experience is with lua.
I use lua to do this kind of thing "all the time". The code to embed and parse an expression like that is very small. It would look something like this (untested):
std::string my_expression = "2*x + math.sin( math.tan( x ) ) + x * x";
//Initialise lua and load the basic math library.
lua_State * L = lua_open();
lua_openmath(L);
//Create your function and load it into lua
std::string fn = "function myfunction(x) return "+my_expression+"end";
luaL_dostring( L, fn.c_str(), fn.size() );
//Use your function
for(int i=0; i<10; ++i)
{
// add the function to the stack
lua_getfield(L, LUA_GLOBALSINDEX, "myfunction");
// add the argument to the stack
lua_pushnumber(L, i);
// Make the call, using one argument and expecting one result.
// stack looks like this : FN ARG
lua_pcall(L,1,1)
// stack looks like this now : RESULT
// so get the result and print it
double result = lua_getnumber(L,-1);
std::cout<<i<<" : "<<result<<std::endl;
// The result is still on the stack, so clean it up.
lua_pop(L,1);
}

What is the difference between for(;;) and while(1)? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it?
I was wondering what is the difference between for(;;) and while(1) when both perform same function? Will there be any difference of speed of compilation
The difference with these is that many compilers will warn about while(true) ("constant expression used as loop expression"), while none I know of warn about for(;;).
They should generate the same code, though.
no functional difference at all, just a matter of taste.
With for, you can do this:
#define ever (; ;) // note the two happy faces? ;)
for ever { ... } // endless loop
Which is not possible with while.
Both will cause infinite loop unless
break is called explicitly.
Personally I prefer while(1), it's
more readable
No difference. I prefer the latter.
6 of one, 110 of the other.
The latter appears more concise.
No difference, unless you want to make use some kind counter later as below.
for (int i =0; i < 100; i++) {
// some code
}
Both are the same in C++. However, your post is tagged with c# and c++.
If you're using C#, you'll need to use while (true) {...}. Personally, I prefer the same in C++: numbers are used only when dealing with... well, numbers! When dealing with boolean values, true and false are used instead.
They both defines the exact same functional behavior and produce exactly the same IL code from C#.
I'm old-school, I still do the following:
#define TRUE 1
#define FALSE 0
while (TRUE) { /*--do something, mutley--* }

Infinite loops - top or bottom? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In the spirit of questions like Do your loops test at the top or bottom?:
Which style do you use for an infinite loop, and why?
while (true) { }
do { } while (true);
for (;;) { }
label: ... goto label;
while(true) {}
It seems to convey the meaning of the loop most effectively.
for (;;)
{
/* No warnings are generated about constant value in the loop conditional
plus it is easy to change when you realize you do need limits */
}
#define forever for(;;)
forever {
/*stuff*/
}
while(1)
{
//do it
}
That's how I roll.
I like to use the for(;;) approach because the MSVC++ compiler complains about while loop approach:
void main()
{
while(1) // test.cpp(5) : warning C4127: conditional expression is constant
{
}
for(;;)
{
}
}
I prefer while(1) or while(true) -- it's the clearest. do { } while(true) seems like needless obfuscation. Likewise, for(;;) can be confusing to people that have never seen it before, whereas while(true) is very intuitive. And there's absolutely no reason to do label: ... goto label;, it's just more confusing.
10 some l33t code
20 goto 10
I usually use for(;;) { } which I always think of as "for-ever".
Some languages offer a repeat { } construct which will natively loop forever. I find the for(;;) { } construct visually the most similar to this because it is so different from the normal for() construct. This is an important attribute for an infinite loop that while(1) { } doesn't really have.
Infinite tail-recursion ;)
It's somewhat compiler-dependant...
I use for (;;) in C-style languages and while true in languages that don't support that construct.
I learned the for (;;) method in K&R and it has always felt like idiomatic C to me.
Let the flaming begin...
If the loop is a true infinite loop (i.e. there is no break condition -- only an external event can terminate the thread's/process' execution), then I actually prefer the label and goto. Here's why:
First, the use of while, for, and do ... while, all imply that the loop might terminate. Even if the terminating condition is never achievable, the syntactical meaning of these constructs is that there is some termination condition.
Second, using a loop construct introduces an extra level of indentation. I hate indentation that's not necessary. It wastes valuable columnar real-estate.
Third, the only true infinite loop is the one that unconditionally jumps back to the beginning of the loop. Only goto fits that purpose exactly.
The truth is I don't really care that much about it. They all get the job done and most will result in the exact same assembly instructions anyway. However, the assembly that's generated will in all probability be an unconditional jump (if you're optimizer is worth a damn), which maps directly to which C construct, kids? That's right... your old friend goto.
When writing code for myself I use for(;;). Other people tend to be confused by its syntax and so for code that other people must see/use, I use while(true).
offtopic: if you think about what you are trying to express, you usually won't need an infinite loop.
for(;;);
Filler text.
for (;;) is what I usually see.
Infinite loops are a bad idea, but in practice that doesn't always hold up.
I prefer while(1) { } but make sure something within the loop can cause it to break out.
I usually use while() {}, but after learning that for(;;) {} isn't some sort of crazy invalid syntax, I'll be sure to use the more unique option.
Differentiates infinite loops from actual conditionals, you see.
I now prefer the "for (;;)" idiom because it seems to 'stick out' more. I used to use the "while (true)" idiom because I thought it expressed intent better, but I've switched over because I think the "for (;;)" idiom is well known enough to adequately express intent as well as I believe it's better by being more visible.
Kind of like how Stroustrup made the new casts in C++ purposefully ugly - so they stick out.