1// Metal's shading language from the shader compiler's SPIR-V2// (PLAN.md, F7b): the module the compiler wrote from the checked3// WGSL, its types, layouts and control flow already settled, read back4// and written as MSL source, which the Metal device compiles while the5// program runs. Only what the compiler emits is read: structured6// selections and loops, no phi.7//8// Every value gets a variable declared at the top of its function, so9// structured control flow needs no scopes; components are read by index10// (`v[1]`), never by swizzle. Structs that buffers hold keep their WGSL11// offsets through padding, a 3-component vector in one being packed. A12// function reads the resources it uses, its callees' too, as parameters.13// An entry point `name` becomes `alloy_name`, its resources at the Metal14// indices `metal_index` gives, its stage's inputs and outputs in structs.1516import std::string;17import std::vector;18import std::option;19import std::map;20import std::text;21import std::sort;2223import spirv;24import compiler;2526type Block = struct {27 label: u32,28 body: Vector<Instruction>, // its instructions but the merge and the terminator29 merge: Option<Instruction> = ::None,30 terminator: Instruction,31};3233type Function = struct {34 id: u32,35 result: u32, // its result type's id36 parameters: Vector<u32> = Vector<u32>::empty(),37 blocks: Vector<Block> = Vector<Block>::empty(),38 resources: Vector<u32> = Vector<u32>::empty(), // the resource variables it reads, its callees' too39};4041type Loop = struct {42 header: u32,43 merge: u32,44 continue_label: u32,45};4647// A member's offset in a struct buffers hold.48type MemberOffset = struct {49 structure: u32,50 member: u32,51 offset: u32,52};5354// A size and an alignment, in bytes.55type Layout = struct {56 size: u32,57 alignment: u32,58};5960// The image and sampler a sampled image combines.61type Sampled = struct {62 image: u32,63 sampler: u32,64};6566type Writer = struct {67 words: Vector<u32>,68 definitions: Map<u32, Instruction> = Map<u32, Instruction>::empty(), // types, constants, variables, by result id69 decorations: Vector<Instruction> = Vector<Instruction>::empty(),70 entry_points: Vector<Instruction> = Vector<Instruction>::empty(),71 functions: Vector<Function> = Vector<Function>::empty(),72 struct_ids: Vector<u32> = Vector<u32>::empty(), // in the order the module declares them73 offsets: Vector<MemberOffset> = Vector<MemberOffset>::empty(),74 strides: Map<u32, u32> = Map<u32, u32>::empty(), // arrays' strides, by id75 laid_out: Vector<u32> = Vector<u32>::empty(), // struct ids that buffers hold, laid out by their offsets76 // the size a struct needs to reach the stride of the arrays holding it77 struct_sizes: Map<u32, u32> = Map<u32, u32>::empty(),78 out: String = String::empty(),79 indent: u64 = 0,80 error: String = String::empty(),81 // the function being written82 loops: Vector<Loop> = Vector<Loop>::empty(),83 blocks: Map<u32, u64> = Map<u32, u64>::empty(), // its blocks by label84 current: u64 = 0,85 entry: Option<u64> = ::None, // which entry point's function it is86 places: Map<u32, String> = Map<u32, String>::empty(), // pointers' expressions by id87 sampled: Map<u32, Sampled> = Map<u32, Sampled>::empty(),88 read_only: Vector<u32> = Vector<u32>::empty(), // the storage buffers' variables only read89};9091// The MSL source of the compiled module; the error when something in it92// has no MSL here.93pub type Msl = struct {94 pub source: String,95 pub error: String,96};9798// The name of the entry point's MSL function.99pub fn msl_entry_name(name: &[u8]) -> String => f"alloy_{name}";100101// The Metal index of the entry point's `k`th resource: buffers, textures102// and samplers each numbered from 0 in the order the entry uses them.103// Vertex buffers come after the vertex stage's buffers.104pub fn metal_index(resources: &[ShaderResource], used: &[u32], k: u64) -> u32 {105 const class = resources[used[k] to u64].kind.class();106 var index: u32 = 0;107 for (used[..k]) |r| {108 if (resources[r to u64].kind.class() == class) {109 index += 1;110 }111 }112 return index;113}114115// How many buffers the entry point binds, where its vertex buffers start.116pub fn metal_buffers(resources: &[ShaderResource], used: &[u32]) -> u32 {117 var count: u32 = 0;118 for (used) |r| {119 if (resources[r to u64].kind.class() is ::Buffer) {120 count += 1;121 }122 }123 return count;124}125126pub fn write_msl(compiled: &Compiled) -> Msl {127 var w = Writer { .words = copy compiled.words };128 w.read();129 w.find_resources();130 for (compiled.resources.view()) |&r| {131 if (r.kind is ::StorageRead) {132 w.read_only.push(w.resource_variable(r.group, r.binding));133 }134 }135 w.line(&"#include <metal_stdlib>");136 w.line(&"using namespace metal;");137 w.line(&"");138 w.structs();139 for ([..w.functions.length()]) |k| {140 if (w.entry_of(w.functions.get(k).id) is ::None) {141 w.prototype(k, true);142 }143 }144 w.line(&"");145 for ([..w.functions.length()]) |k| {146 w.function(k, &compiled);147 }148 return Msl { .source = move w.out, .error = move w.error };149}150151/* --- Reading the module --- */152153fn operand(self w: &Writer, i: &Instruction, k: u64) -> u32 => w.words.get(i.at + k);154155fn read(self w: &var Writer) {156 const list = if (instructions(&w.words.view()) is ::Some |move l|) move l else {157 w.error = String::from(&"a SPIR-V instruction of no words");158 return;159 };160 var function: Option<Function> = ::None;161 var block: Option<Block> = ::None;162 for (list.view()) |&i| {163 match (i.opcode) {164 ::Decorate {165 w.decorations.push(i);166 if (w.operand(&i, 1) == Decoration::ArrayStride to u32) {167 w.strides.insert(w.operand(&i, 0), w.operand(&i, 2));168 }169 continue;170 }171 ::MemberDecorate {172 w.decorations.push(i);173 if (w.operand(&i, 2) == Decoration::Offset to u32) {174 w.offsets.push(MemberOffset {175 .structure = w.operand(&i, 0),176 .member = w.operand(&i, 1),177 .offset = w.operand(&i, 3)178 });179 }180 continue;181 }182 ::EntryPoint {183 w.entry_points.push(i);184 continue;185 }186 ::TypeStruct {187 w.struct_ids.push(w.operand(&i, 0));188 w.definitions.insert(w.operand(&i, 0), i);189 continue;190 }191 ::TypeVoid, ::TypeBool, ::TypeInt, ::TypeFloat, ::TypeVector, ::TypeMatrix, ::TypeImage,192 ::TypeSampler, ::TypeSampledImage, ::TypeArray, ::TypeRuntimeArray, ::TypePointer,193 ::TypeFunction {194 w.definitions.insert(w.operand(&i, 0), i);195 continue;196 }197 ::ConstantTrue, ::ConstantFalse, ::Constant, ::ConstantComposite, ::ConstantNull {198 w.definitions.insert(w.operand(&i, 1), i);199 continue;200 }201 ::Variable {202 if (function is ::None) {203 w.definitions.insert(w.operand(&i, 1), i);204 continue;205 }206 }207 ::Function {208 function = ::Some(Function { .id = w.operand(&i, 1), .result = w.operand(&i, 0) });209 continue;210 }211 ::FunctionParameter {212 if (function is ::Some |&var f|) {213 f.parameters.push(w.operand(&i, 1));214 }215 w.definitions.insert(w.operand(&i, 1), i);216 continue;217 }218 ::FunctionEnd {219 if (function is ::Some |move f|) {220 w.functions.push(move f);221 }222 function = ::None;223 continue;224 }225 ::Label {226 block = ::Some(Block {227 .label = w.operand(&i, 0),228 .body = Vector<Instruction>::empty(),229 .terminator = i230 });231 continue;232 }233 }234 if (block is ::Some |&var b|) {235 match (i.opcode) {236 ::SelectionMerge, ::LoopMerge {237 b.merge = ::Some(i);238 }239 ::Branch, ::BranchConditional, ::Return, ::ReturnValue, ::Kill {240 b.terminator = i;241 if (function is ::Some |&var f|) {242 if (block is ::Some |move ended|) {243 f.blocks.push(move ended);244 }245 }246 block = ::None;247 }248 else {249 if (i.opcode is ::Variable) {250 w.definitions.insert(w.operand(&i, 1), i);251 }252 b.body.push(i);253 }254 }255 }256 }257}258259// The resources each function reads, through its callees too.260fn find_resources(self w: &var Writer) {261 var changed = true;262 while (changed) {263 changed = false;264 for ([..w.functions.length()]) |k| {265 var found = copy w.functions.get(k).resources;266 for (w.functions.get(k).blocks.view()) |&b| {267 for (b.body.view()) |&i| {268 // the pointer a load, an access chain or a store uses269 const pointer = match (i.opcode) {270 ::Load, ::AccessChain w.operand(&i, 2);271 ::Store w.operand(&i, 0);272 else 0;273 };274 if (w.is_resource(pointer) && !contains(&found.view(), pointer)) {275 found.push(pointer);276 }277 if (i.opcode is ::FunctionCall) {278 const callee = w.operand(&i, 2);279 for (w.functions.view()) |&f| {280 if (f.id == callee) {281 for (f.resources.view()) |r| {282 if (!contains(&found.view(), r)) {283 found.push(r);284 }285 }286 }287 }288 }289 }290 }291 if (found.length() != w.functions.get(k).resources.length()) {292 sort(&var found.items());293 w.functions.get_var(k).resources = move found;294 changed = true;295 }296 }297 }298}299300fn contains(list: &[u32], id: u32) -> bool {301 for (list) |x| {302 if (x == id) {303 return true;304 }305 }306 return false;307}308309// Whether the id is a module variable holding a resource.310fn is_resource(self w: &Writer, id: u32) -> bool {311 if (312 w.definitions.try_get(&id) is ::Some |&i|313 && i.opcode is ::Variable314 && StorageClass::from(w.operand(&i, 2)) is ::Some |storage|315 ) {316 return storage.is_resource();317 }318 return false;319}320321// The instruction defining the id, or a Nop when none does.322fn definition(self w: &Writer, id: u32) -> Instruction {323 if (w.definitions.try_get(&id) is ::Some |&i|) {324 return i;325 }326 return Instruction { .opcode = ::Nop, .at = 0, .end = 0 };327}328329fn decoration(self w: &Writer, id: u32, kind: Decoration) -> Option<u32> {330 for (w.decorations.view()) |&d| {331 if (d.opcode is ::Decorate && w.operand(&d, 0) == id && w.operand(&d, 1) == kind to u32) {332 return ::Some(if (d.count() > 2) w.operand(&d, 2) else 0);333 }334 }335 return ::None;336}337338// The entry point whose function the id is, by its index.339fn entry_of(self w: &Writer, id: u32) -> Option<u64> {340 for ([..w.entry_points.length()]) |k| {341 if (w.operand(&w.entry_points.get(k), 1) == id) {342 return ::Some(k);343 }344 }345 return ::None;346}347348/* --- Types --- */349350fn type_name(self w: &var Writer, id: u32) -> String {351 const t = w.definition(id);352 match (t.opcode) {353 ::TypeVoid {354 return String::from(&"void");355 }356 ::TypeBool {357 return String::from(&"bool");358 }359 ::TypeInt {360 return String::from(if (w.operand(&t, 2) == 1) &"int" else &"uint");361 }362 ::TypeFloat {363 return String::from(&"float");364 }365 ::TypeVector {366 const scalar = w.type_name(w.operand(&t, 1));367 return f"{scalar}{w.operand(&t, 2)}";368 }369 ::TypeMatrix {370 const column = w.definition(w.operand(&t, 1));371 return f"float{w.operand(&t, 2)}x{w.operand(&column, 2)}";372 }373 ::TypeArray {374 const element = w.type_name(w.operand(&t, 1));375 return f"array<{element}, {w.constant_value(w.operand(&t, 2))}>";376 }377 ::TypeStruct {378 return f"S{id}";379 }380 ::TypeImage {381 return String::from(&"texture2d<float>");382 }383 ::TypeSampler {384 return String::from(&"sampler");385 }386 ::TypePointer {387 return w.type_name(w.operand(&t, 2));388 }389 }390 w.fail(&f"SPIR-V type {t.opcode to u32} has no MSL here".view());391 return String::from(&"void");392}393394fn fail(self w: &var Writer, message: &[u8]) {395 if (w.error.length() == 0) {396 w.error = String::from(&message);397 }398}399400// An integer constant's value.401fn constant_value(self w: &Writer, id: u32) -> u32 {402 const c = w.definition(id);403 return if (c.opcode is ::Constant) w.operand(&c, 2) else 0;404}405406// The type's size and alignment in a struct laid out by offsets, a407// 3-component vector there packed.408fn layout_of(self w: &Writer, id: u32, member: bool) -> Layout {409 const t = w.definition(id);410 match (t.opcode) {411 ::TypeVector {412 const n = w.operand(&t, 2);413 if (n == 3) {414 return if (member) Layout { .size = 12, .alignment = 4 } else Layout {415 .size = 16,416 .alignment = 16417 };418 }419 return Layout { .size = n * 4, .alignment = n * 4 };420 }421 ::TypeMatrix {422 const column = w.layout_of(w.operand(&t, 1), false);423 return Layout { .size = column.size * w.operand(&t, 2), .alignment = column.alignment };424 }425 ::TypeArray {426 const element = w.layout_of(w.operand(&t, 1), false);427 const stride = round_up(element.size, element.alignment);428 return Layout {429 .size = stride * w.constant_value(w.operand(&t, 2)),430 .alignment = element.alignment431 };432 }433 ::TypeRuntimeArray {434 return Layout {435 .size = 0,436 .alignment = w.layout_of(w.operand(&t, 1), false).alignment437 };438 }439 ::TypeStruct {440 var end: u32 = 0;441 var alignment: u32 = 1;442 const laid = contains(&w.laid_out.view(), id);443 for ([1..t.count()]) |k| {444 const m = w.layout_of(w.operand(&t, k), laid);445 const offset = if (laid) w.offset_of(446 id,447 (k - 1) to u32448 ) else round_up(end, m.alignment);449 end = offset + m.size;450 if (m.alignment > alignment) {451 alignment = m.alignment;452 }453 }454 var size = round_up(end, alignment);455 if (w.struct_sizes.try_get(&id) is ::Some |&tail| && tail > size) {456 size = tail;457 }458 return Layout { .size = size, .alignment = alignment };459 }460 }461 return Layout { .size = 4, .alignment = 4 };462}463464fn round_up(value: u32, alignment: u32) -> u32 => (value + alignment - 1) / alignment * alignment;465466fn offset_of(self w: &Writer, id: u32, member: u32) -> u32 {467 for (w.offsets.view()) |&o| {468 if (o.structure == id && o.member == member) {469 return o.offset;470 }471 }472 return 0;473}474475// The structs, in the order the module declares them, which is the order476// they use each other in.477fn structs(self w: &var Writer) {478 for (w.struct_ids.view()) |id| {479 for (w.offsets.view()) |&o| {480 if (o.structure == id && !contains(&w.laid_out.view(), id)) {481 w.laid_out.push(id);482 }483 }484 }485 // an array of a struct needs the struct as long as its stride486 for (w.strides.entries()) |&e| {487 const element = w.operand(&w.definition(e.key), 1);488 if (w.definition(element).opcode is ::TypeStruct) {489 const longest = if (w.struct_sizes.try_get(&element) is ::Some |&size|) size else 0;490 if (e.value > longest) {491 w.struct_sizes.insert(element, e.value);492 }493 }494 }495 const ids = copy w.struct_ids;496 for (ids.view()) |id| {497 w.write_struct(id);498 }499}500501fn write_struct(self w: &var Writer, id: u32) {502 const t = w.definition(id);503 const laid = contains(&w.laid_out.view(), id);504 w.line(&f"struct S{id} {{".view());505 w.indent += 1;506 var end: u32 = 0;507 var alignment: u32 = 1;508 for ([1..t.count()]) |k| {509 const member = (k - 1) to u32;510 const ty = w.operand(&t, k);511 const m = w.layout_of(ty, laid);512 const offset = if (laid) w.offset_of(id, member) else end;513 if (offset > end) {514 w.line(&f"char pad{member}[{offset - end}];".view());515 }516 const d = w.definition(ty);517 if (d.opcode is ::TypeRuntimeArray) {518 const element = w.type_name(w.operand(&d, 1));519 w.line(&f"{element} m{member}[1];".view());520 } else if (laid && d.opcode is ::TypeVector && w.operand(&d, 2) == 3) {521 const scalar = w.type_name(w.operand(&d, 1));522 w.line(&f"packed_{scalar}3 m{member};".view());523 } else {524 const name = w.type_name(ty);525 w.line(&f"{name} m{member};".view());526 }527 end = offset + m.size;528 if (m.alignment > alignment) {529 alignment = m.alignment;530 }531 }532 if (laid) {533 const size = w.layout_of(id, true).size;534 const natural = round_up(end, alignment);535 if (size > natural) {536 // reaches the stride of the arrays holding it537 w.line(&f"char tail[{size - natural}];".view());538 }539 }540 w.indent -= 1;541 w.line(&"};");542 w.line(&"");543}544545/* --- Values --- */546547// An id's expression: a constant written out, a pointer's place, else548// the variable holding the value.549fn expression(self w: &var Writer, id: u32) -> String {550 if (w.places.try_get(&id) is ::Some |&place|) {551 return copy place;552 }553 const d = w.definition(id);554 match (d.opcode) {555 ::ConstantTrue {556 return String::from(&"true");557 }558 ::ConstantFalse {559 return String::from(&"false");560 }561 ::Constant {562 return w.literal(w.operand(&d, 0), w.operand(&d, 2));563 }564 ::ConstantNull {565 const name = w.type_name(w.operand(&d, 0));566 return f"{name}{{}}";567 }568 ::ConstantComposite {569 const ty = w.operand(&d, 0);570 const parts = w.list(&d, 2);571 const name = w.type_name(ty);572 const shape = w.definition(ty).opcode;573 if (shape is ::TypeVector || shape is ::TypeMatrix) {574 return f"{name}({parts})";575 }576 return f"{name}{{{parts}}}";577 }578 ::Variable, ::FunctionParameter {579 return f"v{id}";580 }581 }582 return f"_{id}";583}584585// The expressions of the instruction's operands from the `first`th,586// separated by commas.587fn list(self w: &var Writer, i: &Instruction, first: u64) -> String {588 var parts = String::empty();589 for ([first..i.count()]) |k| {590 if (k > first) {591 parts.append(&", ");592 }593 const part = w.expression(w.operand(&i, k));594 parts.append(&part.view());595 }596 return move parts;597}598599// A scalar constant of the type, from its bits.600fn literal(self w: &var Writer, ty: u32, bits: u32) -> String {601 const t = w.definition(ty);602 if (t.opcode is ::TypeFloat) {603 const text = f"{bits as f32}";604 const view = &text.view();605 if (view.contains(&"inf") || view.contains(&"nan")) {606 return f"as_type<float>({bits}u)";607 }608 if (view.contains(&".") || view.contains(&"e")) {609 return f"{text}f";610 }611 return f"{text}.0f";612 }613 if (w.operand(&t, 2) == 1) {614 const signed = bits as i32;615 if (signed == -2147483647 - 1) {616 return String::from(&"(-2147483647 - 1)");617 }618 if (signed < 0) {619 return f"({signed})";620 }621 return f"{signed}";622 }623 return f"{bits}u";624}625626/* --- Functions --- */627628fn line(self w: &var Writer, text: &[u8]) {629 for ([..w.indent]) {630 w.out.append(&" ");631 }632 w.out.append(&text);633 w.out.push('\n');634}635636fn resource_parameter(self w: &var Writer, id: u32) -> String {637 const v = w.definition(id);638 const pointer = w.definition(w.operand(&v, 0));639 const pointee = w.operand(&pointer, 2);640 const name = w.type_name(pointee);641 return match (StorageClass::from(w.operand(&v, 2))) {642 ::Some |storage| match (storage) {643 ::Uniform f"constant {name}& v{id}";644 ::StorageBuffer if (645 contains(&w.read_only.view(), id)646 ) f"const device {name}& v{id}" else f"device {name}& v{id}";647 else f"{name} v{id}";648 };649 ::None f"{name} v{id}";650 };651}652653// A function's declaration: its result, name and parameters, its654// resources last.655fn prototype(self w: &var Writer, k: u64, declaration: bool) {656 const f = &w.functions.get(k);657 const id = f.id;658 var text = w.type_name(f.result);659 text.append(&f" f{id}(".view());660 var first = true;661 const parameters = copy f.parameters;662 const resources = copy f.resources;663 for (parameters.view()) |p| {664 if (!first) {665 text.append(&", ");666 }667 first = false;668 const ty = w.operand(&w.definition(p), 0);669 const name = w.type_name(ty);670 text.append(&f"{name} v{p}".view());671 }672 for (resources.view()) |r| {673 if (!first) {674 text.append(&", ");675 }676 first = false;677 const parameter = w.resource_parameter(r);678 text.append(¶meter.view());679 }680 text.append(&if (declaration) ");" else ") {");681 w.line(&text.view());682}683684fn function(self w: &var Writer, k: u64, compiled: &Compiled) {685 w.current = k;686 w.places.clear();687 w.sampled.clear();688 w.blocks.clear();689 w.loops.clear();690 w.entry = w.entry_of(w.functions.get(k).id);691 if (w.entry is ::Some |e|) {692 w.entry_header(e, &compiled);693 } else {694 w.prototype(k, false);695 }696 w.indent += 1;697 const blocks = &w.functions.get(k).blocks;698 for ([..blocks.length()]) |b| {699 w.blocks.insert(blocks.get(b).label, b);700 }701 // every value's variable first702 for ([..blocks.length()]) |b| {703 const body = copy w.functions.get(k).blocks.get(b).body;704 for (body.view()) |&i| {705 w.declare(&i);706 }707 }708 if (w.returns_out() && w.entry is ::Some |e|) {709 const name = w.entry_name(&w.entry_points.get(e));710 w.line(&f"alloy_{name}_out out = {{}};".view());711 }712 if (blocks.length() > 0) {713 w.emit(blocks.get(0).label, ::None);714 }715 w.indent -= 1;716 w.line(&"}");717 w.line(&"");718}719720// Declares the variable of an instruction's result, or records the721// expression of a pointer it gives.722fn declare(self w: &var Writer, i: &Instruction) {723 match (i.opcode) {724 ::Variable {725 const pointer = w.definition(w.operand(&i, 0));726 const name = w.type_name(w.operand(&pointer, 2));727 const id = w.operand(&i, 1);728 if (i.count() > 3) {729 const initial = w.expression(w.operand(&i, 3));730 w.line(&f"{name} v{id} = {initial};".view());731 } else {732 w.line(&f"{name} v{id} = {{}};".view());733 }734 return;735 }736 ::Store, ::AccessChain, ::SampledImage {737 return;738 }739 }740 if (i.count() < 2) {741 return;742 }743 const ty = w.operand(&i, 0);744 // a load of an image or a sampler is only a name for it745 match (w.definition(ty).opcode) {746 ::TypeVoid, ::TypeImage, ::TypeSampler, ::Nop {747 return;748 }749 }750 const name = w.type_name(ty);751 w.line(&f"{name} _{w.operand(&i, 1)};".view());752}753754// Writes the blocks from `start` on, in structured order, until `stop`.755fn emit(self w: &var Writer, start: u32, stop: Option<u32>) {756 var label = start;757 while (!is_label(stop, label)) {758 const index = if (w.blocks.try_get(&label) is ::Some |b|) b else {759 w.fail(&f"a branch to a block not found ({label})".view());760 return;761 };762 const block = copy w.functions.get(w.current).blocks.get(index);763 if (block.merge is ::Some |&m| && m.opcode is ::LoopMerge) {764 const merge = w.operand(&m, 0);765 const continue_label = w.operand(&m, 1);766 w.line(&"while (true) {");767 w.indent += 1;768 w.loops.push(Loop {769 .header = label,770 .merge = merge,771 .continue_label = continue_label772 });773 w.body(&block);774 const t = block.terminator;775 if (t.opcode is ::BranchConditional) {776 const condition = w.expression(w.operand(&t, 0));777 if (w.operand(&t, 2) == merge) {778 w.line(&f"if (!{condition}) {{".view());779 w.line(&" break;");780 w.line(&"}");781 w.emit(w.operand(&t, 1), ::Some(continue_label));782 } else {783 w.line(&f"if ({condition}) {{".view());784 w.line(&" break;");785 w.line(&"}");786 w.emit(w.operand(&t, 2), ::Some(continue_label));787 }788 } else {789 w.emit(w.operand(&t, 0), ::Some(continue_label));790 }791 w.emit(continue_label, ::Some(label));792 w.loops.pop();793 w.indent -= 1;794 w.line(&"}");795 label = merge;796 continue;797 }798 w.body(&block);799 const t = block.terminator;800 match (t.opcode) {801 ::Return {802 w.line(&if (w.returns_out()) "return out;" else "return;");803 return;804 }805 ::ReturnValue {806 const value = w.expression(w.operand(&t, 0));807 w.line(&f"return {value};".view());808 return;809 }810 ::Kill {811 w.line(&"discard_fragment();");812 w.line(813 &if (814 w.returns_out()815 ) "return out;" else if (w.returns_value()) "return {};" else "return;"816 );817 return;818 }819 ::Branch {820 const target = w.operand(&t, 0);821 if (w.loops.try_last() is ::Some |&l| && !is_label(stop, target)) {822 if (target == l.merge) {823 w.line(&"break;");824 return;825 }826 if (target == l.continue_label) {827 // `continue`: the continuing block, then the next turn828 w.emit(l.continue_label, ::Some(l.header));829 w.line(&"continue;");830 return;831 }832 }833 label = target;834 }835 ::BranchConditional {836 const merge = if (block.merge is ::Some |&m|) w.operand(&m, 0) else {837 w.fail(&"a conditional branch with no merge");838 return;839 };840 const condition = w.expression(w.operand(&t, 0));841 const then_label = w.operand(&t, 1);842 const else_label = w.operand(&t, 2);843 if (then_label == merge) {844 w.line(&f"if (!{condition}) {{".view());845 w.indent += 1;846 w.emit(else_label, ::Some(merge));847 w.indent -= 1;848 w.line(&"}");849 } else {850 w.line(&f"if ({condition}) {{".view());851 w.indent += 1;852 w.emit(then_label, ::Some(merge));853 w.indent -= 1;854 if (else_label != merge) {855 w.line(&"} else {");856 w.indent += 1;857 w.emit(else_label, ::Some(merge));858 w.indent -= 1;859 }860 w.line(&"}");861 }862 label = merge;863 }864 else {865 return;866 }867 }868 }869}870871fn is_label(stop: Option<u32>, label: u32) -> bool => if (stop is ::Some |s|) s == label else false;872873// Whether the function is a vertex or fragment stage's, which returns its874// outputs.875fn returns_out(self w: &Writer) -> bool {876 if (w.entry is ::Some |e|) {877 return !(w.stage_of(e) is ::Compute);878 }879 return false;880}881882fn returns_value(self w: &Writer) -> bool {883 const result = w.functions.get(w.current).result;884 return !(w.definition(result).opcode is ::TypeVoid);885}886887// The entry point's stage, compute for a model not a stage's.888fn stage_of(self w: &Writer, entry: u64) -> Stage {889 const model = w.operand(&w.entry_points.get(entry), 0);890 return if (Stage::from(model) is ::Some |stage|) stage else ::Compute;891}892893/* --- Instructions --- */894895fn body(self w: &var Writer, block: &Block) {896 for (block.body.view()) |&i| {897 w.instruction(&i);898 }899}900901fn set(self w: &var Writer, i: &Instruction, value: &[u8]) {902 w.line(&f"_{w.operand(&i, 1)} = {value};".view());903}904905// The place a composite's part is at, by the indices from the906// instruction's `first`th operand: a member's name or an element's index.907fn part(self w: &var Writer, place: &var String, ty: u32, i: &Instruction, first: u64) {908 var t = ty;909 for ([first..i.count()]) |k| {910 const index = w.operand(&i, k);911 const d = w.definition(t);912 if (d.opcode is ::TypeStruct) {913 place.append(&f".m{index}".view());914 t = w.operand(&d, 1 + index to u64);915 } else {916 place.append(&f"[{index}]".view());917 t = w.operand(&d, 1);918 }919 }920}921922fn instruction(self w: &var Writer, i: &Instruction) {923 match (i.opcode) {924 ::Variable {}925 ::AccessChain {926 var place = w.expression(w.operand(&i, 2));927 var ty = w.pointee_type(w.operand(&i, 2));928 for ([3..i.count()]) |k| {929 const index = w.operand(&i, k);930 const t = w.definition(ty);931 if (t.opcode is ::TypeStruct) {932 const member = w.constant_value(index);933 place.append(&f".m{member}".view());934 ty = w.operand(&t, 1 + member to u64);935 } else {936 const at = w.expression(index);937 place.append(&f"[{at}]".view());938 ty = w.operand(&t, 1);939 }940 }941 w.places.insert(w.operand(&i, 1), move place);942 }943 ::Load {944 const loaded = w.definition(w.operand(&i, 0)).opcode;945 if (loaded is ::TypeImage || loaded is ::TypeSampler) {946 w.places.insert(w.operand(&i, 1), w.expression(w.operand(&i, 2)));947 return;948 }949 const source = w.expression(w.operand(&i, 2));950 w.set(&i, &source.view());951 }952 ::Store {953 const target = w.expression(w.operand(&i, 0));954 const value = w.expression(w.operand(&i, 1));955 w.line(&f"{target} = {value};".view());956 }957 ::SampledImage {958 w.sampled.insert(w.operand(&i, 1), Sampled {959 .image = w.operand(&i, 2),960 .sampler = w.operand(&i, 3)961 });962 }963 ::ImageSampleImplicitLod, ::ImageSampleExplicitLod {964 const pair = if (w.sampled.try_get(&w.operand(&i, 2)) is ::Some |p|) p else Sampled {965 .image = 0,966 .sampler = 0967 };968 const image = w.expression(pair.image);969 const sampler = w.expression(pair.sampler);970 const coordinate = w.expression(w.operand(&i, 3));971 if (i.opcode is ::ImageSampleExplicitLod) {972 const lod = w.expression(w.operand(&i, 5));973 w.set(&i, &f"{image}.sample({sampler}, {coordinate}, level({lod}))".view());974 } else {975 w.set(&i, &f"{image}.sample({sampler}, {coordinate})".view());976 }977 }978 ::FunctionCall {979 const callee = w.operand(&i, 2);980 var call = f"f{callee}(";981 call.append(&w.list(&i, 3).view());982 var first = i.count() <= 3;983 var resources = Vector<u32>::empty();984 for (w.functions.view()) |&f| {985 if (f.id == callee) {986 resources = copy f.resources;987 }988 }989 for (resources.view()) |r| {990 if (!first) {991 call.append(&", ");992 }993 first = false;994 call.append(&f"v{r}".view());995 }996 call.push(')');997 if (w.definition(w.operand(&i, 0)).opcode is ::TypeVoid) {998 w.line(&f"{call};".view());999 } else {1000 w.set(&i, &call.view());1001 }1002 }1003 ::CompositeConstruct {1004 const ty = w.operand(&i, 0);1005 const t = w.definition(ty);1006 const name = w.type_name(ty);1007 if (t.opcode is ::TypeStruct) {1008 const id = w.operand(&i, 1);1009 w.line(&f"_{id} = {name}{{}};".view());1010 for ([2..i.count()]) |k| {1011 const part = w.expression(w.operand(&i, k));1012 w.line(&f"_{id}.m{k - 2} = {part};".view());1013 }1014 return;1015 }1016 const parts = w.list(&i, 2);1017 if (t.opcode is ::TypeArray) {1018 w.set(&i, &f"{name}{{{parts}}}".view());1019 } else {1020 w.set(&i, &f"{name}({parts})".view());1021 }1022 }1023 ::CompositeExtract {1024 var value = w.expression(w.operand(&i, 2));1025 w.part(&var value, w.type_of(w.operand(&i, 2)), &i, 3);1026 w.set(&i, &value.view());1027 }1028 ::CompositeInsert {1029 const id = w.operand(&i, 1);1030 const object = w.expression(w.operand(&i, 2));1031 const base = w.expression(w.operand(&i, 3));1032 w.line(&f"_{id} = {base};".view());1033 var place = f"_{id}";1034 w.part(&var place, w.operand(&i, 0), &i, 4);1035 w.line(&f"{place} = {object};".view());1036 }1037 ::VectorShuffle {1038 const a = w.expression(w.operand(&i, 2));1039 const b = w.expression(w.operand(&i, 3));1040 const a_size = w.width(w.type_of(w.operand(&i, 2)));1041 var parts = String::empty();1042 for ([4..i.count()]) |k| {1043 if (k > 4) {1044 parts.append(&", ");1045 }1046 // an undefined component, 0xFFFFFFFF, as the first1047 var c = w.operand(&i, k);1048 if (c == 0xFFFFFFFF) {1049 c = 0;1050 }1051 if (c < a_size) {1052 parts.append(&f"{a}[{c}]".view());1053 } else {1054 parts.append(&f"{b}[{c - a_size}]".view());1055 }1056 }1057 const name = w.type_name(w.operand(&i, 0));1058 w.set(&i, &f"{name}({parts})".view());1059 }1060 ::ExtInst {1061 const instruction = if (Glsl::from(w.operand(&i, 3)) is ::Some |g|) g else {1062 w.fail(&f"GLSL.std.450 instruction {w.operand(&i, 3)} has no MSL here".view());1063 return;1064 };1065 const name: &[u8] = &glsl_name(instruction);1066 const arguments = w.list(&i, 4);1067 w.set(&i, &f"{name}({arguments})".view());1068 }1069 ::Select {1070 const condition = w.expression(w.operand(&i, 2));1071 const yes = w.expression(w.operand(&i, 3));1072 const no = w.expression(w.operand(&i, 4));1073 w.set(&i, &f"select({no}, {yes}, {condition})".view());1074 }1075 ::ConvertFToU, ::ConvertFToS, ::ConvertSToF, ::ConvertUToF {1076 const name = w.type_name(w.operand(&i, 0));1077 const value = w.expression(w.operand(&i, 2));1078 w.set(&i, &f"{name}({value})".view());1079 }1080 ::Bitcast {1081 const name = w.type_name(w.operand(&i, 0));1082 const value = w.expression(w.operand(&i, 2));1083 w.set(&i, &f"as_type<{name}>({value})".view());1084 }1085 ::FRem {1086 const a = w.expression(w.operand(&i, 2));1087 const b = w.expression(w.operand(&i, 3));1088 w.set(&i, &f"fmod({a}, {b})".view());1089 }1090 else {1091 w.operator(&i);1092 }1093 }1094}10951096// An operator's instruction, or a function MSL has under another name.1097fn operator(self w: &var Writer, i: &Instruction) {1098 const unary: &[u8] = &unary_operator(i.opcode);1099 if (unary.length() != 0) {1100 const value = w.expression(w.operand(&i, 2));1101 w.set(&i, &f"{unary}({value})".view());1102 return;1103 }1104 const function: &[u8] = &function_name(i.opcode);1105 if (function.length() != 0) {1106 const arguments = w.list(&i, 2);1107 w.set(&i, &f"{function}({arguments})".view());1108 return;1109 }1110 const binary: &[u8] = &binary_operator(i.opcode);1111 if (binary.length() != 0) {1112 const a = w.expression(w.operand(&i, 2));1113 const b = w.expression(w.operand(&i, 3));1114 w.set(&i, &f"({a} {binary} {b})".view());1115 return;1116 }1117 w.fail(&f"SPIR-V opcode {i.opcode to u32} has no MSL here".view());1118}11191120// The type of a value's id.1121fn type_of(self w: &Writer, id: u32) -> u32 {1122 if (w.definitions.try_get(&id) is ::Some |&d|) {1123 return w.operand(&d, 0);1124 }1125 for (w.functions.get(w.current).blocks.view()) |&b| {1126 for (b.body.view()) |&i| {1127 if (i.count() >= 2 && w.operand(&i, 1) == id && !(i.opcode is ::Store)) {1128 return w.operand(&i, 0);1129 }1130 }1131 }1132 return 0;1133}11341135// The type a pointer's id points at.1136fn pointee_type(self w: &Writer, id: u32) -> u32 {1137 const pointer = w.definition(w.type_of(id));1138 return w.operand(&pointer, 2);1139}11401141fn width(self w: &Writer, ty: u32) -> u32 {1142 const t = w.definition(ty);1143 return if (t.opcode is ::TypeVector) w.operand(&t, 2) else 1;1144}11451146fn unary_operator(opcode: Opcode) -> &[u8] => match (opcode) {1147 ::SNegate, ::FNegate &"-";1148 ::LogicalNot &"!";1149 ::Not &"~";1150 else &"";1151};11521153fn function_name(opcode: Opcode) -> &[u8] => match (opcode) {1154 ::Dot &"dot";1155 ::Any &"any";1156 ::All &"all";1157 ::DPdx &"dfdx";1158 ::DPdy &"dfdy";1159 ::Fwidth &"fwidth";1160 else &"";1161};11621163fn binary_operator(opcode: Opcode) -> &[u8] => match (opcode) {1164 ::IAdd, ::FAdd &"+";1165 ::ISub, ::FSub &"-";1166 ::IMul, ::FMul, ::VectorTimesScalar, ::MatrixTimesScalar, ::VectorTimesMatrix,1167 ::MatrixTimesVector, ::MatrixTimesMatrix &"*";1168 ::UDiv, ::SDiv, ::FDiv &"/";1169 ::UMod, ::SRem, ::FRem &"%";1170 ::LogicalEqual, ::IEqual, ::FOrdEqual &"==";1171 ::LogicalNotEqual, ::INotEqual, ::FOrdNotEqual &"!=";1172 ::LogicalOr &"||";1173 ::LogicalAnd &"&&";1174 ::UGreaterThan, ::SGreaterThan, ::FOrdGreaterThan &">";1175 ::UGreaterThanEqual, ::SGreaterThanEqual, ::FOrdGreaterThanEqual &">=";1176 ::ULessThan, ::SLessThan, ::FOrdLessThan &"<";1177 ::ULessThanEqual, ::SLessThanEqual, ::FOrdLessThanEqual &"<=";1178 ::ShiftRightLogical, ::ShiftRightArithmetic &">>";1179 ::ShiftLeftLogical &"<<";1180 ::BitwiseOr &"|";1181 ::BitwiseXor &"^";1182 ::BitwiseAnd &"&";1183 else &"";1184};11851186// MSL's function for a GLSL.std.450 instruction.1187fn glsl_name(instruction: Glsl) -> &[u8] => match (instruction) {1188 ::RoundEven &"rint";1189 ::Trunc &"trunc";1190 ::FAbs, ::SAbs &"abs";1191 ::FSign &"sign";1192 ::Floor &"floor";1193 ::Ceil &"ceil";1194 ::Fract &"fract";1195 ::Sin &"sin";1196 ::Cos &"cos";1197 ::Tan &"tan";1198 ::Asin &"asin";1199 ::Acos &"acos";1200 ::Atan &"atan";1201 ::Atan2 &"atan2";1202 ::Pow &"pow";1203 ::Exp &"exp";1204 ::Log &"log";1205 ::Exp2 &"exp2";1206 ::Log2 &"log2";1207 ::Sqrt &"sqrt";1208 ::InverseSqrt &"rsqrt";1209 ::FMin, ::UMin, ::SMin &"min";1210 ::FMax, ::UMax, ::SMax &"max";1211 ::FClamp, ::UClamp, ::SClamp &"clamp";1212 ::FMix &"mix";1213 ::Step &"step";1214 ::SmoothStep &"smoothstep";1215 ::Fma &"fma";1216 ::Length &"length";1217 ::Distance &"distance";1218 ::Cross &"cross";1219 ::Normalize &"normalize";1220 ::Reflect &"reflect";1221};12221223/* --- Entry points --- */12241225// An entry point's stage function: its inputs' and outputs' structs, then1226// its header, the resources at their Metal indices.1227fn entry_header(self w: &var Writer, e: u64, compiled: &Compiled) {1228 const point = w.entry_points.get(e);1229 const stage = w.stage_of(e);1230 const name = w.entry_name(&point);1231 // its Input and Output variables, after its name's words1232 const variables = Vector<u32>::from(1233 &w.words.view()[point.at + 2 + (name.length() / 4 + 1) to u64..point.end]1234 );1235 var inputs = Vector<String>::empty();1236 var outputs = Vector<String>::empty();1237 var parameters = Vector<String>::empty();1238 for (variables.view()) |v| {1239 const variable = w.definition(v);1240 const storage = if (StorageClass::from(w.operand(&variable, 2)) is ::Some |s|) s else {1241 continue;1242 };1243 const ty = w.type_name(w.operand(&w.definition(w.operand(&variable, 0)), 2));1244 const location = w.decoration(v, ::Location);1245 const builtin = if (1246 w.decoration(v, ::BuiltIn) is ::Some |b|1247 ) BuiltIn::from(b) else Option<BuiltIn>::None;1248 if (storage is ::Input) {1249 if (location is ::Some |l|) {1250 if (stage is ::Vertex) {1251 inputs.push(f"{ty} l{l} [[attribute({l})]];");1252 } else {1253 const flat: &[u8] = if (1254 w.decoration(v, ::Flat) is ::Some1255 ) &" [[flat]]" else &"";1256 inputs.push(f"{ty} l{l} [[user(locn{l})]]{flat};");1257 }1258 w.places.insert(v, f"in.l{l}");1259 } else if (builtin is ::Some |b|) {1260 const number = b to u32;1261 if (b is ::FragCoord) {1262 inputs.push(f"{ty} b{number} [[position]];");1263 w.places.insert(v, f"in.b{number}");1264 } else {1265 const attribute = &builtin_attribute(b);1266 parameters.push(f"{ty} b{number} [[{attribute}]]");1267 w.places.insert(v, f"b{number}");1268 }1269 }1270 } else if (storage is ::Output) {1271 if (location is ::Some |l|) {1272 if (stage is ::Fragment) {1273 outputs.push(f"{ty} l{l} [[color({l})]];");1274 } else {1275 outputs.push(f"{ty} l{l} [[user(locn{l})]];");1276 }1277 w.places.insert(v, f"out.l{l}");1278 } else if (builtin is ::Some |b|) {1279 const number = b to u32;1280 const attribute: &[u8] = if (b is ::FragDepth) &"depth(any)" else &"position";1281 outputs.push(f"{ty} b{number} [[{attribute}]];");1282 w.places.insert(v, f"out.b{number}");1283 }1284 }1285 }1286 // the resources, which the entry function reads through the WGSL1287 // function it calls1288 if (entry_named(&compiled, &name.view()) is ::Some |&entry|) {1289 const used = &entry.resources.view();1290 for (used, [..used.length()]) |r, k| {1291 const resource = compiled.resources.get(r to u64);1292 const variable = w.resource_variable(resource.group, resource.binding);1293 const parameter = w.resource_parameter(variable);1294 const index = metal_index(&compiled.resources.view(), &used, k);1295 const kind: &[u8] = match (resource.kind.class()) {1296 ::Buffer &"buffer";1297 ::Texture &"texture";1298 ::Sampler &"sampler";1299 };1300 parameters.push(f"{parameter} [[{kind}({index})]]");1301 }1302 }1303 if (inputs.length() > 0) {1304 w.line(&f"struct alloy_{name}_in {{".view());1305 for (inputs.view()) |&i| {1306 w.line(&f" {i}".view());1307 }1308 w.line(&"};");1309 }1310 if (!(stage is ::Compute)) {1311 w.line(&f"struct alloy_{name}_out {{".view());1312 for (outputs.view()) |&o| {1313 w.line(&f" {o}".view());1314 }1315 w.line(&"};");1316 }1317 var header = match (stage) {1318 ::Vertex f"vertex alloy_{name}_out ";1319 ::Fragment f"fragment alloy_{name}_out ";1320 ::Compute String::from(&"kernel void ");1321 };1322 header.append(&msl_entry_name(&name.view()).view());1323 header.push('(');1324 var first = true;1325 if (inputs.length() > 0) {1326 header.append(&f"alloy_{name}_in in [[stage_in]]".view());1327 first = false;1328 }1329 for (parameters.view()) |&p| {1330 if (!first) {1331 header.append(&", ");1332 }1333 first = false;1334 header.append(&p.view());1335 }1336 header.append(&") {");1337 w.line(&header.view());1338}13391340fn entry_name(self w: &Writer, point: &Instruction) -> String => word_text(1341 &w.words.view()[point.at + 2..point.end]1342);13431344fn entry_named(compiled: &Compiled, name: &[u8]) -> Option<&EntryPoint> {1345 for (compiled.entries.view()) |&e| {1346 if (e.name.view() == name) {1347 return ::Some(&e);1348 }1349 }1350 return ::None;1351}13521353// The module variable bound at the group and binding.1354fn resource_variable(self w: &Writer, group: u32, binding: u32) -> u32 {1355 for (w.decorations.view()) |&d| {1356 if (1357 d.opcode is ::Decorate1358 && w.operand(&d, 1) == Decoration::DescriptorSet to u321359 && w.operand(&d, 2) == group1360 ) {1361 const id = w.operand(&d, 0);1362 if (w.decoration(id, ::Binding) is ::Some |b| && b == binding) {1363 return id;1364 }1365 }1366 }1367 return 0;1368}13691370fn builtin_attribute(builtin: BuiltIn) -> &[u8] => match (builtin) {1371 ::VertexIndex &"vertex_id";1372 ::InstanceIndex &"instance_id";1373 ::FrontFacing &"front_facing";1374 ::GlobalInvocationId &"thread_position_in_grid";1375 ::LocalInvocationId &"thread_position_in_threadgroup";1376 ::WorkgroupId &"threadgroup_position_in_grid";1377 ::LocalInvocationIndex &"thread_index_in_threadgroup";1378 ::NumWorkgroups &"threadgroups_per_grid";1379 else &"position";1380};