[foreign] Feature request: Scope.allocate*() with given alignment

Maurizio Cimadamore maurizio.cimadamore at oracle.com
Thu Feb 28 17:50:33 UTC 2019


On 28/02/2019 17:31, Lev Serebryakov wrote:
> On 28.02.2019 19:30, Maurizio Cimadamore wrote:
>
>> We have plans for that - the basic idea is to use special annotation in
>> the underlying layout which will give the runtime hints on alignment.
>   What do you mean by underlying layout here?
>   For example, AVX512 code needs `Array<Float>` but aligned at 64 byte
> boundary, when natural `Float` alignment is only 4 bytes.
>
In Panama, LayoutType has a Layout underneath. A standard-aligned 
20-elems array layout would be something like:

[ 20: f64 ]

But, the idea is to attach a layout annotation to specify alignment:

[ 20: f64 ](align=64)

which will then instruct the Scope to do the right thing.

In any case, note that, I believe, you can do some of this stuff by 
hand, as this test demonstrates:


import java.foreign.NativeTypes;
import java.foreign.Scope;
import java.foreign.layout.Group;
import java.foreign.layout.Padding;
import java.foreign.memory.Pointer;

public class TestAlign {
     public static void main(String[] args) throws Throwable {
         try (Scope s = Scope.globalScope().fork()) {
             check(s, 1);
             check(s, 2);
             check(s, 4);
             check(s, 8);
             check(s, 16);
             check(s, 32);
             check(s, 64);
             check(s, 128);
             check(s, 256);
             check(s, 512);
         }
     }

     static void check(Scope s, long align) throws IllegalAccessException {
         Pointer<Byte> ptr = malloc_aligned(s, 8, align);
         if (ptr.addr() % align != 0) {
             throw new AssertionError("Wrong alignment: address not a 
multiple of " + align);
         }
         for (int i = 0 ; i < 8 ; i++) {
             //try to get, to see if allocated memory is big enough
             ptr.offset(i).get();
         }
     }

     static Pointer<Byte> malloc_aligned(Scope sc, long size, long 
alignment) {
         try {
             Pointer<Byte> buffer = 
sc.allocate(Group.struct(Padding.of(alignment * 8) , Padding.of(size * 8)))
                     .cast(NativeTypes.VOID)
                     .cast(NativeTypes.UINT8);
             long alignMask = alignment - 1;
             long alignedAddr = (buffer.addr() + alignMask) & ~ alignMask;
             return buffer.offset(alignedAddr - buffer.addr());
         } catch (IllegalAccessException ex) {
             throw new IllegalStateException(ex);
         }
     }

}


Is this something that could be useful?

Maurizio




More information about the panama-dev mailing list