spirv-tools icon indicating copy to clipboard operation
spirv-tools copied to clipboard

Can I build a module from zero?

Open bglgwyng opened this issue 9 years ago • 1 comments

I'm trying to build a SPIR-V module using this library, but I'm stuck in creating a valid type_id.

module = Module()    
func = Function(module, None , ???)

What can I pass to type_id argument? I think I understand how to modify an existing module using this, but trying to build from zero, I can't even initialize objects. Could you provide some examples for this?

bglgwyng avatar Aug 24 '16 07:08 bglgwyng

The type_id is the result_id from an OpTypeFunction instruction.

As an example, here is the code needed to create a function adding two floating point vectors:

module = ir.Module()

# Create the type instructions needed to express the function type
float_inst = module.get_global_inst('OpTypeFloat', None, [32])
vec3_inst = module.get_global_inst('OpTypeVector', None,
                                   [float_inst.result_id, 3])
functype_inst = module.get_global_inst('OpTypeFunction', None,
                                       [vec3_inst.result_id,
                                        vec3_inst.result_id,
                                        vec3_inst.result_id])

# Create a function with two vec3 parameters
func = ir.Function(module, [], functype_inst.result_id)
param1_inst = ir.Instruction(module, 'OpFunctionParameter',
                             vec3_inst.result_id, [])
func.append_parameter(param1_inst)
param2_inst = ir.Instruction(module, 'OpFunctionParameter',
                             vec3_inst.result_id, [])
func.append_parameter(param2_inst)

# Create a basic block adding the two parameters, and attach it to the function
basic_block = ir.BasicBlock(module)
add_inst = ir.Instruction(module, 'OpFAdd', vec3_inst.result_id,
                          [param1_inst.result_id, param2_inst.result_id])
basic_block.append_inst(add_inst)
ret_inst = ir.Instruction(module, 'OpReturnValue', vec3_inst.result_id,
                          [add_inst.result_id])
basic_block.append_inst(ret_inst)
func.append_basic_block(basic_block)

# Finally, append the function to the module
module.append_function(func)

kristerw avatar Aug 24 '16 17:08 kristerw