Make certain local variables available to LLVM pass - llvm

I have the following situation.
I need to insert certain CallInst in my code.
The prototype of my function is
void __llvmFooBar(int data, int loc);
The parameter loc is generated by the pass. I don't need any external data to generate that.
But, the parameter data is basically calculated by using some variable declared inside my C-code.
//test.c
int main()
{
int k = 0;
happyEnding(k);
}
void happyEnding(int k)
{
int __data = seed(time()) + k%2;
//callInst to be inserted here, it should be
//__llvmFooBar(__data, 23);
myAlgorithim();
}
//pass.cpp
......
std::vector<Value *> args(2);
args[0] = ??? //need help here
args[1] = ConstantInt::get(IntegerTy, getLoc());
m_builder->CreateCall(hook, args);
In generic sense, how to make all variable with specific naming convention(like starts with __) make available to llvm pass ?

Related

How to Pass Struct Data Member into Function

I want to be able to pass a struct member into a function:
struct threeBuckets {
int bucketA;
int bucketB;
int bucketC;
};
threeBuckets allCombinations[512000] = {{0,0,0}};
int totalCombinations = 1;
int counter = 0;
//note that pourer, receiver, and other are one of the struct members (bucketA, bucketB, and bucketC)
void pour(pourer, receiver, int receiverCap, other) {
int finalTriple[3];
allCombinations[totalCombinations].bucketA = allCombinations[counter].bucketA;
allCombinations[totalCombinations].bucketB = allCombinations[counter].bucketB;
allCombinations[totalCombinations].bucketC = allCombinations[counter].bucketC;
allCombinations[totalCombinations].receiver = allCombinations[totalCombinations].receiver + allCombinations[counter].pourer;
allCombinations[totalCombinations].pourer = 0;
if (allCombinations[totalCombinations].receiver > receiverCap) {
allCombinations[totalCombinations].pourer = allCombinations[totalCombinations].pourer + allCombinations[totalCombinations].receiver - receiverCap;
allCombinations[totalCombinations].receiver = receiverCap;
}
finalTriple[0] = allCombinations[totalCombinations].bucketA;
finalTriple[1] = allCombinations[totalCombinations].bucketB;
finalTriple[2] = allCombinations[totalCombinations].bucketC;
//some more irrelevant code
}
As I've hopefully made clear, the parameters pourer, receiver, and other are bucketA, bucketB, and bucketC (in no particular order, the order does change depending on when I call the function.) There are several places where I want to modify the instance
allCombinations[totalCombinations].pourer
for example. How do I use the struct member as a parameter, and what type do I use to specify it?
Note: I'm mostly a beginner and am new to StackOverflow, so if anything else I'm doing is wrong, please feel free to tell me.
Note 2: If any of you do or have done USACO, you might recognize this problem as the milk3 training gateway problem. This might aid you if you don't know what I'm doing here.
It sounds like you need to use pointer to member variable for the argument types in pour.
void pour(double threeBuckets::(*pourer) ,
double threeBuckets::(*receiver),
int receiverCap,
double threeBuckets::(*other)) {
...
}
In the function, change the use of
allCombinations[totalCombinations].pourer
allCombinations[totalCombinations].receiver
allCombinations[totalCombinations].other
by
allCombinations[totalCombinations].*pourer
allCombinations[totalCombinations].*receiver
allCombinations[totalCombinations].*other
respectively.
At the point of calling the function, use:
pour(&threeBuckets::bucketA,
&threeBuckets::bucketB,
0, // Any appropriate value
&threeBuckets::bucketC);
Another option that is worth considering is:
Change threeBuckets to use an array.
Change the arguments to pour to be indices to the array.
struct threeBuckets {
int buckets[3];
};
void pour(int pourerIndex ,
int receiverIndex,
int receiverCap,
int otherIndex)) {
...
}
Then, instead of using
allCombinations[totalCombinations].pourer
allCombinations[totalCombinations].receiver
allCombinations[totalCombinations].other
use
allCombinations[totalCombinations].buckets[pourerIndex]
allCombinations[totalCombinations].buckets[receiverIndex]
allCombinations[totalCombinations].buckets[otherIndex]
Of course, change the call to use indices.
pour(0,
1
0, // Any appropriate value
2);

How to name a function and a variable with the same name?

The following code cannot be compiled by VC++ and clang.
int f()
{
return 0;
}
int main()
{
// error : called object type 'int' is not a function or function pointer
int f = f();
}
It is necessary in some cases. For example, I have a function to calculate the character count of a string, which is named count, however, another function parameter is also expressively named as count.
size_t count(char* sz)
{
return strlen(sz);
}
bool check_count(char* sz, size_t count)
{
return count == count(sz); // ???
}
How to resolve this issue?
In C++ you can define a namespace for your objects, in your example you could do:
namespace MyFunctions {
int f()
{
return 0;
}
}
int main()
{
int f = MyFunctions::f();
}
The answer is simple. This is not supported. C, as many other languages, cannot support absolutely every scenario. It is unreasonable to put out such a goal. Nobody ever tried to achieve this.
In your particular case, you should rename your parameter. Function always has limited scope. It is always recompiled as a whole. Names of params in prototypes in the header files may have different names. Renaming param in the body of the function will work in 99.9999% of cases.

