LLVM检查数组分配是否具有动态大小或常量大小

时间:2016-10-07 15:07:22

标签: llvm

我想检查数组的堆栈分配是否具有常量大小或动态大小(在运行时计算)。例如

int myInt;
scanf("%d", &myInt);
int buffer[myInt]; //dynamic sized array

动态大小的数组转换为llvm IR,如下所示:

%myInt = alloca i32, align 4
%saved_stack = alloca i8*
%call = call i32 (i8*, ...) @__isoc99_scanf(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @.str, i32 0, i32 0), i32* %myInt)
%0 = load i32, i32* %myInt, align 4
%1 = zext i32 %0 to i64
%2 = call i8* @llvm.stacksave()
store i8* %2, i8** %saved_stack
%vla = alloca i32, i64 %1, align 16 //allocation
%3 = load i8*, i8** %saved_stack
call void @llvm.stackrestore(i8* %3)

一个恒定大小的数组:

int buffer2[123]; 

LLVM IR:

%buffer2 = alloca [123 x i32], align 16 

如何识别alloca指令是否分配动态大小的数组或恒定大小的数组?

1 个答案:

答案 0 :(得分:1)

查看" include / llvm / IR / Instructions.h"中的class AllocaInst。它包含一个返回已分配数组

的大小的方法
  /// Get the number of elements allocated. For a simple allocation of a single
  /// element, this will return a constant 1 value.
  const Value *getArraySize() const { return getOperand(0); }

对于数组大小的Value *,您应该能够使用dyn_cast<ConstantInt>来分析是否为常量。 (grep for this expression。它在代码中被广泛使用。)