changing llvm::Function signature after code generation, before last CreateRet - c++

I'm trying to implement the following functionality;
a function with no explicit return will by default return the last evaluation in the last executed block
So, currently the process i'm doing is
1) create a Function
llvm::Function* result = llvm::Function::Create(Compiler::Detail::getAnonymousFunctionSignature(llvmContext),
llvm::GlobalValue::ExternalLinkage,
name,
module());
result->setCallingConv( llvm::CallingConv::C );
2) add blocks and evaluations to the blocks
builder.createFoo.....
However, only in the second phase i have the llvm::Value* (and compile-time type) that i want to use by default as return value. The problem is that i need to use this type to determine the signature of the created function
Question:
how do i solve the problem?
is possible to change the signature after the function is created? is it legal?
do i need to create a new function with the updated signature and copy/assign the entry block of the first function to it and thats it? or do i need to reevaluate all the expressions?
is possible to not create the function before code generation? if it is so, at what point should i create the function?
a code example of how to achieve this would be awesome. thanks!

You cannot change function signature, because this will mean that it will have different Type (and thus you will need to update all the users, etc.; this procedure in most cases cannot be done automagically).
There are multiple possible solutions, for example, you can create the function with the updated signature, then use the functions from lib/Transforms/Utils/CloneFunction.cpp to copy the function body and then hack on the return type.

A better solution exists than CloneFunctionInto(), according to https://stackoverflow.com/a/18751365/2024042:
NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
Where NF is the new function you're cloning into and F is the old function that you have just cloned.

Related

How to create pass-by-ref parameter in BlueprintCallable UFUNCTION that doesn't need variable plugged to pin and checks if variable was plugged or no?

What I want to achieve:
A Blueprint Callable function that takes UPARAM(ref) bool& as a parameter which can but doesn't have to be passed inside of Blueprint Graph (variable doesn't have to be plugged into input pin to this node for the graph to compile). And by *asing on if the parameter has been passed or not, the function will behave in a slightly different way.
For example, I was able to create something like this in C++ (pastebin imgur):
void Func(bool& param = *(bool*)0)
{
if (&param == nullptr)
// do something
}
Above code compiles and consistently behaves in VS2022, allows to call Func() without passing any parameters in it and execute code basing on if the parameter has been passed which is the exact behavior that I'm looking for.
However, this code is a C++ undefined behaviour not allowed for UFUNCTIONs. So, when I try to declare something similar as BlueprintCallable UFUNCTION in Unreal, this of course will not compile:
UFUNCTION(BlueprintCallable)
static void Func(UPARAM(ref) bool& param = *(bool*)nullptr);
due to error:
C++ Default parameter not parsed: param "(bool)nullptr"
So my question is:
Is the "behaviour/functionality" that I want to achieve even possible in BlueprintCallable functions?
Is there any workaround to what I've described above? For example in form of macros, custom data containers or function specifiers?
I think summary of my question might be a little bit misleading. I just want to recreate this type of code/behaviour pastebin imgur in Unreal's 'UFUNCTION(BlueprintCallable)'. Yes, I understand that given example is an UB, but this is the closest result to what I want to create. This is just an example.
This question is Unreal Engine / UFUNCTION related. This is not a typical C++ issue. Unreal uses macros for UFUNCTION declaration and compiles in a different way than regular C++ (UFunctions). Because of that pointer cannot be used as parameter in this case as Unreal does not allow it. However pointer would be an actual solution to this question if it were only about pure C++.
Possible but not exact solutions:
meta = AutoCreateRefTerm( "param" ) can be specified in the UFUNCTION declaration. This allows Blueprint Node to have default value in pass-by-ref pin. However, with this approach another condition (bool pin) is needed because it is not possible check if actual variable gets passed or not.
In comments TOptional has been mentioned. This data container is actually something that exactly fits here, but TOptional cannot be used as parameter in BlueprintCallable UFUNCTION due to "Error: Unrecognized type 'TOptional' - type must be a UCLASS, USTRUCT, UENUM, or global delegate.", or at least I don't know how to use it.
My question has been closed as a dupe of Is null reference possible? which isn't true. My question asks for high level functionality in Unreal's Blueprints/UFUNCTIONS that would omit the need of "null reference". Something like TOptional::IsSet

