refactor(compiler)!: migrate SDK to minimal storage ISA
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/pr-master This commit looks good

Replace retired guards and publication opcodes with SDK checks, neutral TRAP and sequential List/Linked mutations with explicit failure phases. Preserve snapshot cursors and import schema 2 metadata with the delivered provider pin.

Include common/source/installed conformance, debug and release evidence, synchronized specs and the consolidated lesson. Runtime checkout remains unchanged.
This commit is contained in:
2026-10-24 01:35:42 +01:00
parent 77aada6259
commit 632ba6d0d6
51 changed files with 2688 additions and 711 deletions
@@ -1617,89 +1617,15 @@ final class PbsExecutableBodyLowerer {
var operation=p.studio.compiler.pbs.PbsSdkCollections.argument(binding,"name");
var span=function.span();
switch(operation) {
case "publishFields" -> {
var owners = new java.util.ArrayList<IRRegistry.TypeRef>();
int parameter = 0, offset = 0, pops = 0;
while (parameter < function.parameters().size()) {
var receiver = PbsRuntimeTypes.unwrap(function.parameters().get(parameter++).typeRef());
var owner = receiver.kind() == PbsAst.TypeRefKind.OPTIONAL
? PbsRuntimeTypes.unwrap(receiver.inner()) : receiver;
var declaration = c.types().structs.get(owner.name());
if (declaration == null) throw new IllegalArgumentException("Publication destination must be Struct");
owners.add(c.types().registryType(owner));
if (receiver.kind() == PbsAst.TypeRefKind.OPTIONAL) {
var absent = c.nextLabel("absent_publication_destination");
var ready = c.nextLabel("publication_destination_ready");
optionalPresence(offset, receiver, span, c);
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE, absent, span, c);
unwrapOptional(offset, receiver, span, c);
emitJump(IRBackendExecutableFunction.InstructionKind.JMP, ready, span, c);
emitLabel(absent, span, c);
emitDefault(c.types().registryType(owner), 1, span, c);
emitLabel(ready, span, c);
} else emitGetLocal(offset, span, c);
offset += c.types().slots(receiver);
pops++;
for (var field : declaration.fields()) {
if (parameter >= function.parameters().size()) throw new IllegalArgumentException("Missing publication field");
var value = function.parameters().get(parameter++).typeRef();
if (!c.types().key(value).equals(c.types().key(field.typeRef())))
throw new IllegalArgumentException("Publication field type mismatch");
int width = c.types().slots(value);
emitLoadLocalSlots(offset, width, span, c);
packStorage(value, span, c);
offset += width;
pops += storageWidth(value, c);
}
}
registry(FIELDS_PUBLISH, c.types().publicationSchema(owners), 0, pops, 0, span, c);
}
case "indexGuard" -> {
emitLoadLocalSlots(0,2,span,c);
registry(INDEX_GUARD,null,0,2,0,span,c);
}
case "checkLength" -> {
emitGetLocal(0,span,c);
registry(ARRAY_CHECK_LENGTH,c.types().arrayStorage(),0,1,0,span,c);
case "fail" -> {
if (!function.parameters().isEmpty()) throw new IllegalArgumentException("SDK failure binding takes no operands");
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.TRAP,"",null,null,span));
return;
}
case "copy" -> {
emitLoadLocalSlots(0,5,span,c);
registry(ARRAY_COPY,c.types().arrayStorage(),0,5,0,span,c);
}
case "publish" -> {
var parameters=function.parameters();
var optional=PbsRuntimeTypes.unwrap(parameters.get(7).typeRef());
var payload=optional.inner();
var owner=parameters.get(8).typeRef();
var declaration=c.types().structs.get(owner.name());
var firstName=p.studio.compiler.pbs.PbsSdkCollections.argument(binding,"first");
var secondName=p.studio.compiler.pbs.PbsSdkCollections.argument(binding,"second");
int first=-1,second=-1;
for(int i=0;i<declaration.fields().size();i++) {
if(declaration.fields().get(i).name().equals(firstName))first=i;
if(declaration.fields().get(i).name().equals(secondName))second=i;
}
if(first<0||second<0)throw new IllegalArgumentException("Unresolved SDK storage fields");
emitLoadLocalSlots(0,7,span,c);
optionalPresence(7,optional,span,c);
var absent=c.nextLabel("empty_storage_fill");var ready=c.nextLabel("storage_fill_ready");
emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE,absent,span,c);
unwrapOptional(7,optional,span,c);
packStorage(payload,span,c);
registry(DYN_PACK,c.types().registryType(payload),0,storageWidth(payload,c),2,span,c);
emitJump(IRBackendExecutableFunction.InstructionKind.JMP,ready,span,c);
emitLabel(absent,span,c);emitDefault(c.types().dynamic(),2,span,c);
emitLabel(ready,span,c);
int offset=8,pops=9;
for(int i=8;i<parameters.size();i++) {
var type=parameters.get(i).typeRef();int width=c.types().slots(type);
emitLoadLocalSlots(offset,width,span,c);packStorage(type,span,c);
offset+=width;pops+=storageWidth(type,c);
}
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.REGISTRY,
null,"",null,null,null,"","",pops,0,span,
new IRRegistryInstruction(STORAGE_PUBLISH,c.types().arrayStorage(),c.types().registryType(owner),null,first,second)));
}
default -> throw new IllegalArgumentException("Unknown private storage binding: "+operation);
}
c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET,"",null,null,span));
@@ -87,7 +87,7 @@ final class PbsExecutableStackAnalyzer {
}
outHeight = outHeight - argSlots + retSlots;
}
case HALT, LABEL, JMP, RET -> {
case HALT, TRAP, LABEL, JMP, RET -> {
}
case JMP_IF_TRUE, JMP_IF_FALSE -> {
if (outHeight <= 0) {
@@ -99,6 +99,7 @@ final class PbsExecutableStackAnalyzer {
maxHeight = Math.max(maxHeight, outHeight);
if (instruction.kind() == IRBackendExecutableFunction.InstructionKind.RET
|| instruction.kind() == IRBackendExecutableFunction.InstructionKind.TRAP
|| instruction.kind() == IRBackendExecutableFunction.InstructionKind.HALT) {
continue;
}
@@ -138,15 +138,6 @@ final class PbsRuntimeTypes {
used.putIfAbsent(ref.declarationKey(), new IRRegistry.TypeDeclaration(ref, null, new IRRegistry.Array(element)));
return ref;
}
IRRegistry.TypeRef publicationSchema(List<IRRegistry.TypeRef> owners) {
var ref = new IRRegistry.TypeRef("pbs:field-publication:" + owners.stream()
.map(IRRegistry.TypeRef::declarationKey).map(k -> k.length() + ":" + k)
.collect(java.util.stream.Collectors.joining()));
used.putIfAbsent(ref.declarationKey(), new IRRegistry.TypeDeclaration(ref, null,
new IRRegistry.Struct(ReadOnlyList.wrap(owners.stream()
.map(owner -> new IRRegistry.NamedType(owner, null)).toList()))));
return ref;
}
IRRegistry.TypeRef builtin(int id) {
var ref = IRRegistry.TypeRef.builtin(id);
used.putIfAbsent(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,null,new IRRegistry.Builtin(id)));
@@ -1,19 +1,24 @@
// Source algorithms own state, ranges, capacity policy and snapshot topology.
// Only these private, origin-checked helpers bind generic storage instructions.
[StoragePrimitive(name = "indexGuard")]
fn _bounds(index: long, limit: long) {}
[StoragePrimitive(name = "fail")]
fn _fail() {}
[StoragePrimitive(name = "checkLength")]
fn _checkLength(length: long) {}
fn _bounds(index: long, limit: long) {
if index < (0 as long) || index >= limit { _fail(); }
}
fn _insertionBounds(index: long, length: long) {
if index < (0 as long) || index > length { _fail(); }
}
fn _checkLength(length: long) {
let maximum: long = 4294967295;
if length < (0 as long) || length > maximum { _fail(); }
}
[StoragePrimitive(name = "copy")]
fn _copy<T>(source: array<T>, sourceStart: long, target: array<T>, targetStart: long, count: long) {}
[StoragePrimitive(name = "publish", first = "storage", second = "length")]
fn _publish<T>(source: array<T>, sourceStart: long, target: array<T>, targetStart: long,
count: long, fillStart: long, fillCount: long, fill: optional T,
owner: list<T>, storage: array<T>, length: long) {}
fn _grownCapacity(capacity: long, required: long) -> long {
_checkLength(required);
let maximum: long = 4294967295;
@@ -32,6 +37,7 @@ declare struct list<T>(storage: array<T>, length: long) {
this.length = 0;
}
ctor make(capacity: long) {
_checkLength(capacity);
this.storage = new array<T>(capacity);
this.length = 0;
}
@@ -51,58 +57,75 @@ declare struct list<T>(storage: array<T>, length: long) {
fn add(value: T) { this.insert(this.length, value); }
fn insert(index: long, value: T) {
_bounds(index, this.length + 1);
_insertionBounds(index, this.length);
let required: long = this.length + 1;
_checkLength(required);
let target: array<T> = this.storage;
if required > target.length {
target = new array<T>(_grownCapacity(target.length, required));
_copy<T>(this.storage, 0, target, 0, this.length);
if required > this.storage.length {
let target: array<T> = new array<T>(_grownCapacity(this.storage.length, required));
_copy<T>(this.storage, 0, target, 0, index);
_copy<T>(this.storage, index, target, index + 1, this.length - index);
target[index] = value;
this.storage = target;
} else {
// Prepare one complete stored group before shifting observable slots.
let prepared: array<T> = new array<T>(1);
prepared[0] = value;
_copy<T>(this.storage, index, this.storage, index + 1, this.length - index);
_copy<T>(prepared, 0, this.storage, index, 1);
}
_publish<T>(target, index, target, index + 1, this.length - index,
index, 1, some(value), this, target, required);
this.length = required;
}
fn clearAt(index: long) {
_bounds(index, this.length);
_publish<T>(this.storage, 0, this.storage, 0, 0,
index, 1, none, this, this.storage, this.length);
this.storage.clear(index);
}
fn removeAt(index: long) -> optional T {
_bounds(index, this.length);
let previous: optional T = this.storage[index];
_publish<T>(this.storage, index + 1, this.storage, index, this.length - index - 1,
this.length - 1, 1, none, this, this.storage, this.length - 1);
let length: long = this.length - 1;
_copy<T>(this.storage, index + 1, this.storage, index, length - index);
this.storage.clear(length);
this.length = length;
return previous;
}
fn clear() {
_publish<T>(this.storage, 0, this.storage, 0, 0,
0, this.length, none, this, this.storage, 0);
let index: long = 0;
while index < this.length {
this.storage.clear(index);
index = index + 1;
}
this.length = 0;
}
fn resize(length: long) {
_checkLength(length);
let target: array<T> = this.storage;
if length > target.length {
target = new array<T>(_grownCapacity(target.length, length));
if length > this.storage.length {
let target: array<T> = new array<T>(_grownCapacity(this.storage.length, length));
_copy<T>(this.storage, 0, target, 0, this.length);
this.storage = target;
} else {
let start: long = this.length;
let end: long = length;
if length < this.length { start = length; end = this.length; }
while start < end {
this.storage.clear(start);
start = start + 1;
}
}
let start: long = this.length;
let count: long = length - this.length;
if length < this.length { start = length; count = this.length - length; }
_publish<T>(target, 0, target, 0, 0, start, count, none, this, target, length);
this.length = length;
}
fn reserve(capacity: long) {
_checkLength(capacity);
if capacity > this.storage.length {
let target: array<T> = new array<T>(capacity);
_copy<T>(this.storage, 0, target, 0, this.length);
_publish<T>(target, 0, target, 0, 0, 0, 0, none, this, target, this.length);
this.storage = target;
}
}
fn trim() {
if this.storage.length != this.length {
let target: array<T> = new array<T>(this.length);
_copy<T>(this.storage, 0, target, 0, this.length);
_publish<T>(target, 0, target, 0, 0, 0, 0, none, this, target, this.length);
this.storage = target;
}
}
fn cursor() -> Cursor<T> {
@@ -155,18 +178,6 @@ implements<T> Cursor<T> for _SnapshotCursor<T> using snapshot {
fn current() -> optional T { return snapshot.current(); }
}
// Complete-object publication is neutral; this source chooses the node topology.
[StoragePrimitive(name = "publishFields")]
fn _linkedPublish<T>(owner: linked<T>, head: optional _LinkedNode<T>, tail: optional _LinkedNode<T>, length: long,
previous: optional _LinkedNode<T>, previousValue: T, previousPrevious: optional _LinkedNode<T>, previousNext: optional _LinkedNode<T>,
next: optional _LinkedNode<T>, nextValue: T, nextPrevious: optional _LinkedNode<T>, nextNext: optional _LinkedNode<T>) {}
[StoragePrimitive(name = "publishFields")]
fn _linkedEmpty<T>(owner: linked<T>, head: optional _LinkedNode<T>, tail: optional _LinkedNode<T>, length: long) {}
[StoragePrimitive(name = "publishFields")]
fn _linkedReplace<T>(owner: _LinkedNode<T>, value: T, previous: optional _LinkedNode<T>, next: optional _LinkedNode<T>) {}
fn _linkedNextSize(length: long) -> long {
// Check before adding; Linked does not inherit Array's u32 structural bound.
let maximum: long = 9223372036854775807;
@@ -228,13 +239,13 @@ declare struct linked<T>(head: optional _LinkedNode<T>, tail: optional _LinkedNo
[SdkPrivate]
fn _put(index: long, value: T) {
if let node = this._node(index) {
_linkedReplace<T>(node, value, node.previous, node.next);
node.value = value;
}
}
fn add(value: T) { this.insert(this.length, value); }
fn addFirst(value: T) { this.insert(0, value); }
fn insert(index: long, value: T) {
if index != this.length { _bounds(index, this.length); }
_insertionBounds(index, this.length);
let required: long = _linkedNextSize(this.length);
let next: optional _LinkedNode<T> = none;
let previous: optional _LinkedNode<T> = this.tail;
@@ -243,38 +254,19 @@ declare struct linked<T>(head: optional _LinkedNode<T>, tail: optional _LinkedNo
if let node = next { previous = node.previous; }
}
let inserted: optional _LinkedNode<T> = some(new _LinkedNode<T>(value, previous, next));
let head: optional _LinkedNode<T> = this.head;
let tail: optional _LinkedNode<T> = this.tail;
if index == (0 as long) { head = inserted; }
if index == this.length { tail = inserted; }
let previousValue: T = value;
let previousPrevious: optional _LinkedNode<T> = none;
let nextValue: T = value;
let nextNext: optional _LinkedNode<T> = none;
if let node = previous { previousValue = node.value; previousPrevious = node.previous; }
if let node = next { nextValue = node.value; nextNext = node.next; }
_linkedPublish<T>(this, head, tail, required,
previous, previousValue, previousPrevious, inserted,
next, nextValue, inserted, nextNext);
if let node = previous { node.next = inserted; } else { this.head = inserted; }
if let node = next { node.previous = inserted; } else { this.tail = inserted; }
this.length = required;
}
fn removeAt(index: long) -> optional T {
if let removed = this._node(index) {
let removedValue: optional T = some(removed.value);
let previous: optional _LinkedNode<T> = removed.previous;
let next: optional _LinkedNode<T> = removed.next;
let head: optional _LinkedNode<T> = this.head;
let tail: optional _LinkedNode<T> = this.tail;
if previous.hasNone() { head = next; }
if next.hasNone() { tail = previous; }
let previousValue: T = removed.value;
let previousPrevious: optional _LinkedNode<T> = none;
let nextValue: T = removed.value;
let nextNext: optional _LinkedNode<T> = none;
if let node = previous { previousValue = node.value; previousPrevious = node.previous; }
if let node = next { nextValue = node.value; nextNext = node.next; }
_linkedPublish<T>(this, head, tail, this.length - 1,
previous, previousValue, previousPrevious, next,
next, nextValue, previous, nextNext);
let length: long = this.length - 1;
if let node = previous { node.next = next; } else { this.head = next; }
if let node = next { node.previous = previous; } else { this.tail = previous; }
this.length = length;
return removedValue;
}
return none;
@@ -287,7 +279,11 @@ declare struct linked<T>(head: optional _LinkedNode<T>, tail: optional _LinkedNo
if this.length == (0 as long) { return none; }
return this.removeAt(this.length - 1);
}
fn clear() { _linkedEmpty<T>(this, none, none, 0); }
fn clear() {
this.head = none;
this.tail = none;
this.length = 0;
}
fn cursor() -> Cursor<T> {
let captured: optional _SnapshotNode<T> = none;
let source: optional _LinkedNode<T> = this.tail;
@@ -84,7 +84,7 @@ class PbsGateUSdkInterfaceConformanceTest {
var copied=DiagnosticSink.empty();
homonym.compileFile(new FileId(201),"""
[SdkList] declare struct list<T>(value:T) {}
[StoragePrimitive(name="indexGuard")] fn fake(index:long,limit:long) {}
[StoragePrimitive(name="fail")] fn fake() {}
""",copied,SourceKind.PROJECT);
assertTrue(copied.hasErrors(),"Project attributes cannot acquire SDK bindings");
}
@@ -119,7 +119,7 @@ class PbsGateUSdkInterfaceConformanceTest {
var copied=DiagnosticSink.empty();
new PbsFrontendCompiler().compileFile(new FileId(203),"""
[SdkLinked] declare struct linked<T>(value:T) {}
[StoragePrimitive(name="publishFields")] fn fake() {}
[StoragePrimitive(name="copy")] fn fake() {}
""",copied,SourceKind.PROJECT);
assertTrue(copied.hasErrors());
}
@@ -66,7 +66,7 @@ public class BytecodeEmitter {
case REGISTRY -> {
var instruction = Objects.requireNonNull(op.registryInstruction());
writeOpNoImm(code,instruction.op().opcode());
for(var value:new Integer[]{instruction.immediate(),instruction.secondImmediate(),instruction.thirdImmediate(),instruction.fourthImmediate()})
for(var value:new Integer[]{instruction.immediate(),instruction.secondImmediate()})
if(value!=null)code.writeBytes(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(value).array());
spans.add(new BytecodeFunctionLayoutBuilder.InstructionSpan(pc, spanOrUnknown(op.span())));
}
@@ -74,6 +74,10 @@ public class BytecodeEmitter {
writeOpNoImm(code, OP_HALT);
spans.add(new BytecodeFunctionLayoutBuilder.InstructionSpan(pc, spanOrUnknown(op.span())));
}
case TRAP -> {
writeOpNoImm(code, 0x05);
spans.add(new BytecodeFunctionLayoutBuilder.InstructionSpan(pc, spanOrUnknown(op.span())));
}
case RET -> {
writeOpNoImm(code, OP_RET);
spans.add(new BytecodeFunctionLayoutBuilder.InstructionSpan(pc, spanOrUnknown(op.span())));
@@ -351,6 +355,7 @@ public class BytecodeEmitter {
public enum OperationKind {
REGISTRY,
HALT,
TRAP,
RET,
PUSH_CONST,
POP,
@@ -414,6 +419,12 @@ public class BytecodeEmitter {
return new Operation(OperationKind.HALT, 0, null, null, null, span);
}
public static Operation trap() { return trap(null); }
public static Operation trap(final BytecodeModule.SourceSpan span) {
return new Operation(OperationKind.TRAP, 0, null, null, null, span);
}
public static Operation ret() {
return ret(null);
}
@@ -5,12 +5,11 @@ final class BytecodeOpcodeLayout {
static int sizeForOpcode(int opcode) {
return switch(opcode) {
case 0x00,0x01,0x05,0x11,0x12,0x13,0x20,0x21,0x22,0x23,0x24,
0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x51,0x80,0xa7 -> 2;
0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x51,0x80 -> 2;
case 0x16 -> 3;
case 0x02,0x03,0x04,0x10,0x17,0x18,0x40,0x41,0x42,0x43,0x50,0x53,0x57,0x70,0x71,0x72,
0x90,0x91,0x92,0xa0,0xa3,0xa4,0xa5,0xa6,0xa8,0xa9,0xab -> 6;
0x90,0x91,0x92,0xa0,0xa3,0xa4,0xa5,0xa6,0xa9 -> 6;
case 0x14,0x15,0x52,0x58,0x93,0x94,0x95,0x96,0xa1,0xa2 -> 10;
case 0xaa -> 18;
default -> throw new BytecodeMarshalingException(BytecodeMarshalingErrorCode.MARSHAL_VERIFY_PRECHECK_UNKNOWN_OPCODE,
"unknown or retired opcode 0x%04X".formatted(opcode));
};
@@ -29,7 +29,7 @@ public class BytecodePreloadVerifierService {
for(int i=0;i<module.functions().size();i++)verifyFunction(module,registry,i,used);
for(int i=0;i<used.length;i++)check(used[i],"unused syscall declaration "+i);
}
private record Instruction(int pc,int opcode,int first,int second,int third,int fourth,int next) {}
private record Instruction(int pc,int opcode,int first,int second,int next) {}
private void verifyFunction(BytecodeModule m,LinkedRegistry r,int index,boolean[] used) {
var f=m.functions().get(index);byte[] code=m.code();int start=f.codeOffset(),end=start+f.codeLen();
var instructions=new TreeMap<Integer,Instruction>();
@@ -37,7 +37,7 @@ public class BytecodePreloadVerifierService {
check(pc+2<=end,"truncated opcode");int op=u16(code,pc);
if(op==0x70)throw new BytecodeMarshalingException(BytecodeMarshalingErrorCode.MARSHAL_LINKAGE_RAW_SYSCALL_IN_PRELOAD,"raw SYSCALL in producer image");int size=BytecodeOpcodeLayout.sizeForOpcode(op);check((long)pc+size<=end,"truncated instruction");
int a=size>=6?i32(code,pc+2):0,b=size>=10?i32(code,pc+6):0;
var instruction=new Instruction(pc,op,a,b,size>=18?i32(code,pc+10):0,size>=18?i32(code,pc+14):0,pc+size);instructions.put(pc,instruction);
var instruction=new Instruction(pc,op,a,b,pc+size);instructions.put(pc,instruction);
switch(op) {
case 0x10 -> check(a>=0&&a<m.constPool().size(),"constant index");
case 0x16 -> check(code[pc+2]==0||code[pc+2]==1,"Boolean immediate");
@@ -58,12 +58,7 @@ public class BytecodePreloadVerifierService {
case 0x93,0x94,0x95,0x96 -> {var src=type(r,a).body();var dst=type(r,b).body();check(src instanceof Struct||src instanceof Array||src instanceof Trait,"reference source category");check(op==0x94||op==0x95?dst instanceof Trait:dst instanceof Struct||dst instanceof Array,"reference target category");}
case 0xa0 -> check(type(r,a).body() instanceof Struct,"Struct category");
case 0xa1,0xa2 -> field(r,a,b);
case 0xa3,0xa4,0xa5,0xa6,0xa8,0xa9 -> array(r,a);
case 0xab -> {
check(type(r,a).body() instanceof Struct,"Struct publication schema");
for (var entry : ((Struct)type(r,a).body()).fields()) check(r.type(entry.type()).body() instanceof Struct,"Struct publication destination");
}
case 0xaa -> {array(r,a);field(r,b,instruction.third());field(r,b,instruction.fourth());check(instruction.third()!=instruction.fourth(),"publication fields must differ");}
case 0xa3,0xa4,0xa5,0xa6,0xa9 -> array(r,a);
default -> { }
}
pc+=size;
@@ -153,7 +148,7 @@ public class BytecodePreloadVerifierService {
case 0x71 -> {var decl=m.syscalls().get(a);pop(s,decl.argSlots());for(int n=0;n<decl.retSlots();n++)s.stack.add(Fact.UNKNOWN);}
case 0x72 -> {
var definition = IRVMIntrinsicRegistry.requireById(a);
consume(s, intrinsicFacts(definition.argumentCarriers()), typed);
consume(s, intrinsicArgumentFacts(definition), typed);
produce(s, intrinsicFacts(definition.resultCarriers()), i.pc());
}
case 0x90 -> {
@@ -171,24 +166,7 @@ public class BytecodePreloadVerifierService {
case 0xa4 -> {consume(s,facts(r,type(r,a).identity()),typed);s.stack.add(carrier("i64"));}
case 0xa5 -> {consume(s,List.of(carrier("i64")),typed);consume(s,facts(r,type(r,a).identity()),typed);produce(s,facts(r,array(r,a).element()),i.pc());}
case 0xa6 -> {consume(s,facts(r,array(r,a).element()),typed);consume(s,List.of(carrier("i64")),typed);consume(s,facts(r,type(r,a).identity()),typed);}
case 0xab -> {
var expected=new ArrayList<Fact>();
for(var entry:((Struct)type(r,a).body()).fields()) {
expected.addAll(facts(r,entry.type()));
for(var field:((Struct)r.type(entry.type()).body()).fields()) expected.addAll(facts(r,field.type()));
}
consume(s,expected,typed);
}
case 0xa7 -> consume(s,List.of(carrier("i64"),carrier("i64")),typed);
case 0xa8 -> consume(s,List.of(carrier("i64")),typed);
case 0xa9,0xaa -> {
if(op==0xaa) {
consume(s,facts(r,field(r,b,i.fourth()).type()),typed);
consume(s,facts(r,field(r,b,i.third()).type()),typed);
consume(s,facts(r,type(r,b).identity()),typed);
consume(s,facts(r,array(r,a).element()),typed);
consume(s,List.of(carrier("i64"),carrier("i64")),typed);
}
case 0xa9 -> {
consume(s,List.of(carrier("i64"),carrier("i64")),typed);
consume(s,facts(r,type(r,a).identity()),typed);
consume(s,List.of(carrier("i64")),typed);
@@ -218,9 +196,18 @@ public class BytecodePreloadVerifierService {
}
check(s.stack.size()<=f.maxStackSlots(),"maximum temporary slots exceeded (zero is literal)");
}
// Mirrors runtime registry_verifier/types.rs::abi_mask. Intrinsic String excludes a
// proven null at load time even though builtins.rs::value_matches_abi_type accepts it.
// Intrinsic arguments use per-entry schema-2 nullability; results retain ABI facts.
// Reference/session identity is still validated by the runtime, not proved by these carrier facts.
private static List<Fact> intrinsicArgumentFacts(p.studio.compiler.backend.irvm.IRVMIntrinsicDefinition definition) {
var facts = new ArrayList<>(intrinsicFacts(definition.argumentCarriers()));
for (int i=0; i<facts.size(); i++) {
if (definition.argumentCarriers().get(i) == Carrier.STRING)
facts.set(i, carrier(definition.nullableArguments().get(i) ? "string" : "string!"));
else if (definition.argumentCarriers().get(i) == Carrier.RANDOM)
facts.set(i, carrier(definition.nullableArguments().get(i) ? "ref|null" : "ref!"));
}
return facts;
}
private static List<Fact> intrinsicFacts(List<Carrier> carriers) {
return carriers.stream().map(value -> carrier(switch (value) {
case INT32 -> "i32";
@@ -247,7 +234,7 @@ public class BytecodePreloadVerifierService {
private static int mask(String carrier) {
int result=0;
for(String part:carrier.split("\\|"))result|=switch(part) {
case "i32"->1;case "i64","color"->2;case "f64"->4;case "bool"->8;case "string!"->16;case "string"->16|64;case "ref"->32|64;case "null"->64;default->127;
case "i32"->1;case "i64","color"->2;case "f64"->4;case "bool"->8;case "string!"->16;case "string"->16|64;case "ref!"->32;case "ref"->32|64;case "null"->64;default->127;
};
return result;
}
@@ -2,20 +2,16 @@ package p.studio.compiler.backend.irvm;
import java.util.Objects;
public record IRVMInstruction(IRVMOp op, Integer immediate, Integer secondImmediate,
Integer thirdImmediate, Integer fourthImmediate) {
public IRVMInstruction(IRVMOp op, Integer immediate) { this(op,immediate,null,null,null); }
public IRVMInstruction(IRVMOp op, Integer immediate, Integer secondImmediate) {
this(op,immediate,secondImmediate,null,null);
}
public record IRVMInstruction(IRVMOp op, Integer immediate, Integer secondImmediate) {
public IRVMInstruction(IRVMOp op, Integer immediate) { this(op,immediate,null); }
public IRVMInstruction {
Objects.requireNonNull(op,"op");
int count=(immediate==null?0:1)+(secondImmediate==null?0:1)+(thirdImmediate==null?0:1)+(fourthImmediate==null?0:1);
int count=(immediate==null?0:1)+(secondImmediate==null?0:1);
if(op.name().startsWith("REGISTRY_")) {
if(count*4!=op.immediateSize() || (thirdImmediate!=null&&secondImmediate==null) || (fourthImmediate!=null&&thirdImmediate==null))
if(immediate==null || count*4!=op.immediateSize())
throw new IllegalArgumentException("registry operand count differs from opcode layout");
} else {
if(secondImmediate!=null||thirdImmediate!=null||fourthImmediate!=null)
if(secondImmediate!=null)
throw new IllegalArgumentException("unexpected extra immediate");
if((op.immediateSize()>0)!=(immediate!=null))
throw new IllegalArgumentException("immediate differs from opcode layout: "+op.name());
@@ -4,112 +4,117 @@ import java.util.Objects;
/** Manually maintained target contract. No runtime or CSV lookup occurs during compilation. */
public enum IRVMIntrinsicDefinition {
VEC2_DOT("vec2.dot", 1, 0x1000, "vec2", "dot", 4, 1, "Float|Float|Float|Float", "Float", true, false, "ax|ay|bx|by", 10, false, CostModel.FIXED, 0, 0),
VEC2_LENGTH("vec2.length", 1, 0x1001, "vec2", "length", 2, 1, "Float|Float", "Float", true, false, "x|y", 40, false, CostModel.FIXED, 0, 0),
COLOR_FROM_RAW("color.from_raw", 1, 0x1100, "color", "from_raw", 1, 1, "Int64", "builtin:color", true, false, "raw", 1, false, CostModel.FIXED, 0, 0),
COLOR_RGB("color.rgb", 1, 0x1101, "color", "rgb", 3, 1, "Int64|Int64|Int64", "builtin:color", true, false, "r|g|b", 1, false, CostModel.FIXED, 0, 0),
COLOR_RGBA("color.rgba", 1, 0x1102, "color", "rgba", 4, 1, "Int64|Int64|Int64|Int64", "builtin:color", true, false, "r|g|b|a", 1, false, CostModel.FIXED, 0, 0),
COLOR_HTML_RGBA("color.html_rgba", 1, 0x1103, "color", "html_rgba", 1, 1, "String", "builtin:color", true, false, "value", 1, false, CostModel.FIXED, 0, 0),
COLOR_GRAY_SCALE("color.gray_scale", 1, 0x1104, "color", "gray_scale", 1, 1, "Int64", "builtin:color", true, false, "value", 1, false, CostModel.FIXED, 0, 0),
COLOR_HEX("color.hex", 1, 0x1105, "color", "hex", 1, 1, "builtin:color", "Int64", true, false, "color", 1, false, CostModel.FIXED, 0, 0),
COLOR_ALPHA("color.alpha", 1, 0x1106, "color", "alpha", 1, 1, "builtin:color", "Int64", true, false, "color", 1, false, CostModel.FIXED, 0, 0),
COLOR_BLACK("color.black", 1, 0x1120, "color", "black", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_WHITE("color.white", 1, 0x1121, "color", "white", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_RED("color.red", 1, 0x1122, "color", "red", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_GREEN("color.green", 1, 0x1123, "color", "green", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_BLUE("color.blue", 1, 0x1124, "color", "blue", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_YELLOW("color.yellow", 1, 0x1125, "color", "yellow", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_ORANGE("color.orange", 1, 0x1126, "color", "orange", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_INDIGO("color.indigo", 1, 0x1127, "color", "indigo", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_GRAY("color.gray", 1, 0x1128, "color", "gray", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_CYAN("color.cyan", 1, 0x1129, "color", "cyan", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_MAGENTA("color.magenta", 1, 0x112A, "color", "magenta", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
COLOR_TRANSPARENT("color.transparent", 1, 0x112B, "color", "transparent", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_UP_PRESSED("input.pad.up.pressed", 1, 0x2100, "input.pad.up", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_UP_RELEASED("input.pad.up.released", 1, 0x2101, "input.pad.up", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_UP_DOWN("input.pad.up.down", 1, 0x2102, "input.pad.up", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_UP_HOLD("input.pad.up.hold", 1, 0x2103, "input.pad.up", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_DOWN_PRESSED("input.pad.down.pressed", 1, 0x2104, "input.pad.down", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_DOWN_RELEASED("input.pad.down.released", 1, 0x2105, "input.pad.down", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_DOWN_DOWN("input.pad.down.down", 1, 0x2106, "input.pad.down", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_DOWN_HOLD("input.pad.down.hold", 1, 0x2107, "input.pad.down", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_LEFT_PRESSED("input.pad.left.pressed", 1, 0x2108, "input.pad.left", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_LEFT_RELEASED("input.pad.left.released", 1, 0x2109, "input.pad.left", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_LEFT_DOWN("input.pad.left.down", 1, 0x210A, "input.pad.left", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_LEFT_HOLD("input.pad.left.hold", 1, 0x210B, "input.pad.left", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_RIGHT_PRESSED("input.pad.right.pressed", 1, 0x210C, "input.pad.right", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_RIGHT_RELEASED("input.pad.right.released", 1, 0x210D, "input.pad.right", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_RIGHT_DOWN("input.pad.right.down", 1, 0x210E, "input.pad.right", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_RIGHT_HOLD("input.pad.right.hold", 1, 0x210F, "input.pad.right", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_A_PRESSED("input.pad.a.pressed", 1, 0x2110, "input.pad.a", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_A_RELEASED("input.pad.a.released", 1, 0x2111, "input.pad.a", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_A_DOWN("input.pad.a.down", 1, 0x2112, "input.pad.a", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_A_HOLD("input.pad.a.hold", 1, 0x2113, "input.pad.a", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_B_PRESSED("input.pad.b.pressed", 1, 0x2114, "input.pad.b", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_B_RELEASED("input.pad.b.released", 1, 0x2115, "input.pad.b", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_B_DOWN("input.pad.b.down", 1, 0x2116, "input.pad.b", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_B_HOLD("input.pad.b.hold", 1, 0x2117, "input.pad.b", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_X_PRESSED("input.pad.x.pressed", 1, 0x2118, "input.pad.x", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_X_RELEASED("input.pad.x.released", 1, 0x2119, "input.pad.x", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_X_DOWN("input.pad.x.down", 1, 0x211A, "input.pad.x", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_X_HOLD("input.pad.x.hold", 1, 0x211B, "input.pad.x", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_Y_PRESSED("input.pad.y.pressed", 1, 0x211C, "input.pad.y", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_Y_RELEASED("input.pad.y.released", 1, 0x211D, "input.pad.y", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_Y_DOWN("input.pad.y.down", 1, 0x211E, "input.pad.y", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_Y_HOLD("input.pad.y.hold", 1, 0x211F, "input.pad.y", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_L_PRESSED("input.pad.l.pressed", 1, 0x2120, "input.pad.l", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_L_RELEASED("input.pad.l.released", 1, 0x2121, "input.pad.l", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_L_DOWN("input.pad.l.down", 1, 0x2122, "input.pad.l", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_L_HOLD("input.pad.l.hold", 1, 0x2123, "input.pad.l", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_R_PRESSED("input.pad.r.pressed", 1, 0x2124, "input.pad.r", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_R_RELEASED("input.pad.r.released", 1, 0x2125, "input.pad.r", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_R_DOWN("input.pad.r.down", 1, 0x2126, "input.pad.r", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_R_HOLD("input.pad.r.hold", 1, 0x2127, "input.pad.r", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_START_PRESSED("input.pad.start.pressed", 1, 0x2128, "input.pad.start", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_START_RELEASED("input.pad.start.released", 1, 0x2129, "input.pad.start", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_START_DOWN("input.pad.start.down", 1, 0x212A, "input.pad.start", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_START_HOLD("input.pad.start.hold", 1, 0x212B, "input.pad.start", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_SELECT_PRESSED("input.pad.select.pressed", 1, 0x212C, "input.pad.select", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_SELECT_RELEASED("input.pad.select.released", 1, 0x212D, "input.pad.select", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_SELECT_DOWN("input.pad.select.down", 1, 0x212E, "input.pad.select", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_PAD_SELECT_HOLD("input.pad.select.hold", 1, 0x212F, "input.pad.select", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_TOUCH_BUTTON_PRESSED("input.touch.button.pressed", 1, 0x2130, "input.touch.button", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_TOUCH_BUTTON_RELEASED("input.touch.button.released", 1, 0x2131, "input.touch.button", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_TOUCH_BUTTON_DOWN("input.touch.button.down", 1, 0x2132, "input.touch.button", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_TOUCH_BUTTON_HOLD("input.touch.button.hold", 1, 0x2133, "input.touch.button", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_TOUCH_X("input.touch.x", 1, 0x2134, "input.touch", "x", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
INPUT_TOUCH_Y("input.touch.y", 1, 0x2135, "input.touch", "y", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0),
MATH_I32_MIN("math.i32.min", 1, 0x3000, "math.i32", "min", 2, 1, "Int32|Int32", "Int32", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0),
MATH_I32_MAX("math.i32.max", 1, 0x3001, "math.i32", "max", 2, 1, "Int32|Int32", "Int32", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0),
MATH_I32_CLAMP("math.i32.clamp", 1, 0x3002, "math.i32", "clamp", 3, 1, "Int32|Int32|Int32", "Int32", true, false, "value|min|max", 4, false, CostModel.FIXED, 0, 0),
MATH_I32_ABS("math.i32.abs", 1, 0x3003, "math.i32", "abs", 1, 1, "Int32", "Int32", true, false, "value", 2, false, CostModel.FIXED, 0, 0),
MATH_I64_MIN("math.i64.min", 1, 0x3004, "math.i64", "min", 2, 1, "Int64|Int64", "Int64", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0),
MATH_I64_MAX("math.i64.max", 1, 0x3005, "math.i64", "max", 2, 1, "Int64|Int64", "Int64", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0),
MATH_I64_CLAMP("math.i64.clamp", 1, 0x3006, "math.i64", "clamp", 3, 1, "Int64|Int64|Int64", "Int64", true, false, "value|min|max", 4, false, CostModel.FIXED, 0, 0),
MATH_I64_ABS("math.i64.abs", 1, 0x3007, "math.i64", "abs", 1, 1, "Int64", "Int64", true, false, "value", 2, false, CostModel.FIXED, 0, 0),
MATHF_MIN("mathf.min", 1, 0x3008, "mathf", "min", 2, 1, "Float|Float", "Float", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0),
MATHF_MAX("mathf.max", 1, 0x3009, "mathf", "max", 2, 1, "Float|Float", "Float", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0),
MATHF_CLAMP("mathf.clamp", 1, 0x300A, "mathf", "clamp", 3, 1, "Float|Float|Float", "Float", true, false, "value|min|max", 4, false, CostModel.FIXED, 0, 0),
MATHF_ABS("mathf.abs", 1, 0x300B, "mathf", "abs", 1, 1, "Float", "Float", true, false, "value", 2, false, CostModel.FIXED, 0, 0),
MATHF_FLOOR("mathf.floor", 1, 0x300C, "mathf", "floor", 1, 1, "Float", "Float", true, false, "value", 4, false, CostModel.FIXED, 0, 0),
MATHF_CEIL("mathf.ceil", 1, 0x300D, "mathf", "ceil", 1, 1, "Float", "Float", true, false, "value", 4, false, CostModel.FIXED, 0, 0),
MATHF_TRUNC("mathf.trunc", 1, 0x300E, "mathf", "trunc", 1, 1, "Float", "Float", true, false, "value", 4, false, CostModel.FIXED, 0, 0),
MATHF_ROUND("mathf.round", 1, 0x300F, "mathf", "round", 1, 1, "Float", "Float", true, false, "value", 4, false, CostModel.FIXED, 0, 0),
MATHF_SQRT("mathf.sqrt", 1, 0x3010, "mathf", "sqrt", 1, 1, "Float", "Float", true, false, "value", 16, false, CostModel.FIXED, 0, 0),
MATHF_SIN("mathf.sin", 1, 0x3011, "mathf", "sin", 1, 1, "Float", "Float", true, false, "angle", 32, false, CostModel.FIXED, 0, 0),
MATHF_COS("mathf.cos", 1, 0x3012, "mathf", "cos", 1, 1, "Float", "Float", true, false, "angle", 32, false, CostModel.FIXED, 0, 0),
MATHF_ATAN2("mathf.atan2", 1, 0x3013, "mathf", "atan2", 2, 1, "Float|Float", "Float", true, false, "y|x", 48, false, CostModel.FIXED, 0, 0),
MATH_I32_TO_I64("math.i32.to_i64", 1, 0x3014, "math.i32", "to_i64", 1, 1, "Int32", "Int64", true, false, "value", 2, false, CostModel.FIXED, 0, 0),
MATH_I64_TO_I32("math.i64.to_i32", 1, 0x3015, "math.i64", "to_i32", 1, 1, "Int64", "Int32", true, false, "value", 2, false, CostModel.FIXED, 0, 0),
MATH_I32_TO_FLOAT("math.i32.to_float", 1, 0x3016, "math.i32", "to_float", 1, 1, "Int32", "Float", true, false, "value", 2, false, CostModel.FIXED, 0, 0),
MATH_I64_TO_FLOAT("math.i64.to_float", 1, 0x3017, "math.i64", "to_float", 1, 1, "Int64", "Float", true, false, "value", 2, false, CostModel.FIXED, 0, 0),
MATHF_TO_I32("mathf.to_i32", 1, 0x3018, "mathf", "to_i32", 1, 1, "Float", "Int32", true, false, "value", 2, false, CostModel.FIXED, 0, 0),
MATHF_TO_I64("mathf.to_i64", 1, 0x3019, "mathf", "to_i64", 1, 1, "Float", "Int64", true, false, "value", 2, false, CostModel.FIXED, 0, 0),
RANDOM_NEW("random.new", 1, 0x4000, "random", "new", 1, 1, "Int64", "builtin:Random", true, true, "seed", 32, true, CostModel.FIXED, 0, 0),
RANDOM_NEXT("random.next", 1, 0x4001, "random", "next", 1, 1, "builtin:Random", "Int64", true, false, "rng", 8, true, CostModel.FIXED, 0, 0),
RANDOM_NEXTF("random.nextf", 1, 0x4002, "random", "nextf", 1, 1, "builtin:Random", "Float", true, false, "rng", 12, true, CostModel.FIXED, 0, 0),
RANDOM_RANGE("random.range", 1, 0x4003, "random", "range", 3, 1, "builtin:Random|Int64|Int64", "Int64", true, false, "rng|min|max", 4, true, CostModel.RANDOM_REJECTION_V1, 8, 64);
VEC2_DOT("vec2.dot", 1, 0x1000, "vec2", "dot", 4, 1, "Float|Float|Float|Float", "Float", true, false, "ax|ay|bx|by", 10, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false|false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
VEC2_LENGTH("vec2.length", 1, 0x1001, "vec2", "length", 2, 1, "Float|Float", "Float", true, false, "x|y", 40, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_FROM_RAW("color.from_raw", 1, 0x1100, "color", "from_raw", 1, 1, "Int64", "builtin:color", true, false, "raw", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_RGB("color.rgb", 1, 0x1101, "color", "rgb", 3, 1, "Int64|Int64|Int64", "builtin:color", true, false, "r|g|b", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_RGBA("color.rgba", 1, 0x1102, "color", "rgba", 4, 1, "Int64|Int64|Int64|Int64", "builtin:color", true, false, "r|g|b|a", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false|false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_HTML_RGBA("color.html_rgba", 1, 0x1103, "color", "html_rgba", 1, 1, "String", "builtin:color", true, false, "value", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_GRAY_SCALE("color.gray_scale", 1, 0x1104, "color", "gray_scale", 1, 1, "Int64", "builtin:color", true, false, "value", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_HEX("color.hex", 1, 0x1105, "color", "hex", 1, 1, "builtin:color", "Int64", true, false, "color", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_ALPHA("color.alpha", 1, 0x1106, "color", "alpha", 1, 1, "builtin:color", "Int64", true, false, "color", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_BLACK("color.black", 1, 0x1120, "color", "black", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_WHITE("color.white", 1, 0x1121, "color", "white", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_RED("color.red", 1, 0x1122, "color", "red", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_GREEN("color.green", 1, 0x1123, "color", "green", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_BLUE("color.blue", 1, 0x1124, "color", "blue", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_YELLOW("color.yellow", 1, 0x1125, "color", "yellow", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_ORANGE("color.orange", 1, 0x1126, "color", "orange", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_INDIGO("color.indigo", 1, 0x1127, "color", "indigo", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_GRAY("color.gray", 1, 0x1128, "color", "gray", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_CYAN("color.cyan", 1, 0x1129, "color", "cyan", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_MAGENTA("color.magenta", 1, 0x112A, "color", "magenta", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
COLOR_TRANSPARENT("color.transparent", 1, 0x112B, "color", "transparent", 0, 1, "", "builtin:color", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_UP_PRESSED("input.pad.up.pressed", 1, 0x2100, "input.pad.up", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_UP_RELEASED("input.pad.up.released", 1, 0x2101, "input.pad.up", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_UP_DOWN("input.pad.up.down", 1, 0x2102, "input.pad.up", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_UP_HOLD("input.pad.up.hold", 1, 0x2103, "input.pad.up", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_DOWN_PRESSED("input.pad.down.pressed", 1, 0x2104, "input.pad.down", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_DOWN_RELEASED("input.pad.down.released", 1, 0x2105, "input.pad.down", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_DOWN_DOWN("input.pad.down.down", 1, 0x2106, "input.pad.down", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_DOWN_HOLD("input.pad.down.hold", 1, 0x2107, "input.pad.down", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_LEFT_PRESSED("input.pad.left.pressed", 1, 0x2108, "input.pad.left", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_LEFT_RELEASED("input.pad.left.released", 1, 0x2109, "input.pad.left", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_LEFT_DOWN("input.pad.left.down", 1, 0x210A, "input.pad.left", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_LEFT_HOLD("input.pad.left.hold", 1, 0x210B, "input.pad.left", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_RIGHT_PRESSED("input.pad.right.pressed", 1, 0x210C, "input.pad.right", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_RIGHT_RELEASED("input.pad.right.released", 1, 0x210D, "input.pad.right", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_RIGHT_DOWN("input.pad.right.down", 1, 0x210E, "input.pad.right", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_RIGHT_HOLD("input.pad.right.hold", 1, 0x210F, "input.pad.right", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_A_PRESSED("input.pad.a.pressed", 1, 0x2110, "input.pad.a", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_A_RELEASED("input.pad.a.released", 1, 0x2111, "input.pad.a", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_A_DOWN("input.pad.a.down", 1, 0x2112, "input.pad.a", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_A_HOLD("input.pad.a.hold", 1, 0x2113, "input.pad.a", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_B_PRESSED("input.pad.b.pressed", 1, 0x2114, "input.pad.b", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_B_RELEASED("input.pad.b.released", 1, 0x2115, "input.pad.b", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_B_DOWN("input.pad.b.down", 1, 0x2116, "input.pad.b", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_B_HOLD("input.pad.b.hold", 1, 0x2117, "input.pad.b", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_X_PRESSED("input.pad.x.pressed", 1, 0x2118, "input.pad.x", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_X_RELEASED("input.pad.x.released", 1, 0x2119, "input.pad.x", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_X_DOWN("input.pad.x.down", 1, 0x211A, "input.pad.x", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_X_HOLD("input.pad.x.hold", 1, 0x211B, "input.pad.x", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_Y_PRESSED("input.pad.y.pressed", 1, 0x211C, "input.pad.y", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_Y_RELEASED("input.pad.y.released", 1, 0x211D, "input.pad.y", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_Y_DOWN("input.pad.y.down", 1, 0x211E, "input.pad.y", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_Y_HOLD("input.pad.y.hold", 1, 0x211F, "input.pad.y", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_L_PRESSED("input.pad.l.pressed", 1, 0x2120, "input.pad.l", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_L_RELEASED("input.pad.l.released", 1, 0x2121, "input.pad.l", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_L_DOWN("input.pad.l.down", 1, 0x2122, "input.pad.l", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_L_HOLD("input.pad.l.hold", 1, 0x2123, "input.pad.l", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_R_PRESSED("input.pad.r.pressed", 1, 0x2124, "input.pad.r", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_R_RELEASED("input.pad.r.released", 1, 0x2125, "input.pad.r", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_R_DOWN("input.pad.r.down", 1, 0x2126, "input.pad.r", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_R_HOLD("input.pad.r.hold", 1, 0x2127, "input.pad.r", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_START_PRESSED("input.pad.start.pressed", 1, 0x2128, "input.pad.start", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_START_RELEASED("input.pad.start.released", 1, 0x2129, "input.pad.start", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_START_DOWN("input.pad.start.down", 1, 0x212A, "input.pad.start", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_START_HOLD("input.pad.start.hold", 1, 0x212B, "input.pad.start", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_SELECT_PRESSED("input.pad.select.pressed", 1, 0x212C, "input.pad.select", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_SELECT_RELEASED("input.pad.select.released", 1, 0x212D, "input.pad.select", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_SELECT_DOWN("input.pad.select.down", 1, 0x212E, "input.pad.select", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_PAD_SELECT_HOLD("input.pad.select.hold", 1, 0x212F, "input.pad.select", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_TOUCH_BUTTON_PRESSED("input.touch.button.pressed", 1, 0x2130, "input.touch.button", "pressed", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_TOUCH_BUTTON_RELEASED("input.touch.button.released", 1, 0x2131, "input.touch.button", "released", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_TOUCH_BUTTON_DOWN("input.touch.button.down", 1, 0x2132, "input.touch.button", "down", 0, 1, "", "Bool", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_TOUCH_BUTTON_HOLD("input.touch.button.hold", 1, 0x2133, "input.touch.button", "hold", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_TOUCH_X("input.touch.x", 1, 0x2134, "input.touch", "x", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
INPUT_TOUCH_Y("input.touch.y", 1, 0x2135, "input.touch", "y", 0, 1, "", "Int64", true, false, "", 1, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I32_MIN("math.i32.min", 1, 0x3000, "math.i32", "min", 2, 1, "Int32|Int32", "Int32", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I32_MAX("math.i32.max", 1, 0x3001, "math.i32", "max", 2, 1, "Int32|Int32", "Int32", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I32_CLAMP("math.i32.clamp", 1, 0x3002, "math.i32", "clamp", 3, 1, "Int32|Int32|Int32", "Int32", true, false, "value|min|max", 4, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I32_ABS("math.i32.abs", 1, 0x3003, "math.i32", "abs", 1, 1, "Int32", "Int32", true, false, "value", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I64_MIN("math.i64.min", 1, 0x3004, "math.i64", "min", 2, 1, "Int64|Int64", "Int64", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I64_MAX("math.i64.max", 1, 0x3005, "math.i64", "max", 2, 1, "Int64|Int64", "Int64", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I64_CLAMP("math.i64.clamp", 1, 0x3006, "math.i64", "clamp", 3, 1, "Int64|Int64|Int64", "Int64", true, false, "value|min|max", 4, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I64_ABS("math.i64.abs", 1, 0x3007, "math.i64", "abs", 1, 1, "Int64", "Int64", true, false, "value", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_MIN("mathf.min", 1, 0x3008, "mathf", "min", 2, 1, "Float|Float", "Float", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_MAX("mathf.max", 1, 0x3009, "mathf", "max", 2, 1, "Float|Float", "Float", true, false, "a|b", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_CLAMP("mathf.clamp", 1, 0x300A, "mathf", "clamp", 3, 1, "Float|Float|Float", "Float", true, false, "value|min|max", 4, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_ABS("mathf.abs", 1, 0x300B, "mathf", "abs", 1, 1, "Float", "Float", true, false, "value", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_FLOOR("mathf.floor", 1, 0x300C, "mathf", "floor", 1, 1, "Float", "Float", true, false, "value", 4, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_CEIL("mathf.ceil", 1, 0x300D, "mathf", "ceil", 1, 1, "Float", "Float", true, false, "value", 4, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_TRUNC("mathf.trunc", 1, 0x300E, "mathf", "trunc", 1, 1, "Float", "Float", true, false, "value", 4, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_ROUND("mathf.round", 1, 0x300F, "mathf", "round", 1, 1, "Float", "Float", true, false, "value", 4, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_SQRT("mathf.sqrt", 1, 0x3010, "mathf", "sqrt", 1, 1, "Float", "Float", true, false, "value", 16, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_SIN("mathf.sin", 1, 0x3011, "mathf", "sin", 1, 1, "Float", "Float", true, false, "angle", 32, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_COS("mathf.cos", 1, 0x3012, "mathf", "cos", 1, 1, "Float", "Float", true, false, "angle", 32, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_ATAN2("mathf.atan2", 1, 0x3013, "mathf", "atan2", 2, 1, "Float|Float", "Float", true, false, "y|x", 48, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false|false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I32_TO_I64("math.i32.to_i64", 1, 0x3014, "math.i32", "to_i64", 1, 1, "Int32", "Int64", true, false, "value", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I64_TO_I32("math.i64.to_i32", 1, 0x3015, "math.i64", "to_i32", 1, 1, "Int64", "Int32", true, false, "value", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I32_TO_FLOAT("math.i32.to_float", 1, 0x3016, "math.i32", "to_float", 1, 1, "Int32", "Float", true, false, "value", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATH_I64_TO_FLOAT("math.i64.to_float", 1, 0x3017, "math.i64", "to_float", 1, 1, "Int64", "Float", true, false, "value", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_TO_I32("mathf.to_i32", 1, 0x3018, "mathf", "to_i32", 1, 1, "Float", "Int32", true, false, "value", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
MATHF_TO_I64("mathf.to_i64", 1, 0x3019, "mathf", "to_i64", 1, 1, "Float", "Int64", true, false, "value", 2, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "host_buffered_v1", "existing_contract_v1", "host", null, 0)),
RANDOM_NEW("random.new", 1, 0x4000, "random", "new", 1, 1, "Int64", "builtin:Random", true, true, "seed", 32, true, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "vm_owned_v1", "existing_contract_v1", "vm_state", null, 0)),
RANDOM_NEXT("random.next", 1, 0x4001, "random", "next", 1, 1, "builtin:Random", "Int64", true, false, "rng", 8, true, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "true", "vm_owned_v1", "existing_contract_v1", "vm_state", null, 0)),
RANDOM_NEXTF("random.nextf", 1, 0x4002, "random", "nextf", 1, 1, "builtin:Random", "Float", true, false, "rng", 12, true, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "true", "vm_owned_v1", "existing_contract_v1", "vm_state", null, 0)),
RANDOM_RANGE("random.range", 1, 0x4003, "random", "range", 3, 1, "builtin:Random|Int64|Int64", "Int64", true, false, "rng|min|max", 4, true, CostModel.RANDOM_REJECTION_V1, 8, 64, new IRVMIntrinsicProfile(2, "true|false|false", "vm_owned_v1", "existing_contract_v1", "vm_state", null, 0)),
HASH_I64("hash.i64", 1, 0x4100, "hash", "i64", 1, 1, "Int64", "Int64", true, false, "value", 8, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "borrowed_inline_v1", "none", "none", null, 0)),
HASH_FLOAT("hash.float", 1, 0x4101, "hash", "float", 1, 1, "Float", "Int64", true, false, "value", 8, false, CostModel.FIXED, 0, 0, new IRVMIntrinsicProfile(2, "false", "borrowed_inline_v1", "none", "none", null, 0)),
HASH_STRING("hash.string", 1, 0x4102, "hash", "string", 1, 1, "String", "Int64", true, false, "value", 8, false, CostModel.ARGUMENT_UTF8_BYTES_V1, 0, 0, new IRVMIntrinsicProfile(2, "true", "borrowed_inline_v1", "none", "none", 0, 1));
private final IRVMIntrinsicProfile profile;
private final String canonicalName;
private final long canonicalVersion;
private final int finalId;
@@ -147,7 +152,8 @@ public enum IRVMIntrinsicDefinition {
final boolean mutatesGuestState,
final CostModel costModel,
final long attemptCostCycles,
final int maxAttempts) {
final int maxAttempts,
final IRVMIntrinsicProfile profile) {
this.canonicalName = requireNonBlank(canonicalName, "canonicalName");
this.canonicalVersion = requireNonNegative(canonicalVersion, "canonicalVersion");
this.finalId = finalId;
@@ -172,12 +178,14 @@ public enum IRVMIntrinsicDefinition {
|| (parameterNames.isEmpty() ? 0 : parameterNames.split("\\|", -1).length) != argSlots) {
throw new IllegalArgumentException("incoherent intrinsic definition: " + canonicalName);
}
if (costModel == CostModel.FIXED && (attemptCostCycles != 0 || maxAttempts != 0)
|| costModel == CostModel.RANDOM_REJECTION_V1 && (attemptCostCycles == 0 || maxAttempts == 0)) {
throw new IllegalArgumentException("incoherent cost model: " + canonicalName);
}
this.profile = Objects.requireNonNull(profile, "profile");
profile.validate(argumentCarriers, costModel, deterministic, mayAllocate, mutatesGuestState,
costCycles, attemptCostCycles, maxAttempts);
}
public IRVMIntrinsicProfile profile() { return profile; }
public java.util.List<Boolean> nullableArguments() { return profile.nullableArguments(); }
public String canonicalName() {
return canonicalName;
}
@@ -248,10 +256,14 @@ public enum IRVMIntrinsicDefinition {
}
public enum CostModel {
FIXED("fixed"), RANDOM_REJECTION_V1("random_rejection_v1");
FIXED("fixed"), RANDOM_REJECTION_V1("random_rejection_v1"), ARGUMENT_UTF8_BYTES_V1("argument_utf8_bytes_v1");
private final String token;
CostModel(String token) { this.token = token; }
public String token() { return token; }
public static CostModel fromToken(String token) {
for (var model : values()) if (model.token.equals(token)) return model;
throw new IllegalArgumentException("unsupported intrinsic cost model: " + token);
}
}
/** Explicit runtime ABI atoms, not source-language type aliases. */
@@ -0,0 +1,70 @@
package p.studio.compiler.backend.irvm;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
/** Explicit schema-2 invocation metadata; compilation never consults a runtime CSV. */
public record IRVMIntrinsicProfile(int schemaVersion, String argNullable, String invocationModel,
String scratchModel, String contextAccess, Integer costArgIndex, long costPerByte) {
public IRVMIntrinsicProfile {
if (schemaVersion != 2) throw new IllegalArgumentException("unsupported intrinsic schema: " + schemaVersion);
Objects.requireNonNull(argNullable, "argNullable");
parseNullable(argNullable);
if (!Set.of("host_buffered_v1", "vm_owned_v1", "borrowed_inline_v1").contains(invocationModel)
|| !Set.of("existing_contract_v1", "none").contains(scratchModel)
|| !Set.of("host", "vm_state", "none").contains(contextAccess))
throw new IllegalArgumentException("unsupported intrinsic invocation profile");
boolean coherent = switch (invocationModel) {
case "host_buffered_v1" -> scratchModel.equals("existing_contract_v1") && contextAccess.equals("host");
case "vm_owned_v1" -> scratchModel.equals("existing_contract_v1") && contextAccess.equals("vm_state");
case "borrowed_inline_v1" -> scratchModel.equals("none") && contextAccess.equals("none");
default -> false;
};
if (!coherent || costArgIndex != null && costArgIndex < 0 || costPerByte < 0)
throw new IllegalArgumentException("incoherent intrinsic invocation profile");
}
public List<Boolean> nullableArguments() { return parseNullable(argNullable); }
private static List<Boolean> parseNullable(String mask) {
if (mask.isEmpty()) return List.of();
return Arrays.stream(mask.split("\\|", -1)).map(token -> switch (token) {
case "true" -> true;
case "false" -> false;
default -> throw new IllegalArgumentException("invalid nullable bit: " + token);
}).toList();
}
public void validate(List<IRVMIntrinsicDefinition.Carrier> arguments,
IRVMIntrinsicDefinition.CostModel costModel, boolean deterministic, boolean mayAllocate,
boolean mutatesGuestState, long baseCost, long attemptCost, int maxAttempts) {
var nullable = nullableArguments();
if (nullable.size() != arguments.size()) throw new IllegalArgumentException("nullable mask width mismatch");
for (int i=0; i<arguments.size(); i++)
if (nullable.get(i) && arguments.get(i) != IRVMIntrinsicDefinition.Carrier.STRING
&& arguments.get(i) != IRVMIntrinsicDefinition.Carrier.RANDOM)
throw new IllegalArgumentException("nullable non-reference intrinsic argument");
if (invocationModel.equals("borrowed_inline_v1") && (!deterministic || mayAllocate || mutatesGuestState))
throw new IllegalArgumentException("incoherent borrowed intrinsic effects");
switch (costModel) {
case FIXED -> {
if (costArgIndex != null || costPerByte != 0 || attemptCost != 0 || maxAttempts != 0)
throw new IllegalArgumentException("incoherent fixed cost model");
}
case RANDOM_REJECTION_V1 -> {
if (!invocationModel.equals("vm_owned_v1") || costArgIndex != null || costPerByte != 0
|| baseCost != 4 || attemptCost != 8 || maxAttempts != 64)
throw new IllegalArgumentException("unsupported random rejection parameters");
}
case ARGUMENT_UTF8_BYTES_V1 -> {
if (!invocationModel.equals("borrowed_inline_v1") || costArgIndex == null
|| costArgIndex != 0 || arguments.size() != 1
|| arguments.get(costArgIndex) != IRVMIntrinsicDefinition.Carrier.STRING
|| costPerByte != 1 || baseCost != 8 || attemptCost != 0 || maxAttempts != 0)
throw new IllegalArgumentException("unsupported UTF-8 argument cost parameters");
}
}
}
}
@@ -11,6 +11,7 @@ public record IRVMOp(
boolean internal) {
public static final IRVMOp HALT = new IRVMOp("HALT", 0x01, 0, 0, 0, false, true, false);
public static final IRVMOp TRAP = new IRVMOp("TRAP", 0x05, 0, 0, 0, false, true, false);
public static final IRVMOp RET = new IRVMOp("RET", 0x51, 0, 0, 0, false, true, false);
public static final IRVMOp PUSH_CONST = new IRVMOp("PUSH_CONST", 0x10, 4, 0, 1, false, false, false);
public static final IRVMOp POP = new IRVMOp("POP", 0x11, 0, 1, 0, false, false, false);
@@ -10,6 +10,7 @@ public final class IRVMProfileFeatureGate {
this(Map.of(
"core-v1", Set.of(
IRVMOp.HALT,
IRVMOp.TRAP,
IRVMOp.RET,
IRVMOp.PUSH_CONST,
IRVMOp.POP,
@@ -42,6 +43,7 @@ public final class IRVMProfileFeatureGate {
IRVMOp.PUSH_I32),
"experimental-v1", Set.of(
IRVMOp.HALT,
IRVMOp.TRAP,
IRVMOp.RET,
IRVMOp.PUSH_CONST,
IRVMOp.POP,
@@ -94,6 +94,7 @@ public record IRVMProgram(
}
final var immediate = instruction.immediate() == null ? 0 : instruction.immediate();
return switch (instruction.op().opcode()) {
case 0x05 -> operation.kind() == BytecodeEmitter.OperationKind.TRAP;
case 0x01 -> operation.kind() == BytecodeEmitter.OperationKind.HALT;
case 0x51 -> operation.kind() == BytecodeEmitter.OperationKind.RET;
case 0x10 -> operation.kind() == BytecodeEmitter.OperationKind.PUSH_CONST && operation.immediate() == immediate;
@@ -179,6 +180,7 @@ public record IRVMProgram(
if (instruction.op().name().startsWith("REGISTRY_")) return new BytecodeEmitter.Operation(BytecodeEmitter.OperationKind.REGISTRY, 0, null, null, null, null, instruction);
final var immediate = instruction.immediate() == null ? 0 : instruction.immediate();
return switch (instruction.op().opcode()) {
case 0x05 -> BytecodeEmitter.Operation.trap();
case 0x01 -> BytecodeEmitter.Operation.halt();
case 0x51 -> BytecodeEmitter.Operation.ret();
case 0x10 -> BytecodeEmitter.Operation.pushConst(immediate, null);
@@ -258,6 +260,7 @@ public record IRVMProgram(
return switch (operation.kind()) {
case REGISTRY -> operation.registryInstruction();
case HALT -> new IRVMInstruction(IRVMOp.HALT, null);
case TRAP -> new IRVMInstruction(IRVMOp.TRAP, null);
case RET -> new IRVMInstruction(IRVMOp.RET, null);
case PUSH_CONST -> new IRVMInstruction(IRVMOp.PUSH_CONST, operation.immediate());
case POP -> new IRVMInstruction(IRVMOp.POP, null);
@@ -223,7 +223,7 @@ public class IRVMValidator {
final int outHeight,
final HashMap<Integer, Integer> incomingHeights,
final ArrayDeque<Integer> worklist) {
if (instr.op() == IRVMOp.HALT || instr.op() == IRVMOp.RET) {
if (instr.op() == IRVMOp.HALT || instr.op() == IRVMOp.TRAP || instr.op() == IRVMOp.RET) {
return;
}
@@ -281,6 +281,11 @@ public class LowerToIRVMService {
operations.add(BytecodeEmitter.Operation.halt(sourceSpan));
functionPc += IRVMOp.HALT.immediateSize() + 2;
}
case TRAP -> {
instructions.add(new IRVMInstruction(IRVMOp.TRAP, null));
operations.add(BytecodeEmitter.Operation.trap(sourceSpan));
functionPc += 2;
}
case RET -> {
instructions.add(new IRVMInstruction(IRVMOp.RET, null));
operations.add(BytecodeEmitter.Operation.ret(sourceSpan));
@@ -304,7 +304,7 @@ public class OptimizeIRVMService {
}
reachable[index] = true;
final var instruction = instructions.get(index);
if (instruction.op() == IRVMOp.HALT || instruction.op() == IRVMOp.RET) {
if (instruction.op() == IRVMOp.HALT || instruction.op() == IRVMOp.TRAP || instruction.op() == IRVMOp.RET) {
continue;
}
if (isJump(instruction.op())) {
@@ -13,7 +13,7 @@ public final class RegistryInstructionLowerer {
public static IRVMInstruction lower(IRRegistryInstruction instruction, LinkedRegistry registry,
IRBackendExecutableFunction current, ReadOnlyList<IRBackendExecutableFunction> functions, Map<CallableId,Integer> functionIds) {
int first=instruction.type()==null?instruction.member():registry.id(instruction.type()).index();
Integer second=null,third=null,fourth=null;int pops=0,pushes=0;
Integer second=null;int pops=0,pushes=0;
var body=instruction.type()==null?null:registry.type(instruction.type()).body();
switch(instruction.kind()) {
case MAKE_CLOSURE -> {
@@ -51,25 +51,9 @@ public final class RegistryInstructionLowerer {
pops=instruction.kind()==IRRegistryInstruction.Kind.STRUCT_SET?1+width:1;pushes=instruction.kind()==IRRegistryInstruction.Kind.STRUCT_GET?width:0;
}
}
case FIELDS_PUBLISH -> {
if (!(body instanceof Struct schema)) throw new IllegalArgumentException("Struct publication schema required");
for (var entry : schema.fields()) {
if (!(registry.type(entry.type()).body() instanceof Struct owner)) throw new IllegalArgumentException("Struct publication destination required");
pops = Math.addExact(pops, 1);
for (var field : owner.fields()) pops = Math.addExact(pops, registry.width(field.type()));
}
}
case INDEX_GUARD -> pops=2;
case ARRAY_CHECK_LENGTH,ARRAY_COPY,STORAGE_PUBLISH -> {
if(!(body instanceof Array array))throw new IllegalArgumentException("Array category required");
if(instruction.kind()==IRRegistryInstruction.Kind.ARRAY_CHECK_LENGTH)pops=1;
else if(instruction.kind()==IRRegistryInstruction.Kind.ARRAY_COPY)pops=5;
else {
if(!(registry.type(instruction.targetType()).body() instanceof Struct owner))throw new IllegalArgumentException("Struct publication owner required");
if(instruction.member()>=owner.fields().size()||instruction.secondMember()>=owner.fields().size())throw new IllegalArgumentException("publication field index");
second=registry.id(instruction.targetType()).index();third=instruction.member();fourth=instruction.secondMember();
pops=8+registry.width(array.element())+registry.width(owner.fields().get(third).type())+registry.width(owner.fields().get(fourth).type());
}
case ARRAY_COPY -> {
if (!(body instanceof Array)) throw new IllegalArgumentException("Array category required");
pops=5;
}
case ARRAY_NEW,ARRAY_LEN,ARRAY_GET,ARRAY_SET -> {
if(!(body instanceof Array array))throw new IllegalArgumentException("Array category required");
@@ -77,7 +61,7 @@ public final class RegistryInstructionLowerer {
switch(instruction.kind()) {case ARRAY_NEW,ARRAY_LEN->{pops=1;pushes=1;}case ARRAY_GET->{pops=2;pushes=width;}case ARRAY_SET->pops=2+width;default->throw new AssertionError();}
}
}
int bytes=instruction.kind()==IRRegistryInstruction.Kind.INDEX_GUARD?0:fourth!=null?16:second==null?4:8;
return new IRVMInstruction(new IRVMOp("REGISTRY_"+instruction.kind(),instruction.kind().opcode(),bytes,pops,pushes,false,false,false),bytes==0?null:first,second,third,fourth);
int bytes=second==null?4:8;
return new IRVMInstruction(new IRVMOp("REGISTRY_"+instruction.kind(),instruction.kind().opcode(),bytes,pops,pushes,false,false,false),first,second);
}
}
@@ -0,0 +1,16 @@
package p.studio.compiler.backend.irvm;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class IRVMInstructionTest {
@Test void retainedRegistryImmediatesMustStartWithTheFirstOperand() {
var arrayLen=new IRVMOp("REGISTRY_ARRAY_LEN",0xa4,4,1,1,false,false,false);
assertThrows(IllegalArgumentException.class,()->new IRVMInstruction(arrayLen,null,7));
assertThrows(IllegalArgumentException.class,()->new IRVMInstruction(arrayLen,null));
assertEquals(6,new IRVMInstruction(arrayLen,7).encodedSize());
var field=new IRVMOp("REGISTRY_STRUCT_GET",0xa1,8,1,1,false,false,false);
assertThrows(IllegalArgumentException.class,()->new IRVMInstruction(field,7));
assertEquals(10,new IRVMInstruction(field,7,2).encodedSize());
}
}
@@ -0,0 +1,49 @@
package p.studio.compiler.backend.irvm;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
import static p.studio.compiler.backend.irvm.IRVMIntrinsicDefinition.Carrier.*;
import static p.studio.compiler.backend.irvm.IRVMIntrinsicDefinition.CostModel.*;
class IRVMIntrinsicProfileTest {
private static IRVMIntrinsicProfile borrowed(String mask,Integer index,long bytes) {
return new IRVMIntrinsicProfile(2,mask,"borrowed_inline_v1","none","none",index,bytes);
}
@Test void perEntryStringAdmissionAndVariableCostsAreExplicit() {
assertEquals(List.of(true),IRVMIntrinsicDefinition.HASH_STRING.nullableArguments());
assertEquals(List.of(false),IRVMIntrinsicDefinition.COLOR_HTML_RGBA.nullableArguments());
var profile=IRVMIntrinsicDefinition.HASH_STRING.profile();
assertEquals(0,profile.costArgIndex()); assertEquals(1,profile.costPerByte());
assertEquals(ARGUMENT_UTF8_BYTES_V1,IRVMIntrinsicDefinition.HASH_STRING.costModel());
assertEquals(8,IRVMIntrinsicDefinition.HASH_STRING.costCycles());
assertEquals("vm_owned_v1",IRVMIntrinsicDefinition.RANDOM_RANGE.profile().invocationModel());
assertEquals("host_buffered_v1",IRVMIntrinsicDefinition.VEC2_DOT.profile().invocationModel());
}
@Test void unsupportedSchemaProfilesMasksAndModelsAreRefused() {
for(int schema:new int[]{0,1,3})
assertThrows(IllegalArgumentException.class,()->new IRVMIntrinsicProfile(schema,"false","borrowed_inline_v1","none","none",null,0));
for(String mask:List.of("True","1","false|","|false"))
assertThrows(IllegalArgumentException.class,()->borrowed(mask,null,0));
assertThrows(IllegalArgumentException.class,()->new IRVMIntrinsicProfile(2,"false","future","none","none",null,0));
assertThrows(IllegalArgumentException.class,()->new IRVMIntrinsicProfile(2,"false","borrowed_inline_v1","existing_contract_v1","none",null,0));
assertThrows(IllegalArgumentException.class,()->new IRVMIntrinsicProfile(2,"false","vm_owned_v1","existing_contract_v1","host",null,0));
assertThrows(IllegalArgumentException.class,()->borrowed("false",-1,0));
assertThrows(IllegalArgumentException.class,()->borrowed("false",null,-1));
assertThrows(IllegalArgumentException.class,()->IRVMIntrinsicDefinition.CostModel.fromToken("future"));
}
@Test void incoherentWidthsNullabilityEffectsAndCostParametersAreRefused() {
assertThrows(IllegalArgumentException.class,()->borrowed("",null,0).validate(List.of(INT64),FIXED,true,false,false,8,0,0));
assertThrows(IllegalArgumentException.class,()->borrowed("true",null,0).validate(List.of(INT64),FIXED,true,false,false,8,0,0));
assertThrows(IllegalArgumentException.class,()->borrowed("false",null,0).validate(List.of(INT64),FIXED,true,true,false,8,0,0));
assertThrows(IllegalArgumentException.class,()->borrowed("false",null,0).validate(List.of(INT64),FIXED,true,false,true,8,0,0));
assertThrows(IllegalArgumentException.class,()->borrowed("false",0,1).validate(List.of(STRING),FIXED,true,false,false,8,0,0));
for(Integer index:new Integer[]{null,1})
assertThrows(IllegalArgumentException.class,()->borrowed("true",index,1).validate(List.of(STRING),ARGUMENT_UTF8_BYTES_V1,true,false,false,8,0,0));
assertThrows(IllegalArgumentException.class,()->borrowed("false",0,1).validate(List.of(INT64),ARGUMENT_UTF8_BYTES_V1,true,false,false,8,0,0));
assertThrows(IllegalArgumentException.class,()->borrowed("true",0,0).validate(List.of(STRING),ARGUMENT_UTF8_BYTES_V1,true,false,false,8,0,0));
assertThrows(IllegalArgumentException.class,()->borrowed("true",0,1).validate(List.of(STRING),ARGUMENT_UTF8_BYTES_V1,true,false,false,8,1,1));
var random=IRVMIntrinsicDefinition.RANDOM_RANGE.profile();
assertThrows(IllegalArgumentException.class,()->random.validate(List.of(RANDOM,INT64,INT64),RANDOM_REJECTION_V1,true,false,true,4,8,65));
}
}
@@ -12,13 +12,13 @@ import static org.junit.jupiter.api.Assertions.*;
class IRVMIntrinsicRegistryParityTest {
private static final String RESOURCE = "/runtime-catalog/compiler/";
private static final String HEADER = "final_id_hex,final_id_dec,canonical_name,canonical_version,owner,name,arg_slots,ret_slots,arg_layout,ret_layout,deterministic,may_allocate,parameter_names,cost_cycles,mutates_guest_state,cost_model,attempt_cost_cycles,max_attempts";
private static final String HEADER = "final_id_hex,final_id_dec,canonical_name,canonical_version,owner,name,arg_slots,ret_slots,arg_layout,ret_layout,deterministic,may_allocate,parameter_names,cost_cycles,mutates_guest_state,cost_model,attempt_cost_cycles,max_attempts,schema_version,arg_nullable,invocation_model,scratch_model,context_access,cost_arg_index,cost_per_byte";
@Test
void completeManualDefinitionsMatchIndependentlyPublishedProviderRows() throws Exception {
var lines = text("INTRINSICS.csv").lines().toList();
assertEquals(HEADER, lines.getFirst());
assertEquals(106, lines.size());
assertEquals(109, lines.size());
var actual = new ArrayList<String>();
var ids = new HashSet<Integer>();
var identities = new HashSet<String>();
@@ -32,7 +32,11 @@ class IRVMIntrinsicRegistryParityTest {
Integer.toString(d.argSlots()), Integer.toString(d.retSlots()), d.argLayout(), d.retLayout(),
Boolean.toString(d.deterministic()), Boolean.toString(d.mayAllocate()), d.parameterNames(),
Long.toString(d.costCycles()), Boolean.toString(d.mutatesGuestState()), d.costModel().token(),
Long.toString(d.attemptCostCycles()), Integer.toString(d.maxAttempts())));
Long.toString(d.attemptCostCycles()), Integer.toString(d.maxAttempts()),
Integer.toString(d.profile().schemaVersion()), d.profile().argNullable(),
d.profile().invocationModel(), d.profile().scratchModel(), d.profile().contextAccess(),
d.profile().costArgIndex()==null?"":Integer.toString(d.profile().costArgIndex()),
Long.toString(d.profile().costPerByte())));
}
assertEquals(lines.subList(1, lines.size()), actual);
}
@@ -77,7 +81,7 @@ class IRVMIntrinsicRegistryParityTest {
assertNotNull(input);
properties.load(input);
}
assertEquals("57992cf214e8a5f9de53a40dba9aaa7fab038c91", properties.getProperty("runtime.revision"));
assertEquals("dcf6561ea73446e0a3e1cf1c73eda20923b38df0", properties.getProperty("runtime.revision"));
for (var name : List.of("INTRINSICS.csv", "BUILTIN_CONSTANTS.csv")) {
assertEquals(properties.getProperty(name + ".sha256"),
HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes(name))));
@@ -133,6 +133,21 @@ class RuntimeCatalogPipelineTest {
assertThrows(BytecodeMarshalingException.class, () -> VERIFIER.verify(emit(badReference)));
}
@Test
void nullableStringHashIsAdmittedPerEntryWithoutBroadeningOlderStringIntrinsics() throws Exception {
for(boolean optimize:new boolean[]{false,true}) {
var plan=new BytecodeEmitter.EmissionPlan(0,ReadOnlyList.from(new BytecodeModule.NullConstant()),null,
ReadOnlyList.from(new BytecodeEmitter.FunctionPlan("main",0,0,0,1,ReadOnlyList.from(
BytecodeEmitter.Operation.pushConst(0,null),
BytecodeEmitter.Operation.intrinsic(0x4102,1,1,null),BytecodeEmitter.Operation.halt()))),REGISTRY);
var program=new IRVMProgram(false,plan);
if(optimize)program=new OptimizeIRVMService().optimize(program);
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());
VERIFIER.verify(module);
fixture("catalog-null-hash"+(optimize?"-optimized":""),module);
}
}
@Test
void stringIntrinsicUsesTheProviderLoadTimeCarrierRule() throws Exception {
for (var constant : List.of(new BytecodeModule.StringConstant("#AABBCCDD"), new BytecodeModule.NullConstant())) {
@@ -0,0 +1,71 @@
package p.studio.compiler.backend.registry;
import org.junit.jupiter.api.Test;
import p.studio.compiler.backend.bytecode.*;
import p.studio.compiler.backend.irvm.*;
import p.studio.compiler.models.*;
import p.studio.compiler.models.registry.*;
import p.studio.compiler.models.registry.IRRegistry.*;
import p.studio.compiler.source.identifiers.*;
import p.studio.utilities.structures.ReadOnlyList;
import java.nio.file.*;
import java.util.ArrayList;
import static p.studio.compiler.models.IRBackendExecutableFunction.InstructionKind.*;
import static p.studio.compiler.models.registry.IRRegistryInstruction.Kind.*;
/** Neutral frontend fixtures with independent runtime cost/fault/storage oracles. */
class ArrayCopyPipelineTest {
@Test void completeGroupsEmptyRangesOverlapAndFaultsUseBothProducerPaths() throws Exception {
for(String name:new String[]{"scalar","vec2","string","zero","bad-range","bad-empty-range",
"null-source","null-zero","negative-count","huge-count","fault-order"}) generate(name);
}
private static void generate(String name) throws Exception {
int builtin=name.equals("vec2")?2:name.equals("string")?0x14:0x10;
var element=TypeRef.builtin(builtin);var array=new TypeRef("copy:array");var holder=new TypeRef("copy:holder");
var registry=new IRRegistry(ReadOnlyList.from(new TypeDeclaration(element,null,new Builtin(builtin)),
new TypeDeclaration(array,"CopyArray",new Array(element)),
new TypeDeclaration(holder,"CopyHolder",new Struct(ReadOnlyList.from(new NamedType(array,"empty"))))),null);
var code=new ArrayList<IRBackendExecutableFunction.Instruction>();
class Emit {
void plain(IRBackendExecutableFunction.InstructionKind kind,String value) {
code.add(new IRBackendExecutableFunction.Instruction(kind,null,null,null,null,null,value,null,null,null,null));
}
void number(long value) {plain(PUSH_I64,Long.toString(value));}
void local(IRBackendExecutableFunction.InstructionKind kind) {
code.add(new IRBackendExecutableFunction.Instruction(kind,null,null,null,null,null,null,null,0,null,null));
}
void typed(IRRegistryInstruction.Kind kind,TypeRef type) {
code.add(new IRBackendExecutableFunction.Instruction(REGISTRY,null,null,null,null,null,null,null,null,null,null,
new IRRegistryInstruction(kind,type,null,null,0)));
}
}
var emit=new Emit();emit.number(12);emit.typed(ARRAY_NEW,array);emit.local(SET_LOCAL);
for(int i=0;i<12;i++) {
emit.local(GET_LOCAL);emit.number(i);
if(builtin==2) {emit.plain(PUSH_F64,Double.toString(i+1));emit.plain(PUSH_F64,Double.toString(-i-1));}
else if(builtin==0x14)emit.plain(PUSH_CONST,"slot-"+i+"-Δ");
else emit.plain(PUSH_I32,Integer.toString(i+1));
emit.typed(ARRAY_SET,array);
}
if(name.startsWith("null-")||name.equals("fault-order")) {
emit.typed(STRUCT_NEW,holder);emit.typed(STRUCT_GET,holder);
} else emit.local(GET_LOCAL);
emit.number(name.equals("bad-range")?3:name.equals("bad-empty-range")?13:name.equals("zero")?12:0);
emit.local(GET_LOCAL);emit.number(name.equals("zero")||name.equals("bad-empty-range")?12:2);
emit.number(name.equals("zero")||name.equals("null-zero")||name.equals("bad-empty-range")?0:
name.equals("negative-count")||name.equals("fault-order")?-1:name.equals("huge-count")?4294967296L:10);
emit.typed(ARRAY_COPY,array);emit.plain(HALT,null);
var function=new IRBackendExecutableFunction(new FileId(0),new ModuleId(0),"main",new CallableId(0),0,0,0,1,0,5,
ReadOnlyList.wrap(code),null,FunctionMetadata.empty());
var backend=IRBackend.builder().entryPointModuleId(new ModuleId(0)).entryPointCallableName("main")
.registry(registry).executableFunctions(ReadOnlyList.from(function)).build();
for(boolean optimize:new boolean[]{false,true}) {
var program=new LowerToIRVMService().lower(backend);
if(optimize)program=new OptimizeIRVMService().optimize(program);
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());
new BytecodePreloadVerifierService().verify(module);
var directory=Path.of("build/registry-conformance");Files.createDirectories(directory);
Files.write(directory.resolve("common-copy-"+name+(optimize?"-optimized":"")+".pbx"),module.serialize());
}
}
}
@@ -63,6 +63,16 @@ class PbxRegistryConformanceTest {
assertThrows(BytecodeMarshalingException.class,()->VERIFIER.verify(emptyFunction(hex("01 00 50 00 ff ff ff ff"),0)));
for(int op:new int[]{0x54,0x55,0x56,0x70})assertThrows(RuntimeException.class,()->VERIFIER.verify(emptyFunction(new byte[]{1,0,(byte)op,0,0,0,0,0},0)));
}
@Test void retiredStorageOpcodesRejectEvenAfterHaltAndDataBytesRemainData() throws Exception {
for(int opcode:new int[]{0xa7,0xa8,0xaa,0xab}) {
var retired=emptyFunction(instructions(op(1),op(opcode,0,0,0,0)),0);
assertThrows(BytecodeMarshalingException.class,()->VERIFIER.verify(retired));
fixture("retired-storage-"+Integer.toHexString(opcode),retired);
// The same value inside an Int32 immediate is not an instruction.
var data=emptyFunction(instructions(op(0x17,opcode),op(0x11),op(1)),1);
VERIFIER.verify(data);fixture("storage-immediate-"+Integer.toHexString(opcode),data);
}
}
@Test void literalZeroAndExactReturnHeight() {
assertThrows(BytecodeMarshalingException.class,()->VERIFIER.verify(emptyFunction(hex("17 00 00 00 00 00 11 00 51 00"),0)));
assertThrows(BytecodeMarshalingException.class,()->VERIFIER.verify(emptyFunction(hex("17 00 00 00 00 00 51 00"),1)));
@@ -31,20 +31,18 @@ class StoragePublicationPipelineTest {
}
private void number(long value){literal(PUSH_I64,Long.toString(value));}
@Test void multiObjectFieldsPublishThroughNeutralOrdinaryAndOptimizedProducers() throws Exception {
var schema = new TypeRef("synthetic:publication-schema");
@Test void ordinaryFieldStoresUseNeutralOrdinaryAndOptimizedProducers() throws Exception {
var registry = new IRRegistry(ReadOnlyList.from(
new TypeDeclaration(INTEGER,null,new Builtin(0x10)),
new TypeDeclaration(LONG,null,new Builtin(0x11)),
new TypeDeclaration(OWNER,"State",new Struct(ReadOnlyList.from(
new NamedType(LONG,"generation"),new NamedType(INTEGER,"answer")))),
new TypeDeclaration(schema,null,new Struct(ReadOnlyList.from(
new NamedType(OWNER,null),new NamedType(OWNER,null))))),null);
new NamedType(LONG,"generation"),new NamedType(INTEGER,"answer"))))),null);
typed(STRUCT_NEW,OWNER,0);local(SET_LOCAL,0);
typed(STRUCT_NEW,OWNER,0);local(SET_LOCAL,1);
local(GET_LOCAL,0);number(7);literal(PUSH_I32,"20");
local(GET_LOCAL,1);number(9);literal(PUSH_I32,"42");
typed(FIELDS_PUBLISH,schema,0);
local(GET_LOCAL,0);number(7);typed(STRUCT_SET,OWNER,0);
local(GET_LOCAL,0);literal(PUSH_I32,"20");typed(STRUCT_SET,OWNER,1);
local(GET_LOCAL,1);number(9);typed(STRUCT_SET,OWNER,0);
local(GET_LOCAL,1);literal(PUSH_I32,"42");typed(STRUCT_SET,OWNER,1);
local(GET_LOCAL,1);typed(STRUCT_GET,OWNER,1);literal(RET,null);
var function=new IRBackendExecutableFunction(new FileId(0),new ModuleId(0),"main",new CallableId(0),0,0,0,2,1,6,
ReadOnlyList.wrap(instructions),null,new FunctionMetadata(new Signature(null,ReadOnlyList.from(INTEGER)),null,Role.NONE));
@@ -60,21 +58,44 @@ class StoragePublicationPipelineTest {
}
}
@Test void guardsTransfersAndPublicationSurviveBothProducerPaths() throws Exception {
@Test void terminalFailureKeepsEarlierStoresAndSourceSpanThroughBothProducerPaths() throws Exception {
var registry=new IRRegistry(ReadOnlyList.from(
new TypeDeclaration(INTEGER,null,new Builtin(0x10)),new TypeDeclaration(LONG,null,new Builtin(0x11)),
new TypeDeclaration(OWNER,"State",new Struct(ReadOnlyList.from(
new NamedType(LONG,"generation"),new NamedType(INTEGER,"answer"))))),null);
typed(STRUCT_NEW,OWNER,0);local(SET_LOCAL,0);
local(GET_LOCAL,0);literal(PUSH_I32,"20");typed(STRUCT_SET,OWNER,1);
instructions.add(new IRBackendExecutableFunction.Instruction(TRAP,"",null,null,
new p.studio.compiler.source.Span(new FileId(0),12,18)));
var function=new IRBackendExecutableFunction(new FileId(0),new ModuleId(0),"main",new CallableId(0),0,18,0,1,1,2,
ReadOnlyList.wrap(instructions),null,new FunctionMetadata(new Signature(null,ReadOnlyList.from(INTEGER)),null,Role.NONE));
var backend=IRBackend.builder().entryPointModuleId(new ModuleId(0)).entryPointCallableName("main")
.registry(registry).executableFunctions(ReadOnlyList.from(function)).build();
for(boolean optimize:new boolean[]{false,true}) {
var program=new LowerToIRVMService().lower(backend);
if(optimize)program=new OptimizeIRVMService().optimize(program);
assertTrue(program.module().functions().getFirst().instructions().getLast().op().terminator());
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());
new BytecodePreloadVerifierService().verify(module);
assertTrue(module.debugInfo().pcToSpan().stream().anyMatch(s->s.span().start()==12&&s.span().end()==18));
var directory=Path.of("build/registry-conformance");Files.createDirectories(directory);
Files.write(directory.resolve("common-partial-fault"+(optimize?"-optimized":"")+".pbx"),module.serialize());
}
}
@Test void typedCopyAndOrdinaryStoresSurviveBothProducerPaths() throws Exception {
var registry=new IRRegistry(ReadOnlyList.from(
new TypeDeclaration(INTEGER,null,new Builtin(0x10)),new TypeDeclaration(LONG,null,new Builtin(0x11)),
new TypeDeclaration(BUFFER,"Buffer",new Array(INTEGER)),
new TypeDeclaration(OWNER,"State",new Struct(ReadOnlyList.from(new NamedType(LONG,"generation"),new NamedType(INTEGER,"answer"))))),null);
number(3);typed(ARRAY_CHECK_LENGTH,BUFFER,0);
number(3);typed(ARRAY_NEW,BUFFER,0);local(SET_LOCAL,0);
typed(STRUCT_NEW,OWNER,0);local(SET_LOCAL,1);
number(0);number(1);typed(INDEX_GUARD,null,0);
for(int i=0;i<2;i++) {local(GET_LOCAL,0);number(i);literal(PUSH_I32,Integer.toString((i+1)*10));typed(ARRAY_SET,BUFFER,0);}
local(GET_LOCAL,0);number(0);local(GET_LOCAL,0);number(1);number(2);typed(ARRAY_COPY,BUFFER,0);
local(GET_LOCAL,0);number(1);local(GET_LOCAL,0);number(0);number(2);number(2);number(1);
literal(PUSH_I32,"7");local(GET_LOCAL,1);number(9);literal(PUSH_I32,"42");
instructions.add(new IRBackendExecutableFunction.Instruction(REGISTRY,null,null,null,null,null,null,null,null,null,null,
new IRRegistryInstruction(STORAGE_PUBLISH,BUFFER,OWNER,null,0,1)));
local(GET_LOCAL,0);number(1);local(GET_LOCAL,0);number(0);number(2);typed(ARRAY_COPY,BUFFER,0);
local(GET_LOCAL,0);number(2);literal(PUSH_I32,"7");typed(ARRAY_SET,BUFFER,0);
local(GET_LOCAL,1);number(9);typed(STRUCT_SET,OWNER,0);
local(GET_LOCAL,1);literal(PUSH_I32,"42");typed(STRUCT_SET,OWNER,1);
local(GET_LOCAL,1);typed(STRUCT_GET,OWNER,1);literal(RET,null);
var function=new IRBackendExecutableFunction(new FileId(0),new ModuleId(0),"main",new CallableId(0),0,0,0,2,1,11,
ReadOnlyList.wrap(instructions),null,new FunctionMetadata(new Signature(null,ReadOnlyList.from(INTEGER)),null,Role.NONE));
@@ -83,14 +104,17 @@ class StoragePublicationPipelineTest {
for(boolean optimize:new boolean[]{false,true}) {
var program=new LowerToIRVMService().lower(backend);
if(optimize)program=new OptimizeIRVMService().optimize(program);
var publication=program.module().functions().getFirst().instructions().stream()
.filter(i->i.op().opcode()==0xaa).findFirst().orElseThrow();
assertEquals(18,publication.encodedSize());assertEquals(0,publication.thirdImmediate());assertEquals(1,publication.fourthImmediate());
for (var instruction:program.module().functions().getFirst().instructions())
assertFalse(java.util.Set.of(0xa7,0xa8,0xaa,0xab).contains(instruction.op().opcode()));
var copy=program.module().functions().getFirst().instructions().stream()
.filter(i->i.op().opcode()==0xa9).findFirst().orElseThrow();
assertEquals(6,copy.encodedSize());
var module=new BytecodeEmitter().emit(program.coherentEmissionPlan());
new BytecodePreloadVerifierService().verify(module);
var directory=Path.of("build/registry-conformance");Files.createDirectories(directory);
Files.write(directory.resolve("common-storage"+(optimize?"-optimized":"")+".pbx"),module.serialize());
}
assertThrows(IllegalArgumentException.class,()->new IRRegistryInstruction(STORAGE_PUBLISH,BUFFER,OWNER,null,1,1));
for (int opcode:new int[]{0xa7,0xa8,0xaa,0xab})
assertFalse(java.util.Arrays.stream(IRRegistryInstruction.Kind.values()).anyMatch(k->k.opcode()==opcode));
}
}
@@ -220,7 +220,7 @@ public class IRBackend implements IRBackendReader {
instruction.expectedRetSlots(),
instruction.span(), instruction.registryInstruction() == null ? null :
new p.studio.compiler.models.registry.IRRegistryInstruction(instruction.registryInstruction().kind(), instruction.registryInstruction().type(), instruction.registryInstruction().targetType(),
instruction.registryInstruction().function() == null ? null : remapCallableId(instruction.registryInstruction().function(), callableRemap, "Registry instruction"), instruction.registryInstruction().member(), instruction.registryInstruction().secondMember())));
instruction.registryInstruction().function() == null ? null : remapCallableId(instruction.registryInstruction().function(), callableRemap, "Registry instruction"), instruction.registryInstruction().member())));
}
return new IRBackendExecutableFunction(
function.fileId(),
@@ -385,7 +385,7 @@ public record IRBackendExecutableFunction(
throw new IllegalArgumentException("CALL_INTRINSIC must not carry host metadata");
}
}
case HALT, RET, POP, ADD, SUB, MUL, DIV, MOD, EQ, NEQ, LT, LTE, GT, GTE, AND, OR, NOT, NEG -> {
case HALT, TRAP, RET, POP, ADD, SUB, MUL, DIV, MOD, EQ, NEQ, LT, LTE, GT, GTE, AND, OR, NOT, NEG -> {
if (!calleeCallableName.isBlank() || calleeCallableId != null || hostCall != null || intrinsicCall != null) {
throw new IllegalArgumentException(kind + " must not carry callsite metadata");
}
@@ -457,6 +457,7 @@ public record IRBackendExecutableFunction(
NOT,
NEG,
HALT,
TRAP,
RET,
CALL_FUNC,
CALL_HOST,
@@ -5,32 +5,27 @@ import java.util.Objects;
/** Semantic Registry operands before image linking. No frontend syntax is exposed. */
public record IRRegistryInstruction(Kind kind, IRRegistry.TypeRef type, IRRegistry.TypeRef targetType,
CallableId function, int member, int secondMember) {
public IRRegistryInstruction(Kind kind, IRRegistry.TypeRef type, IRRegistry.TypeRef targetType, CallableId function, int member) {
this(kind,type,targetType,function,member,0);
}
CallableId function, int member) {
public enum Kind {
MAKE_CLOSURE(0x52), CALL_CLOSURE(0x53), GET_CAPTURE(0x57), CALL_TRAIT(0x58),
DYN_PACK(0x90), DYN_UNPACK(0x91), DYN_CAN_UNPACK(0x92),
REF_IS_EXACT(0x93), REF_IMPLEMENTS(0x94), REF_TO_TRAIT(0x95), REF_CAST(0x96),
STRUCT_NEW(0xa0), STRUCT_GET(0xa1), STRUCT_SET(0xa2),
ARRAY_NEW(0xa3), ARRAY_LEN(0xa4), ARRAY_GET(0xa5), ARRAY_SET(0xa6),
INDEX_GUARD(0xa7), ARRAY_CHECK_LENGTH(0xa8), ARRAY_COPY(0xa9), STORAGE_PUBLISH(0xaa), FIELDS_PUBLISH(0xab);
ARRAY_COPY(0xa9);
private final int opcode;
Kind(int opcode) { this.opcode=opcode; }
public int opcode(){return opcode;}
}
public IRRegistryInstruction {
Objects.requireNonNull(kind);
if(member<0 || secondMember<0)throw new IllegalArgumentException("negative member index");
if(kind!=Kind.GET_CAPTURE && kind!=Kind.INDEX_GUARD)Objects.requireNonNull(type,"type");
if(kind!=Kind.STORAGE_PUBLISH && secondMember!=0)throw new IllegalArgumentException("unexpected second member");
if(kind==Kind.STORAGE_PUBLISH && member==secondMember)throw new IllegalArgumentException("publication fields must differ");
if(member<0)throw new IllegalArgumentException("negative member index");
if(kind!=Kind.GET_CAPTURE)Objects.requireNonNull(type,"type");
if(kind==Kind.MAKE_CLOSURE) {Objects.requireNonNull(function,"function");function.getIndex();}
else if(function!=null)throw new IllegalArgumentException("unexpected function operand");
boolean pair=(kind.opcode()>=0x93&&kind.opcode()<=0x96)||kind==Kind.STORAGE_PUBLISH;
boolean pair=(kind.opcode()>=0x93&&kind.opcode()<=0x96);
if(pair)Objects.requireNonNull(targetType,"targetType");
else if(targetType!=null)throw new IllegalArgumentException("unexpected target type");
if((kind==Kind.GET_CAPTURE||kind==Kind.INDEX_GUARD)&&type!=null)throw new IllegalArgumentException("capture index is not a TypeId");
if(kind==Kind.GET_CAPTURE&&type!=null)throw new IllegalArgumentException("capture index is not a TypeId");
}
}