首页 > 解决方案 > 在 LLVM IR 中添加来自外部库 (rpclib) 的函数调用

问题描述

我有一个非常简单的程序,它接受两个整数并将它们相加。我想在这个程序中添加一段代码,以便在哪里add调用函数的位置为用户提供选择,而不是在本地或服务器上进行计算。

我的原始程序如下所示:

#include <iostream>

using namespace std;

extern "C" double add(double a, double b);

int main()
{
    double a, b, result;
    cout<<"Enter first argument: ";
    cin>>a;
    cout<<"Enter second argument: ";
    cin>>b;
    result = add(a, b);
    cout<<"Locally computed result: "<<result<<endl;
    return 0;
}


extern "C" double add(double a, double b)
{
    return a + b;
}

期望的转变:

#include <iostream>
#include "rpc/client.h"
#include "rpc/rpc_error.h"

using namespace std;

extern "C" double add(double a, double b);

const int PORT = 20143;

int main()
{
    // Init RPC client
    rpc::client c("localhost", PORT);
    double a, b, result;
    cout<<"Enter first argument: ";
    cin>>a;
    cout<<"Enter second argument: ";
    cin>>b;
    char location;
    cout<<"execute function on server or client? (s/c) ";
    cin>>location;
    if (location == 'c') {
        result = add(a, b);
        cout<<"Locally computed result: "<<result<<endl;
    }
    else if (location == 's') {
        result = c.call("run_on_server", "add", a, b).as<double>();
        cout<<"Response received from edge: "<<result<<endl;
    }
    return 0;
}

extern "C" double add(double a, double b)
{
    return a + b;
}

我正在使用rpclib进行远程调用。我用不同版本的程序生成了 IR 来比较它们,看看我需要添加什么。

  1. 为原始程序生成了一个非常正常的 IR
  2. 如果我添加 rpc 标头和rpc::client c("localhost", PORT);大约 50 行。
  3. 当我添加result = c.call("run_on_server", "add", a, b).as<double>();它时,它会爆炸并添加大约 11k 行。我不知道为什么。它不应该已经添加了我创建对象的第 2 步所需的一切吗?

我的问题是,我该如何进行这样的转变?我可以向 IR 添加简单的函数调用,但不确定我应该如何包含 rpc 标头。

标签: llvmrpcllvm-ir

解决方案


创建一个可以完成所有繁重工作的辅助函数。就像是

extern "C" void helper(const char* funcName)
{
rpc::client c("localhost", PORT);
c.call("run_on_server", funcName);
}

将此代码编译成一个.bc文件并将其链接到您的通行证中。之后,将呼叫插入到helper()您想要的任何位置。

您可以将helpers 代码用作一种模板并添加所需的参数和返回值。


推荐阅读