Dynamic function calls at runtime (va_list)

There is a way in C to obtain a dynamic length argument list with va_list, as described here:
http://www.cprogramming.com/tutorial/c/lesson17.html
That quite simple, but most times in C++ not needed. I am currently building a top level wrapper class for encapsulating some Zend functionality.
Anyway, I do need to make a call to such a dynamic function like printf from a normal function dynamically.
I mean the reverse way of the example described above, here is waht I got so war, maybe this explains my idea a little better:
void ZendParams::setRequired( int &Var )
{
// save every var pointer to a stack
// and save the type with it. (if needed, does not seems to be)
// after call to ZendParams::fetch()
// the values are stored in the passed variables
this->_params.push_back( (void*) &Var );
this->_paramStr.append( 'i' );
}
size_t ZendParams::fetch()
{
if ( zend_parse_parameters(
ZEND_NUM_ARGS() TSRMLS_CC, ,
this->_paramStr.c_str(),
...
) !== FAILURE)
{
}
return 0;
}
So I want to make the call to zend_parse_parameters dynamically.
The base idea is to add pointer to vars in a list and pass them to the zend function (as reference) dynamically.
I thought there must be a way to do this with va_list , too.
But how?
To get it more simple, I am using this example:
list<int> myList;
myList.push_back(1);
myList.push_back(5);
myList.push_back(10);
myList.push_back(37);
myList.push_back(42);
double function avg( int num, ... )
va_list arguments;
int sum = 0;
va_start ( arguments, num );
for ( int x = 0; x < num; x++ )
{
sum += va_arg ( arguments, int );
}
va_end ( arguments );
return sum / num;
}
I want to call avg with all numbers I got in the list. I took the example function from the tutorial mentioned above, but it should show up what I mean in a very simple way.
However, I can not change the function called, as it is part of the zend framework.
Is there any way in C or C++ to do this?
My 2nd approach:
template <typename... Arguments>
size_t Zend::getMethodParams( string paramStr, Arguments... Args )
{
if ( zend_parse_parameters(
ZEND_NUM_ARGS() TSRMLS_CC, ,
paramStr.c_str(),
Args...
) == FAILURE)
{
return 0;
}
}
To be called like this (to get the defined 3 Parameters):
string My1stParam;
int My2ndParam;
int My3rdParam;
Zend::getMethodParams<string, int, int>( "sii", &My1stParam, &My2ndParam, &My3rdParam );
I think that should work, but there is one hard issue with that:
The zend_parse_parameters function returns 2 values for a string (c-style string!):
- a char pointer and
- the string length.
So I would either have to call it that way:
char* My1stParam_str;
int My1stParam_length
int My2ndParam;
int My3rdParam;
Zend::getMethodParams<string, int, int>( "sii", &My1stParam_str, &My1stParam_length, &My2ndParam, &My3rdParam );
string My1stParam;
My1stParam.assign(My1stParam_str, My1stParam_length);
Anyway, that was what I wanted to prevent.
Or I would have to modify the list of arguments passed to the zend_parse_parameters function to do these additional steps internally.
I am hoping to be able to call it at least in that way:
string My1stParam;
int My2ndParam;
int My3rdParam;
Zend::getMethodParams<string, int, int>( "sii", &My1stParam, &My2ndParam, &My3rdParam );
So say this clearly: The parameters are known at compile time, but the function call will be very different within all occurrences in the later sourcecode.
I found a way around this within the zend framework. I did indeed search for such a solution before, but it seems to be not very good documented ( n.m. already mentoined, that there is no zend internal way like a va_list taking function ).
But there is indeed one!
For everyone else stucking with this problem:
long arg;
zval ***args;
int i, argc = ZEND_NUM_ARGS( );
if (zend_parse_parameters(1 TSRMLS_CC, "l", &arg) == FAILURE) return;
array_init(return_value);
add_index_long(return_value, 0, arg);
if(argc>1) {
args = (zval ***)emalloc(argc * sizeof(zval **));
if(zend_get_parameters_array_ex(argc, args) == FAILURE) {
efree(args);
return;
}
for(i = 1; i < argc; i++) {
zval_add_ref(args[i]);
add_index_zval(return_value,i, *args[i]);
}
efree(args);
}
That is the solution ;)
This snippet, found on http://docstore.mik.ua/orelly/webprog/php/ch14_07.htm parses all parameters dynamically into the c representation of an PHP array.

A variable that is read-only after assignment at run-time?

