Representing ''Class " construct in LLVM IR - llvm

I am implementing a llvm transformation pass. And while inserting a function call, I need to pass custom 'class' object as an argument.
I have a Thread object that I need to pass as an argument: the function signature as follows:
void MyThread::initialize(int num ,MyThread* myThread)
and through my pass , I need to add the following instruction:
myThread->initialize(Count, myThread);
I don't know how to represent the myThread object's type while preparing it as an argument. For example, if it is an integer we know how to get the type but in our case how to represent class construct as a type?

Classes are normally represented as structs in LLVM IR. You could check what clang does, certainly.

Related

Can list cast correctly in Kotlin?

I am new to Kotlin,
data class RewardDetail(
val name: String
val isActivated: Boolean
val amountInCents: Int?
val Campain: String?
val expirationDate: Long?
)
class Rewards(Array<Reward>)
class Reward(
    val name: String
   
isActive: Boolean
   
amountInCents: Int
    campaignId: String
    expirationDate: LocalDateTime
)
val details : List<RewardDetail> = blablabla
val rewards = Rewards(details)
can details cast to rewards successfully?
Also note campaignId and Campain field name are different in RewardDetail and Reward and some fields can be nullable in RewardsDetail
What is the best way to handle situation like this?
Kotlin is strongly-typed. You can never successfully cast one thing into a different class. You can only cast an object into a type that it already satisfies. For example, if you have an Int that is currently only known to the compiler to be a Number, you can cast to Int to tell the compiler that it has an Int, so the compiler will allow you to use the functions that are specific to Int. But nothing but an Int can ever be cast to an Int.
So, unlike weakly typed languages, casting does not convert from one type to another. Casting is only you making a promise to the compiler that an object already is of the other type.
In your example, the only way to get a RewardDetail from a Reward is by writing a function that manually converts each property to the appropriate type.
The Rewards class above is largely redundant. There's no need for a wrapper class around a single Array or List unless you need to do validation of items added to or retrieved from the list. In that case, it would probably make more sense to create a subclass of ArrayList for that purpose, so you could still easily iterate the list and use all the List and Iterable helper functions on it.
Probably about 95% of the time, you should prefer using List over using Array. Arrays should be used only when you need a fixed size collection that is also mutable, or if you are working with highly performance-critical code. The reason it should be limited to these uses is that mutability should be avoided when possible for robustness and Arrays are more cumbersome to work with than MutableLists.
A typical implementation of a function that converts from one type to another would be to write an extension function RewardDetail.toReward() extension function, or a toReward() function inside the RewardDetail class. However, in your case you need to decide what you need to happen when some of the values of RewardDetail are null. Maybe you just return null so your conversion function should be toRewardOrNull(), or you provide default values for the properties that have no value in RewardDetail.

Passing function pointer with or without &

I'm currently learning game development with c++ in Unreal Engine and I came across the function that takes a function pointer as an input:
InputHandle->BindAction("Grab",IE_Pressed, this, &UGrabber::Grab);
From basic C++ I know that in passing a function pointer as an attribute (UGrabber::Grab) - & is optional, however UEngine complains with the following error code if I omit the &:
error C3867: 'UGrabber::Grab': non-standard syntax; use '&' to create a pointer to member
Could someone explain why?
BindAction function declaration looks like this:
FInputActionBinding& BindAction( const FName ActionName, const EInputEvent KeyEvent, UserClass* Object, typename FInputActionHandlerSignature::TUObjectMethodDelegate< UserClass >::FMethodPtr Func )
The BindAction function makes use of a Dynamic Multicast Delegate.
They are one of Unreal's ways of having callback functions. In this case, they rely not just on calling a function, but calling a specific object's function. This is why you need to bass the third parameter (in this example, the parameter is this).
What it's saying is, when the input action is IE_Pressed, call the UGrabber function Grab on object this (this has to be a UGrabber instance of course). This is why it's a pointer to the method. It actually utilizes Unreal's reflection system to find the method on the object. So the this object needs to be UObject, otherwise you can't call a funciton on an object by name in C++.
For more info on this, search for "unreal delegates" and "unreal reflection" in your search engine of choice. Using them is quite easy, and it's not necessary to understand the reflection system to reliably use them. Just don't forget to bind and unbind at the appropriate times.
p.s. You can get quite in depth in this subject of callbacks you want. There are other delegate types that don't rely on reflection, for example non-dynamic delegates, that can bind to lambda functions, and or a more familiar if you're coming from a pure C++ background, where commonly a void* opaque is used, expected to be cast to the needed class pointer.

How can I make a class that type-erases objects until a function is called on them without specifying the list of possible functions up front?

Background
The title probably sounds confusing, so let me explain. First of all, here is a minimal version of my implementation, so you can follow along with the concepts more easily. If you've seen some of Sean Parent's talks, you'll know he came up with a way to abstract polymorphism, allowing code such as this:
std::vector<Drawable> figures{Circle{}, Square{}};
for (auto &&figure : figures) {draw(figure);}
Notice that there are no pointers or anything. Calling draw on a Drawable will call the appropriate draw function on the contained object without the type of the object being easily accessible. One major downside to this is that similar classes to Drawable have to be written for each task. I'm trying to abstract this a bit so that the function does not have to be known by the class. My current solution is as follows:
std::vector<Applicator<Draw>> figures{Circle{}, Square{}};
for (auto &&figure : figures) {figure.apply(Draw{});}
Here, Draw is a functor with an operator()(Circle) and opeator()(Square), or a generic version. In this way, this is also sort of a visitor pattern implementation. If you wanted to also, say, print the name of each figure, you could do Applicator<Draw, PrintName>. When calling apply, the desired function is chosen.
My implementation works by passing a boost::variant of the callable types to the virtual function and having it visit that variant and call the function within. Overall, I would say this implementation is acceptable, but I haven't yet thought much about allowing any number of parameters or a return type, let alone ones that differ from function to function.
Question
I spent days trying to think of a way to have this work without making Applicator a template. Ideally, the use would be more similar to this. For the sake of simplicity, assume the functions called must have the signature void(ObjectType).
//For added type strictness, I could make this Applicator<Figure> and have
//using Figure<struct Circle> = Circle; etc
std::vector<Applicator> figures{Circle{}, Square{}};
for (auto &&figure : figures) {figure.apply(Draw{});} //or .apply(draw); if I can
The problem usually comes down to the fact that the type of the object can only be obtained within a function called on it. Internally, the class uses virtual functions, which means no templates. When apply is called, here's what happens (identical to Sean's talks):
The internal base class's apply is called on a pointer to the base class with the runtime type of a derived class.
The call is dispatched to the derived class, which knows the type of the stored object.
So by the time I have the object, the function to call must be reduced to a single type known within the class that both knows which function to call and takes the object. I cannot for the life of me come up with a way to do this.
Attempts
Here are a couple of failed attempts so you can see why I find this difficult:
The premise for both of the first two is to have a type that holds a function call minus the unknown first argument (the stored object). This would need to at least be templated on the type of the callable object. By using Sean Parent's technique, it's easy enough to make a FunctionCall<F> class that can be stored in a GenericFunctionCall, much like a Circle in a Figure. This GenericFunctionCall can be passed into the virtual function, whereas the other cannot.
Attempt 1
apply() is called with a known callable object type.
The type of the callable object is used to create a FunctionCall<Type> and store it as a type-erased GenericFunctionCall.
This GenericFunctionCall object is passed to the virtual apply function.
The derived class gets the call object and has the object to be used as the first argument available.
For the same reason of virtual functions not being allowed to be templates, the GenericFunctionCall could call the necessary function on the right FunctionCall<Type>, but not forward the first (stored object) argument.
Attempt 2
As a continuation of attempt 1:
In order to pass the stored object into the function called on the GenericFunctionCall, the stored object could be type-erased into a GenericObject.
One of two things would be possible:
A function is called and given a proper FunctionCall<Type>, but has a GenericObject to give to it, with the type unknown outside of a function called on it. Recall that the function cannot be templated on the function call type.
A function is called and given a proper T representing the stored object, but has a GenericFunctionCall to extract the right function call type from. We're back where we started in the derived class's apply function.
Attempt 3
Take the known type of a callable object when calling apply and use it to make something that stores a function that it can call with a known stored object type (like std::function).
Type-erase that into a boost::any and pass it to the virtual function.
Cast it back to the appropriate type when the stored object type is known in the derived class and then pass the object in.
Realize that this whole approach requires the stored object type to be known when calling apply.
Are there any bright ideas out there for how to turn this class into one that doesn't need the template arguments, but can rather take any callable object and call it with the stored object?
P.S. I'm open for suggestions on better names than Applicator and apply.
This is not possible. Consider a program composed of three translation units:
// tu1.cpp
void populate(std::vector<Applicator>& figures) {
figures.push_back(Circle{});
figures.push_back(Square{});
}
// tu2.cpp
void draw(std::vector<Applicator>& figures) {
for (auto &&figure : figures) { figure.apply(Draw{}); }
}
// tu3.cpp
void combine() {
std::vector<Applicator>& figures;
populate(figures);
draw(figures);
}
It must be possible for each TU to be translated separately, indeed in causal isolation. But this means that at no point is there a compiler that simultaneously has access to Draw and to Circle, so code for Draw to call Circle::draw can never be generated.

Llvm C++ API pass Pointer to Function to another Function

How can I pass a pointer to function to another function? I have a function like this:
std::string PRINT_STATE_NAME(pPrintState func);
where pPrintState is a typedef like this:
typedef void (*pPrintState)(std::string* buffer);
So I JITed pPrintState and have its llvm::FunctionType available.
Next I want to call PRINT_STATE_NAME() as defined above from llvm C++ API. Unfortunately I can't figure out what parameter to pass to the call instruction. Atm I made an llvm::GlobalVariable with inner type of converted pPrintState. But what should I pass as initializer? Or am I completely on the wrong track here? Any help is appreciated! Thanks!
You need to obtain the address of pPrintState (the JIT'ed one, via getPointerToFunction() or getPointerToNamedFunction()) cast this address (as integer) to pPrintState and pass as an argument.

Lua encapsulation class

I am actually trying to create a class in C++ to encapsulate calls of Lua, actually trying to encapsulate a function to load a Lua script on the constructor, but the main problem is when I try to make a function call of the Lua script I can't find how to store the multiple returns value and how to correctly push all the arguments.
I'm trying to find an idea of the implementaion of a function who call a lua fonction with any number of any type of parameter, (the function will push arguments and call the function, but i dont want dynamic cast for example to know if i have to "lua_pushnumber" or push string for example.
You could try to accept an array of some type of variant class in your constructor, and use their type to determine how to pump them into Lua. On the other hand, there is really only two types that are interchangeable between C/C++ and Lua: string and number/double. A possible solution is to give pass in an array of strings (or a char** and an int, if you prefer), passing in your doubles as strings as well.
You could then do your loadstring() call by appending a string representation of your string or double after the string "return ". When you execute the function pushed to the stack by loadstring(), the lua engine will push your variable (string or double with appropriate type) to the lua stack. You would have the overhead of string-parsing your doubles, but if you were dying for speed I bet you would be coding purely in C++ anyways :) The advantage of this method is that you could actually pass in a function this way too: (i.e. "return function() print("hello"); end")