简体   繁体   English

如何在LLVM IR中获取字符串文字的值?

[英]How to get the value of a string literal in LLVM IR?

I'm new to LLVM. 我是LLVM的新手。 I'm trying to write a basic Pass that will inspect the arguments of a printf call, when it is given the Intermediate Representation. 我正在尝试编写一个基本的Pass,它将检查printf调用的参数,当它被赋予中间表示时。
If the format string is not a string literal, then of course I can't inspect it. 如果格式字符串不是字符串文字,那么我当然无法检查它。 But quite often, it is. 但通常情况确实如此。

The sample IR I'm trying to inspect is: 我试图检查的样本IR是:

@.str = private unnamed_addr constant [7 x i8] c"Hi %u\0A\00", align 1

define i32 @main() nounwind {
entry:
  %retval = alloca i32, align 4
  store i32 0, i32* %retval
  %call = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([7 x i8]* @.str, i32 0, i32 0), i32 1)
  ret i32 0
}

declare i32 @printf(i8*, ...)

I found the preexisting Pass called ExternalFunctionsPassedConstants , which seemed relevant: 我找到了一个名为ExternalFunctionsPassedConstants的预先存在的Pass,它看似相关:

struct ExternalFunctionsPassedConstants : public ModulePass {
  static char ID; // Pass ID, replacement for typeid
  ExternalFunctionsPassedConstants() : ModulePass(ID) {}
  virtual bool runOnModule(Module &M) {
    for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
      if (!I->isDeclaration()) continue;

      bool PrintedFn = false;
      for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
           UI != E; ++UI) {
        Instruction *User = dyn_cast<Instruction>(*UI);
        if (!User) continue;

        CallSite CS(cast<Value>(User));
        if (!CS) continue;

        ...

So I added the code: 所以我添加了代码:

        if (I->getName() == "printf") {
          errs() << "printf() arg0 type: "
                 << CS.getArgument(0)->getType()->getTypeID() << "\n";
        }

So far, so good -- I see that the type ID is 14, which means it's a PointerTyID . 到目前为止,这么好 - 我看到类型ID是14,这意味着它是一个PointerTyID

But now, how do I get the contents of the string literal that is being passed as an argument, so I can validate the number of expected arguments against the number actually given? 但是现在,我如何得到作为参数传递的字符串文字的内容 ,所以我可以根据实际给出的数字验证预期参数的数量?

CS.getArgument(0)  

represents the GetElementPtrConstantExpr 表示GetElementPtrConstantExpr

i8* getelementptr inbounds ([7 x i8]* @.str, i32 0, i32 0)

, it is an User object. ,它是一个User对象。 The string you want (ie @.str) is this GetElementPtrConstantExpr's first operand. 你想要的字符串(即@ .str)是这个GetElementPtrConstantExpr的第一个操作数。

So, you can get the string literal through 所以,你可以得到字符串文字

CS.getArgument(0).getOperand(0)

However, I have not tested this code. 但是,我还没有测试过这段代码。 If there are any mistakes, please tell me. 如果有任何错误,请告诉我。

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

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