Fairly new programmer here, and an advance apology for silly questions.
I have an int variable in a program that I use to determine what the lengths of my arrays should be in some of my structures. I used to put it in my header as a const int. Now, I want to fork my program to give the variable different values depending on the arguments given in, but keep it read-only after I assign it at run-time.
A few ideas I've had to do this. Is there a preferred way?
Declare a const int * in my header and assigning it to a const int in my main function, but that seems clunky.
Make it a plain int in my main function.
Pass the variable as an argument when the function is called.
Something else I haven't thought of yet.
I'd use a function-static variable and a simple function. Observe:
int GetConstValue(int initialValue = 0)
{
static int theValue = initialValue;
return theValue;
}
Since this is a function-level static variable, it is initialized only the first time through. So the initialValue parameter is useless after the first run of the function. Therefore, all you need to do is ensure that the first call of the function is the one that initializes it.
C++ doesn't have a built-in solution for this, but if you really want to make sure that your int is only assigned once, you can build your own special int class:
class MyConstInt
{
public:
MyConstInt(): assigned(false) {}
MyConstInt& operator=(int v)
{
assert(!assigned);
value = v;
assigned = true;
return *this;
}
operator int() const
{
assert(assigned);
return value;
}
private:
int value;
bool assigned;
};
MyConstInt mi;
// int i = mi; // assertion failure; mi has no value yet
mi = 42;
// mi = 43; // assertion failure; mi already has a value
int* array = new int[mi];
When exactly do you know the correct value? If you read it from a file or whatever, you can just say:
const int n = determine_correct_value();
I'm tempted to say that what you want doesn't make sense. A constant is something that doesn't change its value, not something that maybe changes its value once or twice. If you want a global variable, just make it non-constant.
On the other hand, if you have scope-constant values, you would just declare and initialize them at the same time, following the general C++ guideline to declare as close to the usage site as possible. For example, mark the use of constants in the following local scope:
for (auto it = v.begin(), end = v.end(); it != end; ++it)
{
const Foo & x = *it;
const std::size_t n = x.get_number_of_bars();
// use x and n ...
const bool res = gobble(x, zip(n));
if (res && shmargle(x)) { return 8; }
}
Here the compiler may even choose not to generate any special code for the variables at all if their value is already known through other means.

Lua C API: Handling and storing additional arguments

CreateEntity is a C function I bound to Lua in my project. It takes an entity class name string as first argument, and any number of additional arguments which should get passed to the constructor of the chosen entity.
For example, if CreateEntity was a normal Lua function I could do it this way:
function CreateEntity( class, ... )
-- (choose a constructor function based on class)
args = {...}
-- (store args somewhere for whatever reason)
TheConstructor( ... )
end
But how can I do this with a C Lua function?
The C function lua_gettop will return how many parameters were passed to your C function. You must either read these all from the stack and store them in a C data structure, or place them in the Lua registry (see Registry and luaL_ref) and store references to them for later use. The example program below uses the registry approach.
#include <lauxlib.h>
#include <lua.h>
#include <lualib.h>
#include <stdio.h>
#include <stdlib.h>
/* this function prints the name and extra variables as a demonstration */
static void
TheConstructor(lua_State *L, const char *name, int *registry, int n)
{
int i;
puts(name);
for (i = 0; i < n; ++i) {
lua_rawgeti(L, LUA_REGISTRYINDEX, registry[i]);
puts(lua_tostring(L, -1));
}
free(registry);
}
static int
CreateEntity(lua_State *L)
{
const char *NAME = luaL_checkstring(L, 1);
int *registry;
int i, n;
/* remove the name parameter from the stack */
lua_remove(L, 1);
/* check how many arguments are left */
n = lua_gettop(L);
/* create an array of registry entries */
registry = calloc(n, sizeof (int));
for (i = n; i > 0; --i)
registry[i-1] = luaL_ref(L, LUA_REGISTRYINDEX);
TheContructor(L, NAME, registry, n);
return 0;
}
int
main(int argc, char **argv[])
{
const char TEST_CHUNK[] =
"CreateEntity('foo', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)";
lua_State *L;
L = luaL_newstate();
lua_register(L, "CreateEntity", CreateEntity);
luaL_dostring(L, TEST_CHUNK);
lua_close(L);
return EXIT_SUCCESS;
}
args = {...}
-- (store args somewhere for whatever reason)
The arguments of the call are on the Lua stack and you can do with them as you please: put them in a structure of your own (std::vector<boost::any> or something like that) or store individual arguments in the Lua registry or create a Lua table with the arguments and store that in the registry instead. What suits you better?
TheConstructor( ... )
I'm fairly convinced this part is not possible in C++ the way it is in Lua. C++ requires the number of parameters you pass to a function to be known at compile time.
It's a major inconvenience to try and do those things in C++. Maybe be betters solution will come if you tell us why do you want your CreateEntity function to be on the C++ side instead of Lua.