LLVM: null node in the leaf position of a callgraph - llvm

I am trying to iterate through a callgraph in a DFS way, and here is my code(simplified):
CallGraph CG = CallGraph(M);
for (auto IT = df_begin(&CG), EI = df_end(&CG); IT != EI; IT++) {
if(Function *F = IT->getFunction()){
dbgs() << "fun name " << F->getName() << "\n";
}else{
dbgs() << "fun address " << IT->getFunction() << "\n";
}
dbgs() << "distance " << IT.getPathLength() << "\n"
}
I got the printed result from the console like this:
fun address 0x0
distance 1
fun name s2n_alpn_send
distance 2
fun name s2n_calculate_stacktrace
distance 3
fun address 0x0
distance 4
fun name strlen
distance 3
fun name s2n_stuffer_write_uint16
distance 3
I wonder why the DFS goes to 0x0 with a distance of 4, why is there a null point in the leaf position?
Besides, I observed this because I was trying to collect all the functions that are being called by one function together, and I am doing this by iterating the DFS graph and collecting the functions in the same path. However, I found that there is some path/node missing compared to CG.dump().

nullptr the CallGraph can be either the ExtrenalCallingNode or the CallsExternalNode. This means that your function could be called from outside the Module or that it may call a function from outside the Module.

Related

Squaring numbers in consecutive order 0-9

I am extremely new to the coding world. I just have a basic question regarding this function that squares integers from 0-9. I understand most of what's going on until I get to
std::cout << i << " " << square << "\n";
i = i + 1;
I'm not too sure how that ends up causing the output to square the results in order from 0-9. Can someone explain the reasoning behind this line of code? Here is the code for this function.
#include <iostream>
int main() {
int i = 0;
int square = 0;
while ( i <= 9) {
square = i*i;
std::cout << i << " " << square << "\n";
i = i + 1;
}
return 0;
}
This code:
std::cout << i << " " << square << "\n";
i = i + 1;
Doesn't square anything. It is merely outputting the current square that has already been calculated, and then increments i for the next loop iteration.
The actual squaring happens here:
square = i*i;
So, the code starts at i=0, calculates square=0*0 and displays it, then sets i=1, calculates square=1*1 and displays it, then sets i=2, calculates square=2*2 and displays it, and so on until i exceeds 9, then the loop stops.
Lets start from beginning and what is happening, I will ignore first several lines and start at:
int i = 0;
int square = 0;
You see when you say int i; your compiler says I need to allocate bucket of memory to hold value for i. When you say i = 0 zero is put into that memory bucket. That is what is happening for square as well.
Now to loop
while ( i <= 9 ) {
square = i*i;
std::cout << i << " " << square << "\n";
i = i + 1;
}
So, lets ignore
square = i*i;
std::cout << i << " " << square << "\n";
for now we will come to it later.
So
while ( i <= 9 ) {
i = i + 1;
}
goes into the loop and gets value from i's bucket, adds 1 and puts new value into the i's bucket. So in first loop it will be i = 0 + 1, put 1 into i bucket. Second, i = 1 + 1 put 2 in, third i = 2 + 1 put 3.
So lets go back to square and its bucket.
square = i*i;
So first time we go into the loop i = 0 and square = 0 * 0 so compiler puts 0 into square's memory bucket. Next time it hits square i has been incremented to 1 so square = 1 * 1, thus compiler puts 1 into the bucket. Third time i is 2 so square = 2 * 2, and compiler puts 4 into the bucket. And so on till it i <= 9. When i hits 10 loop is not executed.
In comments you have stated that you do not know the difference between a math equation and an assignment statement. You are not alone.
I will try to explain, as an addition to existing answers, to provide a different angle.
First, two examples of math equations:
x = 1 +1
y+1 = x*2
To illustrate their meaning, let me point our that you first can determine that x is 2 and in a second step that y is 3.
Now examples of assignment statements.
x = 1 +1;
y = x*2;
The minor difference is the ; at the end, tipping you off that it is a program code line.
Here the first one looks pretty much the same as the first equation example. But for a C compiler this is different. It is a command, requesting that the program, when executing this line, assigns the value 2 to the variable x.
The second assingment statement I made similar to the second equation example, but importantly different, because the left side of = is not an expression, not something to calculate. The equation-turned-statement
y +1 = x*2;
does not work, the compiler will complain that it cannot assign a value (no problem with doing a little calculation on the right side) to an expression. It cannot assign the value 4 to the expression y+1.
This helps with your problem, because you need to understand that both lines
i = i + 1;
square = i*i;
are statements which, when executed (and only then) cause a change to the value of the variable in that line.
Your program starts off with the value 0 in the variable i. At some point it executes the first of the statements above, causing the value of i to change from 0 to 1. Later, when the same line is executed again, the value of i changes from 1 to 2. So the values of i change, loop iteration by loop iteration, to 2,3,4,5,6,7,8,9
The second assignment line causes the value of square to become the value of i, whatever it is during that loop iteration and multiplied by itself. I.e. it gets to be 4,9,16,25,36....
Outputting the value of square each time in the loop gets you the squares.
Since you state that you basically understand loops, I just mention that the loop ends when i is not lower or equal to 9 any more.
Now from the other point of view.
If you try to solve the equation
i = i + 1
for i, you should hear your math teacher groaning.
You can subtract i from both sides and get
0 = 1
The solution is "Don't try.", it is not an equation.
std::cout << i << " " << square << "\n"; prints every
number i next to its square, which is previously computed
(square = i*i;).
i = i + 1; increments i to compute the next square. It stops when i reaches 10.
The output will look like this:
0 0
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
9 81
So we have a while loop here, which run while i <= 9. The square of any number i is i * i.
while(i <=9){ //check the condition and then enter the body
//body
}
But we need a condition to get out of the loop, otherwise our program will enter into an infinite loop.
To ensure, we will exit from the loop we increase the value of i by 1.
so at first when i = 0 square = 0 * 0 = 0,now we increase the value of i i.e now i becomes one which still satisfies the condition to stay inside the loop , again it will calculate square = 1 * 1 until and unless the value of i remains less than or equal to 9.
Once the condition fails, the execution comes out of the loop.

Understanding the Syntax of Gps_traits_2::Polygons_with_holes_2 in CGAL and Additional Related Questions

Good day,
I am currently in the learning process of CGAL while being relatively new to C++. For my current project I need to use Minkowski sums and then do additional operations on the boundary of it.
However, before I do these additional operations I need to get a better understanding of the output of offset_polygon_2(), the exact Minkowski offset computation.
Question 1: What is the Syntax of the output for .outer_boundary?
From what I understand so far, it outputs a list of a conic circles defined here. I would also imagine you would need some kind of arc-angle range for each of these concic circles and origin point, correct? An example of the output goes something like this:
89 {-1*x^2 + -1*y^2 + 0*xy + 1400*x + 0*y + -489975} : (705,0) --ccw--> (700,5) {0*x^2 + 0*y^2 + 0*xy + 0*x + 0*y + 0} : (700,5) --l--> (699.97,5)...
Question 2: How do you use CGAL::draw() for the above?
I have the following code, but I am unsure of what else needs to be done before it can be drawn.
Offset_polygon_with_holes_2 offset = CGAL::offset_polygon_2(P, 5, traits);
double secs = timer.time();
std::cout << "The offset polygon has " << offset.outer_boundary().size()
<< " vertices, " << offset.number_of_holes() << " holes."
<< std::endl;
std::cout << "Offset computation took " << secs << " seconds." << std::endl;
Question 3: What other operations can be done on the "offset"?
So in the example code for Minkowski sums (also see above) offset.outer_boundary() is done, is there a list of other operations that can be done? Note: I do not think "operations" is the correct term here, please correct me.
I think that is all I have for now, thanks!

C/C++ - printf acting weird

My program needs to compute a bounding box from a vector a boundary objects, and min/max 3d vectors of this bounding box need to be used in a CUDA kernel.
To do so i get my bounding box in a c++ routine (systemparticlesph.cpp) :
void SystemParticleSPH::computeNeighborhood()
{
//cellSize
UniformGridParameters grid_params;
grid_params.cellSize = sph_parameters.ParticleRadius;
//bbox
std::pair<glm::vec3, glm::vec3> bbox = CollisionObjectsContainer::getInstance()->getBBox();
grid_params.min = std::get<0>(bbox);
grid_params.max = std::get<1>(bbox);
//works fine here !
std::cout << "cpp cellSize " << grid_params.cellSize << std::endl;
std::cout << "cpp min " << grid_params.min.x << " " << grid_params.min.y << " " << grid_params.min.z << std::endl;
std::cout << "cpp max " << grid_params.max.x << " " << grid_params.max.y << " " << grid_params.max.z << std::endl;
//cuda call
computeNeighborsCuda(grid_params);
}
The results printed with cout are exactly what i expect according to the boundary objects i created :
cpp cellSize 0.02
cpp min -0.25 -0.25 -0.25
cpp max 0.25 0.25 0.25
I'm having a really hard time when i try to print the same exact data in the computeNeighborsCuda(grid_params); function located in systemparticlessph.cu :
void computeNeighborsCuda(UniformGridParameters grid_params)
{
printf("cellsize %g min %g %g %g max %g %g %g\n",grid_params.cellSize, grid_params.min.x, grid_params.min.y, grid_params.min.z, grid_params.max.x, grid_params.max.y, grid_params.max.z );
int numBlock = m_dPos.size()/256 + 1;
calcHashD<<<numBlock, 256>>>(thrust::raw_pointer_cast(&m_dGridParticleHash[0]), thrust::raw_pointer_cast(&m_dGridParticleIndex[0]), thrust::raw_pointer_cast(&m_dPos[0]), grid_params, m_dPos.size());
}
The results displayed (when i comment the 3 cout) should be the same but here is what i get :
cellsize -0,25 min -0,25 -0,25 0,25 max 0,25 0,25 -7168,19
It looks like there is some offset making the whole thing wrong : cellSize has the value of min.x, while max.z has an arbitrary value.
Note that the problem is exactly the same when i call printf from the CUDA kernel.
Also note that it is getting worse when i display both with cout and printf at the same time :
cpp cellSize 0.02
cpp min -0.25 -0.25 -0.25
cpp max 0.25 0.25 0.25
cellsize -1,79826e+36 min 0 1,21731e-37 0 max 1,21731e-37 0 1,21731e-37
Do you have any idea of to get the same result in the C function (and kernel) ?
Thanks in advance, this is really giving me a hard time.
Mathias
Edit :
Passing a reference instead of a copy of the structure, everything works perfectly fine.
Still, i have no idea why it does not work with a copy of the structure.
I would suggest to make your own struct with simple variables and copy the exact data you want to show from the c++ program into the CUDA function.

How Does This Recursive Function Operate in C++? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'd like to know how the 2nd output in the following code example is produced. How is the function able to count backwards after the if statement and recursive function call have ended?
void Recursion(int x)
{
if(x < 4) {
cout << x << " "; // 1st output: 1 2 3
Recursion(x + 1);
}
cout << x << " "; // 2nd output: 4 3 2 1
}
int main()
{
Recursion(1);
}
I'm going to interpret the question as "how can the function remember what it was doing when it returns?".
The C++ standard doesn't say (IIRC it's left to implementations to find a solution that works). In practice, though, the answer is "the stack".
In computer science generally, a stack is a last-in-first-out data structure. Push the sequence 1, 2 then 3 into a stack then do three pops and you get 3, 2 then 1.
In the early days, programming languages often didn't support recursive or re-entrant calls. Each function/procedure had a little block of memory it owned where it stored its parameters, local variables and which function to return to after completion. If you tried to call a function that was already running, that would mean storing two sets of local variables and two return addresses in the space for one, so that was an error.
However, one of the innovations in IIRC the Algol programming language was support for recursion. And at around the same time, "processor stacks" were becoming a thing.
A processor stack (among other things) allows you to use a different method for handling parameters, local variables and return addresses. You don't need a permanently allocated block for each function - you allocate a block (at the top of the stack) when you call the function. The location of the current "stack frame" is relative to the current "stack pointer". And this means you can have multiple stack frames for the same function on the stack at the same time.
So calling a function involves creating a new stack frame at the top of the stack, and adjusting the stack pointer to suit. And returning from a function involves discarding that stack frame and adjusting the stack pointer back, so the top stack frame is now the stack frame for the caller. That caller may or may not have been the same function - it doesn't matter because each call got it's own stack frame storing a separate set of parameters, local variables, a separate return address etc.
So just before the Recursion (3) call, the stack would look something like...
|-------------------+-------------------+
| Recursion Frame 1 | Recursion Frame 2 |
|---------------+---+---------------+---+
| ??? | X | ??? | X |
|---------------+---+---------------+---+
| ??? | 1 | ??? | 2 |
|---------------+---+---------------+---+
^
|
STACK
POINTER
The ??? represents "housekeeping" stuff like the return address.
Think about just the first call to Recursion.
The function is going to print a "1", then other stuff is going to happen, then it prints a "1" again.
So the output is going to be 1 ... 1
Now think about the second call to Recursion, its going to print a "2", then other stuff is going to happen, then it prints a "2" again.
So its output is 2 ... 2.
Stick those two together and you get 1 2 ... 2 1
And then just keep going.
You should try stepping through the code, executing it with pencil and paper (or a virtual scratch pad). Let's keep the function definition close:
void Recursion(int x)
{
1 if(x < 4) {
2 cout << x << " "; // 1st output: 1 2 3
3 Recursion(x + 1);
. }
.
4 cout << x << " "; // 2nd output: 4 3 2 1
5 return;
}
Now, let's call main:
call main
call Recursion(1) -> x := 1
(1) if (x < 4) -> true
(2) cout << x << " "; // with x == 1
(3) call Recursion(x + 1) -> x := 2
(1) if (x < 4) -> true
(2) cout << x << " "; // with x == 2
(3) call Recursion(x + 1) -> x := 3
(1) if (x < 4) -> true
(2) cout << x << " "; // with x == 3
(3) call Recursion(x + 1) -> x := 4
(1) if (x < 4) -> false
(4) cout << x << " "; // with x == 4
(5) end Recursion -> x:= 3
(4) cout << x << " "; // with x == 3
(5) end Recursion -> x:= 2
(4) cout << x << " "; // with x == 2
(5) end Recursion -> x:= 1
(4) cout << x << " "; // with x == 1
(5) end Recursion -> del x
end main
And now, you can just check what is outputed: cout << x << " "; is called successively with values: 1, 2, 3, 4, 3, 2, 1, yielding "1 2 3 4 3 2 1 ".
Does it help if you look at this:
string RecursiveReturn(int x)
{
if(x >= 4) {
return to_string(x);
}
return to_string(x) + " " + RecursiveReturn(x+1) + " " + to_string(x);
}
int main()
{
cout << Recursion(1);
}
A recursive call is like any other function call... it is evaluated, and when it returns the calling function continues.
The stack depicts that when "1st output" is performed to stdout, the "2nd output" is inserted into stack("function stack").
When the function "recursion" returns to "main" function the unwinding or popping contents of stack happens. If you visulaise properly this is how it gives output.

Check for every rugby score the recursive way without repetitions

Just for fun I created an algorithm that computes every possible combination from a given rugby score (3, 5 or 7 points). I found two methods : The first one is brute force, 3 imbricated for loops. The other one is recursion.
Problem is some combinations appear multiple times. How can I avoid that ?
My code :
#include <iostream>
using namespace std;
void computeScore( int score, int nbTryC, int nbTryNC, int nbPenalties );
int main()
{
int score = 0;
while (true)
{
cout << "Enter score : ";
cin >> score;
cout << "---------------" << endl << "SCORE = " << score << endl
<< "---------------" << endl;
// Recursive call
computeScore(score, 0, 0, 0);
}
return 0;
}
void computeScore( int score, int nbTryC, int nbTryNC, int nbPenalties )
{
const int tryC = 7;
const int tryNC = 5;
const int penalty = 3;
if (score == 0)
{
cout << "* Tries: " << nbTryC << " | Tries NT: " << nbTryNC
<< " | Penal/Drops: " << nbPenalties << endl;
cout << "---------------" << endl;
}
else if (score < penalty)
{
// Invalid combination
}
else
{
computeScore(score - tryC, nbTryC+1, nbTryNC, nbPenalties);
computeScore(score - tryNC, nbTryC, nbTryNC+1, nbPenalties);
computeScore(score - penalty, nbTryC, nbTryNC, nbPenalties+1);
}
}
One way to think about this is to realize that any time you have a sum, you can put it into some "canonical" form by sorting all the values. For example, given
20 = 5 + 7 + 3 + 5
You could also write this as
20 = 7 + 5 + 5 + 3
This gives a few different options for how to solve your problem. First, you could always sort and record all of the sums that you make, never outputting the same sum twice. This has the problem that you're going to end up repeatedly generating the same sums multiple different times, which is extremely inefficient.
The other (and much better) way to do this is to update the recursion to work in a slightly different way. Right now, your recursion works by always adding 3, 5, and 7 at each step. This is what gets everything out of order in the first place. An alternative approach would be to think about adding in all the 7s you're going to add, then all the 5's, then all the 3's. In other words, your recursion would work something like this:
Let kValues = {7, 5, 3}
function RecursivelyMakeTarget(target, values, index) {
// Here, target is the target to make, values are the number of 7's,
// 5's, and 3's you've used, and index is the index of the number you're
// allowed to add.
// Base case: If we overshot the target, we're done.
if (target < 0) return;
// Base case: If we've used each number but didn't make it, we're done.
if (index == length(kValues)) return;
// Base case: If we made the target, we're done.
if (target == 0) print values; return;
// Otherwise, we have two options:
// 1. Add the current number into the target.
// 2. Say that we're done using the current number.
// Case one
values[index]++;
RecursivelyMakeTarget(target - kValues[index], values, index);
values[index]--;
// Case two
RecursivelyMakeTarget(target, values, index + 1);
}
function MakeTarget(target) {
RecursivelyMakeTarget(target, [0, 0, 0], 0);
}
The idea here is to add in all of the 7's you're going to use before you add in any 5's, and to add in any 5's before you add in any 3's. If you look at the shape of the recursion tree that's made this way, you will find that no two paths end up trying out the same sum, because when the path branches either a different number was added in or the recursion chose to start using the next number in the series. Consequently, each sum is generated exactly once, and no duplicates will be used.
Moreover, this above approach scales to work with any number of possible values to add, so if rugby introduces a new SUPER GOAL that's worth 15 points, you could just update the kValues array and everything would work out just fine.
Hope this helps!
Each time you find a solution you could store it in a dictionary ( a set of strings for example, with strings looking like "TC-TNT-P" )
Before printing a solution you verify it was not in the dictionary.
A nested for-loop is the natural way to do this. Using recursion is just silly (as you seem to have discovered).