| ... | ... | @@ -4,9 +4,6 @@ const Target = std.Target; |
| 4 | 4 | const log = std.log.scoped(.codegen); |
| 5 | 5 | const assert = std.debug.assert; |
| 6 | 6 | |
| 7 | | const spec = @import("spirv/spec.zig"); |
| 8 | | const Opcode = spec.Opcode; |
| 9 | | |
| 10 | 7 | const Module = @import("../Module.zig"); |
| 11 | 8 | const Decl = Module.Decl; |
| 12 | 9 | const Type = @import("../type.zig").Type; |
| ... | ... | @@ -15,180 +12,75 @@ const LazySrcLoc = Module.LazySrcLoc; |
| 15 | 12 | const Air = @import("../Air.zig"); |
| 16 | 13 | const Liveness = @import("../Liveness.zig"); |
| 17 | 14 | |
| 18 | | pub const Word = u32; |
| 19 | | pub const ResultId = u32; |
| 15 | const spec = @import("spirv/spec.zig"); |
| 16 | const Opcode = spec.Opcode; |
| 17 | const Word = spec.Word; |
| 18 | const IdRef = spec.IdRef; |
| 19 | const IdResult = spec.IdResult; |
| 20 | const IdResultType = spec.IdResultType; |
| 21 | |
| 22 | const SpvModule = @import("spirv/Module.zig"); |
| 23 | const SpvSection = @import("spirv/Section.zig"); |
| 20 | 24 | |
| 21 | | pub const TypeMap = std.HashMap(Type, u32, Type.HashContext64, std.hash_map.default_max_load_percentage); |
| 22 | | pub const InstMap = std.AutoHashMap(Air.Inst.Index, ResultId); |
| 25 | const TypeCache = std.HashMapUnmanaged(Type, IdResultType, Type.HashContext64, std.hash_map.default_max_load_percentage); |
| 26 | const InstMap = std.AutoHashMapUnmanaged(Air.Inst.Index, IdRef); |
| 23 | 27 | |
| 24 | 28 | const IncomingBlock = struct { |
| 25 | | src_label_id: ResultId, |
| 26 | | break_value_id: ResultId, |
| 29 | src_label_id: IdRef, |
| 30 | break_value_id: IdRef, |
| 27 | 31 | }; |
| 28 | 32 | |
| 29 | | pub const BlockMap = std.AutoHashMap(Air.Inst.Index, struct { |
| 30 | | label_id: ResultId, |
| 33 | pub const BlockMap = std.AutoHashMapUnmanaged(Air.Inst.Index, struct { |
| 34 | label_id: IdRef, |
| 31 | 35 | incoming_blocks: *std.ArrayListUnmanaged(IncomingBlock), |
| 32 | 36 | }); |
| 33 | 37 | |
| 34 | | pub fn writeOpcode(code: *std.ArrayList(Word), opcode: Opcode, arg_count: u16) !void { |
| 35 | | const word_count: Word = arg_count + 1; |
| 36 | | try code.append((word_count << 16) | @enumToInt(opcode)); |
| 37 | | } |
| 38 | | |
| 39 | | pub fn writeInstruction(code: *std.ArrayList(Word), opcode: Opcode, args: []const Word) !void { |
| 40 | | try writeOpcode(code, opcode, @intCast(u16, args.len)); |
| 41 | | try code.appendSlice(args); |
| 42 | | } |
| 43 | | |
| 44 | | pub fn writeInstructionWithString(code: *std.ArrayList(Word), opcode: Opcode, args: []const Word, str: []const u8) !void { |
| 45 | | // Str needs to be written zero-terminated, so we need to add one to the length. |
| 46 | | const zero_terminated_len = str.len + 1; |
| 47 | | const str_words = (zero_terminated_len + @sizeOf(Word) - 1) / @sizeOf(Word); |
| 48 | | |
| 49 | | try writeOpcode(code, opcode, @intCast(u16, args.len + str_words)); |
| 50 | | try code.ensureUnusedCapacity(args.len + str_words); |
| 51 | | code.appendSliceAssumeCapacity(args); |
| 52 | | |
| 53 | | // TODO: Not actually sure whether this is correct for big-endian. |
| 54 | | // See https://www.khronos.org/registry/spir-v/specs/unified1/SPIRV.html#Literal |
| 55 | | var i: usize = 0; |
| 56 | | while (i < zero_terminated_len) : (i += @sizeOf(Word)) { |
| 57 | | var word: Word = 0; |
| 58 | | |
| 59 | | var j: usize = 0; |
| 60 | | while (j < @sizeOf(Word) and i + j < str.len) : (j += 1) { |
| 61 | | word |= @as(Word, str[i + j]) << @intCast(std.math.Log2Int(Word), j * std.meta.bitCount(u8)); |
| 62 | | } |
| 63 | | |
| 64 | | code.appendAssumeCapacity(word); |
| 65 | | } |
| 66 | | } |
| 67 | | |
| 68 | | /// This structure represents a SPIR-V (binary) module being compiled, and keeps track of all relevant information. |
| 69 | | /// That includes the actual instructions, the current result-id bound, and data structures for querying result-id's |
| 70 | | /// of data which needs to be persistent over different calls to Decl code generation. |
| 71 | | pub const SPIRVModule = struct { |
| 72 | | /// A general-purpose allocator which may be used to allocate temporary resources required for compilation. |
| 73 | | gpa: Allocator, |
| 74 | | |
| 75 | | /// The parent module. |
| 38 | /// This structure is used to compile a declaration, and contains all relevant meta-information to deal with that. |
| 39 | pub const DeclGen = struct { |
| 40 | /// The Zig module that we are generating decls for. |
| 76 | 41 | module: *Module, |
| 77 | 42 | |
| 78 | | /// SPIR-V instructions return result-ids. This variable holds the module-wide counter for these. |
| 79 | | next_result_id: ResultId, |
| 80 | | |
| 81 | | /// Code of the actual SPIR-V binary, divided into the relevant logical sections. |
| 82 | | /// Note: To save some bytes, these could also be unmanaged, but since there is only one instance of SPIRVModule |
| 83 | | /// and this removes some clutter in the rest of the backend, it's fine like this. |
| 84 | | binary: struct { |
| 85 | | /// OpCapability and OpExtension instructions (in that order). |
| 86 | | capabilities_and_extensions: std.ArrayList(Word), |
| 87 | | |
| 88 | | /// OpString, OpSourceExtension, OpSource, OpSourceContinued. |
| 89 | | debug_strings: std.ArrayList(Word), |
| 90 | | |
| 91 | | /// Type declaration instructions, constant instructions, global variable declarations, OpUndef instructions. |
| 92 | | types_globals_constants: std.ArrayList(Word), |
| 93 | | |
| 94 | | /// Regular functions. |
| 95 | | fn_decls: std.ArrayList(Word), |
| 96 | | }, |
| 97 | | |
| 98 | | /// Global type cache to reduce the amount of generated types. |
| 99 | | types: TypeMap, |
| 100 | | |
| 101 | | /// Cache for results of OpString instructions for module file names fed to OpSource. |
| 102 | | /// Since OpString is pretty much only used for those, we don't need to keep track of all strings, |
| 103 | | /// just the ones for OpLine. Note that OpLine needs the result of OpString, and not that of OpSource. |
| 104 | | file_names: std.StringHashMap(ResultId), |
| 105 | | |
| 106 | | pub fn init(gpa: Allocator, module: *Module) SPIRVModule { |
| 107 | | return .{ |
| 108 | | .gpa = gpa, |
| 109 | | .module = module, |
| 110 | | .next_result_id = 1, // 0 is an invalid SPIR-V result ID. |
| 111 | | .binary = .{ |
| 112 | | .capabilities_and_extensions = std.ArrayList(Word).init(gpa), |
| 113 | | .debug_strings = std.ArrayList(Word).init(gpa), |
| 114 | | .types_globals_constants = std.ArrayList(Word).init(gpa), |
| 115 | | .fn_decls = std.ArrayList(Word).init(gpa), |
| 116 | | }, |
| 117 | | .types = TypeMap.init(gpa), |
| 118 | | .file_names = std.StringHashMap(ResultId).init(gpa), |
| 119 | | }; |
| 120 | | } |
| 121 | | |
| 122 | | pub fn deinit(self: *SPIRVModule) void { |
| 123 | | self.file_names.deinit(); |
| 124 | | self.types.deinit(); |
| 125 | | |
| 126 | | self.binary.fn_decls.deinit(); |
| 127 | | self.binary.types_globals_constants.deinit(); |
| 128 | | self.binary.debug_strings.deinit(); |
| 129 | | self.binary.capabilities_and_extensions.deinit(); |
| 130 | | } |
| 131 | | |
| 132 | | pub fn allocResultId(self: *SPIRVModule) Word { |
| 133 | | defer self.next_result_id += 1; |
| 134 | | return self.next_result_id; |
| 135 | | } |
| 136 | | |
| 137 | | pub fn resultIdBound(self: *SPIRVModule) Word { |
| 138 | | return self.next_result_id; |
| 139 | | } |
| 140 | | |
| 141 | | fn resolveSourceFileName(self: *SPIRVModule, decl: *Decl) !ResultId { |
| 142 | | const path = decl.getFileScope().sub_file_path; |
| 143 | | const result = try self.file_names.getOrPut(path); |
| 144 | | if (!result.found_existing) { |
| 145 | | result.value_ptr.* = self.allocResultId(); |
| 146 | | try writeInstructionWithString(&self.binary.debug_strings, .OpString, &[_]Word{result.value_ptr.*}, path); |
| 147 | | try writeInstruction(&self.binary.debug_strings, .OpSource, &[_]Word{ |
| 148 | | @enumToInt(spec.SourceLanguage.Unknown), // TODO: Register Zig source language. |
| 149 | | 0, // TODO: Zig version as u32? |
| 150 | | result.value_ptr.*, |
| 151 | | }); |
| 152 | | } |
| 153 | | |
| 154 | | return result.value_ptr.*; |
| 155 | | } |
| 156 | | }; |
| 43 | /// The SPIR-V module code should be put in. |
| 44 | spv: *SpvModule, |
| 157 | 45 | |
| 158 | | /// This structure is used to compile a declaration, and contains all relevant meta-information to deal with that. |
| 159 | | pub const DeclGen = struct { |
| 160 | | /// The SPIR-V module code should be put in. |
| 161 | | spv: *SPIRVModule, |
| 46 | /// The decl we are currently generating code for. |
| 47 | decl: *Decl, |
| 162 | 48 | |
| 49 | /// The intermediate code of the declaration we are currently generating. Note: If |
| 50 | /// the declaration is not a function, this value will be undefined! |
| 163 | 51 | air: Air, |
| 52 | |
| 53 | /// The liveness analysis of the intermediate code for the declaration we are currently generating. |
| 54 | /// Note: If the declaration is not a function, this value will be undefined! |
| 164 | 55 | liveness: Liveness, |
| 165 | 56 | |
| 166 | 57 | /// An array of function argument result-ids. Each index corresponds with the |
| 167 | 58 | /// function argument of the same index. |
| 168 | | args: std.ArrayList(ResultId), |
| 59 | args: std.ArrayListUnmanaged(IdRef) = .{}, |
| 169 | 60 | |
| 170 | 61 | /// A counter to keep track of how many `arg` instructions we've seen yet. |
| 171 | 62 | next_arg_index: u32, |
| 172 | 63 | |
| 64 | /// A cache for zig types to prevent having to re-process a particular type. This structure is kept around |
| 65 | /// after a call to `gen` so that they don't have to be re-resolved for different decls. |
| 66 | type_cache: TypeCache = .{}, |
| 67 | |
| 173 | 68 | /// A map keeping track of which instruction generated which result-id. |
| 174 | | inst_results: InstMap, |
| 69 | inst_results: InstMap = .{}, |
| 175 | 70 | |
| 176 | 71 | /// We need to keep track of result ids for block labels, as well as the 'incoming' |
| 177 | 72 | /// blocks for a block. |
| 178 | | blocks: BlockMap, |
| 73 | blocks: BlockMap = .{}, |
| 179 | 74 | |
| 180 | 75 | /// The label of the SPIR-V block we are currently generating. |
| 181 | | current_block_label_id: ResultId, |
| 76 | current_block_label_id: IdRef, |
| 182 | 77 | |
| 183 | 78 | /// The actual instructions for this function. We need to declare all locals in |
| 184 | 79 | /// the first block, and because we don't know which locals there are going to be, |
| 185 | 80 | /// we're just going to generate everything after the locals-section in this array. |
| 186 | 81 | /// Note: It will not contain OpFunction, OpFunctionParameter, OpVariable and the |
| 187 | | /// initial OpLabel. These will be generated into spv.binary.fn_decls directly. |
| 188 | | code: std.ArrayList(Word), |
| 189 | | |
| 190 | | /// The decl we are currently generating code for. |
| 191 | | decl: *Decl, |
| 82 | /// initial OpLabel. These will be generated into spv.sections.functions directly. |
| 83 | code: SpvSection = .{}, |
| 192 | 84 | |
| 193 | 85 | /// If `gen` returned `Error.CodegenFail`, this contains an explanatory message. |
| 194 | 86 | /// Memory is owned by `module.gpa`. |
| ... | ... | @@ -244,18 +136,15 @@ pub const DeclGen = struct { |
| 244 | 136 | |
| 245 | 137 | /// Initialize the common resources of a DeclGen. Some fields are left uninitialized, |
| 246 | 138 | /// only set when `gen` is called. |
| 247 | | pub fn init(spv: *SPIRVModule) DeclGen { |
| 139 | pub fn init(module: *Module, spv: *SpvModule) DeclGen { |
| 248 | 140 | return .{ |
| 141 | .module = module, |
| 249 | 142 | .spv = spv, |
| 143 | .decl = undefined, |
| 250 | 144 | .air = undefined, |
| 251 | 145 | .liveness = undefined, |
| 252 | | .args = std.ArrayList(ResultId).init(spv.gpa), |
| 253 | 146 | .next_arg_index = undefined, |
| 254 | | .inst_results = InstMap.init(spv.gpa), |
| 255 | | .blocks = BlockMap.init(spv.gpa), |
| 256 | 147 | .current_block_label_id = undefined, |
| 257 | | .code = std.ArrayList(Word).init(spv.gpa), |
| 258 | | .decl = undefined, |
| 259 | 148 | .error_msg = undefined, |
| 260 | 149 | }; |
| 261 | 150 | } |
| ... | ... | @@ -265,15 +154,16 @@ pub const DeclGen = struct { |
| 265 | 154 | /// returns such a reportable error, it is valid to be called again for a different decl. |
| 266 | 155 | pub fn gen(self: *DeclGen, decl: *Decl, air: Air, liveness: Liveness) !?*Module.ErrorMsg { |
| 267 | 156 | // Reset internal resources, we don't want to re-allocate these. |
| 157 | self.decl = decl; |
| 268 | 158 | self.air = air; |
| 269 | 159 | self.liveness = liveness; |
| 270 | 160 | self.args.items.len = 0; |
| 271 | 161 | self.next_arg_index = 0; |
| 162 | // Note: don't clear type_cache. |
| 272 | 163 | self.inst_results.clearRetainingCapacity(); |
| 273 | 164 | self.blocks.clearRetainingCapacity(); |
| 274 | 165 | self.current_block_label_id = undefined; |
| 275 | | self.code.items.len = 0; |
| 276 | | self.decl = decl; |
| 166 | self.code.reset(); |
| 277 | 167 | self.error_msg = null; |
| 278 | 168 | |
| 279 | 169 | self.genDecl() catch |err| switch (err) { |
| ... | ... | @@ -286,25 +176,38 @@ pub const DeclGen = struct { |
| 286 | 176 | |
| 287 | 177 | /// Free resources owned by the DeclGen. |
| 288 | 178 | pub fn deinit(self: *DeclGen) void { |
| 289 | | self.args.deinit(); |
| 290 | | self.inst_results.deinit(); |
| 291 | | self.blocks.deinit(); |
| 292 | | self.code.deinit(); |
| 179 | self.args.deinit(self.spv.gpa); |
| 180 | self.type_cache.deinit(self.spv.gpa); |
| 181 | self.inst_results.deinit(self.spv.gpa); |
| 182 | self.blocks.deinit(self.spv.gpa); |
| 183 | self.code.deinit(self.spv.gpa); |
| 293 | 184 | } |
| 294 | 185 | |
| 186 | /// Return the target which we are currently compiling for. |
| 295 | 187 | fn getTarget(self: *DeclGen) std.Target { |
| 296 | | return self.spv.module.getTarget(); |
| 188 | return self.module.getTarget(); |
| 297 | 189 | } |
| 298 | 190 | |
| 299 | 191 | fn fail(self: *DeclGen, comptime format: []const u8, args: anytype) Error { |
| 300 | 192 | @setCold(true); |
| 301 | 193 | const src: LazySrcLoc = .{ .node_offset = 0 }; |
| 302 | 194 | const src_loc = src.toSrcLoc(self.decl); |
| 303 | | self.error_msg = try Module.ErrorMsg.create(self.spv.module.gpa, src_loc, format, args); |
| 195 | assert(self.error_msg == null); |
| 196 | self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, format, args); |
| 197 | return error.CodegenFail; |
| 198 | } |
| 199 | |
| 200 | fn todo(self: *DeclGen, comptime format: []const u8, args: anytype) Error { |
| 201 | @setCold(true); |
| 202 | const src: LazySrcLoc = .{ .node_offset = 0 }; |
| 203 | const src_loc = src.toSrcLoc(self.decl); |
| 204 | assert(self.error_msg == null); |
| 205 | self.error_msg = try Module.ErrorMsg.create(self.module.gpa, src_loc, "TODO (SPIR-V): " ++ format, args); |
| 304 | 206 | return error.CodegenFail; |
| 305 | 207 | } |
| 306 | 208 | |
| 307 | | fn resolve(self: *DeclGen, inst: Air.Inst.Ref) !ResultId { |
| 209 | /// Fetch the result-id for a previously generated instruction or constant. |
| 210 | fn resolve(self: *DeclGen, inst: Air.Inst.Ref) !IdRef { |
| 308 | 211 | if (self.air.value(inst)) |val| { |
| 309 | 212 | return self.genConstant(self.air.typeOf(inst), val); |
| 310 | 213 | } |
| ... | ... | @@ -312,9 +215,13 @@ pub const DeclGen = struct { |
| 312 | 215 | return self.inst_results.get(index).?; // Assertion means instruction does not dominate usage. |
| 313 | 216 | } |
| 314 | 217 | |
| 315 | | fn beginSPIRVBlock(self: *DeclGen, label_id: ResultId) !void { |
| 316 | | try writeInstruction(&self.code, .OpLabel, &[_]Word{label_id}); |
| 317 | | self.current_block_label_id = label_id; |
| 218 | /// Start a new SPIR-V block, Emits the label of the new block, and stores which |
| 219 | /// block we are currently generating. |
| 220 | /// Note that there is no such thing as nested blocks like in ZIR or AIR, so we don't need to |
| 221 | /// keep track of the previous block. |
| 222 | fn beginSpvBlock(self: *DeclGen, label_id: IdResult) !void { |
| 223 | try self.code.emit(self.spv.gpa, .OpLabel, .{.id_result = label_id}); |
| 224 | self.current_block_label_id = label_id.toRef(); |
| 318 | 225 | } |
| 319 | 226 | |
| 320 | 227 | /// SPIR-V requires enabling specific integer sizes through capabilities, and so if they are not enabled, we need |
| ... | ... | @@ -396,13 +303,18 @@ pub const DeclGen = struct { |
| 396 | 303 | const int_info = ty.intInfo(target); |
| 397 | 304 | // TODO: Maybe it's useful to also return this value. |
| 398 | 305 | const maybe_backing_bits = self.backingIntBits(int_info.bits); |
| 399 | | break :blk ArithmeticTypeInfo{ .bits = int_info.bits, .is_vector = false, .signedness = int_info.signedness, .class = if (maybe_backing_bits) |backing_bits| |
| 400 | | if (backing_bits == int_info.bits) |
| 401 | | ArithmeticTypeInfo.Class.integer |
| 306 | break :blk ArithmeticTypeInfo{ |
| 307 | .bits = int_info.bits, |
| 308 | .is_vector = false, |
| 309 | .signedness = int_info.signedness, |
| 310 | .class = if (maybe_backing_bits) |backing_bits| |
| 311 | if (backing_bits == int_info.bits) |
| 312 | ArithmeticTypeInfo.Class.integer |
| 313 | else |
| 314 | ArithmeticTypeInfo.Class.strange_integer |
| 402 | 315 | else |
| 403 | | ArithmeticTypeInfo.Class.strange_integer |
| 404 | | else |
| 405 | | .composite_integer }; |
| 316 | .composite_integer, |
| 317 | }; |
| 406 | 318 | }, |
| 407 | 319 | // As of yet, there is no vector support in the self-hosted compiler. |
| 408 | 320 | .Vector => self.fail("TODO: SPIR-V backend: implement arithmeticTypeInfo for Vector", .{}), |
| ... | ... | @@ -413,15 +325,15 @@ pub const DeclGen = struct { |
| 413 | 325 | |
| 414 | 326 | /// Generate a constant representing `val`. |
| 415 | 327 | /// TODO: Deduplication? |
| 416 | | fn genConstant(self: *DeclGen, ty: Type, val: Value) Error!ResultId { |
| 328 | fn genConstant(self: *DeclGen, ty: Type, val: Value) Error!IdRef { |
| 417 | 329 | const target = self.getTarget(); |
| 418 | | const code = &self.spv.binary.types_globals_constants; |
| 419 | | const result_id = self.spv.allocResultId(); |
| 330 | const section = &self.spv.sections.types_globals_constants; |
| 331 | const result_id = self.spv.allocId(); |
| 420 | 332 | const result_type_id = try self.genType(ty); |
| 421 | 333 | |
| 422 | 334 | if (val.isUndef()) { |
| 423 | | try writeInstruction(code, .OpUndef, &[_]Word{ result_type_id, result_id }); |
| 424 | | return result_id; |
| 335 | try section.emit(self.spv.gpa, .OpUndef, .{ .id_result_type = result_type_id, .id_result = result_id }); |
| 336 | return result_id.toRef(); |
| 425 | 337 | } |
| 426 | 338 | |
| 427 | 339 | switch (ty.zigTypeTag()) { |
| ... | ... | @@ -436,76 +348,71 @@ pub const DeclGen = struct { |
| 436 | 348 | // SPIR-V native type (up to i/u64 with Int64). If SPIR-V ever supports native ints of a larger size, this |
| 437 | 349 | // might need to be updated. |
| 438 | 350 | assert(self.largestSupportedIntBits() <= std.meta.bitCount(u64)); |
| 351 | |
| 352 | // Note, value is required to be sign-extended, so we don't need to mask off the upper bits. |
| 353 | // See https://www.khronos.org/registry/SPIR-V/specs/unified1/SPIRV.html#Literal |
| 439 | 354 | var int_bits = if (ty.isSignedInt()) @bitCast(u64, val.toSignedInt()) else val.toUnsignedInt(); |
| 440 | 355 | |
| 441 | | // Mask the low bits which make up the actual integer. This is to make sure that negative values |
| 442 | | // only use the actual bits of the type. |
| 443 | | // TODO: Should this be the backing type bits or the actual type bits? |
| 444 | | int_bits &= (@as(u64, 1) << @intCast(u6, backing_bits)) - 1; |
| 445 | | |
| 446 | | switch (backing_bits) { |
| 447 | | 0 => unreachable, |
| 448 | | 1...32 => try writeInstruction(code, .OpConstant, &[_]Word{ |
| 449 | | result_type_id, |
| 450 | | result_id, |
| 451 | | @truncate(u32, int_bits), |
| 452 | | }), |
| 453 | | 33...64 => try writeInstruction(code, .OpConstant, &[_]Word{ |
| 454 | | result_type_id, |
| 455 | | result_id, |
| 456 | | @truncate(u32, int_bits), |
| 457 | | @truncate(u32, int_bits >> @bitSizeOf(u32)), |
| 458 | | }), |
| 459 | | else => unreachable, // backing_bits is bounded by largestSupportedIntBits. |
| 460 | | } |
| 356 | const value: spec.LiteralContextDependentNumber = switch (backing_bits) { |
| 357 | 1...32 => .{.uint32 = @truncate(u32, int_bits)}, |
| 358 | 33...64 => .{.uint64 = int_bits}, |
| 359 | else => unreachable, |
| 360 | }; |
| 361 | |
| 362 | try section.emit(self.spv.gpa, .OpConstant, .{ |
| 363 | .id_result_type = result_type_id, |
| 364 | .id_result = result_id, |
| 365 | .value = value, |
| 366 | }); |
| 461 | 367 | }, |
| 462 | 368 | .Bool => { |
| 463 | | const opcode: Opcode = if (val.toBool()) .OpConstantTrue else .OpConstantFalse; |
| 464 | | try writeInstruction(code, opcode, &[_]Word{ result_type_id, result_id }); |
| 369 | const operands = .{ .id_result_type = result_type_id, .id_result = result_id }; |
| 370 | if (val.toBool()) { |
| 371 | try section.emit(self.spv.gpa, .OpConstantTrue, operands); |
| 372 | } else { |
| 373 | try section.emit(self.spv.gpa, .OpConstantFalse, operands); |
| 374 | } |
| 465 | 375 | }, |
| 466 | 376 | .Float => { |
| 467 | 377 | // At this point we are guaranteed that the target floating point type is supported, otherwise the function |
| 468 | 378 | // would have exited at genType(ty). |
| 469 | 379 | |
| 470 | | // f16 and f32 require one word of storage. f64 requires 2, low-order first. |
| 471 | | |
| 472 | | switch (ty.floatBits(target)) { |
| 473 | | 16 => try writeInstruction(code, .OpConstant, &[_]Word{ result_type_id, result_id, @bitCast(u16, val.toFloat(f16)) }), |
| 474 | | 32 => try writeInstruction(code, .OpConstant, &[_]Word{ result_type_id, result_id, @bitCast(u32, val.toFloat(f32)) }), |
| 475 | | 64 => { |
| 476 | | const float_bits = @bitCast(u64, val.toFloat(f64)); |
| 477 | | try writeInstruction(code, .OpConstant, &[_]Word{ |
| 478 | | result_type_id, |
| 479 | | result_id, |
| 480 | | @truncate(u32, float_bits), |
| 481 | | @truncate(u32, float_bits >> @bitSizeOf(u32)), |
| 482 | | }); |
| 483 | | }, |
| 380 | const value: spec.LiteralContextDependentNumber = switch (ty.floatBits(target)) { |
| 381 | // Prevent upcasting to f32 by bitcasting and writing as a uint32. |
| 382 | 16 => .{.uint32 = @bitCast(u16, val.toFloat(f16))}, |
| 383 | 32 => .{.float32 = val.toFloat(f32)}, |
| 384 | 64 => .{.float64 = val.toFloat(f64)}, |
| 484 | 385 | 128 => unreachable, // Filtered out in the call to genType. |
| 485 | | // TODO: Insert case for long double when the layout for that is determined. |
| 386 | // TODO: Insert case for long double when the layout for that is determined? |
| 486 | 387 | else => unreachable, |
| 487 | | } |
| 388 | }; |
| 389 | |
| 390 | try section.emit(self.spv.gpa, .OpConstant, .{ |
| 391 | .id_result_type = result_type_id, |
| 392 | .id_result = result_id, |
| 393 | .value = value, |
| 394 | }); |
| 488 | 395 | }, |
| 489 | 396 | .Void => unreachable, |
| 490 | 397 | else => return self.fail("TODO: SPIR-V backend: constant generation of type {}", .{ty}), |
| 491 | 398 | } |
| 492 | 399 | |
| 493 | | return result_id; |
| 400 | return result_id.toRef(); |
| 494 | 401 | } |
| 495 | 402 | |
| 496 | | fn genType(self: *DeclGen, ty: Type) Error!ResultId { |
| 403 | fn genType(self: *DeclGen, ty: Type) Error!IdResultType { |
| 497 | 404 | // We can't use getOrPut here so we can recursively generate types. |
| 498 | | if (self.spv.types.get(ty)) |already_generated| { |
| 405 | if (self.type_cache.get(ty)) |already_generated| { |
| 499 | 406 | return already_generated; |
| 500 | 407 | } |
| 501 | 408 | |
| 502 | 409 | const target = self.getTarget(); |
| 503 | | const code = &self.spv.binary.types_globals_constants; |
| 504 | | const result_id = self.spv.allocResultId(); |
| 410 | const section = &self.spv.sections.types_globals_constants; |
| 411 | const result_id = self.spv.allocId(); |
| 505 | 412 | |
| 506 | 413 | switch (ty.zigTypeTag()) { |
| 507 | | .Void => try writeInstruction(code, .OpTypeVoid, &[_]Word{result_id}), |
| 508 | | .Bool => try writeInstruction(code, .OpTypeBool, &[_]Word{result_id}), |
| 414 | .Void => try section.emit(self.spv.gpa, .OpTypeVoid, .{.id_result = result_id}), |
| 415 | .Bool => try section.emit(self.spv.gpa, .OpTypeBool, .{.id_result = result_id}), |
| 509 | 416 | .Int => { |
| 510 | 417 | const int_info = ty.intInfo(target); |
| 511 | 418 | const backing_bits = self.backingIntBits(int_info.bits) orelse { |
| ... | ... | @@ -514,11 +421,11 @@ pub const DeclGen = struct { |
| 514 | 421 | }; |
| 515 | 422 | |
| 516 | 423 | // TODO: If backing_bits != int_info.bits, a duplicate type might be generated here. |
| 517 | | try writeInstruction(code, .OpTypeInt, &[_]Word{ |
| 518 | | result_id, |
| 519 | | backing_bits, |
| 520 | | switch (int_info.signedness) { |
| 521 | | .unsigned => 0, |
| 424 | try section.emit(self.spv.gpa, .OpTypeInt, .{ |
| 425 | .id_result = result_id, |
| 426 | .width = backing_bits, |
| 427 | .signedness = switch (int_info.signedness) { |
| 428 | .unsigned => @as(spec.LiteralInteger, 0), |
| 522 | 429 | .signed => 1, |
| 523 | 430 | }, |
| 524 | 431 | }); |
| ... | ... | @@ -539,7 +446,7 @@ pub const DeclGen = struct { |
| 539 | 446 | return self.fail("Floating point width of {} bits is not supported for the current SPIR-V feature set", .{bits}); |
| 540 | 447 | } |
| 541 | 448 | |
| 542 | | try writeInstruction(code, .OpTypeFloat, &[_]Word{ result_id, bits }); |
| 449 | try section.emit(self.spv.gpa, .OpTypeFloat, .{.id_result = result_id, .width = bits}); |
| 543 | 450 | }, |
| 544 | 451 | .Fn => { |
| 545 | 452 | // We only support zig-calling-convention functions, no varargs. |
| ... | ... | @@ -558,14 +465,16 @@ pub const DeclGen = struct { |
| 558 | 465 | |
| 559 | 466 | const return_type_id = try self.genType(ty.fnReturnType()); |
| 560 | 467 | |
| 468 | try section.emitRaw(self.spv.gpa, .OpTypeFunction, 2 + @intCast(u16, ty.fnParamLen())); |
| 469 | |
| 561 | 470 | // result id + result type id + parameter type ids. |
| 562 | | try writeOpcode(code, .OpTypeFunction, 2 + @intCast(u16, ty.fnParamLen())); |
| 563 | | try code.appendSlice(&.{ result_id, return_type_id }); |
| 471 | section.writeOperand(IdResult, result_id); |
| 472 | section.writeOperand(IdResultType, return_type_id); |
| 564 | 473 | |
| 565 | 474 | i = 0; |
| 566 | 475 | while (i < params) : (i += 1) { |
| 567 | | const param_type_id = self.spv.types.get(ty.fnParamType(i)).?; |
| 568 | | try code.append(param_type_id); |
| 476 | const param_type_id = self.type_cache.get(ty.fnParamType(i)).?; |
| 477 | section.writeOperand(IdRef, param_type_id.toRef()); |
| 569 | 478 | } |
| 570 | 479 | }, |
| 571 | 480 | // When recursively generating a type, we cannot infer the pointer's storage class. See genPointerType. |
| ... | ... | @@ -594,26 +503,29 @@ pub const DeclGen = struct { |
| 594 | 503 | else => |tag| return self.fail("TODO: SPIR-V backend: implement type {}s", .{tag}), |
| 595 | 504 | } |
| 596 | 505 | |
| 597 | | try self.spv.types.putNoClobber(ty, result_id); |
| 598 | | return result_id; |
| 506 | try self.type_cache.putNoClobber(self.spv.gpa, ty, result_id.toResultType()); |
| 507 | return result_id.toResultType(); |
| 599 | 508 | } |
| 600 | 509 | |
| 601 | 510 | /// SPIR-V requires pointers to have a storage class (address space), and so we have a special function for that. |
| 602 | 511 | /// TODO: The result of this needs to be cached. |
| 603 | | fn genPointerType(self: *DeclGen, ty: Type, storage_class: spec.StorageClass) !ResultId { |
| 512 | fn genPointerType(self: *DeclGen, ty: Type, storage_class: spec.StorageClass) !IdResultType { |
| 604 | 513 | assert(ty.zigTypeTag() == .Pointer); |
| 605 | 514 | |
| 606 | | const code = &self.spv.binary.types_globals_constants; |
| 607 | | const result_id = self.spv.allocResultId(); |
| 515 | const result_id = self.spv.allocId(); |
| 608 | 516 | |
| 609 | 517 | // TODO: There are many constraints which are ignored for now: We may only create pointers to certain types, and to other types |
| 610 | 518 | // if more capabilities are enabled. For example, we may only create pointers to f16 if Float16Buffer is enabled. |
| 611 | 519 | // These also relates to the pointer's address space. |
| 612 | 520 | const child_id = try self.genType(ty.elemType()); |
| 613 | 521 | |
| 614 | | try writeInstruction(code, .OpTypePointer, &[_]Word{ result_id, @enumToInt(storage_class), child_id }); |
| 522 | try self.spv.sections.types_globals_constants.emit(self.spv.gpa, .OpTypePointer, .{ |
| 523 | .id_result = result_id, |
| 524 | .storage_class = storage_class, |
| 525 | .type = child_id.toRef(), |
| 526 | }); |
| 615 | 527 | |
| 616 | | return result_id; |
| 528 | return result_id.toResultType(); |
| 617 | 529 | } |
| 618 | 530 | |
| 619 | 531 | fn genDecl(self: *DeclGen) !void { |
| ... | ... | @@ -623,38 +535,43 @@ pub const DeclGen = struct { |
| 623 | 535 | if (decl.val.castTag(.function)) |_| { |
| 624 | 536 | assert(decl.ty.zigTypeTag() == .Fn); |
| 625 | 537 | const prototype_id = try self.genType(decl.ty); |
| 626 | | try writeInstruction(&self.spv.binary.fn_decls, .OpFunction, &[_]Word{ |
| 627 | | self.spv.types.get(decl.ty.fnReturnType()).?, // This type should be generated along with the prototype. |
| 628 | | result_id, |
| 629 | | @bitCast(Word, spec.FunctionControl{}), // TODO: We can set inline here if the type requires it. |
| 630 | | prototype_id, |
| 538 | try self.spv.sections.functions.emit(self.spv.gpa, .OpFunction, .{ |
| 539 | .id_result_type = self.type_cache.get(decl.ty.fnReturnType()).?, // This type should be generated along with the prototype. |
| 540 | .id_result = result_id, |
| 541 | .function_control = .{}, // TODO: We can set inline here if the type requires it. |
| 542 | .function_type = prototype_id.toRef(), |
| 631 | 543 | }); |
| 632 | 544 | |
| 633 | 545 | const params = decl.ty.fnParamLen(); |
| 634 | 546 | var i: usize = 0; |
| 635 | 547 | |
| 636 | | try self.args.ensureUnusedCapacity(params); |
| 548 | try self.args.ensureUnusedCapacity(self.spv.gpa, params); |
| 637 | 549 | while (i < params) : (i += 1) { |
| 638 | | const param_type_id = self.spv.types.get(decl.ty.fnParamType(i)).?; |
| 639 | | const arg_result_id = self.spv.allocResultId(); |
| 640 | | try writeInstruction(&self.spv.binary.fn_decls, .OpFunctionParameter, &[_]Word{ param_type_id, arg_result_id }); |
| 641 | | self.args.appendAssumeCapacity(arg_result_id); |
| 550 | const param_type_id = self.type_cache.get(decl.ty.fnParamType(i)).?; |
| 551 | const arg_result_id = self.spv.allocId(); |
| 552 | try self.spv.sections.functions.emit(self.spv.gpa, .OpFunctionParameter, .{ |
| 553 | .id_result_type = param_type_id, |
| 554 | .id_result = arg_result_id, |
| 555 | }); |
| 556 | self.args.appendAssumeCapacity(arg_result_id.toRef()); |
| 642 | 557 | } |
| 643 | 558 | |
| 644 | 559 | // TODO: This could probably be done in a better way... |
| 645 | | const root_block_id = self.spv.allocResultId(); |
| 560 | const root_block_id = self.spv.allocId(); |
| 646 | 561 | |
| 647 | | // We need to generate the label directly in the fn_decls here because we're going to write the local variables after |
| 648 | | // here. Since we're not generating in self.code, we're just going to bypass self.beginSPIRVBlock here. |
| 649 | | try writeInstruction(&self.spv.binary.fn_decls, .OpLabel, &[_]Word{root_block_id}); |
| 650 | | self.current_block_label_id = root_block_id; |
| 562 | // We need to generate the label directly in the functions section here because we're going to write the local variables after |
| 563 | // here. Since we're not generating in self.code, we're just going to bypass self.beginSpvBlock here. |
| 564 | try self.spv.sections.functions.emit(self.spv.gpa, .OpLabel, .{ |
| 565 | .id_result = root_block_id, |
| 566 | }); |
| 567 | self.current_block_label_id = root_block_id.toRef(); |
| 651 | 568 | |
| 652 | 569 | const main_body = self.air.getMainBody(); |
| 653 | 570 | try self.genBody(main_body); |
| 654 | 571 | |
| 655 | | // Append the actual code into the fn_decls section. |
| 656 | | try self.spv.binary.fn_decls.appendSlice(self.code.items); |
| 657 | | try writeInstruction(&self.spv.binary.fn_decls, .OpFunctionEnd, &[_]Word{}); |
| 572 | // Append the actual code into the functions section. |
| 573 | try self.spv.sections.functions.append(self.spv.gpa, self.code); |
| 574 | try self.spv.sections.functions.emit(self.spv.gpa, .OpFunctionEnd, {}); |
| 658 | 575 | } else { |
| 659 | 576 | return self.fail("TODO: SPIR-V backend: generate decl type {}", .{decl.ty.zigTypeTag()}); |
| 660 | 577 | } |
| ... | ... | @@ -670,9 +587,9 @@ pub const DeclGen = struct { |
| 670 | 587 | const air_tags = self.air.instructions.items(.tag); |
| 671 | 588 | const result_id = switch (air_tags[inst]) { |
| 672 | 589 | // zig fmt: off |
| 673 | | .add, .addwrap => try self.airArithOp(inst, .{.OpFAdd, .OpIAdd, .OpIAdd}), |
| 674 | | .sub, .subwrap => try self.airArithOp(inst, .{.OpFSub, .OpISub, .OpISub}), |
| 675 | | .mul, .mulwrap => try self.airArithOp(inst, .{.OpFMul, .OpIMul, .OpIMul}), |
| 590 | .add, .addwrap => try self.airArithOp(inst, .OpFAdd, .OpIAdd, .OpIAdd), |
| 591 | .sub, .subwrap => try self.airArithOp(inst, .OpFSub, .OpISub, .OpISub), |
| 592 | .mul, .mulwrap => try self.airArithOp(inst, .OpFMul, .OpIMul, .OpIMul), |
| 676 | 593 | |
| 677 | 594 | .bit_and => try self.airBinOpSimple(inst, .OpBitwiseAnd), |
| 678 | 595 | .bit_or => try self.airBinOpSimple(inst, .OpBitwiseOr), |
| ... | ... | @@ -682,12 +599,12 @@ pub const DeclGen = struct { |
| 682 | 599 | |
| 683 | 600 | .not => try self.airNot(inst), |
| 684 | 601 | |
| 685 | | .cmp_eq => try self.airCmp(inst, .{.OpFOrdEqual, .OpLogicalEqual, .OpIEqual}), |
| 686 | | .cmp_neq => try self.airCmp(inst, .{.OpFOrdNotEqual, .OpLogicalNotEqual, .OpINotEqual}), |
| 687 | | .cmp_gt => try self.airCmp(inst, .{.OpFOrdGreaterThan, .OpSGreaterThan, .OpUGreaterThan}), |
| 688 | | .cmp_gte => try self.airCmp(inst, .{.OpFOrdGreaterThanEqual, .OpSGreaterThanEqual, .OpUGreaterThanEqual}), |
| 689 | | .cmp_lt => try self.airCmp(inst, .{.OpFOrdLessThan, .OpSLessThan, .OpULessThan}), |
| 690 | | .cmp_lte => try self.airCmp(inst, .{.OpFOrdLessThanEqual, .OpSLessThanEqual, .OpULessThanEqual}), |
| 602 | .cmp_eq => try self.airCmp(inst, .OpFOrdEqual, .OpLogicalEqual, .OpIEqual), |
| 603 | .cmp_neq => try self.airCmp(inst, .OpFOrdNotEqual, .OpLogicalNotEqual, .OpINotEqual), |
| 604 | .cmp_gt => try self.airCmp(inst, .OpFOrdGreaterThan, .OpSGreaterThan, .OpUGreaterThan), |
| 605 | .cmp_gte => try self.airCmp(inst, .OpFOrdGreaterThanEqual, .OpSGreaterThanEqual, .OpUGreaterThanEqual), |
| 606 | .cmp_lt => try self.airCmp(inst, .OpFOrdLessThan, .OpSLessThan, .OpULessThan), |
| 607 | .cmp_lte => try self.airCmp(inst, .OpFOrdLessThanEqual, .OpSLessThanEqual, .OpULessThanEqual), |
| 691 | 608 | |
| 692 | 609 | .arg => self.airArg(), |
| 693 | 610 | .alloc => try self.airAlloc(inst), |
| ... | ... | @@ -710,22 +627,25 @@ pub const DeclGen = struct { |
| 710 | 627 | }), |
| 711 | 628 | }; |
| 712 | 629 | |
| 713 | | try self.inst_results.putNoClobber(inst, result_id); |
| 630 | try self.inst_results.putNoClobber(self.spv.gpa, inst, result_id); |
| 714 | 631 | } |
| 715 | 632 | |
| 716 | | fn airBinOpSimple(self: *DeclGen, inst: Air.Inst.Index, opcode: Opcode) !ResultId { |
| 633 | fn airBinOpSimple(self: *DeclGen, inst: Air.Inst.Index, comptime opcode: Opcode) !IdRef { |
| 717 | 634 | const bin_op = self.air.instructions.items(.data)[inst].bin_op; |
| 718 | 635 | const lhs_id = try self.resolve(bin_op.lhs); |
| 719 | 636 | const rhs_id = try self.resolve(bin_op.rhs); |
| 720 | | const result_id = self.spv.allocResultId(); |
| 637 | const result_id = self.spv.allocId(); |
| 721 | 638 | const result_type_id = try self.genType(self.air.typeOfIndex(inst)); |
| 722 | | try writeInstruction(&self.code, opcode, &[_]Word{ |
| 723 | | result_type_id, result_id, lhs_id, rhs_id, |
| 639 | try self.code.emit(self.spv.gpa, opcode, .{ |
| 640 | .id_result_type = result_type_id, |
| 641 | .id_result = result_id, |
| 642 | .operand_1 = lhs_id, |
| 643 | .operand_2 = rhs_id, |
| 724 | 644 | }); |
| 725 | | return result_id; |
| 645 | return result_id.toRef(); |
| 726 | 646 | } |
| 727 | 647 | |
| 728 | | fn airArithOp(self: *DeclGen, inst: Air.Inst.Index, ops: [3]Opcode) !ResultId { |
| 648 | fn airArithOp(self: *DeclGen, inst: Air.Inst.Index, comptime fop: Opcode, comptime sop: Opcode, comptime uop: Opcode) !IdRef { |
| 729 | 649 | // LHS and RHS are guaranteed to have the same type, and AIR guarantees |
| 730 | 650 | // the result to be the same as the LHS and RHS, which matches SPIR-V. |
| 731 | 651 | const ty = self.air.typeOfIndex(inst); |
| ... | ... | @@ -733,7 +653,7 @@ pub const DeclGen = struct { |
| 733 | 653 | const lhs_id = try self.resolve(bin_op.lhs); |
| 734 | 654 | const rhs_id = try self.resolve(bin_op.rhs); |
| 735 | 655 | |
| 736 | | const result_id = self.spv.allocResultId(); |
| 656 | const result_id = self.spv.allocId(); |
| 737 | 657 | const result_type_id = try self.genType(ty); |
| 738 | 658 | |
| 739 | 659 | assert(self.air.typeOf(bin_op.lhs).eql(ty)); |
| ... | ... | @@ -757,20 +677,31 @@ pub const DeclGen = struct { |
| 757 | 677 | .float => 0, |
| 758 | 678 | else => unreachable, |
| 759 | 679 | }; |
| 760 | | const opcode = ops[opcode_index]; |
| 761 | | try writeInstruction(&self.code, opcode, &[_]Word{ result_type_id, result_id, lhs_id, rhs_id }); |
| 762 | 680 | |
| 681 | const operands = .{ |
| 682 | .id_result_type = result_type_id, |
| 683 | .id_result = result_id, |
| 684 | .operand_1 = lhs_id, |
| 685 | .operand_2 = rhs_id, |
| 686 | }; |
| 687 | |
| 688 | switch (opcode_index) { |
| 689 | 0 => try self.code.emit(self.spv.gpa, fop, operands), |
| 690 | 1 => try self.code.emit(self.spv.gpa, sop, operands), |
| 691 | 2 => try self.code.emit(self.spv.gpa, uop, operands), |
| 692 | else => unreachable, |
| 693 | } |
| 763 | 694 | // TODO: Trap on overflow? Probably going to be annoying. |
| 764 | 695 | // TODO: Look into SPV_KHR_no_integer_wrap_decoration which provides NoSignedWrap/NoUnsignedWrap. |
| 765 | 696 | |
| 766 | | return result_id; |
| 697 | return result_id.toRef(); |
| 767 | 698 | } |
| 768 | 699 | |
| 769 | | fn airCmp(self: *DeclGen, inst: Air.Inst.Index, ops: [3]Opcode) !ResultId { |
| 700 | fn airCmp(self: *DeclGen, inst: Air.Inst.Index, comptime fop: Opcode, comptime sop: Opcode, comptime uop: Opcode) !IdRef { |
| 770 | 701 | const bin_op = self.air.instructions.items(.data)[inst].bin_op; |
| 771 | 702 | const lhs_id = try self.resolve(bin_op.lhs); |
| 772 | 703 | const rhs_id = try self.resolve(bin_op.rhs); |
| 773 | | const result_id = self.spv.allocResultId(); |
| 704 | const result_id = self.spv.allocId(); |
| 774 | 705 | const result_type_id = try self.genType(Type.initTag(.bool)); |
| 775 | 706 | const op_ty = self.air.typeOf(bin_op.lhs); |
| 776 | 707 | assert(op_ty.eql(self.air.typeOf(bin_op.rhs))); |
| ... | ... | @@ -793,53 +724,71 @@ pub const DeclGen = struct { |
| 793 | 724 | .unsigned => @as(usize, 2), |
| 794 | 725 | }, |
| 795 | 726 | }; |
| 796 | | const opcode = ops[opcode_index]; |
| 797 | 727 | |
| 798 | | try writeInstruction(&self.code, opcode, &[_]Word{ result_type_id, result_id, lhs_id, rhs_id }); |
| 799 | | return result_id; |
| 728 | const operands = .{ |
| 729 | .id_result_type = result_type_id, |
| 730 | .id_result = result_id, |
| 731 | .operand_1 = lhs_id, |
| 732 | .operand_2 = rhs_id, |
| 733 | }; |
| 734 | |
| 735 | switch (opcode_index) { |
| 736 | 0 => try self.code.emit(self.spv.gpa, fop, operands), |
| 737 | 1 => try self.code.emit(self.spv.gpa, sop, operands), |
| 738 | 2 => try self.code.emit(self.spv.gpa, uop, operands), |
| 739 | else => unreachable, |
| 740 | } |
| 741 | |
| 742 | return result_id.toRef(); |
| 800 | 743 | } |
| 801 | 744 | |
| 802 | | fn airNot(self: *DeclGen, inst: Air.Inst.Index) !ResultId { |
| 745 | fn airNot(self: *DeclGen, inst: Air.Inst.Index) !IdRef { |
| 803 | 746 | const ty_op = self.air.instructions.items(.data)[inst].ty_op; |
| 804 | 747 | const operand_id = try self.resolve(ty_op.operand); |
| 805 | | const result_id = self.spv.allocResultId(); |
| 748 | const result_id = self.spv.allocId(); |
| 806 | 749 | const result_type_id = try self.genType(Type.initTag(.bool)); |
| 807 | | const opcode: Opcode = .OpLogicalNot; |
| 808 | | try writeInstruction(&self.code, opcode, &[_]Word{ result_type_id, result_id, operand_id }); |
| 809 | | return result_id; |
| 750 | try self.code.emit(self.spv.gpa, .OpLogicalNot, .{ |
| 751 | .id_result_type = result_type_id, |
| 752 | .id_result = result_id, |
| 753 | .operand = operand_id, |
| 754 | }); |
| 755 | return result_id.toRef(); |
| 810 | 756 | } |
| 811 | 757 | |
| 812 | | fn airAlloc(self: *DeclGen, inst: Air.Inst.Index) !ResultId { |
| 758 | fn airAlloc(self: *DeclGen, inst: Air.Inst.Index) !IdRef { |
| 813 | 759 | const ty = self.air.typeOfIndex(inst); |
| 814 | 760 | const storage_class = spec.StorageClass.Function; |
| 815 | 761 | const result_type_id = try self.genPointerType(ty, storage_class); |
| 816 | | const result_id = self.spv.allocResultId(); |
| 762 | const result_id = self.spv.allocId(); |
| 817 | 763 | |
| 818 | | // Rather than generating into code here, we're just going to generate directly into the fn_decls section so that |
| 764 | // Rather than generating into code here, we're just going to generate directly into the functions section so that |
| 819 | 765 | // variable declarations appear in the first block of the function. |
| 820 | | try writeInstruction(&self.spv.binary.fn_decls, .OpVariable, &[_]Word{ result_type_id, result_id, @enumToInt(storage_class) }); |
| 821 | | |
| 822 | | return result_id; |
| 766 | try self.spv.sections.functions.emit(self.spv.gpa, .OpVariable, .{ |
| 767 | .id_result_type = result_type_id, |
| 768 | .id_result = result_id, |
| 769 | .storage_class = storage_class, |
| 770 | }); |
| 771 | return result_id.toRef(); |
| 823 | 772 | } |
| 824 | 773 | |
| 825 | | fn airArg(self: *DeclGen) ResultId { |
| 774 | fn airArg(self: *DeclGen) IdRef { |
| 826 | 775 | defer self.next_arg_index += 1; |
| 827 | 776 | return self.args.items[self.next_arg_index]; |
| 828 | 777 | } |
| 829 | 778 | |
| 830 | | fn airBlock(self: *DeclGen, inst: Air.Inst.Index) !?ResultId { |
| 831 | | // In IR, a block doesn't really define an entry point like a block, but more like a scope that breaks can jump out of and |
| 779 | fn airBlock(self: *DeclGen, inst: Air.Inst.Index) !?IdRef { |
| 780 | // In AIR, a block doesn't really define an entry point like a block, but more like a scope that breaks can jump out of and |
| 832 | 781 | // "return" a value from. This cannot be directly modelled in SPIR-V, so in a block instruction, we're going to split up |
| 833 | 782 | // the current block by first generating the code of the block, then a label, and then generate the rest of the current |
| 834 | 783 | // ir.Block in a different SPIR-V block. |
| 835 | 784 | |
| 836 | | const label_id = self.spv.allocResultId(); |
| 785 | const label_id = self.spv.allocId(); |
| 837 | 786 | |
| 838 | 787 | // 4 chosen as arbitrary initial capacity. |
| 839 | 788 | var incoming_blocks = try std.ArrayListUnmanaged(IncomingBlock).initCapacity(self.spv.gpa, 4); |
| 840 | 789 | |
| 841 | | try self.blocks.putNoClobber(inst, .{ |
| 842 | | .label_id = label_id, |
| 790 | try self.blocks.putNoClobber(self.spv.gpa, inst, .{ |
| 791 | .label_id = label_id.toRef(), |
| 843 | 792 | .incoming_blocks = &incoming_blocks, |
| 844 | 793 | }); |
| 845 | 794 | defer { |
| ... | ... | @@ -853,7 +802,7 @@ pub const DeclGen = struct { |
| 853 | 802 | const body = self.air.extra[extra.end..][0..extra.data.body_len]; |
| 854 | 803 | |
| 855 | 804 | try self.genBody(body); |
| 856 | | try self.beginSPIRVBlock(label_id); |
| 805 | try self.beginSpvBlock(label_id); |
| 857 | 806 | |
| 858 | 807 | // If this block didn't produce a value, simply return here. |
| 859 | 808 | if (!ty.hasRuntimeBits()) |
| ... | ... | @@ -861,7 +810,7 @@ pub const DeclGen = struct { |
| 861 | 810 | |
| 862 | 811 | // Combine the result from the blocks using the Phi instruction. |
| 863 | 812 | |
| 864 | | const result_id = self.spv.allocResultId(); |
| 813 | const result_id = self.spv.allocId(); |
| 865 | 814 | |
| 866 | 815 | // TODO: OpPhi is limited in the types that it may produce, such as pointers. Figure out which other types |
| 867 | 816 | // are not allowed to be created from a phi node, and throw an error for those. For now, genType already throws |
| ... | ... | @@ -869,13 +818,13 @@ pub const DeclGen = struct { |
| 869 | 818 | const result_type_id = try self.genType(ty); |
| 870 | 819 | _ = result_type_id; |
| 871 | 820 | |
| 872 | | try writeOpcode(&self.code, .OpPhi, 2 + @intCast(u16, incoming_blocks.items.len * 2)); // result type + result + variable/parent... |
| 821 | try self.code.emitRaw(self.spv.gpa, .OpPhi, 2 + @intCast(u16, incoming_blocks.items.len * 2)); // result type + result + variable/parent... |
| 873 | 822 | |
| 874 | 823 | for (incoming_blocks.items) |incoming| { |
| 875 | | try self.code.appendSlice(&[_]Word{ incoming.break_value_id, incoming.src_label_id }); |
| 824 | self.code.writeOperand(spec.PairIdRefIdRef, .{ incoming.break_value_id, incoming.src_label_id }); |
| 876 | 825 | } |
| 877 | 826 | |
| 878 | | return result_id; |
| 827 | return result_id.toRef(); |
| 879 | 828 | } |
| 880 | 829 | |
| 881 | 830 | fn airBr(self: *DeclGen, inst: Air.Inst.Index) !void { |
| ... | ... | @@ -889,7 +838,7 @@ pub const DeclGen = struct { |
| 889 | 838 | try block.incoming_blocks.append(self.spv.gpa, .{ .src_label_id = self.current_block_label_id, .break_value_id = operand_id }); |
| 890 | 839 | } |
| 891 | 840 | |
| 892 | | try writeInstruction(&self.code, .OpBranch, &[_]Word{block.label_id}); |
| 841 | try self.code.emit(self.spv.gpa, .OpBranch, .{.target_label = block.label_id}); |
| 893 | 842 | } |
| 894 | 843 | |
| 895 | 844 | fn airCondBr(self: *DeclGen, inst: Air.Inst.Index) !void { |
| ... | ... | @@ -900,63 +849,70 @@ pub const DeclGen = struct { |
| 900 | 849 | const condition_id = try self.resolve(pl_op.operand); |
| 901 | 850 | |
| 902 | 851 | // These will always generate a new SPIR-V block, since they are ir.Body and not ir.Block. |
| 903 | | const then_label_id = self.spv.allocResultId(); |
| 904 | | const else_label_id = self.spv.allocResultId(); |
| 852 | const then_label_id = self.spv.allocId(); |
| 853 | const else_label_id = self.spv.allocId(); |
| 905 | 854 | |
| 906 | 855 | // TODO: We can generate OpSelectionMerge here if we know the target block that both of these will resolve to, |
| 907 | 856 | // but i don't know if those will always resolve to the same block. |
| 908 | 857 | |
| 909 | | try writeInstruction(&self.code, .OpBranchConditional, &[_]Word{ |
| 910 | | condition_id, |
| 911 | | then_label_id, |
| 912 | | else_label_id, |
| 858 | try self.code.emit(self.spv.gpa, .OpBranchConditional, .{ |
| 859 | .condition = condition_id, |
| 860 | .true_label = then_label_id.toRef(), |
| 861 | .false_label = else_label_id.toRef(), |
| 913 | 862 | }); |
| 914 | 863 | |
| 915 | | try self.beginSPIRVBlock(then_label_id); |
| 864 | try self.beginSpvBlock(then_label_id); |
| 916 | 865 | try self.genBody(then_body); |
| 917 | | try self.beginSPIRVBlock(else_label_id); |
| 866 | try self.beginSpvBlock(else_label_id); |
| 918 | 867 | try self.genBody(else_body); |
| 919 | 868 | } |
| 920 | 869 | |
| 921 | 870 | fn airDbgStmt(self: *DeclGen, inst: Air.Inst.Index) !void { |
| 922 | 871 | const dbg_stmt = self.air.instructions.items(.data)[inst].dbg_stmt; |
| 923 | 872 | const src_fname_id = try self.spv.resolveSourceFileName(self.decl); |
| 924 | | try writeInstruction(&self.code, .OpLine, &[_]Word{ src_fname_id, dbg_stmt.line, dbg_stmt.column }); |
| 873 | try self.code.emit(self.spv.gpa, .OpLine, .{ |
| 874 | .file = src_fname_id, |
| 875 | .line = dbg_stmt.line, |
| 876 | .column = dbg_stmt.column, |
| 877 | }); |
| 925 | 878 | } |
| 926 | 879 | |
| 927 | | fn airLoad(self: *DeclGen, inst: Air.Inst.Index) !ResultId { |
| 880 | fn airLoad(self: *DeclGen, inst: Air.Inst.Index) !IdRef { |
| 928 | 881 | const ty_op = self.air.instructions.items(.data)[inst].ty_op; |
| 929 | 882 | const operand_id = try self.resolve(ty_op.operand); |
| 930 | 883 | const ty = self.air.typeOfIndex(inst); |
| 931 | 884 | |
| 932 | 885 | const result_type_id = try self.genType(ty); |
| 933 | | const result_id = self.spv.allocResultId(); |
| 886 | const result_id = self.spv.allocId(); |
| 934 | 887 | |
| 935 | | const operands = if (ty.isVolatilePtr()) |
| 936 | | &[_]Word{ result_type_id, result_id, operand_id, @bitCast(u32, spec.MemoryAccess{ .Volatile = true }) } |
| 937 | | else |
| 938 | | &[_]Word{ result_type_id, result_id, operand_id }; |
| 888 | const access = spec.MemoryAccess.Extended{ |
| 889 | .Volatile = ty.isVolatilePtr(), |
| 890 | }; |
| 939 | 891 | |
| 940 | | try writeInstruction(&self.code, .OpLoad, operands); |
| 892 | try self.code.emit(self.spv.gpa, .OpLoad, .{ |
| 893 | .id_result_type = result_type_id, |
| 894 | .id_result = result_id, |
| 895 | .pointer = operand_id, |
| 896 | .memory_access = access, |
| 897 | }); |
| 941 | 898 | |
| 942 | | return result_id; |
| 899 | return result_id.toRef(); |
| 943 | 900 | } |
| 944 | 901 | |
| 945 | 902 | fn airLoop(self: *DeclGen, inst: Air.Inst.Index) !void { |
| 946 | 903 | const ty_pl = self.air.instructions.items(.data)[inst].ty_pl; |
| 947 | 904 | const loop = self.air.extraData(Air.Block, ty_pl.payload); |
| 948 | 905 | const body = self.air.extra[loop.end..][0..loop.data.body_len]; |
| 949 | | const loop_label_id = self.spv.allocResultId(); |
| 906 | const loop_label_id = self.spv.allocId(); |
| 950 | 907 | |
| 951 | 908 | // Jump to the loop entry point |
| 952 | | try writeInstruction(&self.code, .OpBranch, &[_]Word{loop_label_id}); |
| 909 | try self.code.emit(self.spv.gpa, .OpBranch, .{.target_label = loop_label_id.toRef()}); |
| 953 | 910 | |
| 954 | 911 | // TODO: Look into OpLoopMerge. |
| 955 | | |
| 956 | | try self.beginSPIRVBlock(loop_label_id); |
| 912 | try self.beginSpvBlock(loop_label_id); |
| 957 | 913 | try self.genBody(body); |
| 958 | 914 | |
| 959 | | try writeInstruction(&self.code, .OpBranch, &[_]Word{loop_label_id}); |
| 915 | try self.code.emit(self.spv.gpa, .OpBranch, .{.target_label = loop_label_id.toRef()}); |
| 960 | 916 | } |
| 961 | 917 | |
| 962 | 918 | fn airRet(self: *DeclGen, inst: Air.Inst.Index) !void { |
| ... | ... | @@ -964,9 +920,9 @@ pub const DeclGen = struct { |
| 964 | 920 | const operand_ty = self.air.typeOf(operand); |
| 965 | 921 | if (operand_ty.hasRuntimeBits()) { |
| 966 | 922 | const operand_id = try self.resolve(operand); |
| 967 | | try writeInstruction(&self.code, .OpReturnValue, &[_]Word{operand_id}); |
| 923 | try self.code.emit(self.spv.gpa, .OpReturnValue, .{.value = operand_id}); |
| 968 | 924 | } else { |
| 969 | | try writeInstruction(&self.code, .OpReturn, &[_]Word{}); |
| 925 | try self.code.emit(self.spv.gpa, .OpReturn, {}); |
| 970 | 926 | } |
| 971 | 927 | } |
| 972 | 928 | |
| ... | ... | @@ -976,15 +932,18 @@ pub const DeclGen = struct { |
| 976 | 932 | const src_val_id = try self.resolve(bin_op.rhs); |
| 977 | 933 | const lhs_ty = self.air.typeOf(bin_op.lhs); |
| 978 | 934 | |
| 979 | | const operands = if (lhs_ty.isVolatilePtr()) |
| 980 | | &[_]Word{ dst_ptr_id, src_val_id, @bitCast(u32, spec.MemoryAccess{ .Volatile = true }) } |
| 981 | | else |
| 982 | | &[_]Word{ dst_ptr_id, src_val_id }; |
| 935 | const access = spec.MemoryAccess.Extended{ |
| 936 | .Volatile = lhs_ty.isVolatilePtr(), |
| 937 | }; |
| 983 | 938 | |
| 984 | | try writeInstruction(&self.code, .OpStore, operands); |
| 939 | try self.code.emit(self.spv.gpa, .OpStore, .{ |
| 940 | .pointer = dst_ptr_id, |
| 941 | .object = src_val_id, |
| 942 | .memory_access = access, |
| 943 | }); |
| 985 | 944 | } |
| 986 | 945 | |
| 987 | 946 | fn airUnreach(self: *DeclGen) !void { |
| 988 | | try writeInstruction(&self.code, .OpUnreachable, &[_]Word{}); |
| 947 | try self.code.emit(self.spv.gpa, .OpUnreachable, {}); |
| 989 | 948 | } |
| 990 | 949 | }; |