Search code examples
llvm-clang

How to get a GetElementPtrInst's value after it was define?


I used llvm compiled this code,which means I want to send a message if I find a Potential divide-by-zero fault:

  int main() {
    int x[3];
    int y;
    x[0] = 0;
    x[1] = tainted_input();
    x[2] = 1;
    y = 4 / x[0]; 
}

and compiling result is:

define dso_local i32 @main() #0 {
entry:
  %x = alloca [3 x i32], align 4
  %y = alloca i32, align 4
  %arrayidx = getelementptr inbounds [3 x i32], [3 x i32]* %x, i64 0, i64 0
  store i32 0, i32* %arrayidx, align 4
  %call = call i32 (...) @tainted_input()
  %arrayidx1 = getelementptr inbounds [3 x i32], [3 x i32]* %x, i64 0, i64 1
  store i32 %call, i32* %arrayidx1, align 4
  %arrayidx2 = getelementptr inbounds [3 x i32], [3 x i32]* %x, i64 0, i64 2
  store i32 1, i32* %arrayidx2, align 4
  %arrayidx3 = getelementptr inbounds [3 x i32], [3 x i32]* %x, i64 0, i64 0
  %0 = load i32, i32* %arrayidx3, align 4
  %div = sdiv i32 4, %0
  store i32 %div, i32* %y, align 4
  ret i32 0
}

I find that there is some difference between twice apperance of x[0]" ,First time there is:

`%arrayidx = getelementptr inbounds [3 x i32], [3 x i32]* %x, i64 0, i64 0`  

But next time there is :

`%arrayidx3 = getelementptr inbounds [3 x i32], [3 x i32]* %x, i64 0, i64 0`

So,I don't know how to get %arrayidx3's value and check it if x[0] is equal to 0.

Could you help me to solve this problem?

If you can't understand what I want to do,please say it in the comment.Thanks a lot!


Solution

  • You're using C/C++, which is a statically compiled language. This means there's a lot of runtime information the compiler hasn't got access to, and these include zero division errors. So checking if x[0] equals 0 is impossible at compile time as the values have not yet been loaded into actual memory.