简体   繁体   English

LLVM-如何将ConstantExpr转换为ConstantDataArray,以便可以打印全局变量char *的值?

[英]LLVM - How to convert ConstantExpr to ConstantDataArray so I can print value of global variable char*?

I'm writing LLVM pass which writes value of global variable when opt is called with -var [global_variable_name]. 我正在写LLVM传递,当使用-var [global_variable_name]调用opt时,它将写入全局变量的值。 But I'm not able to find out how to write strings defined as char *string = "help"; 但是我不知道如何写定义为char * string =“ help”;的字符串。 in .c source code. 在.c源代码中。

I have tried: 我努力了:

if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
        writeConstant(Out, CE->getAggregateElement(CV));
        return;
}

but this resulted in SEGFAULT. 但这导致SEGFAULT。

This is part of function for writing global variable of int type: 这是用于编写int类型的全局变量的函数的一部分:

void writeConstant(raw_ostream &Out, const Constant *CV)
{
    if (const ConstantInt *CI = dyn_cast<ConstantInt>(CV)) {
        if (CI->getType()->isIntegerTy(1)) {
             Out << (CI->getZExtValue() ? "true" : "false");
            return;
        }
    }
   APInt AI = CI->getValue();
        if( CI->getBitWidth() == 8) { // if sizeof constant == sizeof char
            const uint64_t *letter = AI.getRawData();
            if(char letter2 = (char) (*letter)) {
                Out << letter2;
                return;
            }
        }
        Out << CI->getValue();
        return;
    }

Excpected result: 预期结果:

In testsource.c is line as follows: 在testsource.c中的行如下:

char *testString = "Hello";

Calling in bash: 调用bash:

opt -load pass.so -var testString < testsource.bc > /dev/null

Output of command above: 上面命令的输出:

Hello

Finally found out solution, it was needed to get operand of constant expression which could be represented as global variable and thus it has initializer of constant data array type so it was just needed to call my function over this type of Constant. 最终找到解决方案,需要获取可以表示为全局变量的常量表达式的操作数,因此它具有常量数据数组类型的初始化程序,因此仅需要在此类型的Constant上调用我的函数。 See code below: 参见下面的代码:

    if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CV)) {
        Value *firstop = CE->getOperand(0);
        if (GlobalVariable *GV = dyn_cast<GlobalVariable>(firstop)) {
            Constant *v = GV->getInitializer();
            writeConstant(Out, v);
        }
        return;
    }

For more information look up in repo: https://github.com/Petku/GlobalVariablePass/blob/master/globvars/globvars.cpp 有关更多信息,请在回购中查找: https : //github.com/Petku/GlobalVariablePass/blob/master/globvars/globvars.cpp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM