I am working on a toy language written using the llvm c++ api and I am trying to implement arrays. I have tried several different things none of which have worked very well.
Here is what I am going for:
- A type that can resemble an array (struct, vector or array would work)
- Can be passed to and returned from functions
- Can have infinitely nested arrays (eg.
[8 x [8 x [8 x [...]) - Can be re-assignable
- Arrays are all of the same type
- Arrays are of finite length specified on creation.
Ideally, they would resemble arrays in swift.
Current solution
Currently I am using the basic array type. This checks all of the boxes except that while a one dimensional array can be passed to and returned from a function, multidimensional (nested) arrays must be passed by pointer. This means that I have to not only bitcast the returned pointer to the proper type but then loop through every element and store it in the appropriate place. Quickly this becomes not only very messy but also slow.
Vectors
As far as I can tell, you cannot have nested vectors. eg. this does not work:
<8 x <8 x i32>>
Using malloc
Lastly, I tried using malloc to allocate the appropriate space then just use pointers for everything. This had many of the same problems as my current solution.
Something like C++?
Take the following example:
%1 = alloca [5 x i32], align 16
%2 = alloca i32*, align 8
%3 = getelementptr inbounds [5 x i32], [5 x i32]* %1, i32 0, i32 0
%4 = call i32* @_Z8getArrayPi(i32* %3)
store i32* %4, i32** %2, align 8
There is no way to store the pointer %4 into %1 so a new allocation must be created. Otherwise (with nested arrays) each element would need to be copied and there would be the same problem as in my current solution. Also, ideally the compiler would deal with all the pointers, so it would just look like an array to the user of the language.
Question
In case it was not clear - my question is how do I implement arrays so that I can do all of the things listed above (without having to copy every element).