Creating a function that takes a container "X" as a parameter, which passes X.size() parameters to a variadic function that it calls

I am currently working on an HTTP API that I want to use to perform CRUD operations on a database. I try to write the code for it as generic and modular as possible. I am using the MySQL X DevAPI.
Currently, I am stuck on the following problem:
mysqlx::Result MySQLDatabaseHandler::jsonToCUDOperation (const nlohmann::json& json, mysqlx::Table& table, int crudEnum)
The function above takes as an argument a reference to a json object, a reference to a table object and an integer.
What I want this function to do is:
Check the integer to decide what operation to perform
Check the size of the json to know how many parameters are gonna be passed to the variadic function of the X DevAPI that is used to perform the operation.
Assemble and perform the function call
For example, assume a table "users", as well as a json object "X" with following contents:
{"id":1,"username":"test_user","email":"test#test.com","first_name":"test"}
Now, when I would call the function like this
jsonToCUDOperation(X, users, MySQLDatabaseHandler::cud::create);
I would want the function to parse the json object and call the mysqlx::Table::Insert function with parameters (and parameter count) based on the json object's keys and values, so eventually calling
users.insert("id", "username", "email", "first_name")
.values("1", "test_user", "test#test.com", "test").execute();
I first thought about achieving this behavior using a template function, but then I figured it wouldn't make sense, since the template function definitions are generated at compile time, and what I desire would require dynamic behavior at runtime. So I thought that it is not possible to design this as I intend, as it was my understanding that the behavior of a C++ function cannot change at runtime based on the parameters you pass to it. But I've figured that before I begin developing a solution which can only handle a limited json object size, I'd ask here to assure that I actually cant do what I want.
Thanks in advance for enlightening me
You can actually just pass STL containers to the CRUD functions provided by MySQL's X DevAPI

move function body, avoiding full cloning

This is a follow up question from this one.
I am using llvm::CloneFunctionInto defined in llvm/Transforms/Utils/Cloning.h in order to create a new function after code generation with the right signature inferred from the type of the return values. This works nicely but it is slow
I am trying to optimize this a little bit by some way to move or transfer the function body from the old function to the new one, is there a utility for that?
I am trying to hack a way to do the transfer by looking at the code in CloneFunctionInto, but wanted to see if an existing function exists
Shamelessly stolen from the Arg Promotion pass (search for splice):
// Since we have now created the new function, splice the body of the old
// function right into the new function, leaving the old rotting hulk of the
// function empty.
NF->getBasicBlockList().splice(NF->begin(), F->getBasicBlockList());
Where NF is the new function you're cloning into and F is the old function that you have just cloned.

Lua: how to verify that a table contains a specific function

I'm developing a module that returns a table full of functions based on the arguments that are passed in. Specifically, the module returns a set of data transformation rules (functions) that need to be applied to a data set depending on which customer is sending it.
I decided to decouple my rule library (biz logic) from the code that decides which of the rules should be applied (config logic).
Here's the unit test I'm writing to verify that the ruleBuilder is adding the correct rule (function) based on one of my scenarios:
ruleBuilder = require("ruleBuilder")
ruleLibrary = require("ruleLibrary")
local rules = ruleBuilder.assembleRules("Customer1231")
assert(rules[1] == ruleLibrary.missingSSNRule)
Is this the correct way to do that verification? Will this work even if the ruleLibrary.missingSSNRule function has references to several other functions via a closure or parameter?
To verify that a table contains a particular function you may use the fact that keys in Lua tables can be anything (including functions). In your assembleRules code you can write something like this:
function assembleRules(...)
...
return {
[someOtherCoolModule.coolFunction] = someOtherCoolModule.coolFunction,
[yetAnotherModule.anotherFunction] = yetAnotherModule.anotherFunction,
}
end
Then later you can simply check if the key exists:
local rules = ruleBuilder.assembleRules("somedata")
assert(rules[someOtherCoolModule.coolFunction])
On the assumption that the return value of ruleBuilder.assembleRules is supposed to somehow know to put someOtherCoolModule.coolFunction in the 0-th index (note: Lua uses 1-based indices. Don't use 0 as an index) of its return value, then yes.
Will this work even if someOtherCoolModule.coolFunction is a closure?
All functions in Lua are closures. However, I'm going to assume that you mean that ruleBuilder.assembleRules is going to take someOtherCoolModule.coolFunction and build a new function around it.
A function is equal to itself. But it is only equal to itself. Just like two tables are only equal if they are the same table object, two functions are only equal if they are the same function. Functions are not equal to a different instantiation of the same function, nor is it equal to any other function. Here are examples of this.

C++: use of “().” and “()[].”

I am trying to understand the programming of Siemens scanner using C++ and given that my C++ skills are limited, I am having problems in understanding many parts of the code provided by the vendor.
Problem 1
For instance, the code uses reference (rMrProt) to object MrProt and notations (such as the use of use of (). and ()[].) are very confusing to me.
For instance:
ImageSamples = rMrProt.kSpace().baseResolution()
ImageSize = rMrProt.sliceSeries()[0].readoutFOV()
Some explanation of these statements would be appreciated.
All information regarding object MrProt are in “MrProt.h”, “MrProt.dll”, “MrProt.lib”. All these files have been shared at:
https://docs.google.com/open?id=0B0Ah9soYnrlIYWZkNDU2M2EtYTNmNC00YTc5LTllMzItYzIyMWU4M2ZhY2Fi
Problem 2
Also, I have been trying to read MrProt.dll and MrProt.lib without any success. Only now, I came to know of dumpbin. Any help would be appreciated.
Problem 3
Another confusion that I have is related to some part of MrProt.h itself. There is a statement in MrProt.h:
class __IMP_EXP MrProt: public MrProtocolData::MrProtDataDelegate
{
typedef MrProtocolData::MrProtDataDelegate BasicImplementation;
public:
MrProt();
MrProt(const MrProt& rSource);
…
….
}
Here, __IMP_EXP, I guess that it’s some compiler specific stuff.. some decoration etc. But, I still have no idea what to make of this.
Problem 1.
rMrProt.sliceSeries()[0].readoutFOV()
means
Take rMrProt's sliceSeries member and call that. Apparently, it returns an array-like object, something that can be indexed.
From the result, take the first element ([0]). That's some kind of object.
On that element/object, call readoutFOV.
Problem 2. You're not really supposed to read binary files. There should be documentation with them.
1)
ImageSamples = rMrProt.kSpace().baseResolution()
This is just method chaining. You call the method kSpace() on rMrPrto which returns an object, and you call baseResolution() on that object.
2) Those are binary files. What would you expect to see? To read them you'd have to be an expert in asm or at least know some low-level concepts.
3) __IMP_EXP is a common type of directive that tells the compiler that the class is either exported or imported.
It expands to _declspec(dllimport) or _declspec(dllexport), depending on whether the definition of the class is in the current module or another module.
identifier() is a method/function call
identifier[i] returns the i'th element in an array.
identifier()[i] returns the i'th element of the array returned by identifier()
I can only help on problem 1:
if the return value of rMrProt.kSpace() is a struct. instead of saving it to a struct and then access it's member you can directly access a member of his with rMrProt.kSpace().MemberName
same for rMrProt.sliceSeries() which I guess is returning an array. so rMrProt.sliceSeries()[0] will access the first value in the returning array.