From 6545cc2d48553e3129ef8e925531a1ca7e03e8a6 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 14 Jul 2023 14:54:49 +0100 Subject: Stub out expr and const files --- src/tilde_const.cpp | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 src/tilde_const.cpp (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp new file mode 100644 index 000000000..e59c6f8ab --- /dev/null +++ b/src/tilde_const.cpp @@ -0,0 +1,5 @@ +gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value) { + TB_Node *node = nullptr; + + return cg_value(node, type); +} \ No newline at end of file -- cgit v1.2.3 From b17ebeb6f66f5f7e24b5a1ca32baf6855185eea8 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 14 Jul 2023 17:03:28 +0100 Subject: Mock out more of the addr related stuff --- src/tilde_backend.cpp | 81 +++++++------ src/tilde_backend.hpp | 6 +- src/tilde_const.cpp | 40 +++++++ src/tilde_expr.cpp | 6 + src/tilde_stmt.cpp | 325 +++++++++++++++++++++++++++++++++++--------------- 5 files changed, 323 insertions(+), 135 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index 9b0c9105b..0dee72fe3 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -4,58 +4,61 @@ gb_internal TB_DataType cg_data_type(Type *t) { GB_ASSERT(t != nullptr); t = core_type(t); + i64 sz = type_size_of(t); switch (t->kind) { case Type_Basic: switch (t->Basic.kind) { - case Basic_bool: return TB_TYPE_BOOL; - case Basic_b8: return TB_TYPE_BOOL; - case Basic_b16: return TB_TYPE_I16; - case Basic_b32: return TB_TYPE_I32; - case Basic_b64: return TB_TYPE_I64; - - case Basic_i8: return TB_TYPE_I8; - case Basic_u8: return TB_TYPE_I8; - case Basic_i16: return TB_TYPE_I16; - case Basic_u16: return TB_TYPE_I16; - case Basic_i32: return TB_TYPE_I32; - case Basic_u32: return TB_TYPE_I32; - case Basic_i64: return TB_TYPE_I64; - case Basic_u64: return TB_TYPE_I64; - case Basic_i128: return TB_TYPE_I128; - case Basic_u128: return TB_TYPE_I128; - - case Basic_rune: return TB_TYPE_I32; + case Basic_bool: + case Basic_b8: + case Basic_b16: + case Basic_b32: + case Basic_b64: + + case Basic_i8: + case Basic_u8: + case Basic_i16: + case Basic_u16: + case Basic_i32: + case Basic_u32: + case Basic_i64: + case Basic_u64: + case Basic_i128: + case Basic_u128: + + case Basic_rune: + + case Basic_int: + case Basic_uint: + case Basic_uintptr: + case Basic_typeid: + return TB_TYPE_INTN(cast(u16)(8*sz)); case Basic_f16: return TB_TYPE_I16; case Basic_f32: return TB_TYPE_F32; case Basic_f64: return TB_TYPE_F64; - case Basic_int: return TB_TYPE_INTN(cast(u16)build_context.int_size); - case Basic_uint: return TB_TYPE_INTN(cast(u16)build_context.int_size); - case Basic_uintptr: return TB_TYPE_INTN(cast(u16)build_context.ptr_size); case Basic_rawptr: return TB_TYPE_PTR; case Basic_cstring: return TB_TYPE_PTR; - case Basic_typeid: return TB_TYPE_INTN(cast(u16)build_context.ptr_size); // Endian Specific Types - case Basic_i16le: return TB_TYPE_I16; - case Basic_u16le: return TB_TYPE_I16; - case Basic_i32le: return TB_TYPE_I32; - case Basic_u32le: return TB_TYPE_I32; - case Basic_i64le: return TB_TYPE_I64; - case Basic_u64le: return TB_TYPE_I64; - case Basic_i128le: return TB_TYPE_I128; - case Basic_u128le: return TB_TYPE_I128; - - case Basic_i16be: return TB_TYPE_I16; - case Basic_u16be: return TB_TYPE_I16; - case Basic_i32be: return TB_TYPE_I32; - case Basic_u32be: return TB_TYPE_I32; - case Basic_i64be: return TB_TYPE_I64; - case Basic_u64be: return TB_TYPE_I64; - case Basic_i128be: return TB_TYPE_I128; - case Basic_u128be: return TB_TYPE_I128; + case Basic_i16le: + case Basic_u16le: + case Basic_i32le: + case Basic_u32le: + case Basic_i64le: + case Basic_u64le: + case Basic_i128le: + case Basic_u128le: + case Basic_i16be: + case Basic_u16be: + case Basic_i32be: + case Basic_u32be: + case Basic_i64be: + case Basic_u64be: + case Basic_i128be: + case Basic_u128be: + return TB_TYPE_INTN(cast(u16)(8*sz)); case Basic_f16le: return TB_TYPE_I16; case Basic_f32le: return TB_TYPE_F32; diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 9d13a87d5..24a352fe1 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -7,8 +7,9 @@ #include "tilde/tb.h" -#define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } - +#define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } +#define TB_TYPE_INT TB_TYPE_INTN(cast(u16)build_context.int_size) +#define TB_TYPE_INTPTR TB_TYPE_INTN(cast(u16)build_context.ptr_size) #if defined(GB_SYSTEM_WINDOWS) #pragma warning(pop) @@ -162,6 +163,7 @@ struct cgModule { PtrMap file_id_map; // Key: AstFile.id (i32 cast to uintptr) std::atomic nested_type_name_guid; + std::atomic const_nil_guid; }; #ifndef ABI_PKG_NAME_SEPARATOR diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index e59c6f8ab..6f9736554 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -1,5 +1,45 @@ +gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { + Type *original_type = type; + type = core_type(type); + i64 size = type_size_of(type); + i64 align = type_align_of(type); + TB_DataType dt = cg_data_type(type); + if (TB_IS_VOID_TYPE(dt)) { + TB_Module *m = p->module->mod; + char name[32] = {}; + gb_snprintf(name, 31, "cnil$%u", 1+p->module->const_nil_guid.fetch_add(1)); + TB_Global *global = tb_global_create(m, name, nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(m, tb_module_get_rdata(m), global, size, align, 0); + + TB_Symbol *symbol = cast(TB_Symbol *)global; + TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); + return cg_lvalue_addr(node, type); + } + + if (is_type_internally_pointer_like(type)) { + return cg_value(tb_inst_ptr(p->func, 0), type); + } else if (is_type_integer(type) || is_type_boolean(type) || is_type_bit_set(type)) { + return cg_value(tb_inst_uint(p->func, dt, 0), type); + } else if (is_type_float(type)) { + switch (size) { + case 2: + return cg_value(tb_inst_uint(p->func, dt, 0), type); + case 4: + return cg_value(tb_inst_float32(p->func, 0), type); + case 8: + return cg_value(tb_inst_float64(p->func, 0), type); + } + } + GB_PANIC("TODO(bill): cg_const_nil %s", type_to_string(original_type)); + return {}; +} + gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value) { TB_Node *node = nullptr; + if (value.kind == ExactValue_Invalid) { + return cg_const_nil(p, type); + } + return cg_value(node, type); } \ No newline at end of file diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 9910801bd..4aae872cf 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1,3 +1,9 @@ +gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *type) { + // TODO(bill): cg_emit_conv + return value; +} + + gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { u16 prev_state_flags = p->state_flags; diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index a2a6923c4..52bbb3ab9 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -1,3 +1,223 @@ + +gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_volatile=false) { + GB_ASSERT(is_type_pointer(ptr.type)); + Type *type = type_deref(ptr.type); + TB_DataType dt = cg_data_type(type); + + if (TB_IS_VOID_TYPE(dt)) { + switch (ptr.kind) { + case cgValue_Value: + return cg_lvalue_addr(ptr.node, type); + case cgValue_Addr: + GB_PANIC("NOT POSSIBLE"); + break; + case cgValue_Symbol: + return cg_lvalue_addr(tb_inst_get_symbol_address(p->func, ptr.symbol), type); + } + } + + TB_CharUnits alignment = 1; // for the time being + + TB_Node *the_ptr = nullptr; + switch (ptr.kind) { + case cgValue_Value: + the_ptr = ptr.node; + break; + case cgValue_Addr: + the_ptr = tb_inst_load(p->func, TB_TYPE_PTR, ptr.node, alignment, is_volatile); + break; + case cgValue_Symbol: + the_ptr = tb_inst_get_symbol_address(p->func, ptr.symbol); + break; + } + return cg_value(tb_inst_load(p->func, dt, the_ptr, alignment, is_volatile), type); +} + +gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, bool is_volatile=false) { + if (dst.kind == cgValue_Addr) { + dst = cg_emit_load(p, dst, is_volatile); + } else if (dst.kind = cgValue_Symbol) { + dst = cg_value(tb_inst_get_symbol_address(p->func, dst.symbol), dst.type); + } + + GB_ASSERT(is_type_pointer(dst.type)); + Type *dst_type = type_deref(dst.type); + + GB_ASSERT_MSG(are_types_identical(dst_type, src.type), "%s vs %s", type_to_string(dst_type), type_to_string(src.type)); + + TB_DataType dt = cg_data_type(dst_type); + TB_DataType st = cg_data_type(src.type); + GB_ASSERT(dt.raw == st.raw); + + TB_CharUnits alignment = 1; // for the time being + + if (TB_IS_VOID_TYPE(dt)) { + TB_Node *dst_ptr = nullptr; + TB_Node *src_ptr = nullptr; + + switch (dst.kind) { + case cgValue_Value: + dst_ptr = dst.node; + break; + case cgValue_Addr: + GB_PANIC("DST cgValue_Addr should be handled above"); + break; + case cgValue_Symbol: + dst_ptr = tb_inst_get_symbol_address(p->func, dst.symbol); + break; + } + + switch (src.kind) { + case cgValue_Value: + GB_PANIC("SRC cgValue_Value should be handled above"); + break; + case cgValue_Symbol: + GB_PANIC("SRC cgValue_Symbol should be handled above"); + break; + case cgValue_Addr: + src_ptr = src.node; + break; + } + + // IMPORTANT TODO(bill): needs to be memmove + i64 sz = type_size_of(dst_type); + TB_Node *count = tb_inst_uint(p->func, TB_TYPE_INT, cast(u64)sz); + tb_inst_memcpy(p->func, dst_ptr, src_ptr, count, alignment, is_volatile); + return; + } + + switch (dst.kind) { + case cgValue_Value: + switch (dst.kind) { + case cgValue_Value: + tb_inst_store(p->func, dt, dst.node, src.node, alignment, is_volatile); + return; + case cgValue_Addr: + tb_inst_store(p->func, dt, dst.node, + tb_inst_load(p->func, st, src.node, alignment, is_volatile), + alignment, is_volatile); + return; + case cgValue_Symbol: + tb_inst_store(p->func, dt, dst.node, + tb_inst_get_symbol_address(p->func, src.symbol), + alignment, is_volatile); + return; + } + case cgValue_Addr: + GB_PANIC("cgValue_Addr should be handled above"); + break; + case cgValue_Symbol: + GB_PANIC(" cgValue_Symbol should be handled above"); + break; + } +} + + +gb_internal cgValue cg_address_from_load(cgProcedure *p, cgValue value) { + switch (value.kind) { + case cgValue_Value: + { + TB_Node *load_inst = value.node; + GB_ASSERT_MSG(load_inst->type == TB_LOAD, "expected a load instruction"); + TB_Node *ptr = load_inst->inputs[1]; + return cg_value(ptr, alloc_type_pointer(value.type)); + } + case cgValue_Addr: + return cg_value(value.node, alloc_type_pointer(value.type)); + case cgValue_Symbol: + GB_PANIC("Symbol is an invalid use case for cg_address_from_load"); + return {}; + } +} + +gb_internal bool cg_addr_is_empty(cgAddr const &addr) { + switch (addr.kind) { + case cgValue_Value: + case cgValue_Addr: + return addr.addr.node == nullptr; + case cgValue_Symbol: + return addr.addr.symbol == nullptr; + } + return true; +} + +gb_internal Type *cg_addr_type(cgAddr const &addr) { + if (cg_addr_is_empty(addr)) { + return nullptr; + } + switch (addr.kind) { + case cgAddr_Map: + { + Type *t = base_type(addr.map.type); + GB_ASSERT(is_type_map(t)); + return t->Map.value; + } + case cgAddr_Swizzle: + return addr.swizzle.type; + case cgAddr_SwizzleLarge: + return addr.swizzle_large.type; + case cgAddr_Context: + if (addr.ctx.sel.index.count > 0) { + Type *t = t_context; + for_array(i, addr.ctx.sel.index) { + GB_ASSERT(is_type_struct(t)); + t = base_type(t)->Struct.fields[addr.ctx.sel.index[i]]->type; + } + return t; + } + break; + } + return type_deref(addr.addr.type); +} + +gb_internal cgValue cg_addr_load(cgProcedure *p, cgAddr addr) { + GB_PANIC("TODO(bill): cg_addr_load"); + return {}; +} + + +gb_internal void cg_addr_store(cgProcedure *p, cgAddr addr, cgValue value) { + if (cg_addr_is_empty(addr)) { + return; + } + GB_ASSERT(value.type != nullptr); + if (is_type_untyped_uninit(value.type)) { + Type *t = cg_addr_type(addr); + value = cg_value(tb_inst_poison(p->func), t); + // TODO(bill): IS THIS EVEN A GOOD IDEA? + } else if (is_type_untyped_nil(value.type)) { + Type *t = cg_addr_type(addr); + value = cg_const_nil(p, t); + } + + if (addr.kind == cgAddr_RelativePointer && addr.relative.deref) { + addr = cg_addr(cg_address_from_load(p, cg_addr_load(p, addr))); + } + + if (addr.kind == cgAddr_RelativePointer) { + GB_PANIC("TODO(bill): cgAddr_RelativePointer"); + } else if (addr.kind == cgAddr_RelativeSlice) { + GB_PANIC("TODO(bill): cgAddr_RelativeSlice"); + } else if (addr.kind == cgAddr_Map) { + GB_PANIC("TODO(bill): cgAddr_Map"); + } else if (addr.kind == cgAddr_Context) { + GB_PANIC("TODO(bill): cgAddr_Context"); + } else if (addr.kind == cgAddr_SoaVariable) { + GB_PANIC("TODO(bill): cgAddr_SoaVariable"); + } else if (addr.kind == cgAddr_Swizzle) { + GB_ASSERT(addr.swizzle.count <= 4); + GB_PANIC("TODO(bill): cgAddr_Swizzle"); + } else if (addr.kind == cgAddr_SwizzleLarge) { + GB_PANIC("TODO(bill): cgAddr_SwizzleLarge"); + } + + value = cg_emit_conv(p, value, cg_addr_type(addr)); + cg_emit_store(p, addr.addr, value); +} + + + + gb_internal cgBranchBlocks cg_lookup_branch_blocks(cgProcedure *p, Ast *ident) { GB_ASSERT(ident->kind == Ast_Ident); Entity *e = entity_of_node(ident); @@ -91,95 +311,12 @@ gb_internal void cg_emit_defer_stmts(cgProcedure *p, cgDeferExitKind kind, TB_No // TODO(bill): cg_emit_defer_stmts } -gb_internal void cg_build_assignment(cgProcedure *p, Array const &lhs, Slice const &rhs) { - -} - - -gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_volatile=false) { - GB_ASSERT(is_type_pointer(ptr.type)); - Type *type = type_deref(ptr.type); - TB_DataType dt = cg_data_type(type); - - if (TB_IS_VOID_TYPE(dt)) { - switch (ptr.kind) { - case cgValue_Value: - return cg_lvalue_addr(ptr.node, type); - case cgValue_Addr: - GB_PANIC("NOT POSSIBLE"); - break; - case cgValue_Symbol: - return cg_lvalue_addr(tb_inst_get_symbol_address(p->func, ptr.symbol), type); - } - } - - TB_CharUnits alignment = 1; // for the time being - - TB_Node *the_ptr = nullptr; - switch (ptr.kind) { - case cgValue_Value: - the_ptr = ptr.node; - break; - case cgValue_Addr: - the_ptr = tb_inst_load(p->func, TB_TYPE_PTR, ptr.node, alignment, is_volatile); - break; - case cgValue_Symbol: - the_ptr = tb_inst_get_symbol_address(p->func, ptr.symbol); - break; - } - return cg_value(tb_inst_load(p->func, dt, the_ptr, alignment, is_volatile), type); -} - -gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, bool is_volatile=false) { - if (dst.kind == cgValue_Addr) { - dst = cg_emit_load(p, dst, is_volatile); - } else if (dst.kind = cgValue_Symbol) { - dst = cg_value(tb_inst_get_symbol_address(p->func, dst.symbol), dst.type); - } - - GB_ASSERT(is_type_pointer(dst.type)); - Type *dst_type = type_deref(dst.type); - - GB_ASSERT_MSG(are_types_identical(dst_type, src.type), "%s vs %s", type_to_string(dst_type), type_to_string(src.type)); - - TB_DataType dt = cg_data_type(dst_type); - TB_DataType st = cg_data_type(src.type); - GB_ASSERT(dt.raw == st.raw); - - if (TB_IS_VOID_TYPE(dt)) { - // TODO(bill): needs to be memmove - GB_PANIC("todo emit store to aggregate type"); +gb_internal void cg_build_assignment(cgProcedure *p, Array const &lvals, Slice const &values) { + if (values.count == 0) { return; } - - TB_CharUnits alignment = 1; // for the time being - - switch (dst.kind) { - case cgValue_Value: - switch (dst.kind) { - case cgValue_Value: - tb_inst_store(p->func, dt, dst.node, src.node, alignment, is_volatile); - return; - case cgValue_Addr: - tb_inst_store(p->func, dt, dst.node, - tb_inst_load(p->func, st, src.node, alignment, is_volatile), - alignment, is_volatile); - return; - case cgValue_Symbol: - tb_inst_store(p->func, dt, dst.node, - tb_inst_get_symbol_address(p->func, src.symbol), - alignment, is_volatile); - return; - } - case cgValue_Addr: - case cgValue_Symbol: - GB_PANIC("should be handled above"); - break; - } } - - gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { if (as->op.kind == Token_Eq) { auto lvals = array_make(permanent_allocator(), 0, as->lhs.count); @@ -213,19 +350,19 @@ gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { cgValue new_value = lb_emit_logical_binary_expr(p, op, as->lhs[0], as->rhs[0], type); cgAddr lhs = lb_build_addr(p, as->lhs[0]); - lb_addr_store(p, lhs, new_value); + cg_addr_store(p, lhs, new_value); } else { cgAddr lhs = lb_build_addr(p, as->lhs[0]); - lbValue value = lb_build_expr(p, as->rhs[0]); + cgValue value = lb_build_expr(p, as->rhs[0]); Type *lhs_type = lb_addr_type(lhs); // NOTE(bill): Allow for the weird edge case of: // array *= matrix if (op == Token_Mul && is_type_matrix(value.type) && is_type_array(lhs_type)) { - lbValue old_value = lb_addr_load(p, lhs); + cgValue old_value = lb_addr_load(p, lhs); Type *type = old_value.type; - lbValue new_value = lb_emit_vector_mul_matrix(p, old_value, value, type); - lb_addr_store(p, lhs, new_value); + cgValue new_value = lb_emit_vector_mul_matrix(p, old_value, value, type); + cg_addr_store(p, lhs, new_value); return; } @@ -233,12 +370,12 @@ gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { lb_build_assign_stmt_array(p, op, lhs, value); return; } else { - lbValue old_value = lb_addr_load(p, lhs); + cgValue old_value = lb_addr_load(p, lhs); Type *type = old_value.type; - lbValue change = lb_emit_conv(p, value, type); - lbValue new_value = lb_emit_arith(p, op, old_value, change, type); - lb_addr_store(p, lhs, new_value); + cgValue change = lb_emit_conv(p, value, type); + cgValue new_value = lb_emit_arith(p, op, old_value, change, type); + cg_addr_store(p, lhs, new_value); } } */ -- cgit v1.2.3 From ca442defbbaae4269ff947dfc14059f69a5cdaec Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 14 Jul 2023 17:34:00 +0100 Subject: Mocking out call related stuff --- src/tilde_backend.cpp | 8 +-- src/tilde_backend.hpp | 18 +++++- src/tilde_const.cpp | 9 ++- src/tilde_expr.cpp | 174 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/tilde_proc.cpp | 5 ++ src/tilde_stmt.cpp | 7 +- 6 files changed, 207 insertions(+), 14 deletions(-) create mode 100644 src/tilde_proc.cpp (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index 0dee72fe3..d695c846c 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -708,14 +708,12 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { if (p == nullptr || p->func == nullptr) { return; } - gb_printf_err("cg_procedure_begin %.*s\n", LIT(p->name)); } gb_internal void cg_procedure_end(cgProcedure *p) { if (p == nullptr || p->func == nullptr) { return; } - gb_printf_err("cg_procedure_end %.*s\n", LIT(p->name)); tb_inst_ret(p->func, 0, nullptr); tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST); } @@ -731,18 +729,16 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { p->name != "main") { return; } - if (p->body != nullptr) { - cg_build_stmt(p, p->body); - } + cg_build_stmt(p, p->body); } #include "tilde_const.cpp" #include "tilde_expr.cpp" +#include "tilde_proc.cpp" #include "tilde_stmt.cpp" - gb_internal bool cg_generate_code(Checker *c) { TIME_SECTION("Tilde Module Initializtion"); diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 24a352fe1..44591190a 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -194,8 +194,22 @@ gb_internal cgAddr cg_addr(cgValue const &value); gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value); - +gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type); gb_internal void cg_build_stmt(cgProcedure *p, Ast *stmt); gb_internal void cg_build_stmt_list(cgProcedure *p, Slice const &stmts); -gb_internal void cg_build_when_stmt(cgProcedure *p, AstWhenStmt *ws); \ No newline at end of file +gb_internal void cg_build_when_stmt(cgProcedure *p, AstWhenStmt *ws); + +gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr); +gb_internal cgAddr cg_build_addr(cgProcedure *p, Ast *expr); + +gb_internal Type * cg_addr_type(cgAddr const &addr); +gb_internal cgValue cg_addr_load(cgProcedure *p, cgAddr addr); +gb_internal void cg_addr_store(cgProcedure *p, cgAddr addr, cgValue value); + +gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_volatile=false); +gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, bool is_volatile=false); + +gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero_init); + +gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); \ No newline at end of file diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 6f9736554..7a8be70c7 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -17,7 +17,7 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { } if (is_type_internally_pointer_like(type)) { - return cg_value(tb_inst_ptr(p->func, 0), type); + return cg_value(tb_inst_uint(p->func, dt, 0), type); } else if (is_type_integer(type) || is_type_boolean(type) || is_type_bit_set(type)) { return cg_value(tb_inst_uint(p->func, dt, 0), type); } else if (is_type_float(type)) { @@ -34,7 +34,7 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { return {}; } -gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value) { +gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value) { TB_Node *node = nullptr; if (value.kind == ExactValue_Invalid) { @@ -42,4 +42,9 @@ gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const } return cg_value(node, type); +} + +gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value) { + GB_ASSERT(p != nullptr); + return cg_const_value(p->module, p, type, value); } \ No newline at end of file diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 4aae872cf..ccd126747 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1,8 +1,52 @@ +gb_internal cgValue cg_typeid(cgModule *m, Type *t) { + GB_ASSERT("TODO(bill): cg_typeid"); + return {}; +} + + gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *type) { // TODO(bill): cg_emit_conv return value; } +gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) { + GB_ASSERT(type_size_of(value.type) == type_size_of(type)); + + if (value.kind == cgValue_Symbol) { + GB_ASSERT(is_type_pointer(value.type)); + value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), type); + } + + i64 src_align = type_align_of(value.type); + i64 dst_align = type_align_of(type); + + if (dst_align > src_align) { + cgAddr local = cg_add_local(p, type, nullptr, false); + cgValue dst = local.addr; + dst.type = alloc_type_pointer(value.type); + cg_emit_store(p, dst, value); + return cg_addr_load(p, local); + } + + TB_DataType dt = cg_data_type(type); + switch (value.kind) { + case cgValue_Value: + GB_ASSERT(!TB_IS_VOID_TYPE(dt)); + value.type = type; + value.node = tb_inst_bitcast(p->func, value.node, dt); + return value; + case cgValue_Addr: + value.type = type; + return value; + case cgValue_Symbol: + GB_PANIC("should be handled above"); + break; + } + return value; + +} + + gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { @@ -68,8 +112,138 @@ gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { } + gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { + cgModule *m = p->module; + + expr = unparen_expr(expr); + + TokenPos expr_pos = ast_token(expr).pos; + TypeAndValue tv = type_and_value_of_expr(expr); + Type *type = type_of_expr(expr); + GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %s\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), token_pos_to_string(expr_pos), LIT(p->name), type_to_string(p->type)); + + if (tv.value.kind != ExactValue_Invalid) { + // NOTE(bill): The commented out code below is just for debug purposes only + // if (is_type_untyped(type)) { + // gb_printf_err("%s %s : %s @ %p\n", token_pos_to_string(expr_pos), expr_to_string(expr), type_to_string(expr->tav.type), expr); + // GB_PANIC("%s\n", type_to_string(tv.type)); + // } + + // NOTE(bill): Short on constant values + return cg_const_value(p, type, tv.value); + } else if (tv.mode == Addressing_Type) { + // NOTE(bill, 2023-01-16): is this correct? I hope so at least + return cg_typeid(m, tv.type); + } + + switch (expr->kind) { + case_ast_node(bl, BasicLit, expr); + TokenPos pos = bl->token.pos; + GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(token_strings[bl->token.kind])); + case_end; + + case_ast_node(bd, BasicDirective, expr); + TokenPos pos = bd->token.pos; + GB_PANIC("Non-constant basic literal %s - %.*s", token_pos_to_string(pos), LIT(bd->name.string)); + case_end; + + case_ast_node(i, Ident, expr); + Entity *e = entity_from_expr(expr); + e = strip_entity_wrapping(e); + + GB_ASSERT_MSG(e != nullptr, "%s in %.*s %p", expr_to_string(expr), LIT(p->name), expr); + + if (e->kind == Entity_Builtin) { + Token token = ast_token(expr); + GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n" + "\t at %s", LIT(builtin_procs[e->Builtin.id].name), + token_pos_to_string(token.pos)); + return {}; + } else if (e->kind == Entity_Nil) { + // TODO(bill): is this correct? + return cg_value(cast(TB_Node *)nullptr, e->type); + } + GB_ASSERT(e->kind != Entity_ProcGroup); + // return cg_find_ident(p, m, e, expr); + GB_PANIC("TODO: cg_find_ident"); + return {}; + case_end; + + case_ast_node(i, Implicit, expr); + return cg_addr_load(p, cg_build_addr(p, expr)); + case_end; + + case_ast_node(u, Uninit, expr); + if (is_type_untyped(type)) { + return cg_value(cast(TB_Node *)nullptr, t_untyped_uninit); + } + return cg_value(tb_inst_poison(p->func), type); + case_end; + + case_ast_node(de, DerefExpr, expr); + return cg_addr_load(p, cg_build_addr(p, expr)); + case_end; + + + case_ast_node(se, SelectorExpr, expr); + TypeAndValue tav = type_and_value_of_expr(expr); + GB_ASSERT(tav.mode != Addressing_Invalid); + return cg_addr_load(p, cg_build_addr(p, expr)); + case_end; + + case_ast_node(ise, ImplicitSelectorExpr, expr); + TypeAndValue tav = type_and_value_of_expr(expr); + GB_ASSERT(tav.mode == Addressing_Constant); + + return cg_const_value(p, type, tv.value); + case_end; + + + case_ast_node(se, SelectorCallExpr, expr); + GB_ASSERT(se->modified_call); + return cg_build_call_expr(p, se->call); + case_end; + + case_ast_node(i, CallExpr, expr); + return cg_build_call_expr(p, expr); + case_end; + + + case_ast_node(te, TernaryIfExpr, expr); + GB_PANIC("TODO(bill): TernaryIfExpr"); + case_end; + + case_ast_node(te, TernaryWhenExpr, expr); + TypeAndValue tav = type_and_value_of_expr(te->cond); + GB_ASSERT(tav.mode == Addressing_Constant); + GB_ASSERT(tav.value.kind == ExactValue_Bool); + if (tav.value.value_bool) { + return cg_build_expr(p, te->x); + } else { + return cg_build_expr(p, te->y); + } + case_end; + + case_ast_node(tc, TypeCast, expr); + cgValue e = cg_build_expr(p, tc->expr); + switch (tc->token.kind) { + case Token_cast: + return cg_emit_conv(p, e, type); + case Token_transmute: + return cg_emit_transmute(p, e, type); + } + GB_PANIC("Invalid AST TypeCast"); + case_end; + + case_ast_node(ac, AutoCast, expr); + cgValue value = cg_build_expr(p, ac->expr); + return cg_emit_conv(p, value, type); + case_end; + } + GB_PANIC("TODO(bill): cg_build_expr_internal %.*s", LIT(ast_strings[expr->kind])); return {}; + } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp new file mode 100644 index 000000000..306852db3 --- /dev/null +++ b/src/tilde_proc.cpp @@ -0,0 +1,5 @@ +gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr) { + ast_node(ce, CallExpr, expr); + // TODO(bill): cg_build_call_expr + return {}; +} \ No newline at end of file diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 52bbb3ab9..f7e68d483 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -1,5 +1,4 @@ - -gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_volatile=false) { +gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_volatile) { GB_ASSERT(is_type_pointer(ptr.type)); Type *type = type_deref(ptr.type); TB_DataType dt = cg_data_type(type); @@ -33,10 +32,10 @@ gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_vol return cg_value(tb_inst_load(p->func, dt, the_ptr, alignment, is_volatile), type); } -gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, bool is_volatile=false) { +gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, bool is_volatile) { if (dst.kind == cgValue_Addr) { dst = cg_emit_load(p, dst, is_volatile); - } else if (dst.kind = cgValue_Symbol) { + } else if (dst.kind == cgValue_Symbol) { dst = cg_value(tb_inst_get_symbol_address(p->func, dst.symbol), dst.type); } -- cgit v1.2.3 From e2e5641a450f4d7ea67eae468f1bd479361ec198 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 15 Jul 2023 13:15:50 +0100 Subject: Update TB; Fix calling nullptr TB_Node* problems --- src/tilde/tb.h | 56 +++++++++++----------- src/tilde/tb.lib | Bin 4295348 -> 4120106 bytes src/tilde_backend.cpp | 32 +++++++------ src/tilde_backend.hpp | 4 +- src/tilde_const.cpp | 14 +++++- src/tilde_expr.cpp | 3 +- src/tilde_proc.cpp | 126 +++++++++++++++++++++++++++++++++++++++++++++++++- src/tilde_stmt.cpp | 19 ++++---- 8 files changed, 196 insertions(+), 58 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde/tb.h b/src/tilde/tb.h index 0f0aaf4c6..8b698ff30 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -439,7 +439,7 @@ struct TB_Node { typedef struct { // TB_BRANCH // avoid empty structs with flexible members int64_t _; - int64_t keys[/* input_count - 1 */]; + int64_t keys[]; } TB_NodeBranch; typedef struct { // TB_PROJ @@ -538,19 +538,6 @@ typedef struct { TB_Node* value; } TB_SwitchEntry; -typedef struct TB_Loop { - // refers to another entry in TB_LoopInfo... unless it's -1 - ptrdiff_t parent_loop; - - TB_Node* header; - TB_Node* backedge; -} TB_Loop; - -typedef struct TB_LoopInfo { - size_t count; - TB_Loop* loops; -} TB_LoopInfo; - typedef enum { TB_EXECUTABLE_UNKNOWN, TB_EXECUTABLE_PE, @@ -648,7 +635,7 @@ TB_API void tb_module_destroy(TB_Module* m); // When targetting windows & thread local storage, you'll need to bind a tls index // which is usually just a global that the runtime support has initialized, if you // dont and the tls_index is used, it'll crash -TB_API void tb_module_set_tls_index(TB_Module* m, const char* name); +TB_API void tb_module_set_tls_index(TB_Module* m, ptrdiff_t len, const char* name); // You don't need to manually call this unless you want to resolve locations before // exporting. @@ -756,7 +743,7 @@ TB_API TB_External* tb_next_external(TB_External* e); TB_API TB_ExternalType tb_extern_get_type(TB_External* e); TB_Global* tb_extern_transmute(TB_External* e, TB_DebugType* dbg_type, TB_Linkage linkage); -TB_API TB_External* tb_extern_create(TB_Module* m, const char* name, TB_ExternalType type); +TB_API TB_External* tb_extern_create(TB_Module* m, ptrdiff_t len, const char* name, TB_ExternalType type); TB_API TB_FileID tb_file_create(TB_Module* m, const char* path); // Called once you're done with TB operations on a thread (or i guess when it's @@ -798,7 +785,7 @@ TB_API TB_FunctionPrototype* tb_prototype_create(TB_Module* m, TB_CallingConv cc //////////////////////////////// // Globals //////////////////////////////// -TB_API TB_Global* tb_global_create(TB_Module* m, const char* name, TB_DebugType* dbg_type, TB_Linkage linkage); +TB_API TB_Global* tb_global_create(TB_Module* m, ptrdiff_t len, const char* name, TB_DebugType* dbg_type, TB_Linkage linkage); // allocate space for the global TB_API void tb_global_set_storage(TB_Module* m, TB_ModuleSection* section, TB_Global* global, size_t size, size_t align, size_t max_objects); @@ -818,8 +805,11 @@ TB_API TB_ModuleSection* tb_module_get_tls(TB_Module* m); //////////////////////////////// // Function Attributes //////////////////////////////// +TB_API void tb_node_append_attrib(TB_Node* n, TB_Attrib* a); + // These are parts of a function that describe metadata for instructions -TB_API void tb_function_attrib_variable(TB_Function* f, TB_Node* n, const char* name, TB_DebugType* type); +TB_API TB_Attrib* tb_function_attrib_variable(TB_Function* f, ptrdiff_t len, const char* name, TB_DebugType* type); +TB_API TB_Attrib* tb_function_attrib_scope(TB_Function* f, TB_Attrib* parent_scope); //////////////////////////////// // Debug info Generation @@ -830,9 +820,9 @@ TB_API TB_DebugType* tb_debug_get_integer(TB_Module* m, bool is_signed, int bits TB_API TB_DebugType* tb_debug_get_float(TB_Module* m, TB_FloatFormat fmt); TB_API TB_DebugType* tb_debug_create_ptr(TB_Module* m, TB_DebugType* base); TB_API TB_DebugType* tb_debug_create_array(TB_Module* m, TB_DebugType* base, size_t count); -TB_API TB_DebugType* tb_debug_create_struct(TB_Module* m, const char* tag); -TB_API TB_DebugType* tb_debug_create_union(TB_Module* m, const char* tag); -TB_API TB_DebugType* tb_debug_create_field(TB_Module* m, TB_DebugType* type, const char* name, TB_CharUnits offset); +TB_API TB_DebugType* tb_debug_create_struct(TB_Module* m, ptrdiff_t len, const char* tag); +TB_API TB_DebugType* tb_debug_create_union(TB_Module* m, ptrdiff_t len, const char* tag); +TB_API TB_DebugType* tb_debug_create_field(TB_Module* m, TB_DebugType* type, ptrdiff_t len, const char* name, TB_CharUnits offset); TB_API void tb_debug_complete_record(TB_DebugType* type, TB_DebugType** members, size_t count, TB_CharUnits size, TB_CharUnits align); //////////////////////////////// @@ -869,12 +859,14 @@ TB_API void tb_inst_set_location(TB_Function* f, TB_FileID file, int line); TB_API TB_DataType tb_vector_type(TB_DataTypeEnum type, int width); // if section is NULL, default to .text -TB_API TB_Function* tb_function_create(TB_Module* m, const char* name, TB_Linkage linkage, TB_ComdatType comdat); +TB_API TB_Function* tb_function_create(TB_Module* m, ptrdiff_t len, const char* name, TB_Linkage linkage, TB_ComdatType comdat); TB_API void* tb_function_get_jit_pos(TB_Function* f); +// if len is -1, it's null terminated +TB_API void tb_symbol_set_name(TB_Symbol* s, ptrdiff_t len, const char* name); + TB_API void tb_symbol_bind_ptr(TB_Symbol* s, void* ptr); -TB_API void tb_symbol_set_name(TB_Symbol* s, const char* name); TB_API const char* tb_symbol_get_name(TB_Symbol* s); // if arena is NULL, defaults to module arena which is freed on tb_free_thread_resources @@ -915,7 +907,6 @@ TB_API TB_Node* tb_inst_load(TB_Function* f, TB_DataType dt, TB_Node* addr, TB_C TB_API void tb_inst_store(TB_Function* f, TB_DataType dt, TB_Node* addr, TB_Node* val, TB_CharUnits align, bool is_volatile); TB_API TB_Node* tb_inst_bool(TB_Function* f, bool imm); -TB_API TB_Node* tb_inst_ptr(TB_Function* f, uint64_t imm); TB_API TB_Node* tb_inst_sint(TB_Function* f, TB_DataType dt, int64_t imm); TB_API TB_Node* tb_inst_uint(TB_Function* f, TB_DataType dt, uint64_t imm); TB_API TB_Node* tb_inst_float32(TB_Function* f, float imm); @@ -923,9 +914,12 @@ TB_API TB_Node* tb_inst_float64(TB_Function* f, double imm); TB_API TB_Node* tb_inst_cstring(TB_Function* f, const char* str); TB_API TB_Node* tb_inst_string(TB_Function* f, size_t len, const char* str); -// Broadcasts 'val' across 'count' elements starting 'dst' +// write 'val' over 'count' bytes on 'dst' TB_API void tb_inst_memset(TB_Function* f, TB_Node* dst, TB_Node* val, TB_Node* count, TB_CharUnits align, bool is_volatile); +// zero 'count' bytes on 'dst' +TB_API void tb_inst_memzero(TB_Function* f, TB_Node* dst, TB_Node* val, TB_Node* count, TB_CharUnits align, bool is_volatile); + // performs a copy of 'count' elements from one memory location to another // both locations cannot overlap. TB_API void tb_inst_memcpy(TB_Function* f, TB_Node* dst, TB_Node* src, TB_Node* count, TB_CharUnits align, bool is_volatile); @@ -1052,13 +1046,15 @@ TB_API TB_FuncOpt* tb_funcopt_enter(TB_Function* f, TB_Arena* arena); TB_API void tb_funcopt_exit(TB_FuncOpt* opt); TB_API bool tb_funcopt_peephole(TB_FuncOpt* opt); -TB_API bool tb_funcopt_mem2reg(TB_FuncOpt* f); -TB_API bool tb_funcopt_loop(TB_FuncOpt* f); +TB_API bool tb_funcopt_mem2reg(TB_FuncOpt* opt); +TB_API bool tb_funcopt_loop(TB_FuncOpt* opt); -TB_API void tb_funcopt_kill(TB_FuncOpt* restrict queue, TB_Node* n); +// isn't an optimization, just does the name flat form of IR printing +TB_API bool tb_funcopt_print(TB_FuncOpt* opt); -TB_API bool tb_funcopt_mark(TB_FuncOpt* restrict queue, TB_Node* n); -TB_API void tb_funcopt_mark_users(TB_FuncOpt* restrict queue, TB_Node* n); +TB_API void tb_funcopt_kill(TB_FuncOpt* opt, TB_Node* n); +TB_API bool tb_funcopt_mark(TB_FuncOpt* opt, TB_Node* n); +TB_API void tb_funcopt_mark_users(TB_FuncOpt* opt, TB_Node* n); //////////////////////////////// // IR access diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index a1f893968..a6ac5cbff 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index d695c846c..0572e2fd0 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -184,7 +184,7 @@ gb_internal void cg_create_global_variables(cgModule *m) { // gb_printf_err("max_type_info_count: %td\n", max_type_info_count); Type *t = alloc_type_array(t_type_info, max_type_info_count); - TB_Global *g = tb_global_create(m->mod, CG_TYPE_INFO_DATA_NAME, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, CG_TYPE_INFO_DATA_NAME, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, max_type_info_count); cgValue value = cg_value(g, alloc_type_pointer(t)); @@ -219,7 +219,7 @@ gb_internal void cg_create_global_variables(cgModule *m) { { char const *name = CG_TYPE_INFO_TYPES_NAME; Type *t = alloc_type_array(t_type_info_ptr, count); - TB_Global *g = tb_global_create(m->mod, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); cg_global_type_info_member_types = cg_addr(cg_value(g, alloc_type_pointer(t))); @@ -227,14 +227,14 @@ gb_internal void cg_create_global_variables(cgModule *m) { { char const *name = CG_TYPE_INFO_NAMES_NAME; Type *t = alloc_type_array(t_string, count); - TB_Global *g = tb_global_create(m->mod, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); cg_global_type_info_member_names = cg_addr(cg_value(g, alloc_type_pointer(t))); } { char const *name = CG_TYPE_INFO_OFFSETS_NAME; Type *t = alloc_type_array(t_uintptr, count); - TB_Global *g = tb_global_create(m->mod, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); cg_global_type_info_member_offsets = cg_addr(cg_value(g, alloc_type_pointer(t))); } @@ -242,7 +242,7 @@ gb_internal void cg_create_global_variables(cgModule *m) { { char const *name = CG_TYPE_INFO_USINGS_NAME; Type *t = alloc_type_array(t_bool, count); - TB_Global *g = tb_global_create(m->mod, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); cg_global_type_info_member_usings = cg_addr(cg_value(g, alloc_type_pointer(t))); } @@ -250,7 +250,7 @@ gb_internal void cg_create_global_variables(cgModule *m) { { char const *name = CG_TYPE_INFO_TAGS_NAME; Type *t = alloc_type_array(t_string, count); - TB_Global *g = tb_global_create(m->mod, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *g = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, count); cg_global_type_info_member_tags = cg_addr(cg_value(g, alloc_type_pointer(t))); } @@ -268,7 +268,7 @@ cgModule *cg_module_create(Checker *c) { TB_FeatureSet feature_set = {}; bool is_jit = false; m->mod = tb_module_create(TB_ARCH_X86_64, TB_SYSTEM_WINDOWS, &feature_set, is_jit); - tb_module_set_tls_index(m->mod, "_tls_index"); + tb_module_set_tls_index(m->mod, 10, "_tls_index"); map_init(&m->values); array_init(&m->procedures_to_generate, heap_allocator()); @@ -634,8 +634,6 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i // p->scope_stack.allocator = a; // map_init(&p->tuple_fix_map, 0); - char const *link_name_c = alloc_cstring(temporary_allocator(), link_name); - TB_Linkage linkage = TB_LINKAGE_PRIVATE; if (p->is_export) { linkage = TB_LINKAGE_PUBLIC; @@ -643,11 +641,11 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i if (ignore_body) { linkage = TB_LINKAGE_PUBLIC; } - p->symbol = cast(TB_Symbol *)tb_extern_create(m->mod, link_name_c, TB_EXTERNAL_SO_LOCAL); + p->symbol = cast(TB_Symbol *)tb_extern_create(m->mod, link_name.len, cast(char const *)link_name.text, TB_EXTERNAL_SO_LOCAL); } if (p->symbol == nullptr) { - p->func = tb_function_create(m->mod, link_name_c, linkage, TB_COMDAT_NONE); + p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); p->symbol = cast(TB_Symbol *)p->func; } @@ -688,12 +686,9 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li // map_init(&p->tuple_fix_map, 0); - - char const *link_name_c = alloc_cstring(temporary_allocator(), link_name); - TB_Linkage linkage = TB_LINKAGE_PRIVATE; - p->func = tb_function_create(m->mod, link_name_c, linkage, TB_COMDAT_NONE); + p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); p->symbol = cast(TB_Symbol *)p->func; @@ -715,6 +710,13 @@ gb_internal void cg_procedure_end(cgProcedure *p) { return; } tb_inst_ret(p->func, 0, nullptr); + if (p->name == "main") { + TB_Arena *arena = tb_default_arena(); + defer (arena->free(arena)); + TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); + defer (tb_funcopt_exit(opt)); + tb_funcopt_print(opt); + } tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST); } diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 44591190a..6c17f8ba3 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -212,4 +212,6 @@ gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero_init); -gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); \ No newline at end of file +gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); + +gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e); \ No newline at end of file diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 7a8be70c7..97fee838e 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -8,7 +8,7 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { TB_Module *m = p->module->mod; char name[32] = {}; gb_snprintf(name, 31, "cnil$%u", 1+p->module->const_nil_guid.fetch_add(1)); - TB_Global *global = tb_global_create(m, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *global = tb_global_create(m, -1, name, nullptr, TB_LINKAGE_PRIVATE); tb_global_set_storage(m, tb_module_get_rdata(m), global, size, align, 0); TB_Symbol *symbol = cast(TB_Symbol *)global; @@ -41,6 +41,18 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac return cg_const_nil(p, type); } + if (value.kind == ExactValue_Procedure) { + Ast *expr = unparen_expr(value.value_procedure); + Entity *e = entity_of_node(expr); + if (e != nullptr) { + cgValue found = cg_find_procedure_value_from_entity(m, e); + GB_ASSERT(are_types_identical(type, found.type)); + return found; + } + + } + + GB_ASSERT(node != nullptr); return cg_value(node, type); } diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index ccd126747..702cb42ad 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -101,7 +101,7 @@ gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { cgValue res = cg_build_expr_internal(p, expr); if (res.kind == cgValue_Symbol) { - GB_ASSERT(is_type_pointer(res.type)); + GB_ASSERT(is_type_internally_pointer_like(res.type)); res = cg_value(tb_inst_get_symbol_address(p->func, res.symbol), res.type); } @@ -161,6 +161,7 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { token_pos_to_string(token.pos)); return {}; } else if (e->kind == Entity_Nil) { + GB_PANIC("TODO: cg_find_ident nil"); // TODO(bill): is this correct? return cg_value(cast(TB_Node *)nullptr, e->type); } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 306852db3..dbebae853 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -1,5 +1,127 @@ +gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e) { + GB_ASSERT(is_type_proc(e->type)); + e = strip_entity_wrapping(e); + GB_ASSERT(e != nullptr); + GB_ASSERT(e->kind == Entity_Procedure); + + cgValue *found = nullptr; + rw_mutex_shared_lock(&m->values_mutex); + found = map_get(&m->values, e); + rw_mutex_shared_unlock(&m->values_mutex); + if (found) { + return *found; + } + + GB_PANIC("Error in: %s, missing procedure %.*s\n", token_pos_to_string(e->token.pos), LIT(e->token.string)); + return {}; +} + + + +gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr) { + expr = unparen_expr(expr); ast_node(ce, CallExpr, expr); - // TODO(bill): cg_build_call_expr + + cgValue res = cg_build_call_expr_internal(p, expr); + + if (ce->optional_ok_one) { // TODO(bill): Minor hack for #optional_ok procedures + GB_PANIC("Handle optional_ok_one"); + // GB_ASSERT(is_type_tuple(res.type)); + // GB_ASSERT(res.type->Tuple.variables.count == 2); + // return cg_emit_struct_ev(p, res, 0); + } + return res; +} + +gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice args) { + if (value.kind == cgValue_Symbol) { + value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), value.type); + } + GB_ASSERT(value.kind == cgValue_Value); + + TB_FunctionPrototype *proto = cg_procedure_type_as_prototype(p->module, value.type); + TB_Node *target = value.node; + auto params = slice_make(temporary_allocator(), 0); + + GB_ASSERT(target != nullptr); + TB_MultiOutput multi_output = tb_inst_call(p->func, proto, target, 0, nullptr); + gb_unused(multi_output); return {}; -} \ No newline at end of file +} + +gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { + ast_node(ce, CallExpr, expr); + + TypeAndValue tv = type_and_value_of_expr(expr); + + TypeAndValue proc_tv = type_and_value_of_expr(ce->proc); + AddressingMode proc_mode = proc_tv.mode; + if (proc_mode == Addressing_Type) { + GB_ASSERT(ce->args.count == 1); + cgValue x = cg_build_expr(p, ce->args[0]); + return cg_emit_conv(p, x, tv.type); + } + + Ast *proc_expr = unparen_expr(ce->proc); + if (proc_mode == Addressing_Builtin) { + Entity *e = entity_of_node(proc_expr); + BuiltinProcId id = BuiltinProc_Invalid; + if (e != nullptr) { + id = cast(BuiltinProcId)e->Builtin.id; + } else { + id = BuiltinProc_DIRECTIVE; + } + if (id == BuiltinProc___entry_point) { + if (p->module->info->entry_point) { + cgValue entry_point = cg_find_procedure_value_from_entity(p->module, p->module->info->entry_point); + GB_ASSERT(entry_point.node != nullptr); + cg_emit_call(p, entry_point, {}); + } + return {}; + } + GB_PANIC("TODO(bill): builtin procs %d %.*s", id, LIT(builtin_procs[id].name)); + } + + // NOTE(bill): Regular call + cgValue value = {}; + + Entity *proc_entity = entity_of_node(proc_expr); + if (proc_entity != nullptr) { + if (proc_entity->flags & EntityFlag_Disabled) { + GB_ASSERT(tv.type == nullptr); + return {}; + } + } + + if (proc_expr->tav.mode == Addressing_Constant) { + ExactValue v = proc_expr->tav.value; + switch (v.kind) { + case ExactValue_Integer: + { + u64 u = big_int_to_u64(&v.value_integer); + cgValue x = cg_value(tb_inst_uint(p->func, TB_TYPE_PTR, u), t_rawptr); + value = cg_emit_conv(p, x, proc_expr->tav.type); + break; + } + case ExactValue_Pointer: + { + u64 u = cast(u64)v.value_pointer; + cgValue x = cg_value(tb_inst_uint(p->func, TB_TYPE_PTR, u), t_rawptr); + value = cg_emit_conv(p, x, proc_expr->tav.type); + break; + } + } + } + + if (value.node == nullptr) { + value = cg_build_expr(p, proc_expr); + } + if (value.kind == cgValue_Addr) { + value = cg_emit_load(p, value); + } + GB_ASSERT(value.kind == cgValue_Value); + GB_ASSERT(is_type_proc(value.type)); + + return cg_emit_call(p, value, {}); +} diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index f7e68d483..07bfc0555 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -8,14 +8,16 @@ gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_vol case cgValue_Value: return cg_lvalue_addr(ptr.node, type); case cgValue_Addr: - GB_PANIC("NOT POSSIBLE"); + GB_PANIC("NOT POSSIBLE - Cannot load an lvalue to begin with"); break; case cgValue_Symbol: return cg_lvalue_addr(tb_inst_get_symbol_address(p->func, ptr.symbol), type); } } - TB_CharUnits alignment = 1; // for the time being + // use the natural alignment + // if people need a special alignment, they can use `intrinsics.unaligned_load` + TB_CharUnits alignment = cast(TB_CharUnits)type_align_of(type); TB_Node *the_ptr = nullptr; switch (ptr.kind) { @@ -48,7 +50,9 @@ gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, TB_DataType st = cg_data_type(src.type); GB_ASSERT(dt.raw == st.raw); - TB_CharUnits alignment = 1; // for the time being + // use the natural alignment + // if people need a special alignment, they can use `intrinsics.unaligned_store` + TB_CharUnits alignment = cast(TB_CharUnits)type_align_of(dst_type); if (TB_IS_VOID_TYPE(dt)) { TB_Node *dst_ptr = nullptr; @@ -281,10 +285,9 @@ gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { // NOTE(bill): for debugging purposes only - char const *name = alloc_cstring(permanent_allocator(), e->token.string); - - TB_DebugType *debug_type = cg_debug_type(p->module, type); - tb_function_attrib_variable(p->func, local, name, debug_type); + // String name = e->token.string; + // TB_DebugType *debug_type = cg_debug_type(p->module, type); + // tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type); } if (zero_init) { @@ -546,7 +549,7 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { case_end; case_ast_node(as, AssignStmt, node); - cg_build_assign_stmt(p, as); + // cg_build_assign_stmt(p, as); case_end; case_ast_node(rs, ReturnStmt, node); -- cgit v1.2.3 From ee8372145d62bf90c0fe43c78b96a02b6247321e Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 15 Jul 2023 14:26:47 +0100 Subject: Begin working on proper expressions --- src/tilde/tb.lib | Bin 4120106 -> 4112646 bytes src/tilde_backend.cpp | 178 ++++++++++++++++++++++++--------- src/tilde_backend.hpp | 11 ++- src/tilde_const.cpp | 97 ++++++++++++++---- src/tilde_expr.cpp | 265 ++++++++++++++++++++++++++++++++++++++++++++++++-- src/tilde_proc.cpp | 84 +++++++++++++++- src/tilde_stmt.cpp | 75 ++++++++++++-- 7 files changed, 630 insertions(+), 80 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index a6ac5cbff..bad51e7e6 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index 97f92e3db..dfe39c385 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -33,7 +33,7 @@ gb_internal TB_DataType cg_data_type(Type *t) { case Basic_typeid: return TB_TYPE_INTN(cast(u16)(8*sz)); - case Basic_f16: return TB_TYPE_I16; + case Basic_f16: return TB_TYPE_F16; case Basic_f32: return TB_TYPE_F32; case Basic_f64: return TB_TYPE_F64; @@ -60,11 +60,11 @@ gb_internal TB_DataType cg_data_type(Type *t) { case Basic_u128be: return TB_TYPE_INTN(cast(u16)(8*sz)); - case Basic_f16le: return TB_TYPE_I16; + case Basic_f16le: return TB_TYPE_F16; case Basic_f32le: return TB_TYPE_F32; case Basic_f64le: return TB_TYPE_F64; - case Basic_f16be: return TB_TYPE_I16; + case Basic_f16be: return TB_TYPE_F16; case Basic_f32be: return TB_TYPE_F32; case Basic_f64be: return TB_TYPE_F64; } @@ -173,9 +173,128 @@ gb_internal isize cg_type_info_index(CheckerInfo *info, Type *type, bool err_on_ return -1; } -gb_internal void cg_create_global_variables(cgModule *m) { +struct cgGlobalVariable { + cgValue var; + cgValue init; + DeclInfo *decl; + bool is_initialized; +}; + +// Returns already_has_entry_point +gb_internal bool cg_global_variables_create(cgModule *m) { + isize global_variable_max_count = 0; + bool already_has_entry_point = false; + + for (Entity *e : m->info->entities) { + String name = e->token.string; + + if (e->kind == Entity_Variable) { + global_variable_max_count++; + } else if (e->kind == Entity_Procedure) { + if ((e->scope->flags&ScopeFlag_Init) && name == "main") { + GB_ASSERT(e == m->info->entry_point); + } + if (build_context.command_kind == Command_test && + (e->Procedure.is_export || e->Procedure.link_name.len > 0)) { + String link_name = e->Procedure.link_name; + if (e->pkg->kind == Package_Runtime) { + if (link_name == "main" || + link_name == "DllMain" || + link_name == "WinMain" || + link_name == "wWinMain" || + link_name == "mainCRTStartup" || + link_name == "_start") { + already_has_entry_point = true; + } + } + } + } + } + auto global_variables = array_make(permanent_allocator(), 0, global_variable_max_count); + + auto *min_dep_set = &m->info->minimum_dependency_set; + + for (DeclInfo *d : m->info->variable_init_order) { + Entity *e = d->entity; + + if ((e->scope->flags & ScopeFlag_File) == 0) { + continue; + } + + if (!ptr_set_exists(min_dep_set, e)) { + continue; + } + + DeclInfo *decl = decl_info_of_entity(e); + if (decl == nullptr) { + continue; + } + GB_ASSERT(e->kind == Entity_Variable); + + bool is_foreign = e->Variable.is_foreign; + bool is_export = e->Variable.is_export; + + String name = cg_get_entity_name(m, e); + + TB_Linkage linkage = TB_LINKAGE_PRIVATE; + + if (is_foreign) { + linkage = TB_LINKAGE_PUBLIC; + // lb_add_foreign_library_path(m, e->Variable.foreign_library); + // lb_set_wasm_import_attributes(g.value, e, name); + } else if (is_export) { + linkage = TB_LINKAGE_PUBLIC; + } + // lb_set_linkage_from_entity_flags(m, g.value, e->flags); + + TB_DebugType *debug_type = cg_debug_type(m, e->type); + TB_Global *global = tb_global_create(m->mod, name.len, cast(char const *)name.text, debug_type, linkage); + cgValue g = cg_value(global, alloc_type_pointer(e->type)); + + TB_ModuleSection *section = tb_module_get_data(m->mod); + + if (e->Variable.thread_local_model != "") { + section = tb_module_get_tls(m->mod); + } + if (e->Variable.link_section.len > 0) { + // TODO(bill): custom module sections + // LLVMSetSection(g.value, alloc_cstring(permanent_allocator(), e->Variable.link_section)); + } + + size_t max_objects = 0; + tb_global_set_storage(m->mod, section, global, type_size_of(e->type), type_align_of(e->type), max_objects); + + cgGlobalVariable var = {}; + var.var = g; + var.decl = decl; + + if (decl->init_expr != nullptr) { + // TypeAndValue tav = type_and_value_of_expr(decl->init_expr); + // if (!is_type_any(e->type) && !is_type_union(e->type)) { + // if (tav.mode != Addressing_Invalid) { + // if (tav.value.kind != ExactValue_Invalid) { + // ExactValue v = tav.value; + // lbValue init = lb_const_value(m, tav.type, v); + // LLVMSetInitializer(g.value, init.value); + // var.is_initialized = true; + // } + // } + // } + // if (!var.is_initialized && is_type_untyped_nil(tav.type)) { + // var.is_initialized = true; + // } + } + + array_add(&global_variables, var); + + cg_add_entity(m, e, g); + cg_add_member(m, name, g); + } + + + if (build_context.no_rtti) { - return; + return already_has_entry_point; } CheckerInfo *info = m->info; @@ -256,9 +375,11 @@ gb_internal void cg_create_global_variables(cgModule *m) { } } } + + return already_has_entry_point; } -cgModule *cg_module_create(Checker *c) { +gb_internal cgModule *cg_module_create(Checker *c) { cgModule *m = gb_alloc_item(permanent_allocator(), cgModule); m->checker = c; @@ -286,7 +407,7 @@ cgModule *cg_module_create(Checker *c) { return m; } -void cg_module_destroy(cgModule *m) { +gb_internal void cg_module_destroy(cgModule *m) { map_destroy(&m->values); array_free(&m->procedures_to_generate); map_destroy(&m->file_id_map); @@ -391,7 +512,7 @@ gb_internal String cg_mangle_name(cgModule *m, Entity *e) { return mangled_name; } -String cg_get_entity_name(cgModule *m, Entity *e) { +gb_internal String cg_get_entity_name(cgModule *m, Entity *e) { if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) { return e->TypeName.ir_mangled_name; } @@ -438,14 +559,6 @@ String cg_get_entity_name(cgModule *m, Entity *e) { return name; } - -struct cgGlobalVariable { - cgValue var; - cgValue init; - DeclInfo *decl; - bool is_initialized; -}; - #include "tilde_const.cpp" #include "tilde_expr.cpp" #include "tilde_proc.cpp" @@ -463,37 +576,8 @@ gb_internal bool cg_generate_code(Checker *c) { TIME_SECTION("Tilde Global Variables"); - cg_create_global_variables(m); - - // isize global_variable_max_count = 0; - // bool already_has_entry_point = false; - - // for (Entity *e : info->entities) { - // String name = e->token.string; - - // if (e->kind == Entity_Variable) { - // global_variable_max_count++; - // } else if (e->kind == Entity_Procedure) { - // if ((e->scope->flags&ScopeFlag_Init) && name == "main") { - // GB_ASSERT(e == info->entry_point); - // } - // if (build_context.command_kind == Command_test && - // (e->Procedure.is_export || e->Procedure.link_name.len > 0)) { - // String link_name = e->Procedure.link_name; - // if (e->pkg->kind == Package_Runtime) { - // if (link_name == "main" || - // link_name == "DllMain" || - // link_name == "WinMain" || - // link_name == "wWinMain" || - // link_name == "mainCRTStartup" || - // link_name == "_start") { - // already_has_entry_point = true; - // } - // } - // } - // } - // } - // auto global_variables = array_make(permanent_allocator(), 0, global_variable_max_count); + bool already_has_entry_point = cg_global_variables_create(m); + gb_unused(already_has_entry_point); if (true) { Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin); diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 1f7300d73..228afb6af 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -7,6 +7,7 @@ #include "tilde/tb.h" +#define TB_TYPE_F16 TB_DataType{ { TB_INT, 0, 16 } } #define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } #define TB_TYPE_INT TB_TYPE_INTN(cast(u16)build_context.int_size) #define TB_TYPE_INTPTR TB_TYPE_INTN(cast(u16)build_context.ptr_size) @@ -127,6 +128,7 @@ struct cgProcedure { Array children; TB_Function *func; + TB_FunctionPrototype *proto; TB_Symbol *symbol; Entity * entity; @@ -151,9 +153,12 @@ struct cgProcedure { Scope *curr_scope; i32 scope_index; + bool in_multi_assignment; Array scope_stack; Array context_stack; + + PtrMap variable_map; }; @@ -226,4 +231,8 @@ gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e); -gb_internal TB_DebugType *cg_debug_type(cgModule *m, Type *type); \ No newline at end of file +gb_internal TB_DebugType *cg_debug_type(cgModule *m, Type *type); + +gb_internal String cg_get_entity_name(cgModule *m, Entity *e); + +gb_internal cgValue cg_typeid(cgModule *m, Type *t); \ No newline at end of file diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 97fee838e..35c87641f 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -1,19 +1,31 @@ -gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { +gb_internal bool cg_is_expr_constant_zero(Ast *expr) { + GB_ASSERT(expr != nullptr); + auto v = exact_value_to_integer(expr->tav.value); + if (v.kind == ExactValue_Integer) { + return big_int_cmp_zero(&v.value_integer) == 0; + } + return false; +} + +gb_internal cgValue cg_const_nil(cgModule *m, cgProcedure *p, Type *type) { Type *original_type = type; type = core_type(type); i64 size = type_size_of(type); i64 align = type_align_of(type); TB_DataType dt = cg_data_type(type); if (TB_IS_VOID_TYPE(dt)) { - TB_Module *m = p->module->mod; char name[32] = {}; - gb_snprintf(name, 31, "cnil$%u", 1+p->module->const_nil_guid.fetch_add(1)); - TB_Global *global = tb_global_create(m, -1, name, nullptr, TB_LINKAGE_PRIVATE); - tb_global_set_storage(m, tb_module_get_rdata(m), global, size, align, 0); + gb_snprintf(name, 31, "cnil$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *global = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, size, align, 0); TB_Symbol *symbol = cast(TB_Symbol *)global; - TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); - return cg_lvalue_addr(node, type); + if (p) { + TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); + return cg_lvalue_addr(node, type); + } else { + GB_PANIC("TODO(bill): cg_const_nil"); + } } if (is_type_internally_pointer_like(type)) { @@ -34,24 +46,71 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { return {}; } -gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value) { +gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { + return cg_const_nil(p->module, p, type); +} + +gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value, bool allow_local = true) { TB_Node *node = nullptr; - if (value.kind == ExactValue_Invalid) { + bool is_local = allow_local && p != nullptr; + gb_unused(is_local); + + TB_DataType dt = cg_data_type(type); + + switch (value.kind) { + case ExactValue_Invalid: return cg_const_nil(p, type); + + case ExactValue_Typeid: + return cg_typeid(m, value.value_typeid); + + case ExactValue_Procedure: + { + Ast *expr = unparen_expr(value.value_procedure); + Entity *e = entity_of_node(expr); + if (e != nullptr) { + cgValue found = cg_find_procedure_value_from_entity(m, e); + GB_ASSERT(are_types_identical(type, found.type)); + return found; + } + GB_PANIC("TODO(bill): cg_const_value ExactValue_Procedure"); + } + break; } - if (value.kind == ExactValue_Procedure) { - Ast *expr = unparen_expr(value.value_procedure); - Entity *e = entity_of_node(expr); - if (e != nullptr) { - cgValue found = cg_find_procedure_value_from_entity(m, e); - GB_ASSERT(are_types_identical(type, found.type)); - return found; + GB_ASSERT(!TB_IS_VOID_TYPE(dt)); + + switch (value.kind) { + case ExactValue_Bool: + return cg_value(tb_inst_uint(p->func, dt, value.value_bool), type); + + case ExactValue_Integer: + GB_ASSERT(dt.raw != TB_TYPE_I128.raw); + if (is_type_unsigned(type)) { + u64 i = exact_value_to_u64(value); + return cg_value(tb_inst_uint(p->func, dt, i), type); + } else { + i64 i = exact_value_to_i64(value); + return cg_value(tb_inst_sint(p->func, dt, i), type); } + break; + case ExactValue_Float: + GB_ASSERT(dt.raw != TB_TYPE_F16.raw); + GB_ASSERT(!is_type_different_to_arch_endianness(type)); + { + f64 f = exact_value_to_f64(value); + if (type_size_of(type) == 8) { + return cg_value(tb_inst_float64(p->func, f), type); + } else { + return cg_value(tb_inst_float32(p->func, cast(f32)f), type); + } + } + break; } + GB_ASSERT(node != nullptr); return cg_value(node, type); } @@ -59,4 +118,8 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value) { GB_ASSERT(p != nullptr); return cg_const_value(p->module, p, type, value); -} \ No newline at end of file +} + +gb_internal cgValue cg_const_int(cgProcedure *p, Type *type, i64 i) { + return cg_const_value(p, type, exact_value_i64(i)); +} diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 22da43cbd..fc22e12d9 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1,3 +1,11 @@ +gb_internal cgValue cg_flatten_value(cgProcedure *p, cgValue value) { + if (value.kind == cgValue_Symbol) { + GB_ASSERT(is_type_internally_pointer_like(value.type)); + value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), value.type); + } + return value; +} + gb_internal cgContextData *cg_push_context_onto_stack(cgProcedure *p, cgAddr ctx) { ctx.kind = cgAddr_Context; cgContextData *cd = array_add_and_get(&p->context_stack); @@ -43,7 +51,7 @@ gb_internal cgValue cg_find_value_from_entity(cgModule *m, Entity *e) { return *found; } - // GB_PANIC("\n\tError in: %s, missing value '%.*s'\n", token_pos_to_string(e->token.pos), LIT(e->token.string)); + GB_PANIC("\n\tError in: %s, missing value '%.*s'\n", token_pos_to_string(e->token.pos), LIT(e->token.string)); return {}; } @@ -57,6 +65,10 @@ gb_internal cgAddr cg_build_addr_from_entity(cgProcedure *p, Entity *e, Ast *exp return {}; } + cgAddr *local_found = map_get(&p->variable_map, e); + if (local_found) { + return *local_found; + } cgValue v = {}; @@ -78,7 +90,9 @@ gb_internal cgAddr cg_build_addr_from_entity(cgProcedure *p, Entity *e, Ast *exp if (v.node == nullptr) { - return cg_addr(cg_find_value_from_entity(m, e)); + cgValue v = cg_find_value_from_entity(m, e); + v = cg_flatten_value(p, v); + return cg_addr(v); } return cg_addr(v); @@ -90,6 +104,17 @@ gb_internal cgValue cg_typeid(cgModule *m, Type *t) { } +gb_internal cgValue cg_correct_endianness(cgProcedure *p, cgValue value) { + Type *src = core_type(value.type); + GB_ASSERT(is_type_integer(src) || is_type_float(src)); + if (is_type_different_to_arch_endianness(src)) { + GB_PANIC("TODO(bill): cg_correct_endianness"); + // Type *platform_src_type = integer_endian_type_to_platform_type(src); + // value = cg_emit_byte_swap(p, value, platform_src_type); + } + return value; +} + gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *type) { // TODO(bill): cg_emit_conv return value; @@ -98,10 +123,7 @@ gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *type) { gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) { GB_ASSERT(type_size_of(value.type) == type_size_of(type)); - if (value.kind == cgValue_Symbol) { - GB_ASSERT(is_type_pointer(value.type)); - value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), type); - } + value = cg_flatten_value(p, value); i64 src_align = type_align_of(value.type); i64 dst_align = type_align_of(type); @@ -133,6 +155,217 @@ gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) } +gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { + ast_node(se, SliceExpr, expr); + + cgValue low = cg_const_int(p, t_int, 0); + cgValue high = {}; + + if (se->low != nullptr) { + low = cg_correct_endianness(p, cg_build_expr(p, se->low)); + } + if (se->high != nullptr) { + high = cg_correct_endianness(p, cg_build_expr(p, se->high)); + } + + bool no_indices = se->low == nullptr && se->high == nullptr; + gb_unused(no_indices); + + cgAddr addr = cg_build_addr(p, se->expr); + cgValue base = cg_addr_load(p, addr); + Type *type = base_type(base.type); + + if (is_type_pointer(type)) { + type = base_type(type_deref(type)); + addr = cg_addr(base); + base = cg_addr_load(p, addr); + } + + switch (type->kind) { + case Type_Slice: { + // Type *slice_type = type; + // cgValue len = cg_slice_len(p, base); + // if (high.value == nullptr) high = len; + + // if (!no_indices) { + // cg_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + // } + + // cgValue elem = cg_emit_ptr_offset(p, cg_slice_elem(p, base), low); + // cgValue new_len = cg_emit_arith(p, Token_Sub, high, low, t_int); + + // cgAddr slice = cg_add_local_generated(p, slice_type, false); + // cg_fill_slice(p, slice, elem, new_len); + // return slice; + GB_PANIC("cg_build_addr_slice_expr Type_Slice"); + break; + } + + case Type_RelativeSlice: + GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the cg_addr_load"); + break; + + case Type_DynamicArray: { + // Type *elem_type = type->DynamicArray.elem; + // Type *slice_type = alloc_type_slice(elem_type); + + // lbValue len = lb_dynamic_array_len(p, base); + // if (high.value == nullptr) high = len; + + // if (!no_indices) { + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + // } + + // lbValue elem = lb_emit_ptr_offset(p, lb_dynamic_array_elem(p, base), low); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + + // lbAddr slice = lb_add_local_generated(p, slice_type, false); + // lb_fill_slice(p, slice, elem, new_len); + // return slice; + GB_PANIC("cg_build_addr_slice_expr Type_DynamicArray"); + break; + } + + case Type_MultiPointer: { + // lbAddr res = lb_add_local_generated(p, type_of_expr(expr), false); + // if (se->high == nullptr) { + // lbValue offset = base; + // LLVMValueRef indices[1] = {low.value}; + // offset.value = LLVMBuildGEP2(p->builder, lb_type(p->module, offset.type->MultiPointer.elem), offset.value, indices, 1, ""); + // lb_addr_store(p, res, offset); + // } else { + // low = lb_emit_conv(p, low, t_int); + // high = lb_emit_conv(p, high, t_int); + + // lb_emit_multi_pointer_slice_bounds_check(p, se->open, low, high); + + // LLVMValueRef indices[1] = {low.value}; + // LLVMValueRef ptr = LLVMBuildGEP2(p->builder, lb_type(p->module, base.type->MultiPointer.elem), base.value, indices, 1, ""); + // LLVMValueRef len = LLVMBuildSub(p->builder, high.value, low.value, ""); + + // LLVMValueRef gep0 = lb_emit_struct_ep(p, res.addr, 0).value; + // LLVMValueRef gep1 = lb_emit_struct_ep(p, res.addr, 1).value; + // LLVMBuildStore(p->builder, ptr, gep0); + // LLVMBuildStore(p->builder, len, gep1); + // } + // return res; + GB_PANIC("cg_build_addr_slice_expr Type_MultiPointer"); + break; + } + + case Type_Array: { + // Type *slice_type = alloc_type_slice(type->Array.elem); + // lbValue len = lb_const_int(p->module, t_int, type->Array.count); + + // if (high.value == nullptr) high = len; + + // bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant; + // bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant; + + // if (!low_const || !high_const) { + // if (!no_indices) { + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + // } + // } + // lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + + // lbAddr slice = lb_add_local_generated(p, slice_type, false); + // lb_fill_slice(p, slice, elem, new_len); + // return slice; + GB_PANIC("cg_build_addr_slice_expr Type_Array"); + break; + } + + case Type_Basic: { + // GB_ASSERT(type == t_string); + // lbValue len = lb_string_len(p, base); + // if (high.value == nullptr) high = len; + + // if (!no_indices) { + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + // } + + // lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + + // lbAddr str = lb_add_local_generated(p, t_string, false); + // lb_fill_string(p, str, elem, new_len); + // return str; + GB_PANIC("cg_build_addr_slice_expr Type_Basic"); + break; + } + + + case Type_Struct: + // if (is_type_soa_struct(type)) { + // lbValue len = lb_soa_struct_len(p, lb_addr_get_ptr(p, addr)); + // if (high.value == nullptr) high = len; + + // if (!no_indices) { + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + // } + // #if 1 + + // lbAddr dst = lb_add_local_generated(p, type_of_expr(expr), true); + // if (type->Struct.soa_kind == StructSoa_Fixed) { + // i32 field_count = cast(i32)type->Struct.fields.count; + // for (i32 i = 0; i < field_count; i++) { + // lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i); + // lbValue field_src = lb_emit_struct_ep(p, lb_addr_get_ptr(p, addr), i); + // field_src = lb_emit_array_ep(p, field_src, low); + // lb_emit_store(p, field_dst, field_src); + // } + + // lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + // lb_emit_store(p, len_dst, new_len); + // } else if (type->Struct.soa_kind == StructSoa_Slice) { + // if (no_indices) { + // lb_addr_store(p, dst, base); + // } else { + // i32 field_count = cast(i32)type->Struct.fields.count - 1; + // for (i32 i = 0; i < field_count; i++) { + // lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i); + // lbValue field_src = lb_emit_struct_ev(p, base, i); + // field_src = lb_emit_ptr_offset(p, field_src, low); + // lb_emit_store(p, field_dst, field_src); + // } + + + // lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + // lb_emit_store(p, len_dst, new_len); + // } + // } else if (type->Struct.soa_kind == StructSoa_Dynamic) { + // i32 field_count = cast(i32)type->Struct.fields.count - 3; + // for (i32 i = 0; i < field_count; i++) { + // lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i); + // lbValue field_src = lb_emit_struct_ev(p, base, i); + // field_src = lb_emit_ptr_offset(p, field_src, low); + // lb_emit_store(p, field_dst, field_src); + // } + + + // lbValue len_dst = lb_emit_struct_ep(p, dst.addr, field_count); + // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + // lb_emit_store(p, len_dst, new_len); + // } + + // return dst; + // #endif + // } + GB_PANIC("cg_build_addr_slice_expr Type_Struct"); + break; + + } + + GB_PANIC("Unknown slicable type"); + return {}; +} + + + gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { @@ -252,6 +485,11 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { return cg_value(cast(TB_Node *)nullptr, e->type); } GB_ASSERT(e->kind != Entity_ProcGroup); + + cgAddr *addr = map_get(&p->variable_map, e); + if (addr) { + return cg_addr_load(p, *addr); + } // return cg_find_ident(p, m, e, expr); GB_PANIC("TODO: cg_find_ident"); return {}; @@ -327,6 +565,17 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { cgValue value = cg_build_expr(p, ac->expr); return cg_emit_conv(p, value, type); case_end; + + case_ast_node(se, SliceExpr, expr); + if (is_type_slice(type_of_expr(se->expr))) { + // NOTE(bill): Quick optimization + if (se->high == nullptr && + (se->low == nullptr || cg_is_expr_constant_zero(se->low))) { + return cg_build_expr(p, se->expr); + } + } + return cg_addr_load(p, cg_build_addr(p, expr)); + case_end; } GB_PANIC("TODO(bill): cg_build_expr_internal %.*s", LIT(ast_strings[expr->kind])); return {}; @@ -384,6 +633,10 @@ gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { Entity *e = entity_of_node(expr); return cg_build_addr_from_entity(p, e, expr); case_end; + + case_ast_node(se, SliceExpr, expr); + return cg_build_addr_slice_expr(p, expr); + case_end; } TokenPos token_pos = ast_token(expr).pos; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index b60e797c3..99b70a6a8 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -113,7 +113,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty } } - if (param.dt.width != 0) { + if (param.dt.raw != 0) { if (is_blank_ident(e->token)) { param.name = alloc_cstring(temporary_allocator(), e->token.string); } @@ -183,6 +183,7 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i // p->branch_blocks.allocator = a; p->context_stack.allocator = a; p->scope_stack.allocator = a; + map_init(&p->variable_map); // map_init(&p->tuple_fix_map, 0); TB_Linkage linkage = TB_LINKAGE_PRIVATE; @@ -196,8 +197,10 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i } if (p->symbol == nullptr) { + TB_Arena *arena = tb_default_arena(); p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); + p->proto = cg_procedure_type_as_prototype(m, p->type); + tb_function_set_prototype(p->func, p->proto, arena); p->symbol = cast(TB_Symbol *)p->func; } @@ -235,13 +238,16 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li // p->branch_blocks.allocator = a; p->scope_stack.allocator = a; p->context_stack.allocator = a; + map_init(&p->variable_map); // map_init(&p->tuple_fix_map, 0); TB_Linkage linkage = TB_LINKAGE_PRIVATE; + TB_Arena *arena = tb_default_arena(); p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - tb_function_set_prototype(p->func, cg_procedure_type_as_prototype(m, p->type), tb_default_arena()); + p->proto = cg_procedure_type_as_prototype(m, p->type); + tb_function_set_prototype(p->func, p->proto, arena); p->symbol = cast(TB_Symbol *)p->func; cgValue proc_value = cg_value(p->symbol, p->type); @@ -255,6 +261,78 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { if (p == nullptr || p->func == nullptr) { return; } + + if (p->body == nullptr) { + return; + } + + GB_ASSERT(p->type->kind == Type_Proc); + TypeProc *pt = &p->type->Proc; + if (pt->params) { + int param_index = 0; + for (Entity *e : pt->params->Tuple.variables) { + if (e->kind != Entity_Variable) { + continue; + } + + if (param_index >= p->proto->param_count) { + break; + } + + TB_Node *ptr = tb_inst_param_addr(p->func, param_index); + cgValue local = cg_value(ptr, alloc_type_pointer(e->type)); + + if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { + // NOTE(bill): for debugging purposes only + String name = e->token.string; + TB_DebugType *debug_type = cg_debug_type(p->module, e->type); + tb_node_append_attrib(ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); + + } + cgAddr addr = cg_addr(local); + if (e) { + map_set(&p->variable_map, e, addr); + } + + // if (arg_type->kind == lbArg_Ignore) { + // continue; + // } else if (arg_type->kind == lbArg_Direct) { + // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { + // LLVMTypeRef param_type = lb_type(p->module, e->type); + // LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index); + // LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type); + + // lbValue param = {}; + // param.value = value; + // param.type = e->type; + + // map_set(&p->direct_parameters, e, param); + + // lbValue ptr = lb_address_from_load_or_generate_local(p, param); + // GB_ASSERT(LLVMIsAAllocaInst(ptr.value)); + // lb_add_entity(p->module, e, ptr); + + // lbBlock *block = p->decl_block; + // if (original_value != value) { + // block = p->curr_block; + // } + // LLVMValueRef debug_storage_value = value; + // if (original_value != value && LLVMIsALoadInst(value)) { + // debug_storage_value = LLVMGetOperand(value, 0); + // } + // lb_add_debug_param_variable(p, debug_storage_value, e->type, e->token, param_index+1, block, arg_type->kind); + // } + // } else if (arg_type->kind == lbArg_Indirect) { + // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { + // lbValue ptr = {}; + // ptr.value = LLVMGetParam(p->value, param_offset+param_index); + // ptr.type = alloc_type_pointer(e->type); + // lb_add_entity(p->module, e, ptr); + // lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block, arg_type->kind); + // } + // } + } + } } gb_internal void cg_procedure_end(cgProcedure *p) { diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 7c3dfcef8..2952539ca 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -131,6 +131,9 @@ gb_internal cgValue cg_address_from_load(cgProcedure *p, cgValue value) { GB_PANIC("Symbol is an invalid use case for cg_address_from_load"); return {}; } + GB_PANIC("Invalid cgValue for cg_address_from_load"); + return {}; + } gb_internal bool cg_addr_is_empty(cgAddr const &addr) { @@ -174,7 +177,14 @@ gb_internal Type *cg_addr_type(cgAddr const &addr) { } gb_internal cgValue cg_addr_load(cgProcedure *p, cgAddr addr) { - GB_PANIC("TODO(bill): cg_addr_load"); + if (addr.addr.node == nullptr) { + return {}; + } + switch (addr.kind) { + case cgAddr_Default: + return cg_emit_load(p, addr.addr); + } + GB_PANIC("TODO(bill): cg_addr_load %p", addr.addr.node); return {}; } @@ -285,19 +295,23 @@ gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { // NOTE(bill): for debugging purposes only - // String name = e->token.string; - // TB_DebugType *debug_type = cg_debug_type(p->module, type); - // tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type); + String name = e->token.string; + TB_DebugType *debug_type = cg_debug_type(p->module, type); + tb_node_append_attrib(local, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); } if (zero_init) { bool is_volatile = false; - TB_Node *zero = tb_inst_uint(p->func, TB_TYPE_I8, 0); + TB_Node *zero = tb_inst_uint(p->func, TB_TYPE_I8, 0); TB_Node *count = tb_inst_uint(p->func, TB_TYPE_I32, cast(u64)size); tb_inst_memset(p->func, local, zero, count, alignment, is_volatile); } - return cg_addr(cg_value(local, alloc_type_pointer(type))); + cgAddr addr = cg_addr(cg_value(local, alloc_type_pointer(type))); + if (e) { + map_set(&p->variable_map, e, addr); + } + return addr; } @@ -313,10 +327,59 @@ gb_internal void cg_emit_defer_stmts(cgProcedure *p, cgDeferExitKind kind, TB_No // TODO(bill): cg_emit_defer_stmts } + +gb_internal isize cg_append_tuple_values(cgProcedure *p, Array *dst_values, cgValue src_value) { + isize init_count = dst_values->count; + Type *t = src_value.type; + if (t && t->kind == Type_Tuple) { + GB_PANIC("TODO(bill): tuple assignments"); + // cgTupleFix *tf = map_get(&p->tuple_fix_map, src_value.value); + // if (tf) { + // for (cgValue const &value : tf->values) { + // array_add(dst_values, value); + // } + // } else { + // for_array(i, t->Tuple.variables) { + // cgValue v = cg_emit_tuple_ev(p, src_value, cast(i32)i); + // array_add(dst_values, v); + // } + // } + } else { + array_add(dst_values, src_value); + } + return dst_values->count - init_count; +} gb_internal void cg_build_assignment(cgProcedure *p, Array const &lvals, Slice const &values) { if (values.count == 0) { return; } + + auto inits = array_make(permanent_allocator(), 0, lvals.count); + + for (Ast *rhs : values) { + cgValue init = cg_build_expr(p, rhs); + cg_append_tuple_values(p, &inits, init); + } + + bool prev_in_assignment = p->in_multi_assignment; + + isize lval_count = 0; + for (cgAddr const &lval : lvals) { + if (!cg_addr_is_empty(lval)) { + // check if it is not a blank identifier + lval_count += 1; + } + } + p->in_multi_assignment = lval_count > 1; + + GB_ASSERT(lvals.count == inits.count); + for_array(i, inits) { + cgAddr lval = lvals[i]; + cgValue init = inits[i]; + cg_addr_store(p, lval, init); + } + + p->in_multi_assignment = prev_in_assignment; } gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { -- cgit v1.2.3 From bd73834e196d21aaed0bb1fd0a3d84e323b8aba7 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 17 Jul 2023 16:56:10 +0100 Subject: Update Tilde; mock out `cg_build_return_stmt` 128-bit types are broken --- src/tilde/tb.h | 26 +++++++--- src/tilde/tb.lib | Bin 4112646 -> 4113018 bytes src/tilde_backend.cpp | 4 +- src/tilde_backend.hpp | 3 +- src/tilde_const.cpp | 2 +- src/tilde_proc.cpp | 139 ++++++++++++++++++++++++++------------------------ src/tilde_stmt.cpp | 28 +++++++++- 7 files changed, 125 insertions(+), 77 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde/tb.h b/src/tilde/tb.h index 8b698ff30..4fb5d30ef 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -195,8 +195,6 @@ typedef union TB_DataType { typedef enum TB_NodeTypeEnum { TB_NULL = 0, - TB_RETURN, // fn(r: region, x: data) - // only one per function TB_START, // fn() @@ -823,7 +821,16 @@ TB_API TB_DebugType* tb_debug_create_array(TB_Module* m, TB_DebugType* base, siz TB_API TB_DebugType* tb_debug_create_struct(TB_Module* m, ptrdiff_t len, const char* tag); TB_API TB_DebugType* tb_debug_create_union(TB_Module* m, ptrdiff_t len, const char* tag); TB_API TB_DebugType* tb_debug_create_field(TB_Module* m, TB_DebugType* type, ptrdiff_t len, const char* name, TB_CharUnits offset); -TB_API void tb_debug_complete_record(TB_DebugType* type, TB_DebugType** members, size_t count, TB_CharUnits size, TB_CharUnits align); + +// returns the array you need to fill with fields +TB_API TB_DebugType** tb_debug_record_begin(TB_DebugType* type, size_t count); +TB_API void tb_debug_record_end(TB_DebugType* type, TB_CharUnits size, TB_CharUnits align); + +TB_API TB_DebugType* tb_debug_create_func(TB_Module* m, TB_CallingConv cc, size_t param_count, size_t return_count, bool has_varargs); + +// you'll need to fill these if you make a function +TB_API TB_DebugType** tb_debug_func_params(TB_DebugType* type); +TB_API TB_DebugType** tb_debug_func_returns(TB_DebugType* type); //////////////////////////////// // IR access @@ -850,6 +857,8 @@ TB_API TB_Global* tb_symbol_as_global(TB_Symbol* s); //////////////////////////////// // Function IR Generation //////////////////////////////// +TB_API void tb_get_data_type_size(TB_Module* mod, TB_DataType dt, size_t* size, size_t* align); + // the user_data is expected to be a valid FILE* TB_API void tb_default_print_callback(void* user_data, const char* fmt, ...); @@ -869,6 +878,12 @@ TB_API void tb_symbol_set_name(TB_Symbol* s, ptrdiff_t len, const char* name); TB_API void tb_symbol_bind_ptr(TB_Symbol* s, void* ptr); TB_API const char* tb_symbol_get_name(TB_Symbol* s); +// same as tb_function_set_prototype except it will handle lowering from types like the TB_DebugType +// into the correct ABI and exposing sane looking nodes to the parameters. +// +// returns the parameters +TB_API TB_Node** tb_function_set_prototype_from_dbg(TB_Function* f, TB_DebugType* dbg, TB_Arena* arena, size_t* out_param_count); + // if arena is NULL, defaults to module arena which is freed on tb_free_thread_resources TB_API void tb_function_set_prototype(TB_Function* f, TB_FunctionPrototype* p, TB_Arena* arena); TB_API TB_FunctionPrototype* tb_function_get_prototype(TB_Function* f); @@ -890,7 +905,6 @@ TB_API void tb_inst_keep_alive(TB_Function* f, TB_Node* src); TB_API TB_Node* tb_inst_poison(TB_Function* f); TB_API TB_Node* tb_inst_param(TB_Function* f, int param_id); -TB_API TB_Node* tb_inst_param_addr(TB_Function* f, int param_id); TB_API TB_Node* tb_inst_fpxt(TB_Function* f, TB_Node* src, TB_DataType dt); TB_API TB_Node* tb_inst_sxt(TB_Function* f, TB_Node* src, TB_DataType dt); @@ -902,7 +916,7 @@ TB_API TB_Node* tb_inst_int2float(TB_Function* f, TB_Node* src, TB_DataType dt, TB_API TB_Node* tb_inst_float2int(TB_Function* f, TB_Node* src, TB_DataType dt, bool is_signed); TB_API TB_Node* tb_inst_bitcast(TB_Function* f, TB_Node* src, TB_DataType dt); -TB_API TB_Node* tb_inst_local(TB_Function* f, uint32_t size, TB_CharUnits align); +TB_API TB_Node* tb_inst_local(TB_Function* f, TB_CharUnits size, TB_CharUnits align); TB_API TB_Node* tb_inst_load(TB_Function* f, TB_DataType dt, TB_Node* addr, TB_CharUnits align, bool is_volatile); TB_API void tb_inst_store(TB_Function* f, TB_DataType dt, TB_Node* addr, TB_Node* val, TB_CharUnits align, bool is_volatile); @@ -918,7 +932,7 @@ TB_API TB_Node* tb_inst_string(TB_Function* f, size_t len, const char* str); TB_API void tb_inst_memset(TB_Function* f, TB_Node* dst, TB_Node* val, TB_Node* count, TB_CharUnits align, bool is_volatile); // zero 'count' bytes on 'dst' -TB_API void tb_inst_memzero(TB_Function* f, TB_Node* dst, TB_Node* val, TB_Node* count, TB_CharUnits align, bool is_volatile); +TB_API void tb_inst_memzero(TB_Function* f, TB_Node* dst, TB_Node* count, TB_CharUnits align, bool is_volatile); // performs a copy of 'count' elements from one memory location to another // both locations cannot overlap. diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index bad51e7e6..b52ce4c55 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_backend.cpp b/src/tilde_backend.cpp index dfe39c385..db759b767 100644 --- a/src/tilde_backend.cpp +++ b/src/tilde_backend.cpp @@ -31,7 +31,7 @@ gb_internal TB_DataType cg_data_type(Type *t) { case Basic_uint: case Basic_uintptr: case Basic_typeid: - return TB_TYPE_INTN(cast(u16)(8*sz)); + return TB_TYPE_INTN(cast(u16)gb_min(8*sz, 64)); case Basic_f16: return TB_TYPE_F16; case Basic_f32: return TB_TYPE_F32; @@ -58,7 +58,7 @@ gb_internal TB_DataType cg_data_type(Type *t) { case Basic_u64be: case Basic_i128be: case Basic_u128be: - return TB_TYPE_INTN(cast(u16)(8*sz)); + return TB_TYPE_INTN(cast(u16)gb_min(8*sz, 64)); case Basic_f16le: return TB_TYPE_F16; case Basic_f32le: return TB_TYPE_F32; diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index 073e81f5d..b2192cce4 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -8,7 +8,8 @@ #include "tilde/tb.h" #define TB_TYPE_F16 TB_DataType{ { TB_INT, 0, 16 } } -#define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } +// #define TB_TYPE_I128 TB_DataType{ { TB_INT, 0, 128 } } +#define TB_TYPE_I128 TB_TYPE_INTN(64) #define TB_TYPE_INT TB_TYPE_INTN(cast(u16)(8*build_context.int_size)) #define TB_TYPE_INTPTR TB_TYPE_INTN(cast(u16)(8*build_context.ptr_size)) diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 35c87641f..75b66567e 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -86,7 +86,7 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac return cg_value(tb_inst_uint(p->func, dt, value.value_bool), type); case ExactValue_Integer: - GB_ASSERT(dt.raw != TB_TYPE_I128.raw); + // GB_ASSERT(dt.raw != TB_TYPE_I128.raw); if (is_type_unsigned(type)) { u64 i = exact_value_to_u64(value); return cg_value(tb_inst_uint(p->func, dt, i), type); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index d763e2f8c..af9bee189 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -35,7 +35,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty case Basic_int: case Basic_uint: case Basic_uintptr: - param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + param.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; case Basic_f16: param.dt = TB_TYPE_F16; break; @@ -66,7 +66,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty break; case Basic_typeid: - param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + param.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; // Endian Specific Types @@ -86,7 +86,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty case Basic_u64be: case Basic_i128be: case Basic_u128be: - param.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + param.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; case Basic_f16le: param.dt = TB_TYPE_F16; break; @@ -171,7 +171,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty case Basic_int: case Basic_uint: case Basic_uintptr: - result.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + result.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; case Basic_f16: result.dt = TB_TYPE_I16; break; @@ -186,7 +186,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty break; case Basic_typeid: - result.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + result.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; // Endian Specific Types @@ -206,7 +206,7 @@ gb_internal TB_FunctionPrototype *cg_procedure_type_as_prototype(cgModule *m, Ty case Basic_u64be: case Basic_i128be: case Basic_u128be: - result.dt = TB_TYPE_INTN(cast(u16)(8*sz)); + result.dt = TB_TYPE_INTN(cast(u16)gb_min(64, 8*sz)); break; case Basic_f16le: result.dt = TB_TYPE_I16; break; @@ -395,70 +395,75 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { GB_ASSERT(p->type->kind == Type_Proc); TypeProc *pt = &p->type->Proc; - if (pt->params) { - int param_index = 0; - for (Entity *e : pt->params->Tuple.variables) { - if (e->kind != Entity_Variable) { - continue; - } - - if (param_index >= p->proto->param_count) { - break; - } + if (pt->params == nullptr) { + return; + } + int param_index = 0; + for (Entity *e : pt->params->Tuple.variables) { + if (e->kind != Entity_Variable) { + continue; + } - TB_Node *ptr = tb_inst_param_addr(p->func, param_index); - cgValue local = cg_value(ptr, alloc_type_pointer(e->type)); + if (param_index >= p->proto->param_count) { + break; + } - if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { - // NOTE(bill): for debugging purposes only - String name = e->token.string; - TB_DebugType *debug_type = cg_debug_type(p->module, e->type); - tb_node_append_attrib(ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); + // TB_Node *ptr = tb_inst_param_addr(p->func, param_index); + TB_Node *param = tb_inst_param(p->func, param_index); + TB_Node *ptr = tb_inst_local(p->func, cast(TB_CharUnits)type_size_of(e->type), cast(TB_CharUnits)type_align_of(e->type)); + TB_DataType dt = cg_data_type(e->type); + tb_inst_store(p->func, dt, ptr, param, cast(TB_CharUnits)type_align_of(e->type), false); + cgValue local = cg_value(ptr, alloc_type_pointer(e->type)); - } - cgAddr addr = cg_addr(local); - if (e) { - map_set(&p->variable_map, e, addr); - } + if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { + // NOTE(bill): for debugging purposes only + String name = e->token.string; + TB_DebugType *debug_type = cg_debug_type(p->module, e->type); + tb_node_append_attrib(ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); - // if (arg_type->kind == lbArg_Ignore) { - // continue; - // } else if (arg_type->kind == lbArg_Direct) { - // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { - // LLVMTypeRef param_type = lb_type(p->module, e->type); - // LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index); - // LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type); - - // lbValue param = {}; - // param.value = value; - // param.type = e->type; - - // map_set(&p->direct_parameters, e, param); - - // lbValue ptr = lb_address_from_load_or_generate_local(p, param); - // GB_ASSERT(LLVMIsAAllocaInst(ptr.value)); - // lb_add_entity(p->module, e, ptr); - - // lbBlock *block = p->decl_block; - // if (original_value != value) { - // block = p->curr_block; - // } - // LLVMValueRef debug_storage_value = value; - // if (original_value != value && LLVMIsALoadInst(value)) { - // debug_storage_value = LLVMGetOperand(value, 0); - // } - // lb_add_debug_param_variable(p, debug_storage_value, e->type, e->token, param_index+1, block, arg_type->kind); - // } - // } else if (arg_type->kind == lbArg_Indirect) { - // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { - // lbValue ptr = {}; - // ptr.value = LLVMGetParam(p->value, param_offset+param_index); - // ptr.type = alloc_type_pointer(e->type); - // lb_add_entity(p->module, e, ptr); - // lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block, arg_type->kind); - // } - // } } + cgAddr addr = cg_addr(local); + if (e) { + map_set(&p->variable_map, e, addr); + } + + // if (arg_type->kind == lbArg_Ignore) { + // continue; + // } else if (arg_type->kind == lbArg_Direct) { + // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { + // LLVMTypeRef param_type = lb_type(p->module, e->type); + // LLVMValueRef original_value = LLVMGetParam(p->value, param_offset+param_index); + // LLVMValueRef value = OdinLLVMBuildTransmute(p, original_value, param_type); + + // lbValue param = {}; + // param.value = value; + // param.type = e->type; + + // map_set(&p->direct_parameters, e, param); + + // lbValue ptr = lb_address_from_load_or_generate_local(p, param); + // GB_ASSERT(LLVMIsAAllocaInst(ptr.value)); + // lb_add_entity(p->module, e, ptr); + + // lbBlock *block = p->decl_block; + // if (original_value != value) { + // block = p->curr_block; + // } + // LLVMValueRef debug_storage_value = value; + // if (original_value != value && LLVMIsALoadInst(value)) { + // debug_storage_value = LLVMGetOperand(value, 0); + // } + // lb_add_debug_param_variable(p, debug_storage_value, e->type, e->token, param_index+1, block, arg_type->kind); + // } + // } else if (arg_type->kind == lbArg_Indirect) { + // if (e->token.string.len != 0 && !is_blank_ident(e->token.string)) { + // lbValue ptr = {}; + // ptr.value = LLVMGetParam(p->value, param_offset+param_index); + // ptr.type = alloc_type_pointer(e->type); + // lb_add_entity(p->module, e, ptr); + // lb_add_debug_param_variable(p, ptr.value, e->type, e->token, param_index+1, p->decl_block, arg_type->kind); + // } + // } } } @@ -466,7 +471,9 @@ gb_internal void cg_procedure_end(cgProcedure *p) { if (p == nullptr || p->func == nullptr) { return; } - tb_inst_ret(p->func, 0, nullptr); + if (tb_inst_get_control(p->func)) { + tb_inst_ret(p->func, 0, nullptr); + } if (p->name == "main") { TB_Arena *arena = tb_default_arena(); defer (arena->free(arena)); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index a38886c2e..787b94a58 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -736,7 +736,33 @@ gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { } gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return_results) { - + TypeTuple *tuple = &p->type->Proc.results->Tuple; + isize return_count = p->type->Proc.result_count; + gb_unused(tuple); + isize res_count = return_results.count; + gb_unused(res_count); + + if (return_count == 0) { + tb_inst_ret(p->func, 0, nullptr); + return; + } else if (return_count == 1) { + Entity *e = tuple->variables[0]; + if (res_count == 0) { + cgValue zero = cg_const_nil(p, tuple->variables[0]->type); + if (zero.kind == cgValue_Value) { + tb_inst_ret(p->func, 1, &zero.node); + } + return; + } + cgValue res = cg_build_expr(p, return_results[0]); + res = cg_emit_conv(p, res, e->type); + if (res.kind == cgValue_Value) { + tb_inst_ret(p->func, 1, &res.node); + } + return; + } else { + GB_PANIC("TODO(bill): MUTLIPLE RETURN VALUES"); + } } -- cgit v1.2.3 From 73f25ed182288eb311abc75cc4b69f1421bfd94a Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 19 Jul 2023 13:37:56 +0100 Subject: Add basic `switch` statement Implement as naive if-else chain --- src/tilde_const.cpp | 3 ++ src/tilde_stmt.cpp | 128 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 131 insertions(+) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 75b66567e..7f6de50c7 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -123,3 +123,6 @@ gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const gb_internal cgValue cg_const_int(cgProcedure *p, Type *type, i64 i) { return cg_const_value(p, type, exact_value_i64(i)); } +gb_internal cgValue cg_const_bool(cgProcedure *p, Type *type, bool v) { + return cg_value(tb_inst_bool(p->func, v), type); +} diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 25f8c044b..de936ae3d 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -945,6 +945,130 @@ gb_internal void cg_build_for_stmt(cgProcedure *p, Ast *node) { } tb_inst_set_control(p->func, done); } +gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { + ast_node(ss, SwitchStmt, node); + cg_scope_open(p, ss->scope); + + if (ss->init != nullptr) { + cg_build_stmt(p, ss->init); + } + cgValue tag = {}; + if (ss->tag != nullptr) { + tag = cg_build_expr(p, ss->tag); + } else { + tag = cg_const_bool(p, t_bool, true); + } + + TB_Node *done = tb_inst_region_with_name(p->func, -1, "switch_done"); + + ast_node(body, BlockStmt, ss->body); + + isize case_count = body->stmts.count; + Slice default_stmts = {}; + TB_Node *default_fall = nullptr; + TB_Node *default_block = nullptr; + Scope * default_scope = nullptr; + TB_Node *fall = nullptr; + + auto body_blocks = slice_make(permanent_allocator(), body->stmts.count); + auto body_scopes = slice_make(permanent_allocator(), body->stmts.count); + for_array(i, body->stmts) { + Ast *clause = body->stmts[i]; + ast_node(cc, CaseClause, clause); + + body_blocks[i] = tb_inst_region_with_name(p->func, -1, cc->list.count == 0 ? "switch_default_body" : "switch_case_body"); + body_scopes[i] = cc->scope; + if (cc->list.count == 0) { + default_block = body_blocks[i]; + default_scope = cc->scope; + } + } + + for_array(i, body->stmts) { + Ast *clause = body->stmts[i]; + ast_node(cc, CaseClause, clause); + + TB_Node *body = body_blocks[i]; + Scope *body_scope = body_scopes[i]; + fall = done; + if (i+1 < case_count) { + fall = body_blocks[i+1]; + } + + if (cc->list.count == 0) { + // default case + default_stmts = cc->stmts; + default_fall = fall; + default_block = body; + continue; + } + + TB_Node *next_cond = nullptr; + for (Ast *expr : cc->list) { + expr = unparen_expr(expr); + + next_cond = tb_inst_region_with_name(p->func, -1, "switch_case_next"); + + cgValue cond = {}; + if (is_ast_range(expr)) { + ast_node(ie, BinaryExpr, expr); + TokenKind op = Token_Invalid; + switch (ie->op.kind) { + case Token_Ellipsis: op = Token_LtEq; break; + case Token_RangeFull: op = Token_LtEq; break; + case Token_RangeHalf: op = Token_Lt; break; + default: GB_PANIC("Invalid interval operator"); break; + } + cgValue lhs = cg_build_expr(p, ie->left); + cgValue rhs = cg_build_expr(p, ie->right); + + cgValue cond_lhs = cg_emit_comp(p, Token_LtEq, lhs, tag); + cgValue cond_rhs = cg_emit_comp(p, op, tag, rhs); + cond = cg_emit_arith(p, Token_And, cond_lhs, cond_rhs, t_bool); + } else { + if (expr->tav.mode == Addressing_Type) { + GB_ASSERT(is_type_typeid(tag.type)); + cgValue e = cg_typeid(p->module, expr->tav.type); + e = cg_emit_conv(p, e, tag.type); + cond = cg_emit_comp(p, Token_CmpEq, tag, e); + } else { + cond = cg_emit_comp(p, Token_CmpEq, tag, cg_build_expr(p, expr)); + } + } + + GB_ASSERT(cond.kind == cgValue_Value); + tb_inst_if(p->func, cond.node, body, next_cond); + tb_inst_set_control(p->func, next_cond); + } + + tb_inst_set_control(p->func, body); + + cg_push_target_list(p, ss->label, done, nullptr, fall); + cg_scope_open(p, body_scope); + cg_build_stmt_list(p, cc->stmts); + cg_scope_close(p, cgDeferExit_Default, body); + cg_pop_target_list(p); + + tb_inst_goto(p->func, done); + tb_inst_set_control(p->func, next_cond); + } + + if (default_block != nullptr) { + tb_inst_goto(p->func, default_block); + tb_inst_set_control(p->func, default_block); + + cg_push_target_list(p, ss->label, done, nullptr, default_fall); + cg_scope_open(p, default_scope); + cg_build_stmt_list(p, default_stmts); + cg_scope_close(p, cgDeferExit_Default, default_block); + cg_pop_target_list(p); + } + + tb_inst_goto(p->func, done); + tb_inst_set_control(p->func, done); + + cg_scope_close(p, cgDeferExit_Default, done); +} gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { @@ -1141,6 +1265,10 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { cg_build_for_stmt(p, node); case_end; + case_ast_node(fs, SwitchStmt, node); + cg_build_switch_stmt(p, node); + case_end; + default: GB_PANIC("TODO cg_build_stmt %.*s", LIT(ast_strings[node->kind])); break; -- cgit v1.2.3 From 184563bbe1f55be17f39cdc13cb784a562419b75 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 19 Jul 2023 13:58:56 +0100 Subject: Add trivial `switch` statement check to use a jump table --- src/tilde_backend.hpp | 2 +- src/tilde_const.cpp | 2 +- src/tilde_expr.cpp | 10 ++--- src/tilde_stmt.cpp | 121 +++++++++++++++++++++++++++++++++++++++++++++----- 4 files changed, 115 insertions(+), 20 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_backend.hpp b/src/tilde_backend.hpp index ab8270c90..bb029ef1c 100644 --- a/src/tilde_backend.hpp +++ b/src/tilde_backend.hpp @@ -260,7 +260,7 @@ gb_internal TB_DebugType *cg_debug_type(cgModule *m, Type *type); gb_internal String cg_get_entity_name(cgModule *m, Entity *e); -gb_internal cgValue cg_typeid(cgModule *m, Type *t); +gb_internal cgValue cg_typeid(cgProcedure *m, Type *t); gb_internal cgValue cg_emit_ptr_offset(cgProcedure *p, cgValue ptr, cgValue index); gb_internal cgValue cg_emit_array_ep(cgProcedure *p, cgValue s, cgValue index); diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 7f6de50c7..a036d928c 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -63,7 +63,7 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac return cg_const_nil(p, type); case ExactValue_Typeid: - return cg_typeid(m, value.value_typeid); + return cg_typeid(p, value.value_typeid); case ExactValue_Procedure: { diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 24881b386..526bc4de3 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -120,7 +120,7 @@ gb_internal cgAddr cg_build_addr_from_entity(cgProcedure *p, Entity *e, Ast *exp return cg_addr(v); } -gb_internal cgValue cg_typeid(cgModule *m, Type *t) { +gb_internal cgValue cg_typeid(cgProcedure *p, Type *t) { GB_ASSERT("TODO(bill): cg_typeid"); return {}; } @@ -1747,10 +1747,10 @@ gb_internal cgValue cg_build_binary_expr(cgProcedure *p, Ast *expr) { cgValue right = {}; if (be->left->tav.mode == Addressing_Type) { - left = cg_typeid(p->module, be->left->tav.type); + left = cg_typeid(p, be->left->tav.type); } if (be->right->tav.mode == Addressing_Type) { - right = cg_typeid(p->module, be->right->tav.type); + right = cg_typeid(p, be->right->tav.type); } if (left.node == nullptr) left = cg_build_expr(p, be->left); if (right.node == nullptr) right = cg_build_expr(p, be->right); @@ -1944,8 +1944,6 @@ gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { - cgModule *m = p->module; - expr = unparen_expr(expr); TokenPos expr_pos = ast_token(expr).pos; @@ -1964,7 +1962,7 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { return cg_const_value(p, type, tv.value); } else if (tv.mode == Addressing_Type) { // NOTE(bill, 2023-01-16): is this correct? I hope so at least - return cg_typeid(m, tv.type); + return cg_typeid(p, tv.type); } switch (expr->kind) { diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index de936ae3d..06be4f111 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -945,6 +945,57 @@ gb_internal void cg_build_for_stmt(cgProcedure *p, Ast *node) { } tb_inst_set_control(p->func, done); } + +gb_internal bool cg_switch_stmt_can_be_trivial_jump_table(AstSwitchStmt *ss) { + if (ss->tag == nullptr) { + return false; + } + bool is_typeid = false; + TypeAndValue tv = type_and_value_of_expr(ss->tag); + if (is_type_integer(core_type(tv.type))) { + if (type_size_of(tv.type) > 8) { + return false; + } + // okay + } else if (is_type_typeid(tv.type)) { + // okay + is_typeid = true; + } else { + return false; + } + + ast_node(body, BlockStmt, ss->body); + for (Ast *clause : body->stmts) { + ast_node(cc, CaseClause, clause); + + if (cc->list.count == 0) { + continue; + } + + for (Ast *expr : cc->list) { + expr = unparen_expr(expr); + if (is_ast_range(expr)) { + return false; + } + if (expr->tav.mode == Addressing_Type) { + GB_ASSERT(is_typeid); + continue; + } + tv = type_and_value_of_expr(expr); + if (tv.mode != Addressing_Constant) { + return false; + } + if (!is_type_integer(core_type(tv.type))) { + return false; + } + } + + } + + return true; +} + + gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { ast_node(ss, SwitchStmt, node); cg_scope_open(p, ss->scope); @@ -970,41 +1021,85 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { Scope * default_scope = nullptr; TB_Node *fall = nullptr; - auto body_blocks = slice_make(permanent_allocator(), body->stmts.count); + + auto body_regions = slice_make(permanent_allocator(), body->stmts.count); auto body_scopes = slice_make(permanent_allocator(), body->stmts.count); for_array(i, body->stmts) { Ast *clause = body->stmts[i]; ast_node(cc, CaseClause, clause); - body_blocks[i] = tb_inst_region_with_name(p->func, -1, cc->list.count == 0 ? "switch_default_body" : "switch_case_body"); + body_regions[i] = tb_inst_region_with_name(p->func, -1, cc->list.count == 0 ? "switch_default_body" : "switch_case_body"); body_scopes[i] = cc->scope; if (cc->list.count == 0) { - default_block = body_blocks[i]; + default_block = body_regions[i]; default_scope = cc->scope; } } + bool is_trivial = cg_switch_stmt_can_be_trivial_jump_table(ss); + if (is_trivial) { + isize key_count = 0; + for (Ast *clause : body->stmts) { + ast_node(cc, CaseClause, clause); + key_count += cc->list.count; + } + TB_SwitchEntry *keys = gb_alloc_array(temporary_allocator(), TB_SwitchEntry, key_count); + isize key_index = 0; + for_array(i, body->stmts) { + Ast *clause = body->stmts[i]; + ast_node(cc, CaseClause, clause); + + TB_Node *region = body_regions[i]; + for (Ast *expr : cc->list) { + i64 key = 0; + expr = unparen_expr(expr); + GB_ASSERT(!is_ast_range(expr)); + if (expr->tav.mode == Addressing_Type) { + GB_PANIC("TODO(bill): cg_typeid as i64"); + // key = cg_typeid(p, expr->tav.value.value_typeid); + } else { + auto tv = type_and_value_of_expr(expr); + GB_ASSERT(tv.mode == Addressing_Constant); + key = exact_value_to_i64(tv.value); + } + keys[key_index++] = {key, region}; + } + } + GB_ASSERT(key_index == key_count); + + TB_Node *end_block = done; + if (default_block) { + end_block = default_block; + } + + TB_DataType dt = cg_data_type(tag.type); + GB_ASSERT(tag.kind == cgValue_Value); + GB_ASSERT(!TB_IS_VOID_TYPE(dt)); + + tb_inst_branch(p->func, dt, tag.node, end_block, key_count, keys); + } + for_array(i, body->stmts) { Ast *clause = body->stmts[i]; ast_node(cc, CaseClause, clause); - TB_Node *body = body_blocks[i]; + TB_Node *body_region = body_regions[i]; Scope *body_scope = body_scopes[i]; fall = done; if (i+1 < case_count) { - fall = body_blocks[i+1]; + fall = body_regions[i+1]; } if (cc->list.count == 0) { // default case default_stmts = cc->stmts; default_fall = fall; - default_block = body; + GB_ASSERT(default_block == body_region); continue; } TB_Node *next_cond = nullptr; - for (Ast *expr : cc->list) { + if (!is_trivial) for (Ast *expr : cc->list) { expr = unparen_expr(expr); next_cond = tb_inst_region_with_name(p->func, -1, "switch_case_next"); @@ -1028,7 +1123,7 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { } else { if (expr->tav.mode == Addressing_Type) { GB_ASSERT(is_type_typeid(tag.type)); - cgValue e = cg_typeid(p->module, expr->tav.type); + cgValue e = cg_typeid(p, expr->tav.type); e = cg_emit_conv(p, e, tag.type); cond = cg_emit_comp(p, Token_CmpEq, tag, e); } else { @@ -1037,16 +1132,16 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { } GB_ASSERT(cond.kind == cgValue_Value); - tb_inst_if(p->func, cond.node, body, next_cond); + tb_inst_if(p->func, cond.node, body_region, next_cond); tb_inst_set_control(p->func, next_cond); } - tb_inst_set_control(p->func, body); + tb_inst_set_control(p->func, body_region); cg_push_target_list(p, ss->label, done, nullptr, fall); cg_scope_open(p, body_scope); cg_build_stmt_list(p, cc->stmts); - cg_scope_close(p, cgDeferExit_Default, body); + cg_scope_close(p, cgDeferExit_Default, body_region); cg_pop_target_list(p); tb_inst_goto(p->func, done); @@ -1054,7 +1149,9 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { } if (default_block != nullptr) { - tb_inst_goto(p->func, default_block); + if (!is_trivial) { + tb_inst_goto(p->func, default_block); + } tb_inst_set_control(p->func, default_block); cg_push_target_list(p, ss->label, done, nullptr, default_fall); -- cgit v1.2.3 From 0bd33882b67952d80d7123a8af09ff902c96bb56 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 19 Jul 2023 21:43:42 +0100 Subject: Basic constant compound literal support --- src/llvm_backend_const.cpp | 134 ++++++++++--------- src/tilde_const.cpp | 320 ++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 383 insertions(+), 71 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/llvm_backend_const.cpp b/src/llvm_backend_const.cpp index 2a121ff5d..a152e00c2 100644 --- a/src/llvm_backend_const.cpp +++ b/src/llvm_backend_const.cpp @@ -1036,86 +1036,84 @@ gb_internal lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bo LLVMValueRef *values = gb_alloc_array(temporary_allocator(), LLVMValueRef, value_count); bool *visited = gb_alloc_array(temporary_allocator(), bool, value_count); - if (cl->elems.count > 0) { - if (cl->elems[0]->kind == Ast_FieldValue) { - isize elem_count = cl->elems.count; - for (isize i = 0; i < elem_count; i++) { - ast_node(fv, FieldValue, cl->elems[i]); - String name = fv->field->Ident.token.string; + if (cl->elems[0]->kind == Ast_FieldValue) { + isize elem_count = cl->elems.count; + for (isize i = 0; i < elem_count; i++) { + ast_node(fv, FieldValue, cl->elems[i]); + String name = fv->field->Ident.token.string; - TypeAndValue tav = fv->value->tav; - GB_ASSERT(tav.mode != Addressing_Invalid); + TypeAndValue tav = fv->value->tav; + GB_ASSERT(tav.mode != Addressing_Invalid); - Selection sel = lookup_field(type, name, false); - GB_ASSERT(!sel.indirect); + Selection sel = lookup_field(type, name, false); + GB_ASSERT(!sel.indirect); - Entity *f = type->Struct.fields[sel.index[0]]; - i32 index = field_remapping[f->Variable.field_index]; - if (elem_type_can_be_constant(f->type)) { - if (sel.index.count == 1) { - values[index] = lb_const_value(m, f->type, tav.value, allow_local).value; + Entity *f = type->Struct.fields[sel.index[0]]; + i32 index = field_remapping[f->Variable.field_index]; + if (elem_type_can_be_constant(f->type)) { + if (sel.index.count == 1) { + values[index] = lb_const_value(m, f->type, tav.value, allow_local).value; + visited[index] = true; + } else { + if (!visited[index]) { + values[index] = lb_const_value(m, f->type, {}, false).value; visited[index] = true; - } else { - if (!visited[index]) { - values[index] = lb_const_value(m, f->type, {}, false).value; - visited[index] = true; - } - unsigned idx_list_len = cast(unsigned)sel.index.count-1; - unsigned *idx_list = gb_alloc_array(temporary_allocator(), unsigned, idx_list_len); - - if (lb_is_nested_possibly_constant(type, sel, fv->value)) { - bool is_constant = true; - Type *cv_type = f->type; - for (isize j = 1; j < sel.index.count; j++) { - i32 index = sel.index[j]; - Type *cvt = base_type(cv_type); - - if (cvt->kind == Type_Struct) { - if (cvt->Struct.is_raw_union) { - // sanity check which should have been caught by `lb_is_nested_possibly_constant` - is_constant = false; - break; - } - cv_type = cvt->Struct.fields[index]->type; - - if (is_type_struct(cvt)) { - auto cv_field_remapping = lb_get_struct_remapping(m, cvt); - unsigned remapped_index = cast(unsigned)cv_field_remapping[index]; - idx_list[j-1] = remapped_index; - } else { - idx_list[j-1] = cast(unsigned)index; - } - } else if (cvt->kind == Type_Array) { - cv_type = cvt->Array.elem; + } + unsigned idx_list_len = cast(unsigned)sel.index.count-1; + unsigned *idx_list = gb_alloc_array(temporary_allocator(), unsigned, idx_list_len); + + if (lb_is_nested_possibly_constant(type, sel, fv->value)) { + bool is_constant = true; + Type *cv_type = f->type; + for (isize j = 1; j < sel.index.count; j++) { + i32 index = sel.index[j]; + Type *cvt = base_type(cv_type); + + if (cvt->kind == Type_Struct) { + if (cvt->Struct.is_raw_union) { + // sanity check which should have been caught by `lb_is_nested_possibly_constant` + is_constant = false; + break; + } + cv_type = cvt->Struct.fields[index]->type; - idx_list[j-1] = cast(unsigned)index; + if (is_type_struct(cvt)) { + auto cv_field_remapping = lb_get_struct_remapping(m, cvt); + unsigned remapped_index = cast(unsigned)cv_field_remapping[index]; + idx_list[j-1] = remapped_index; } else { - GB_PANIC("UNKNOWN TYPE: %s", type_to_string(cv_type)); + idx_list[j-1] = cast(unsigned)index; } + } else if (cvt->kind == Type_Array) { + cv_type = cvt->Array.elem; + + idx_list[j-1] = cast(unsigned)index; + } else { + GB_PANIC("UNKNOWN TYPE: %s", type_to_string(cv_type)); } - if (is_constant) { - LLVMValueRef elem_value = lb_const_value(m, tav.type, tav.value, allow_local).value; - GB_ASSERT(LLVMIsConstant(elem_value)); - values[index] = LLVMConstInsertValue(values[index], elem_value, idx_list, idx_list_len); - } + } + if (is_constant) { + LLVMValueRef elem_value = lb_const_value(m, tav.type, tav.value, allow_local).value; + GB_ASSERT(LLVMIsConstant(elem_value)); + values[index] = LLVMConstInsertValue(values[index], elem_value, idx_list, idx_list_len); } } } } - } else { - for_array(i, cl->elems) { - Entity *f = type->Struct.fields[i]; - TypeAndValue tav = cl->elems[i]->tav; - ExactValue val = {}; - if (tav.mode != Addressing_Invalid) { - val = tav.value; - } - - i32 index = field_remapping[f->Variable.field_index]; - if (elem_type_can_be_constant(f->type)) { - values[index] = lb_const_value(m, f->type, val, allow_local).value; - visited[index] = true; - } + } + } else { + for_array(i, cl->elems) { + Entity *f = type->Struct.fields[i]; + TypeAndValue tav = cl->elems[i]->tav; + ExactValue val = {}; + if (tav.mode != Addressing_Invalid) { + val = tav.value; + } + + i32 index = field_remapping[f->Variable.field_index]; + if (elem_type_can_be_constant(f->type)) { + values[index] = lb_const_value(m, f->type, val, allow_local).value; + visited[index] = true; } } } diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index a036d928c..616bf7833 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -8,6 +8,7 @@ gb_internal bool cg_is_expr_constant_zero(Ast *expr) { } gb_internal cgValue cg_const_nil(cgModule *m, cgProcedure *p, Type *type) { + GB_ASSERT(m != nullptr); Type *original_type = type; type = core_type(type); i64 size = type_size_of(type); @@ -16,7 +17,7 @@ gb_internal cgValue cg_const_nil(cgModule *m, cgProcedure *p, Type *type) { if (TB_IS_VOID_TYPE(dt)) { char name[32] = {}; gb_snprintf(name, 31, "cnil$%u", 1+m->const_nil_guid.fetch_add(1)); - TB_Global *global = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, size, align, 0); TB_Symbol *symbol = cast(TB_Symbol *)global; @@ -24,7 +25,7 @@ gb_internal cgValue cg_const_nil(cgModule *m, cgProcedure *p, Type *type) { TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); return cg_lvalue_addr(node, type); } else { - GB_PANIC("TODO(bill): cg_const_nil"); + return cg_value(symbol, type); } } @@ -50,6 +51,95 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { return cg_const_nil(p->module, p, type); } +gb_internal TB_Global *cg_global_const_cstring(cgModule *m, String const &str, Type *type) { + char name[32] = {}; + gb_snprintf(name, 31, "csb$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); + i64 size = str.len+1; + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, size, 1, 1); + u8 *data = cast(u8 *)tb_global_add_region(m->mod, global, 0, size+1); + gb_memcopy(data, str.text, str.len); + data[str.len] = 0; + return global; + +} + +gb_internal void cg_write_big_int_at_ptr(void *dst, BigInt const *a, Type *original_type) { + GB_ASSERT(build_context.endian_kind == TargetEndian_Little); + size_t sz = cast(size_t)type_size_of(original_type); + if (big_int_is_zero(a)) { + gb_memset(dst, 0, sz); + return; + } + u64 rop64[4] = {}; // 2 u64 is the maximum we will ever need, so doubling it will be fine :P + u8 *rop = cast(u8 *)rop64; + + size_t max_count = 0; + size_t written = 0; + size_t size = 1; + size_t nails = 0; + mp_endian endian = MP_LITTLE_ENDIAN; + + max_count = mp_pack_count(a, nails, size); + if (sz < max_count) { + debug_print_big_int(a); + gb_printf_err("%s -> %tu\n", type_to_string(original_type), sz);; + } + GB_ASSERT_MSG(sz >= max_count, "max_count: %tu, sz: %tu, written: %tu, type %s", max_count, sz, written, type_to_string(original_type)); + GB_ASSERT(gb_size_of(rop64) >= sz); + + mp_err err = mp_pack(rop, sz, &written, + MP_LSB_FIRST, + size, endian, nails, + a); + GB_ASSERT(err == MP_OKAY); + + if (!is_type_endian_little(original_type)) { + for (size_t i = 0; i < sz/2; i++) { + u8 tmp = rop[i]; + rop[i] = rop[sz-1-i]; + rop[sz-1-i] = tmp; + } + } + + gb_memcopy(dst, rop, sz); + return; +} + + +gb_internal void cg_write_int_at_ptr(void *dst, i64 i, Type *original_type) { + ExactValue v = exact_value_i64(i); + cg_write_big_int_at_ptr(dst, &v.value_integer, original_type); +} +gb_internal void cg_write_uint_at_ptr(void *dst, u64 i, Type *original_type) { + ExactValue v = exact_value_u64(i); + cg_write_big_int_at_ptr(dst, &v.value_integer, original_type); +} + +gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Type *type) { + if (is_type_cstring(type)) { + return cg_global_const_cstring(m, str, type); + } + GB_ASSERT(is_type_string(type)); + + char name[32] = {}; + gb_snprintf(name, 31, "csl$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); + + + i64 size = type_size_of(type); + i64 align = type_align_of(type); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, size, align, 2); + + tb_global_add_symbol_reloc(m->mod, global, 0, cast(TB_Symbol *)cg_global_const_cstring(m, str, t_cstring)); + + void *len_ptr = tb_global_add_region(m->mod, global, build_context.int_size, build_context.int_size); + cg_write_int_at_ptr(len_ptr, str.len, t_int); + + return global; +} + + gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value, bool allow_local = true) { TB_Node *node = nullptr; @@ -79,13 +169,15 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac break; } - GB_ASSERT(!TB_IS_VOID_TYPE(dt)); + Type *original_type = type; switch (value.kind) { case ExactValue_Bool: + GB_ASSERT(!TB_IS_VOID_TYPE(dt)); return cg_value(tb_inst_uint(p->func, dt, value.value_bool), type); case ExactValue_Integer: + GB_ASSERT(!TB_IS_VOID_TYPE(dt)); // GB_ASSERT(dt.raw != TB_TYPE_I128.raw); if (is_type_unsigned(type)) { u64 i = exact_value_to_u64(value); @@ -97,6 +189,7 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac break; case ExactValue_Float: + GB_ASSERT(!TB_IS_VOID_TYPE(dt)); GB_ASSERT(dt.raw != TB_TYPE_F16.raw); GB_ASSERT(!is_type_different_to_arch_endianness(type)); { @@ -108,6 +201,227 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac } } break; + + case ExactValue_String: + { + TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_string(m, value.value_string, type); + if (p) { + TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); + return cg_lvalue_addr(node, type); + } else { + return cg_value(symbol, type); + } + } + + case ExactValue_Pointer: + return cg_value(tb_inst_uint(p->func, dt, exact_value_to_u64(value)), type); + + case ExactValue_Compound: + if (is_type_struct(type)) { + ast_node(cl, CompoundLit, value.value_compound); + + if (cl->elems.count == 0) { + return cg_const_nil(m, p, original_type); + } + + Type *bt = base_type(type); + if (bt->Struct.is_raw_union) { + return cg_const_nil(m, p, original_type); + } + + TEMPORARY_ALLOCATOR_GUARD(); + + isize value_count = bt->Struct.fields.count; + cgValue * values = gb_alloc_array(temporary_allocator(), cgValue, value_count); + bool * visited = gb_alloc_array(temporary_allocator(), bool, value_count); + + + char name[32] = {}; + gb_snprintf(name, 31, "complit$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, original_type), TB_LINKAGE_PRIVATE); + i64 size = type_size_of(original_type); + i64 align = type_align_of(original_type); + + // READ ONLY? + TB_ModuleSection *section = tb_module_get_rdata(m->mod); + tb_global_set_storage(m->mod, section, global, size, align, value_count); + + if (cl->elems[0]->kind == Ast_FieldValue) { + // isize elem_count = cl->elems.count; + // for (isize i = 0; i < elem_count; i++) { + // ast_node(fv, FieldValue, cl->elems[i]); + // String name = fv->field->Ident.token.string; + + // TypeAndValue tav = fv->value->tav; + // GB_ASSERT(tav.mode != Addressing_Invalid); + + // Selection sel = lookup_field(type, name, false); + // GB_ASSERT(!sel.indirect); + + // Entity *f = type->Struct.fields[sel.index[0]]; + // i32 index = field_remapping[f->Variable.field_index]; + // if (elem_type_can_be_constant(f->type)) { + // if (sel.index.count == 1) { + // values[index] = lb_const_value(m, f->type, tav.value, allow_local).value; + // visited[index] = true; + // } else { + // if (!visited[index]) { + // values[index] = lb_const_value(m, f->type, {}, false).value; + // visited[index] = true; + // } + // unsigned idx_list_len = cast(unsigned)sel.index.count-1; + // unsigned *idx_list = gb_alloc_array(temporary_allocator(), unsigned, idx_list_len); + + // if (lb_is_nested_possibly_constant(type, sel, fv->value)) { + // bool is_constant = true; + // Type *cv_type = f->type; + // for (isize j = 1; j < sel.index.count; j++) { + // i32 index = sel.index[j]; + // Type *cvt = base_type(cv_type); + + // if (cvt->kind == Type_Struct) { + // if (cvt->Struct.is_raw_union) { + // // sanity check which should have been caught by `lb_is_nested_possibly_constant` + // is_constant = false; + // break; + // } + // cv_type = cvt->Struct.fields[index]->type; + + // if (is_type_struct(cvt)) { + // auto cv_field_remapping = lb_get_struct_remapping(m, cvt); + // unsigned remapped_index = cast(unsigned)cv_field_remapping[index]; + // idx_list[j-1] = remapped_index; + // } else { + // idx_list[j-1] = cast(unsigned)index; + // } + // } else if (cvt->kind == Type_Array) { + // cv_type = cvt->Array.elem; + + // idx_list[j-1] = cast(unsigned)index; + // } else { + // GB_PANIC("UNKNOWN TYPE: %s", type_to_string(cv_type)); + // } + // } + // if (is_constant) { + // LLVMValueRef elem_value = lb_const_value(m, tav.type, tav.value, allow_local).value; + // GB_ASSERT(LLVMIsConstant(elem_value)); + // values[index] = LLVMConstInsertValue(values[index], elem_value, idx_list, idx_list_len); + // } + // } + // } + // } + // } + } else { + for_array(i, cl->elems) { + i64 field_index = i; + Ast *elem = cl->elems[i]; + TypeAndValue tav = elem->tav; + Entity *f = bt->Struct.fields[field_index]; + if (!elem_type_can_be_constant(f->type)) { + continue; + } + + i64 offset = bt->Struct.offsets[field_index]; + i64 size = type_size_of(f->type); + + + ExactValue value = {}; + if (tav.mode != Addressing_Invalid) { + value = tav.value; + } + + GB_ASSERT(is_type_endian_little(f->type)); + GB_ASSERT(!is_type_different_to_arch_endianness(type)); + + + if (value.kind != ExactValue_Invalid) { + switch (value.kind) { + case ExactValue_Bool: + { + bool *res = cast(bool *)tb_global_add_region(m->mod, global, offset, size); + *res = !!value.value_bool; + } + break; + + case ExactValue_Integer: + { + void *res = tb_global_add_region(m->mod, global, offset, size); + cg_write_big_int_at_ptr(res, &value.value_integer, f->type); + } + break; + + case ExactValue_Float: + { + f64 f = exact_value_to_f64(value); + void *res = tb_global_add_region(m->mod, global, offset, size); + switch (size) { + case 2: *(u16 *)res = f32_to_f16(cast(f32)f); break; + case 4: *(f32 *)res = cast(f32)f; break; + case 8: *(f64 *)res = cast(f64)f; break; + } + } + break; + + case ExactValue_Pointer: + { + void *res = tb_global_add_region(m->mod, global, offset, size); + *(u64 *)res = exact_value_to_u64(value); + } + break; + + case ExactValue_String: + { + TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_string(m, value.value_string, f->type); + tb_global_add_symbol_reloc(m->mod, global, offset, symbol); + } + break; + + case ExactValue_Typeid: + { + void *dst = tb_global_add_region(m->mod, global, offset, size); + u64 id = cg_typeid_as_u64(m, value.value_typeid); + cg_write_uint_at_ptr(dst, id, t_typeid); + } + break; + + case ExactValue_Procedure: + GB_PANIC("TODO(bill): nested procedure values/literals\n"); + break; + case ExactValue_Compound: + GB_PANIC("TODO(bill): nested compound literals\n"); + break; + + case ExactValue_Complex: + GB_PANIC("TODO(bill): nested complex literals\n"); + break; + case ExactValue_Quaternion: + GB_PANIC("TODO(bill): nested quaternions literals\n"); + break; + default: + GB_PANIC("%s", type_to_string(f->type)); + break; + } + visited[i] = true; + continue; + } + + values[i] = cg_const_value(m, p, f->type, value, allow_local); + visited[i] = true; + } + } + + TB_Symbol *symbol = cast(TB_Symbol *)global; + if (p) { + TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); + return cg_lvalue_addr(node, type); + } else { + return cg_value(symbol, type); + } + + } else { + GB_PANIC("TODO(bill): constant compound literal for %s", type_to_string(type)); + } + break; } -- cgit v1.2.3 From a919828003c203b76060a5060d79b1e94a828ab7 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 19 Jul 2023 23:27:06 +0100 Subject: Add complex and quaternion global stuff --- src/tilde_const.cpp | 461 +++++++++++++++++++++++++++++----------------------- 1 file changed, 259 insertions(+), 202 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 616bf7833..ef3f38f09 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -139,12 +139,266 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty return global; } +gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *type, Ast *value_compound, bool allow_local); -gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value, bool allow_local = true) { +gb_internal bool cg_global_const_add_region(cgModule *m, TB_Global *global, ExactValue const &value, Type *type, i64 offset, bool allow_local) { + GB_ASSERT(is_type_endian_little(type)); + GB_ASSERT(!is_type_different_to_arch_endianness(type)); + + i64 size = type_size_of(type); + if (value.kind != ExactValue_Invalid) { + switch (value.kind) { + case ExactValue_Bool: + { + bool *res = cast(bool *)tb_global_add_region(m->mod, global, offset, size); + *res = !!value.value_bool; + } + break; + + case ExactValue_Integer: + { + void *res = tb_global_add_region(m->mod, global, offset, size); + cg_write_big_int_at_ptr(res, &value.value_integer, type); + } + break; + + case ExactValue_Float: + { + f64 f = exact_value_to_f64(value); + void *res = tb_global_add_region(m->mod, global, offset, size); + switch (size) { + case 2: *(u16 *)res = f32_to_f16(cast(f32)f); break; + case 4: *(f32 *)res = cast(f32)f; break; + case 8: *(f64 *)res = cast(f64)f; break; + } + } + break; + + case ExactValue_Pointer: + { + void *res = tb_global_add_region(m->mod, global, offset, size); + *(u64 *)res = exact_value_to_u64(value); + } + break; + + case ExactValue_String: + { + TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_string(m, value.value_string, type); + tb_global_add_symbol_reloc(m->mod, global, offset, symbol); + } + break; + + case ExactValue_Typeid: + { + void *dst = tb_global_add_region(m->mod, global, offset, size); + u64 id = cg_typeid_as_u64(m, value.value_typeid); + cg_write_uint_at_ptr(dst, id, t_typeid); + } + break; + + case ExactValue_Compound: + { + TB_Global *nested_global = cg_global_const_comp_literal(m, type, value.value_compound, allow_local); + tb_global_add_symbol_reloc(m->mod, global, offset, cast(TB_Symbol *)nested_global); + } + break; + + case ExactValue_Procedure: + GB_PANIC("TODO(bill): nested procedure values/literals\n"); + break; + case ExactValue_Complex: + { + Complex128 c = {}; + if (value.value_complex) { + c = *value.value_complex; + } + void *res = tb_global_add_region(m->mod, global, offset, size); + switch (size) { + case 4: + ((u16 *)res)[0] = f32_to_f16(cast(f32)c.real); + ((u16 *)res)[1] = f32_to_f16(cast(f32)c.imag); + break; + case 8: + ((f32 *)res)[0] = cast(f32)c.real; + ((f32 *)res)[1] = cast(f32)c.imag; + break; + case 16: + ((f64 *)res)[0] = cast(f64)c.real; + ((f64 *)res)[1] = cast(f64)c.imag; + break; + } + } + break; + case ExactValue_Quaternion: + { + // @QuaternionLayout + Quaternion256 q = {}; + if (value.value_quaternion) { + q = *value.value_quaternion; + } + void *res = tb_global_add_region(m->mod, global, offset, size); + switch (size) { + case 8: + ((u16 *)res)[0] = f32_to_f16(cast(f32)q.imag); + ((u16 *)res)[1] = f32_to_f16(cast(f32)q.jmag); + ((u16 *)res)[2] = f32_to_f16(cast(f32)q.kmag); + ((u16 *)res)[3] = f32_to_f16(cast(f32)q.real); + break; + case 16: + ((f32 *)res)[0] = cast(f32)q.imag; + ((f32 *)res)[1] = cast(f32)q.jmag; + ((f32 *)res)[2] = cast(f32)q.kmag; + ((f32 *)res)[3] = cast(f32)q.real; + break; + case 32: + ((f64 *)res)[0] = cast(f64)q.imag; + ((f64 *)res)[1] = cast(f64)q.jmag; + ((f64 *)res)[2] = cast(f64)q.kmag; + ((f64 *)res)[3] = cast(f64)q.real; + break; + } + } + break; + default: + GB_PANIC("%s", type_to_string(type)); + break; + } + return true; + } + return false; +} + + +gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *type, Ast *value_compound, bool allow_local) { + Type *original_type = type; + if (is_type_struct(type)) { + ast_node(cl, CompoundLit, value_compound); + + Type *bt = base_type(type); + + char name[32] = {}; + gb_snprintf(name, 31, "complit$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, original_type), TB_LINKAGE_PRIVATE); + i64 size = type_size_of(original_type); + i64 align = type_align_of(original_type); + + // READ ONLY? + TB_ModuleSection *section = tb_module_get_rdata(m->mod); + if (cl->elems.count == 0/* || bt->Struct.is_raw_union*/) { + tb_global_set_storage(m->mod, section, global, size, align, 0); + return global; + } + + TEMPORARY_ALLOCATOR_GUARD(); + isize value_count = bt->Struct.fields.count; + // cgValue * values = gb_alloc_array(temporary_allocator(), cgValue, value_count); + bool * visited = gb_alloc_array(temporary_allocator(), bool, value_count); + tb_global_set_storage(m->mod, section, global, size, align, value_count); + + if (cl->elems[0]->kind == Ast_FieldValue) { + isize elem_count = cl->elems.count; + for (isize i = 0; i < elem_count; i++) { + ast_node(fv, FieldValue, cl->elems[i]); + String name = fv->field->Ident.token.string; + + TypeAndValue tav = fv->value->tav; + GB_ASSERT(tav.mode != Addressing_Invalid); + + Selection sel = lookup_field(type, name, false); + GB_ASSERT(!sel.indirect); + + Entity *f = bt->Struct.fields[sel.index[0]]; + i64 index = f->Variable.field_index; + if (elem_type_can_be_constant(f->type)) { + if (sel.index.count == 1) { + i64 offset = bt->Struct.offsets[index]; + if (cg_global_const_add_region(m, global, fv->value->tav.value, f->type, offset, allow_local)) { + visited[i] = true; + continue; + } + } else { + // if (!visited[index]) { + GB_PANIC("using struct fields"); + // values[index] = lb_const_value(m, f->type, {}, false).value; + // visited[index] = true; + // } + // unsigned idx_list_len = cast(unsigned)sel.index.count-1; + // unsigned *idx_list = gb_alloc_array(temporary_allocator(), unsigned, idx_list_len); + + // if (lb_is_nested_possibly_constant(type, sel, fv->value)) { + // bool is_constant = true; + // Type *cv_type = f->type; + // for (isize j = 1; j < sel.index.count; j++) { + // i32 index = sel.index[j]; + // Type *cvt = base_type(cv_type); + + // if (cvt->kind == Type_Struct) { + // if (cvt->Struct.is_raw_union) { + // // sanity check which should have been caught by `lb_is_nested_possibly_constant` + // is_constant = false; + // break; + // } + // cv_type = cvt->Struct.fields[index]->type; + + // if (is_type_struct(cvt)) { + // auto cv_field_remapping = lb_get_struct_remapping(m, cvt); + // unsigned remapped_index = cast(unsigned)cv_field_remapping[index]; + // idx_list[j-1] = remapped_index; + // } else { + // idx_list[j-1] = cast(unsigned)index; + // } + // } else if (cvt->kind == Type_Array) { + // cv_type = cvt->Array.elem; + + // idx_list[j-1] = cast(unsigned)index; + // } else { + // GB_PANIC("UNKNOWN TYPE: %s", type_to_string(cv_type)); + // } + // } + // if (is_constant) { + // LLVMValueRef elem_value = lb_const_value(m, tav.type, tav.value, allow_local).value; + // GB_ASSERT(LLVMIsConstant(elem_value)); + // values[index] = LLVMConstInsertValue(values[index], elem_value, idx_list, idx_list_len); + // } + // } + } + } + } + } else { + for_array(i, cl->elems) { + i64 field_index = i; + Ast *elem = cl->elems[i]; + TypeAndValue tav = elem->tav; + Entity *f = bt->Struct.fields[field_index]; + if (!elem_type_can_be_constant(f->type)) { + continue; + } + + i64 offset = bt->Struct.offsets[field_index]; + + ExactValue value = {}; + if (tav.mode != Addressing_Invalid) { + value = tav.value; + } + if (cg_global_const_add_region(m, global, value, f->type, offset, allow_local)) { + visited[i] = true; + continue; + } + } + } + + return global; + } + + GB_PANIC("TODO(bill): constant compound literal for %s", type_to_string(type)); + return nullptr; +} + + +gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value, bool allow_local_ = true) { TB_Node *node = nullptr; - bool is_local = allow_local && p != nullptr; - gb_unused(is_local); + bool allow_local = allow_local_ && p != nullptr; TB_DataType dt = cg_data_type(type); @@ -169,8 +423,6 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac break; } - Type *original_type = type; - switch (value.kind) { case ExactValue_Bool: GB_ASSERT(!TB_IS_VOID_TYPE(dt)); @@ -217,209 +469,14 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac return cg_value(tb_inst_uint(p->func, dt, exact_value_to_u64(value)), type); case ExactValue_Compound: - if (is_type_struct(type)) { - ast_node(cl, CompoundLit, value.value_compound); - - if (cl->elems.count == 0) { - return cg_const_nil(m, p, original_type); - } - - Type *bt = base_type(type); - if (bt->Struct.is_raw_union) { - return cg_const_nil(m, p, original_type); - } - - TEMPORARY_ALLOCATOR_GUARD(); - - isize value_count = bt->Struct.fields.count; - cgValue * values = gb_alloc_array(temporary_allocator(), cgValue, value_count); - bool * visited = gb_alloc_array(temporary_allocator(), bool, value_count); - - - char name[32] = {}; - gb_snprintf(name, 31, "complit$%u", 1+m->const_nil_guid.fetch_add(1)); - TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, original_type), TB_LINKAGE_PRIVATE); - i64 size = type_size_of(original_type); - i64 align = type_align_of(original_type); - - // READ ONLY? - TB_ModuleSection *section = tb_module_get_rdata(m->mod); - tb_global_set_storage(m->mod, section, global, size, align, value_count); - - if (cl->elems[0]->kind == Ast_FieldValue) { - // isize elem_count = cl->elems.count; - // for (isize i = 0; i < elem_count; i++) { - // ast_node(fv, FieldValue, cl->elems[i]); - // String name = fv->field->Ident.token.string; - - // TypeAndValue tav = fv->value->tav; - // GB_ASSERT(tav.mode != Addressing_Invalid); - - // Selection sel = lookup_field(type, name, false); - // GB_ASSERT(!sel.indirect); - - // Entity *f = type->Struct.fields[sel.index[0]]; - // i32 index = field_remapping[f->Variable.field_index]; - // if (elem_type_can_be_constant(f->type)) { - // if (sel.index.count == 1) { - // values[index] = lb_const_value(m, f->type, tav.value, allow_local).value; - // visited[index] = true; - // } else { - // if (!visited[index]) { - // values[index] = lb_const_value(m, f->type, {}, false).value; - // visited[index] = true; - // } - // unsigned idx_list_len = cast(unsigned)sel.index.count-1; - // unsigned *idx_list = gb_alloc_array(temporary_allocator(), unsigned, idx_list_len); - - // if (lb_is_nested_possibly_constant(type, sel, fv->value)) { - // bool is_constant = true; - // Type *cv_type = f->type; - // for (isize j = 1; j < sel.index.count; j++) { - // i32 index = sel.index[j]; - // Type *cvt = base_type(cv_type); - - // if (cvt->kind == Type_Struct) { - // if (cvt->Struct.is_raw_union) { - // // sanity check which should have been caught by `lb_is_nested_possibly_constant` - // is_constant = false; - // break; - // } - // cv_type = cvt->Struct.fields[index]->type; - - // if (is_type_struct(cvt)) { - // auto cv_field_remapping = lb_get_struct_remapping(m, cvt); - // unsigned remapped_index = cast(unsigned)cv_field_remapping[index]; - // idx_list[j-1] = remapped_index; - // } else { - // idx_list[j-1] = cast(unsigned)index; - // } - // } else if (cvt->kind == Type_Array) { - // cv_type = cvt->Array.elem; - - // idx_list[j-1] = cast(unsigned)index; - // } else { - // GB_PANIC("UNKNOWN TYPE: %s", type_to_string(cv_type)); - // } - // } - // if (is_constant) { - // LLVMValueRef elem_value = lb_const_value(m, tav.type, tav.value, allow_local).value; - // GB_ASSERT(LLVMIsConstant(elem_value)); - // values[index] = LLVMConstInsertValue(values[index], elem_value, idx_list, idx_list_len); - // } - // } - // } - // } - // } - } else { - for_array(i, cl->elems) { - i64 field_index = i; - Ast *elem = cl->elems[i]; - TypeAndValue tav = elem->tav; - Entity *f = bt->Struct.fields[field_index]; - if (!elem_type_can_be_constant(f->type)) { - continue; - } - - i64 offset = bt->Struct.offsets[field_index]; - i64 size = type_size_of(f->type); - - - ExactValue value = {}; - if (tav.mode != Addressing_Invalid) { - value = tav.value; - } - - GB_ASSERT(is_type_endian_little(f->type)); - GB_ASSERT(!is_type_different_to_arch_endianness(type)); - - - if (value.kind != ExactValue_Invalid) { - switch (value.kind) { - case ExactValue_Bool: - { - bool *res = cast(bool *)tb_global_add_region(m->mod, global, offset, size); - *res = !!value.value_bool; - } - break; - - case ExactValue_Integer: - { - void *res = tb_global_add_region(m->mod, global, offset, size); - cg_write_big_int_at_ptr(res, &value.value_integer, f->type); - } - break; - - case ExactValue_Float: - { - f64 f = exact_value_to_f64(value); - void *res = tb_global_add_region(m->mod, global, offset, size); - switch (size) { - case 2: *(u16 *)res = f32_to_f16(cast(f32)f); break; - case 4: *(f32 *)res = cast(f32)f; break; - case 8: *(f64 *)res = cast(f64)f; break; - } - } - break; - - case ExactValue_Pointer: - { - void *res = tb_global_add_region(m->mod, global, offset, size); - *(u64 *)res = exact_value_to_u64(value); - } - break; - - case ExactValue_String: - { - TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_string(m, value.value_string, f->type); - tb_global_add_symbol_reloc(m->mod, global, offset, symbol); - } - break; - - case ExactValue_Typeid: - { - void *dst = tb_global_add_region(m->mod, global, offset, size); - u64 id = cg_typeid_as_u64(m, value.value_typeid); - cg_write_uint_at_ptr(dst, id, t_typeid); - } - break; - - case ExactValue_Procedure: - GB_PANIC("TODO(bill): nested procedure values/literals\n"); - break; - case ExactValue_Compound: - GB_PANIC("TODO(bill): nested compound literals\n"); - break; - - case ExactValue_Complex: - GB_PANIC("TODO(bill): nested complex literals\n"); - break; - case ExactValue_Quaternion: - GB_PANIC("TODO(bill): nested quaternions literals\n"); - break; - default: - GB_PANIC("%s", type_to_string(f->type)); - break; - } - visited[i] = true; - continue; - } - - values[i] = cg_const_value(m, p, f->type, value, allow_local); - visited[i] = true; - } - } - - TB_Symbol *symbol = cast(TB_Symbol *)global; + { + TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_comp_literal(m, type, value.value_compound, allow_local); if (p) { TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); return cg_lvalue_addr(node, type); } else { return cg_value(symbol, type); } - - } else { - GB_PANIC("TODO(bill): constant compound literal for %s", type_to_string(type)); } break; } -- cgit v1.2.3 From c61e7c05daffc3ba8854170d5f293ddf1e758d4e Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 20 Jul 2023 00:34:24 +0100 Subject: Begin working on global constants --- src/tilde_const.cpp | 297 ++++++++++++++++++++++++++++++++++++++-------------- src/types.cpp | 13 ++- 2 files changed, 227 insertions(+), 83 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index ef3f38f09..d89e43c2f 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -139,9 +139,192 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty return global; } -gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *type, Ast *value_compound, bool allow_local); +gb_internal bool cg_elem_type_can_be_constant(Type *t) { + t = base_type(t); + if (t == t_invalid) { + return false; + } + if (is_type_dynamic_array(t) || is_type_map(t)) { + return false; + } + return true; +} + + +gb_internal bool cg_is_elem_const(Ast *elem, Type *elem_type) { + if (!cg_elem_type_can_be_constant(elem_type)) { + return false; + } + if (elem->kind == Ast_FieldValue) { + elem = elem->FieldValue.value; + } + TypeAndValue tav = type_and_value_of_expr(elem); + GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(elem), type_to_string(tav.type)); + return tav.value.kind != ExactValue_Invalid; +} + +gb_internal bool cg_is_nested_possibly_constant(Type *ft, Selection const &sel, Ast *elem) { + GB_ASSERT(!sel.indirect); + for (i32 index : sel.index) { + Type *bt = base_type(ft); + switch (bt->kind) { + case Type_Struct: + // if (bt->Struct.is_raw_union) { + // return false; + // } + ft = bt->Struct.fields[index]->type; + break; + case Type_Array: + ft = bt->Array.elem; + break; + default: + return false; + } + } + return cg_is_elem_const(elem, ft); +} -gb_internal bool cg_global_const_add_region(cgModule *m, TB_Global *global, ExactValue const &value, Type *type, i64 offset, bool allow_local) { +gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *type) { + type = core_type(type); + + switch (type->kind) { + case Type_Basic: + switch (type->Basic.kind) { + case Basic_string: // ^u8 + int + case Basic_any: // rawptr + typeid + return 2; + } + return 1; + case Type_Pointer: + case Type_MultiPointer: + case Type_Proc: + return true; + case Type_Slice: + return 2; + case Type_DynamicArray: + return 5; + case Type_Map: + return 4; + + case Type_Enum: + case Type_BitSet: + return 1; + + case Type_RelativePointer: + return 1; + case Type_RelativeSlice: + return 1; // technically 1 + case Type_Matrix: + return 1; + + default: + GB_PANIC("TODO(bill): %s", type_to_string(type)); + break; + } + return -1; +} +gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value, Type *type) { + isize count = 0; + switch (value.kind) { + case ExactValue_Invalid: + break; + case ExactValue_Bool: + case ExactValue_Integer: + case ExactValue_Float: + case ExactValue_Pointer: + case ExactValue_Typeid: + case ExactValue_Complex: + case ExactValue_Quaternion: + count += 1; + break; + + case ExactValue_Procedure: + count += 1; + break; + + case ExactValue_String: + if (is_type_cstring(type) || is_type_array_like(type)) { + count += 1; + } else { + count += 2; + } + break; + + case ExactValue_Compound: { + ast_node(cl, CompoundLit, value.value_compound); + Type *bt = base_type(type); + if (bt->kind == Type_Struct) { + if (cl->elems[0]->kind == Ast_FieldValue) { + isize elem_count = cl->elems.count; + for (isize i = 0; i < elem_count; i++) { + ast_node(fv, FieldValue, cl->elems[i]); + String name = fv->field->Ident.token.string; + + Selection sel = lookup_field(type, name, false); + GB_ASSERT(!sel.indirect); + + Entity *f = bt->Struct.fields[sel.index[0]]; + + if (!cg_elem_type_can_be_constant(f->type)) { + continue; + } + + if (sel.index.count == 1) { + count += cg_global_const_calculate_region_count(fv->value->tav.value, f->type); + } else { + TEMPORARY_ALLOCATOR_GUARD(); + isize idx_list_len = sel.index.count-1; + isize *idx_list = gb_alloc_array(temporary_allocator(), isize, idx_list_len); + + count += 1; // just in case + if (cg_is_nested_possibly_constant(type, sel, fv->value)) { + Type *cv_type = f->type; + for (isize j = 1; j < sel.index.count; j++) { + i32 index = sel.index[j]; + Type *cvt = base_type(cv_type); + + idx_list[j-1] = index; + if (cvt->kind == Type_Struct) { + cv_type = cvt->Struct.fields[index]->type; + } else if (cvt->kind == Type_Array) { + cv_type = cvt->Array.elem; + } else { + GB_PANIC("UNKNOWN TYPE: %s", type_to_string(cv_type)); + } + } + + count += cg_global_const_calculate_region_count(fv->value->tav.value, cv_type); + } + } + } + } else { + for_array(i, cl->elems) { + i64 field_index = i; + Ast *elem = cl->elems[i]; + TypeAndValue tav = elem->tav; + Entity *f = bt->Struct.fields[field_index]; + if (!cg_elem_type_can_be_constant(f->type)) { + continue; + } + + ExactValue value = {}; + if (tav.mode != Addressing_Invalid) { + value = tav.value; + } + count += cg_global_const_calculate_region_count(value, type); + } + } + } else { + GB_PANIC("TODO(bill): %s", type_to_string(type)); + } + }break; + } + return count; +} + +gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *type, ExactValue const &value, TB_Global *global, i64 base_offset); + +gb_internal bool cg_global_const_add_region(cgModule *m, TB_Global *global, ExactValue const &value, Type *type, i64 offset) { GB_ASSERT(is_type_endian_little(type)); GB_ASSERT(!is_type_different_to_arch_endianness(type)); @@ -198,8 +381,8 @@ gb_internal bool cg_global_const_add_region(cgModule *m, TB_Global *global, Exac case ExactValue_Compound: { - TB_Global *nested_global = cg_global_const_comp_literal(m, type, value.value_compound, allow_local); - tb_global_add_symbol_reloc(m->mod, global, offset, cast(TB_Symbol *)nested_global); + TB_Global *out_global = cg_global_const_comp_literal(m, type, value, global, offset); + GB_ASSERT(out_global == global); } break; @@ -269,32 +452,36 @@ gb_internal bool cg_global_const_add_region(cgModule *m, TB_Global *global, Exac } -gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *type, Ast *value_compound, bool allow_local) { - Type *original_type = type; - if (is_type_struct(type)) { - ast_node(cl, CompoundLit, value_compound); +gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_type, ExactValue const &value, TB_Global *global, i64 base_offset) { + GB_ASSERT(value.kind == ExactValue_Compound); + Ast *value_compound = value.value_compound; + ast_node(cl, CompoundLit, value_compound); - Type *bt = base_type(type); + TEMPORARY_ALLOCATOR_GUARD(); + if (global == nullptr) { char name[32] = {}; gb_snprintf(name, 31, "complit$%u", 1+m->const_nil_guid.fetch_add(1)); - TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, original_type), TB_LINKAGE_PRIVATE); + global = tb_global_create(m->mod, -1, name, cg_debug_type(m, original_type), TB_LINKAGE_PRIVATE); i64 size = type_size_of(original_type); i64 align = type_align_of(original_type); // READ ONLY? TB_ModuleSection *section = tb_module_get_rdata(m->mod); - if (cl->elems.count == 0/* || bt->Struct.is_raw_union*/) { + if (cl->elems.count == 0) { tb_global_set_storage(m->mod, section, global, size, align, 0); return global; } - TEMPORARY_ALLOCATOR_GUARD(); - isize value_count = bt->Struct.fields.count; - // cgValue * values = gb_alloc_array(temporary_allocator(), cgValue, value_count); - bool * visited = gb_alloc_array(temporary_allocator(), bool, value_count); - tb_global_set_storage(m->mod, section, global, size, align, value_count); + isize global_region_count = cg_global_const_calculate_region_count(value, original_type); + tb_global_set_storage(m->mod, section, global, size, align, global_region_count); + gb_printf_err("global_region_count %td\n", global_region_count); + } + + + Type *bt = base_type(original_type); + if (bt->kind == Type_Struct) { if (cl->elems[0]->kind == Ast_FieldValue) { isize elem_count = cl->elems.count; for (isize i = 0; i < elem_count; i++) { @@ -303,65 +490,18 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *type, Ast TypeAndValue tav = fv->value->tav; GB_ASSERT(tav.mode != Addressing_Invalid); + ExactValue value = tav.value; - Selection sel = lookup_field(type, name, false); + Selection sel = lookup_field(bt, name, false); GB_ASSERT(!sel.indirect); - Entity *f = bt->Struct.fields[sel.index[0]]; - i64 index = f->Variable.field_index; - if (elem_type_can_be_constant(f->type)) { - if (sel.index.count == 1) { - i64 offset = bt->Struct.offsets[index]; - if (cg_global_const_add_region(m, global, fv->value->tav.value, f->type, offset, allow_local)) { - visited[i] = true; - continue; - } - } else { - // if (!visited[index]) { - GB_PANIC("using struct fields"); - // values[index] = lb_const_value(m, f->type, {}, false).value; - // visited[index] = true; - // } - // unsigned idx_list_len = cast(unsigned)sel.index.count-1; - // unsigned *idx_list = gb_alloc_array(temporary_allocator(), unsigned, idx_list_len); - - // if (lb_is_nested_possibly_constant(type, sel, fv->value)) { - // bool is_constant = true; - // Type *cv_type = f->type; - // for (isize j = 1; j < sel.index.count; j++) { - // i32 index = sel.index[j]; - // Type *cvt = base_type(cv_type); - - // if (cvt->kind == Type_Struct) { - // if (cvt->Struct.is_raw_union) { - // // sanity check which should have been caught by `lb_is_nested_possibly_constant` - // is_constant = false; - // break; - // } - // cv_type = cvt->Struct.fields[index]->type; - - // if (is_type_struct(cvt)) { - // auto cv_field_remapping = lb_get_struct_remapping(m, cvt); - // unsigned remapped_index = cast(unsigned)cv_field_remapping[index]; - // idx_list[j-1] = remapped_index; - // } else { - // idx_list[j-1] = cast(unsigned)index; - // } - // } else if (cvt->kind == Type_Array) { - // cv_type = cvt->Array.elem; - - // idx_list[j-1] = cast(unsigned)index; - // } else { - // GB_PANIC("UNKNOWN TYPE: %s", type_to_string(cv_type)); - // } - // } - // if (is_constant) { - // LLVMValueRef elem_value = lb_const_value(m, tav.type, tav.value, allow_local).value; - // GB_ASSERT(LLVMIsConstant(elem_value)); - // values[index] = LLVMConstInsertValue(values[index], elem_value, idx_list, idx_list_len); - // } - // } - } + if (!cg_is_nested_possibly_constant(bt, sel, fv->value)) { + continue; + } + + i64 offset = type_offset_of_from_selection(bt, sel); + if (cg_global_const_add_region(m, global, value, sel.entity->type, base_offset+offset)) { + continue; } } } else { @@ -370,7 +510,7 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *type, Ast Ast *elem = cl->elems[i]; TypeAndValue tav = elem->tav; Entity *f = bt->Struct.fields[field_index]; - if (!elem_type_can_be_constant(f->type)) { + if (!cg_elem_type_can_be_constant(f->type)) { continue; } @@ -380,8 +520,7 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *type, Ast if (tav.mode != Addressing_Invalid) { value = tav.value; } - if (cg_global_const_add_region(m, global, value, f->type, offset, allow_local)) { - visited[i] = true; + if (cg_global_const_add_region(m, global, value, f->type, base_offset+offset)) { continue; } } @@ -390,16 +529,14 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *type, Ast return global; } - GB_PANIC("TODO(bill): constant compound literal for %s", type_to_string(type)); + GB_PANIC("TODO(bill): constant compound literal for %s", type_to_string(original_type)); return nullptr; } -gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value, bool allow_local_ = true) { +gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value) { TB_Node *node = nullptr; - bool allow_local = allow_local_ && p != nullptr; - TB_DataType dt = cg_data_type(type); switch (value.kind) { @@ -470,7 +607,7 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac case ExactValue_Compound: { - TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_comp_literal(m, type, value.value_compound, allow_local); + TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_comp_literal(m, type, value, nullptr, 0); if (p) { TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); return cg_lvalue_addr(node, type); diff --git a/src/types.cpp b/src/types.cpp index ff8c42d83..f513f23d9 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -725,7 +725,7 @@ struct TypePath; gb_internal i64 type_size_of (Type *t); gb_internal i64 type_align_of (Type *t); -gb_internal i64 type_offset_of (Type *t, i32 index, Type **field_type_=nullptr); +gb_internal i64 type_offset_of (Type *t, i64 index, Type **field_type_=nullptr); gb_internal gbString type_to_string (Type *type, bool shorthand=true); gb_internal gbString type_to_string (Type *type, gbAllocator allocator, bool shorthand=true); gb_internal i64 type_size_of_internal(Type *t, TypePath *path); @@ -3907,7 +3907,7 @@ gb_internal i64 type_size_of_internal(Type *t, TypePath *path) { return build_context.ptr_size; } -gb_internal i64 type_offset_of(Type *t, i32 index, Type **field_type_) { +gb_internal i64 type_offset_of(Type *t, i64 index, Type **field_type_) { t = base_type(t); switch (t->kind) { case Type_Struct: @@ -3926,6 +3926,11 @@ gb_internal i64 type_offset_of(Type *t, i32 index, Type **field_type_) { return t->Tuple.offsets[index]; } break; + + case Type_Array: + GB_ASSERT(0 <= index && index < t->Array.count); + return index * type_size_of(t->Array.elem); + case Type_Basic: if (t->Basic.kind == Basic_string) { switch (index) { @@ -3999,8 +4004,10 @@ gb_internal i64 type_offset_of_from_selection(Type *type, Selection sel) { i32 index = sel.index[i]; t = base_type(t); offset += type_offset_of(t, index); - if (t->kind == Type_Struct && !t->Struct.is_raw_union) { + if (t->kind == Type_Struct) { t = t->Struct.fields[index]->type; + } else if (t->kind == Type_Array) { + t = t->Array.elem; } else { // NOTE(bill): No need to worry about custom types, just need the alignment switch (t->kind) { -- cgit v1.2.3 From 737b8e42e4b2c5c0aa94da2aed37c9d9634ce866 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 20 Jul 2023 00:48:52 +0100 Subject: Global constants for arrays --- src/tilde_const.cpp | 103 +++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 93 insertions(+), 10 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index d89e43c2f..dcacefdb0 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -253,10 +253,10 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value case ExactValue_Compound: { ast_node(cl, CompoundLit, value.value_compound); Type *bt = base_type(type); - if (bt->kind == Type_Struct) { + switch (bt->kind) { + case Type_Struct: if (cl->elems[0]->kind == Ast_FieldValue) { - isize elem_count = cl->elems.count; - for (isize i = 0; i < elem_count; i++) { + for (isize i = 0; i < cl->elems.count; i++) { ast_node(fv, FieldValue, cl->elems[i]); String name = fv->field->Ident.token.string; @@ -314,8 +314,44 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value count += cg_global_const_calculate_region_count(value, type); } } - } else { + break; + case Type_Array: + if (!cg_elem_type_can_be_constant(bt->Array.elem)) { + break; + } + for (Ast *elem : cl->elems) { + if (elem->kind == Ast_FieldValue) { + ast_node(fv, FieldValue, elem); + ExactValue const &value = elem->FieldValue.value->tav.value; + if (is_ast_range(fv->field)) { + ast_node(ie, BinaryExpr, fv->field); + TypeAndValue lo_tav = ie->left->tav; + TypeAndValue hi_tav = ie->right->tav; + GB_ASSERT(lo_tav.mode == Addressing_Constant); + GB_ASSERT(hi_tav.mode == Addressing_Constant); + + TokenKind op = ie->op.kind; + i64 lo = exact_value_to_i64(lo_tav.value); + i64 hi = exact_value_to_i64(hi_tav.value); + if (op != Token_RangeHalf) { + hi += 1; + } + + for (i64 i = lo; i < hi; i++) { + count += cg_global_const_calculate_region_count(value, bt->Array.elem); + } + } else { + count += cg_global_const_calculate_region_count(value, bt->Array.elem); + } + } else { + ExactValue const &value = elem->tav.value; + count += cg_global_const_calculate_region_count(value, bt->Array.elem); + } + } + break; + default: GB_PANIC("TODO(bill): %s", type_to_string(type)); + break; } }break; } @@ -479,9 +515,13 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ gb_printf_err("global_region_count %td\n", global_region_count); } + if (cl->elems.count == 0) { + return global; + } Type *bt = base_type(original_type); - if (bt->kind == Type_Struct) { + switch (bt->kind) { + case Type_Struct: if (cl->elems[0]->kind == Ast_FieldValue) { isize elem_count = cl->elems.count; for (isize i = 0; i < elem_count; i++) { @@ -500,9 +540,7 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ } i64 offset = type_offset_of_from_selection(bt, sel); - if (cg_global_const_add_region(m, global, value, sel.entity->type, base_offset+offset)) { - continue; - } + cg_global_const_add_region(m, global, value, sel.entity->type, base_offset+offset); } } else { for_array(i, cl->elems) { @@ -520,10 +558,55 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ if (tav.mode != Addressing_Invalid) { value = tav.value; } - if (cg_global_const_add_region(m, global, value, f->type, base_offset+offset)) { - continue; + cg_global_const_add_region(m, global, value, f->type, base_offset+offset); + } + } + return global; + + case Type_Array: + if (cl->elems[0]->kind == Ast_FieldValue) { + Type *et = bt->Array.elem; + i64 elem_size = type_size_of(et); + for (Ast *elem : cl->elems) { + ast_node(fv, FieldValue, elem); + + ExactValue const &value = fv->value->tav.value; + + if (is_ast_range(fv->field)) { + ast_node(ie, BinaryExpr, fv->field); + TypeAndValue lo_tav = ie->left->tav; + TypeAndValue hi_tav = ie->right->tav; + GB_ASSERT(lo_tav.mode == Addressing_Constant); + GB_ASSERT(hi_tav.mode == Addressing_Constant); + + TokenKind op = ie->op.kind; + i64 lo = exact_value_to_i64(lo_tav.value); + i64 hi = exact_value_to_i64(hi_tav.value); + if (op != Token_RangeHalf) { + hi += 1; + } + + for (i64 i = lo; i < hi; i++) { + i64 offset = i * elem_size; + cg_global_const_add_region(m, global, value, et, base_offset+offset); + } + } else { + TypeAndValue index_tav = fv->field->tav; + GB_ASSERT(index_tav.mode == Addressing_Constant); + i64 i = exact_value_to_i64(index_tav.value); + i64 offset = i * elem_size; + cg_global_const_add_region(m, global, value, et, base_offset+offset); } } + } else { + Type *et = bt->Array.elem; + i64 elem_size = type_size_of(et); + i64 offset = 0; + for (Ast *elem : cl->elems) { + ExactValue const &value = elem->tav.value; + cg_global_const_add_region(m, global, value, et, base_offset+offset); + offset += elem_size; + } } return global; -- cgit v1.2.3 From bcdcad5847fb379269f6e76df52c33cea90f095a Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 20 Jul 2023 01:24:19 +0100 Subject: Add global string constants --- src/tilde_const.cpp | 156 +++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 113 insertions(+), 43 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index dcacefdb0..ead92ca26 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -51,18 +51,6 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { return cg_const_nil(p->module, p, type); } -gb_internal TB_Global *cg_global_const_cstring(cgModule *m, String const &str, Type *type) { - char name[32] = {}; - gb_snprintf(name, 31, "csb$%u", 1+m->const_nil_guid.fetch_add(1)); - TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); - i64 size = str.len+1; - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, size, 1, 1); - u8 *data = cast(u8 *)tb_global_add_region(m->mod, global, 0, size+1); - gb_memcopy(data, str.text, str.len); - data[str.len] = 0; - return global; - -} gb_internal void cg_write_big_int_at_ptr(void *dst, BigInt const *a, Type *original_type) { GB_ASSERT(build_context.endian_kind == TargetEndian_Little); @@ -116,24 +104,34 @@ gb_internal void cg_write_uint_at_ptr(void *dst, u64 i, Type *original_type) { cg_write_big_int_at_ptr(dst, &v.value_integer, original_type); } -gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Type *type) { - if (is_type_cstring(type)) { - return cg_global_const_cstring(m, str, type); - } +gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Type *type, TB_Global *global, i64 offset) { GB_ASSERT(is_type_string(type)); char name[32] = {}; - gb_snprintf(name, 31, "csl$%u", 1+m->const_nil_guid.fetch_add(1)); - TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); + gb_snprintf(name, 31, "csb$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *str_global = tb_global_create(m->mod, -1, name, cg_debug_type(m, t_cstring), TB_LINKAGE_PRIVATE); + i64 size = str.len+1; + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_global, size, 1, 1); + u8 *data = cast(u8 *)tb_global_add_region(m->mod, str_global, 0, size); + gb_memcopy(data, str.text, str.len); + data[str.len] = 0; - i64 size = type_size_of(type); - i64 align = type_align_of(type); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, size, align, 2); + if (is_type_cstring(type)) { + if (global) { + tb_global_add_symbol_reloc(m->mod, global, offset+0, cast(TB_Symbol *)str_global); + } + return str_global; + } - tb_global_add_symbol_reloc(m->mod, global, 0, cast(TB_Symbol *)cg_global_const_cstring(m, str, t_cstring)); + if (global == nullptr) { + global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_global, type_size_of(type), type_align_of(type), 2); + + } - void *len_ptr = tb_global_add_region(m->mod, global, build_context.int_size, build_context.int_size); + tb_global_add_symbol_reloc(m->mod, global, offset+0, cast(TB_Symbol *)str_global); + void *len_ptr = tb_global_add_region(m->mod, global, offset+build_context.int_size, build_context.int_size); cg_write_int_at_ptr(len_ptr, str.len, t_int); return global; @@ -243,7 +241,9 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value break; case ExactValue_String: - if (is_type_cstring(type) || is_type_array_like(type)) { + if (is_type_string(type)) { + count += 2; + } else if (is_type_cstring(type) || is_type_array_like(type)) { count += 1; } else { count += 2; @@ -316,7 +316,10 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value } break; case Type_Array: - if (!cg_elem_type_can_be_constant(bt->Array.elem)) { + case Type_EnumeratedArray: + case Type_SimdVector: { + Type *et = base_array_type(bt); + if (!cg_elem_type_can_be_constant(et)) { break; } for (Ast *elem : cl->elems) { @@ -338,17 +341,29 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value } for (i64 i = lo; i < hi; i++) { - count += cg_global_const_calculate_region_count(value, bt->Array.elem); + count += cg_global_const_calculate_region_count(value, et); } } else { - count += cg_global_const_calculate_region_count(value, bt->Array.elem); + count += cg_global_const_calculate_region_count(value, et); } } else { ExactValue const &value = elem->tav.value; - count += cg_global_const_calculate_region_count(value, bt->Array.elem); + count += cg_global_const_calculate_region_count(value, et); } } + } break; + + case Type_BitSet: + count += 1; + break; + case Type_Matrix: + count += 1; + break; + + case Type_Slice: + count += 2; break; + default: GB_PANIC("TODO(bill): %s", type_to_string(type)); break; @@ -360,7 +375,7 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *type, ExactValue const &value, TB_Global *global, i64 base_offset); -gb_internal bool cg_global_const_add_region(cgModule *m, TB_Global *global, ExactValue const &value, Type *type, i64 offset) { +gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value, Type *type, TB_Global *global, i64 offset) { GB_ASSERT(is_type_endian_little(type)); GB_ASSERT(!is_type_different_to_arch_endianness(type)); @@ -401,10 +416,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, TB_Global *global, Exac break; case ExactValue_String: - { - TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_string(m, value.value_string, type); - tb_global_add_symbol_reloc(m->mod, global, offset, symbol); - } + cg_global_const_string(m, value.value_string, type, global, offset); break; case ExactValue_Typeid: @@ -503,7 +515,13 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ i64 align = type_align_of(original_type); // READ ONLY? - TB_ModuleSection *section = tb_module_get_rdata(m->mod); + TB_ModuleSection *section = nullptr; + if (is_type_string(original_type) || is_type_cstring(original_type)) { + section = tb_module_get_rdata(m->mod); + } else { + section = tb_module_get_data(m->mod); + } + if (cl->elems.count == 0) { tb_global_set_storage(m->mod, section, global, size, align, 0); return global; @@ -512,14 +530,16 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ isize global_region_count = cg_global_const_calculate_region_count(value, original_type); tb_global_set_storage(m->mod, section, global, size, align, global_region_count); - gb_printf_err("global_region_count %td\n", global_region_count); } if (cl->elems.count == 0) { return global; } + Type *bt = base_type(original_type); + i64 bt_size = type_size_of(bt); + switch (bt->kind) { case Type_Struct: if (cl->elems[0]->kind == Ast_FieldValue) { @@ -539,8 +559,9 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ continue; } + i64 offset = type_offset_of_from_selection(bt, sel); - cg_global_const_add_region(m, global, value, sel.entity->type, base_offset+offset); + cg_global_const_add_region(m, value, sel.entity->type, global, base_offset+offset); } } else { for_array(i, cl->elems) { @@ -558,14 +579,16 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ if (tav.mode != Addressing_Invalid) { value = tav.value; } - cg_global_const_add_region(m, global, value, f->type, base_offset+offset); + cg_global_const_add_region(m, value, f->type, global, base_offset+offset); } } return global; case Type_Array: + case Type_EnumeratedArray: + case Type_SimdVector: if (cl->elems[0]->kind == Ast_FieldValue) { - Type *et = bt->Array.elem; + Type *et = base_array_type(bt); i64 elem_size = type_size_of(et); for (Ast *elem : cl->elems) { ast_node(fv, FieldValue, elem); @@ -588,28 +611,75 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ for (i64 i = lo; i < hi; i++) { i64 offset = i * elem_size; - cg_global_const_add_region(m, global, value, et, base_offset+offset); + cg_global_const_add_region(m, value, et, global, base_offset+offset); } } else { TypeAndValue index_tav = fv->field->tav; GB_ASSERT(index_tav.mode == Addressing_Constant); i64 i = exact_value_to_i64(index_tav.value); i64 offset = i * elem_size; - cg_global_const_add_region(m, global, value, et, base_offset+offset); + cg_global_const_add_region(m, value, et, global, base_offset+offset); } } } else { - Type *et = bt->Array.elem; + Type *et = base_array_type(bt); i64 elem_size = type_size_of(et); i64 offset = 0; for (Ast *elem : cl->elems) { ExactValue const &value = elem->tav.value; - cg_global_const_add_region(m, global, value, et, base_offset+offset); + cg_global_const_add_region(m, value, et, global, base_offset+offset); offset += elem_size; } } return global; + + case Type_BitSet: + if (bt_size > 0) { + BigInt bits = {}; + BigInt one = {}; + big_int_from_u64(&one, 1); + + for_array(i, cl->elems) { + Ast *e = cl->elems[i]; + GB_ASSERT(e->kind != Ast_FieldValue); + + TypeAndValue tav = e->tav; + if (tav.mode != Addressing_Constant) { + continue; + } + GB_ASSERT(tav.value.kind == ExactValue_Integer); + i64 v = big_int_to_i64(&tav.value.value_integer); + i64 lower = bt->BitSet.lower; + u64 index = cast(u64)(v-lower); + BigInt bit = {}; + big_int_from_u64(&bit, index); + big_int_shl(&bit, &one, &bit); + big_int_or(&bits, &bits, &bit); + } + + void *dst = tb_global_add_region(m->mod, global, base_offset, bt_size); + cg_write_big_int_at_ptr(dst, &bits, original_type); + } + return global; + + case Type_Matrix: + GB_PANIC("TODO(bill): constant compound literal for %s", type_to_string(original_type)); + break; + + case Type_Slice: + { + i64 count = gb_max(cl->elems.count, cl->max_count); + Type *elem = bt->Slice.elem; + Type *t = alloc_type_array(elem, count); + TB_Global *backing_array = cg_global_const_comp_literal(m, t, value, nullptr, 0); + + tb_global_add_symbol_reloc(m->mod, global, base_offset+0, cast(TB_Symbol *)backing_array); + + void *len_ptr = tb_global_add_region(m->mod, global, base_offset+build_context.int_size, build_context.int_size); + cg_write_int_at_ptr(len_ptr, count, t_int); + } + return global; } GB_PANIC("TODO(bill): constant compound literal for %s", type_to_string(original_type)); @@ -676,7 +746,7 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac case ExactValue_String: { - TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_string(m, value.value_string, type); + TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_string(m, value.value_string, type, nullptr, 0); if (p) { TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); return cg_lvalue_addr(node, type); -- cgit v1.2.3 From b54f3d4ee9a57e0a88140ad581b8fae6ca28a11f Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 20 Jul 2023 01:54:36 +0100 Subject: Mock out more global value stuff --- src/llvm_backend_const.cpp | 2 +- src/tilde_const.cpp | 327 ++++++++++++++++++++++++++++----------------- 2 files changed, 206 insertions(+), 123 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/llvm_backend_const.cpp b/src/llvm_backend_const.cpp index a152e00c2..5c390a370 100644 --- a/src/llvm_backend_const.cpp +++ b/src/llvm_backend_const.cpp @@ -567,7 +567,7 @@ gb_internal lbValue lb_const_value(lbModule *m, Type *type, ExactValue value, bo } } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) { - if (is_type_rune_array(type) && value.kind == ExactValue_String) { + if (is_type_rune_array(type)) { i64 count = type->Array.count; Type *elem = type->Array.elem; LLVMTypeRef et = lb_type(m, elem); diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index ead92ca26..256d3a58a 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -110,7 +110,7 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty char name[32] = {}; gb_snprintf(name, 31, "csb$%u", 1+m->const_nil_guid.fetch_add(1)); - TB_Global *str_global = tb_global_create(m->mod, -1, name, cg_debug_type(m, t_cstring), TB_LINKAGE_PRIVATE); + TB_Global *str_global = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); i64 size = str.len+1; tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_global, size, 1, 1); u8 *data = cast(u8 *)tb_global_add_region(m->mod, str_global, 0, size); @@ -127,7 +127,6 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty if (global == nullptr) { global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_global, type_size_of(type), type_align_of(type), 2); - } tb_global_add_symbol_reloc(m->mod, global, offset+0, cast(TB_Symbol *)str_global); @@ -222,10 +221,34 @@ gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *typ return -1; } gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value, Type *type) { + Type *bt = base_type(type); + if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) { + if (is_type_rune_array(type)) { + return 1; + } + + Type *et = base_array_type(type); + i64 base_count = 2; + if (is_type_cstring(et)) { + base_count = 1; + } + return base_count * bt->Array.count; + } else if (is_type_u8_array(type) && value.kind == ExactValue_String) { + return 1; + } else if (is_type_array(type) && + value.kind != ExactValue_Invalid && + value.kind != ExactValue_String && + value.kind != ExactValue_Compound) { + Type *elem = type->Array.elem; + + i64 base_count = cg_global_const_calculate_region_count(value, elem); + return base_count * type->Array.count; + } + isize count = 0; switch (value.kind) { case ExactValue_Invalid: - break; + return 0; case ExactValue_Bool: case ExactValue_Integer: case ExactValue_Float: @@ -233,22 +256,18 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value case ExactValue_Typeid: case ExactValue_Complex: case ExactValue_Quaternion: - count += 1; - break; + return 1; case ExactValue_Procedure: - count += 1; - break; + return 1; case ExactValue_String: if (is_type_string(type)) { - count += 2; + return 2; } else if (is_type_cstring(type) || is_type_array_like(type)) { - count += 1; - } else { - count += 2; + return 1; } - break; + return 2; case ExactValue_Compound: { ast_node(cl, CompoundLit, value.value_compound); @@ -354,15 +373,12 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value } break; case Type_BitSet: - count += 1; - break; + return 1; case Type_Matrix: - count += 1; - break; + return 1; case Type_Slice: - count += 2; - break; + return 2; default: GB_PANIC("TODO(bill): %s", type_to_string(type)); @@ -379,124 +395,192 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value GB_ASSERT(is_type_endian_little(type)); GB_ASSERT(!is_type_different_to_arch_endianness(type)); + GB_ASSERT(global != nullptr); + i64 size = type_size_of(type); - if (value.kind != ExactValue_Invalid) { - switch (value.kind) { - case ExactValue_Bool: - { - bool *res = cast(bool *)tb_global_add_region(m->mod, global, offset, size); - *res = !!value.value_bool; - } - break; + if (value.kind == ExactValue_Invalid) { + return false; + } + if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) { + if (is_type_rune_array(type)) { + i64 count = type->Array.count; + Rune rune; + isize rune_offset = 0; + isize width = 1; + String s = value.value_string; - case ExactValue_Integer: - { - void *res = tb_global_add_region(m->mod, global, offset, size); - cg_write_big_int_at_ptr(res, &value.value_integer, type); - } - break; + Rune *runes = cast(Rune *)tb_global_add_region(m->mod, global, offset, count*4); + + for (i64 i = 0; i < count && rune_offset < s.len; i++) { + width = utf8_decode(s.text+rune_offset, s.len-rune_offset, &rune); + runes[i] = rune; + rune_offset += width; - case ExactValue_Float: - { - f64 f = exact_value_to_f64(value); - void *res = tb_global_add_region(m->mod, global, offset, size); - switch (size) { - case 2: *(u16 *)res = f32_to_f16(cast(f32)f); break; - case 4: *(f32 *)res = cast(f32)f; break; - case 8: *(f64 *)res = cast(f64)f; break; - } } - break; + GB_ASSERT(offset == s.len); + return true; + } + Type *bt = base_type(type); + Type *et = bt->Array.elem; + i64 elem_size = type_size_of(et); + + for (i64 i = 0; i < bt->Array.count; i++) { + cg_global_const_add_region(m, value, et, global, offset+(i * elem_size)); + } + return true; + } else if (is_type_u8_array(type) && value.kind == ExactValue_String) { + u8 *dst = cast(u8 *)tb_global_add_region(m->mod, global, offset, size); + gb_memcopy(dst, value.value_string.text, gb_min(value.value_string.len, size)); + return true; + } else if (is_type_array(type) && + value.kind != ExactValue_Invalid && + value.kind != ExactValue_String && + value.kind != ExactValue_Compound) { + + Type *bt = base_type(type); + Type *et = bt->Array.elem; + i64 elem_size = type_size_of(et); + + for (i64 i = 0; i < bt->Array.count; i++) { + cg_global_const_add_region(m, value, et, global, offset+(i * elem_size)); + } + + return true; + } else if (is_type_matrix(type) && + value.kind != ExactValue_Invalid && + value.kind != ExactValue_Compound) { + i64 row = type->Matrix.row_count; + i64 column = type->Matrix.column_count; + GB_ASSERT(row == column); + + GB_PANIC("TODO(bill): constant matrix from scalar"); + } else if (is_type_simd_vector(type) && + value.kind != ExactValue_Invalid && + value.kind != ExactValue_Compound) { + GB_PANIC("TODO(bill): constant vector from scalar"); + } + - case ExactValue_Pointer: - { - void *res = tb_global_add_region(m->mod, global, offset, size); - *(u64 *)res = exact_value_to_u64(value); + switch (value.kind) { + case ExactValue_Bool: + { + bool *res = cast(bool *)tb_global_add_region(m->mod, global, offset, size); + *res = !!value.value_bool; + } + break; + + case ExactValue_Integer: + { + void *res = tb_global_add_region(m->mod, global, offset, size); + cg_write_big_int_at_ptr(res, &value.value_integer, type); + } + break; + + case ExactValue_Float: + { + f64 f = exact_value_to_f64(value); + void *res = tb_global_add_region(m->mod, global, offset, size); + switch (size) { + case 2: *(u16 *)res = f32_to_f16(cast(f32)f); break; + case 4: *(f32 *)res = cast(f32)f; break; + case 8: *(f64 *)res = cast(f64)f; break; } - break; + } + break; + + case ExactValue_Pointer: + { + void *res = tb_global_add_region(m->mod, global, offset, size); + *(u64 *)res = exact_value_to_u64(value); + } + break; - case ExactValue_String: + case ExactValue_String: + if (is_type_array_like(type)) { + GB_ASSERT(global != nullptr); + void *data = tb_global_add_region(m->mod, global, offset, size); + gb_memcopy(data, value.value_string.text, gb_min(value.value_string.len, size)); + } else { cg_global_const_string(m, value.value_string, type, global, offset); - break; + } + break; - case ExactValue_Typeid: - { - void *dst = tb_global_add_region(m->mod, global, offset, size); - u64 id = cg_typeid_as_u64(m, value.value_typeid); - cg_write_uint_at_ptr(dst, id, t_typeid); - } - break; + case ExactValue_Typeid: + { + void *dst = tb_global_add_region(m->mod, global, offset, size); + u64 id = cg_typeid_as_u64(m, value.value_typeid); + cg_write_uint_at_ptr(dst, id, t_typeid); + } + break; - case ExactValue_Compound: - { - TB_Global *out_global = cg_global_const_comp_literal(m, type, value, global, offset); - GB_ASSERT(out_global == global); - } - break; + case ExactValue_Compound: + { + TB_Global *out_global = cg_global_const_comp_literal(m, type, value, global, offset); + GB_ASSERT(out_global == global); + } + break; - case ExactValue_Procedure: - GB_PANIC("TODO(bill): nested procedure values/literals\n"); - break; - case ExactValue_Complex: - { - Complex128 c = {}; - if (value.value_complex) { - c = *value.value_complex; - } - void *res = tb_global_add_region(m->mod, global, offset, size); - switch (size) { - case 4: - ((u16 *)res)[0] = f32_to_f16(cast(f32)c.real); - ((u16 *)res)[1] = f32_to_f16(cast(f32)c.imag); - break; - case 8: - ((f32 *)res)[0] = cast(f32)c.real; - ((f32 *)res)[1] = cast(f32)c.imag; - break; - case 16: - ((f64 *)res)[0] = cast(f64)c.real; - ((f64 *)res)[1] = cast(f64)c.imag; - break; - } + case ExactValue_Procedure: + GB_PANIC("TODO(bill): nested procedure values/literals\n"); + break; + case ExactValue_Complex: + { + Complex128 c = {}; + if (value.value_complex) { + c = *value.value_complex; } - break; - case ExactValue_Quaternion: - { - // @QuaternionLayout - Quaternion256 q = {}; - if (value.value_quaternion) { - q = *value.value_quaternion; - } - void *res = tb_global_add_region(m->mod, global, offset, size); - switch (size) { - case 8: - ((u16 *)res)[0] = f32_to_f16(cast(f32)q.imag); - ((u16 *)res)[1] = f32_to_f16(cast(f32)q.jmag); - ((u16 *)res)[2] = f32_to_f16(cast(f32)q.kmag); - ((u16 *)res)[3] = f32_to_f16(cast(f32)q.real); - break; - case 16: - ((f32 *)res)[0] = cast(f32)q.imag; - ((f32 *)res)[1] = cast(f32)q.jmag; - ((f32 *)res)[2] = cast(f32)q.kmag; - ((f32 *)res)[3] = cast(f32)q.real; - break; - case 32: - ((f64 *)res)[0] = cast(f64)q.imag; - ((f64 *)res)[1] = cast(f64)q.jmag; - ((f64 *)res)[2] = cast(f64)q.kmag; - ((f64 *)res)[3] = cast(f64)q.real; - break; - } + void *res = tb_global_add_region(m->mod, global, offset, size); + switch (size) { + case 4: + ((u16 *)res)[0] = f32_to_f16(cast(f32)c.real); + ((u16 *)res)[1] = f32_to_f16(cast(f32)c.imag); + break; + case 8: + ((f32 *)res)[0] = cast(f32)c.real; + ((f32 *)res)[1] = cast(f32)c.imag; + break; + case 16: + ((f64 *)res)[0] = cast(f64)c.real; + ((f64 *)res)[1] = cast(f64)c.imag; + break; } - break; - default: - GB_PANIC("%s", type_to_string(type)); - break; } - return true; + break; + case ExactValue_Quaternion: + { + // @QuaternionLayout + Quaternion256 q = {}; + if (value.value_quaternion) { + q = *value.value_quaternion; + } + void *res = tb_global_add_region(m->mod, global, offset, size); + switch (size) { + case 8: + ((u16 *)res)[0] = f32_to_f16(cast(f32)q.imag); + ((u16 *)res)[1] = f32_to_f16(cast(f32)q.jmag); + ((u16 *)res)[2] = f32_to_f16(cast(f32)q.kmag); + ((u16 *)res)[3] = f32_to_f16(cast(f32)q.real); + break; + case 16: + ((f32 *)res)[0] = cast(f32)q.imag; + ((f32 *)res)[1] = cast(f32)q.jmag; + ((f32 *)res)[2] = cast(f32)q.kmag; + ((f32 *)res)[3] = cast(f32)q.real; + break; + case 32: + ((f64 *)res)[0] = cast(f64)q.imag; + ((f64 *)res)[1] = cast(f64)q.jmag; + ((f64 *)res)[2] = cast(f64)q.kmag; + ((f64 *)res)[3] = cast(f64)q.real; + break; + } + } + break; + default: + GB_PANIC("%s", type_to_string(type)); + break; } - return false; + return true; } @@ -559,7 +643,6 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ continue; } - i64 offset = type_offset_of_from_selection(bt, sel); cg_global_const_add_region(m, value, sel.entity->type, global, base_offset+offset); } -- cgit v1.2.3 From 9fffa19c51e77141b396d3ac15c94fdac1552a5d Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 20 Jul 2023 01:58:46 +0100 Subject: Mock out more global stuff --- src/tilde_const.cpp | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 256d3a58a..9e2eac0ca 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -397,6 +397,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value GB_ASSERT(global != nullptr); + Type *bt = base_type(type); i64 size = type_size_of(type); if (value.kind == ExactValue_Invalid) { return false; @@ -420,7 +421,6 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value GB_ASSERT(offset == s.len); return true; } - Type *bt = base_type(type); Type *et = bt->Array.elem; i64 elem_size = type_size_of(et); @@ -437,7 +437,6 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value value.kind != ExactValue_String && value.kind != ExactValue_Compound) { - Type *bt = base_type(type); Type *et = bt->Array.elem; i64 elem_size = type_size_of(et); @@ -449,15 +448,31 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value } else if (is_type_matrix(type) && value.kind != ExactValue_Invalid && value.kind != ExactValue_Compound) { - i64 row = type->Matrix.row_count; - i64 column = type->Matrix.column_count; + i64 row = bt->Matrix.row_count; + i64 column = bt->Matrix.column_count; GB_ASSERT(row == column); - GB_PANIC("TODO(bill): constant matrix from scalar"); + Type *elem = bt->Matrix.elem; + + i64 elem_size = type_size_of(elem); + + for (i64 i = 0; i < row; i++) { + i64 index = matrix_indices_to_offset(type, i, i); + cg_global_const_add_region(m, value, elem, global, offset+(index * elem_size)); + } + + return true; } else if (is_type_simd_vector(type) && value.kind != ExactValue_Invalid && value.kind != ExactValue_Compound) { - GB_PANIC("TODO(bill): constant vector from scalar"); + + Type *et = type->SimdVector.elem; + i64 elem_size = type_size_of(et); + + for (i64 i = 0; i < bt->SimdVector.count; i++) { + cg_global_const_add_region(m, value, et, global, offset+(i * elem_size)); + } + return true; } -- cgit v1.2.3 From 215bebb01a9ddcd64539d0a6b6d13c404434292c Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 20 Jul 2023 02:00:20 +0100 Subject: Remove dead code --- src/tilde_const.cpp | 21 ++------------------- 1 file changed, 2 insertions(+), 19 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 9e2eac0ca..1f5176bba 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -291,27 +291,9 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value if (sel.index.count == 1) { count += cg_global_const_calculate_region_count(fv->value->tav.value, f->type); } else { - TEMPORARY_ALLOCATOR_GUARD(); - isize idx_list_len = sel.index.count-1; - isize *idx_list = gb_alloc_array(temporary_allocator(), isize, idx_list_len); - count += 1; // just in case if (cg_is_nested_possibly_constant(type, sel, fv->value)) { - Type *cv_type = f->type; - for (isize j = 1; j < sel.index.count; j++) { - i32 index = sel.index[j]; - Type *cvt = base_type(cv_type); - - idx_list[j-1] = index; - if (cvt->kind == Type_Struct) { - cv_type = cvt->Struct.fields[index]->type; - } else if (cvt->kind == Type_Array) { - cv_type = cvt->Array.elem; - } else { - GB_PANIC("UNKNOWN TYPE: %s", type_to_string(cv_type)); - } - } - + Type *cv_type = sel.entity->type; count += cg_global_const_calculate_region_count(fv->value->tav.value, cv_type); } } @@ -475,6 +457,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value return true; } + GB_ASSERT(!is_type_array_like(bt)); switch (value.kind) { case ExactValue_Bool: -- cgit v1.2.3 From 47b924990f72ef990b3fc65d79e1213a312b53bf Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 20 Jul 2023 02:03:02 +0100 Subject: Count extra stuff --- src/tilde_const.cpp | 33 ++++++++++++++++++++++++++------- 1 file changed, 26 insertions(+), 7 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 1f5176bba..6e3979637 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -243,6 +243,14 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value i64 base_count = cg_global_const_calculate_region_count(value, elem); return base_count * type->Array.count; + } else if (is_type_matrix(type) && + value.kind != ExactValue_Invalid && + value.kind != ExactValue_Compound) { + return 1; + } else if (is_type_simd_vector(type) && + value.kind != ExactValue_Invalid && + value.kind != ExactValue_Compound) { + return 1; } isize count = 0; @@ -430,6 +438,8 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value } else if (is_type_matrix(type) && value.kind != ExactValue_Invalid && value.kind != ExactValue_Compound) { + GB_PANIC("TODO(bill): matrices"); + i64 row = bt->Matrix.row_count; i64 column = bt->Matrix.column_count; GB_ASSERT(row == column); @@ -437,23 +447,23 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value Type *elem = bt->Matrix.elem; i64 elem_size = type_size_of(elem); + gb_unused(elem_size); - for (i64 i = 0; i < row; i++) { - i64 index = matrix_indices_to_offset(type, i, i); - cg_global_const_add_region(m, value, elem, global, offset+(index * elem_size)); - } + // 1 region in memory, not many return true; } else if (is_type_simd_vector(type) && value.kind != ExactValue_Invalid && value.kind != ExactValue_Compound) { + GB_PANIC("TODO(bill): #simd vectors"); + Type *et = type->SimdVector.elem; i64 elem_size = type_size_of(et); + gb_unused(elem_size); + + // 1 region in memory, not many - for (i64 i = 0; i < bt->SimdVector.count; i++) { - cg_global_const_add_region(m, value, et, global, offset+(i * elem_size)); - } return true; } @@ -775,9 +785,11 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac switch (value.kind) { case ExactValue_Invalid: + GB_ASSERT(p != nullptr); return cg_const_nil(p, type); case ExactValue_Typeid: + GB_ASSERT(p != nullptr); return cg_typeid(p, value.value_typeid); case ExactValue_Procedure: @@ -787,6 +799,10 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac if (e != nullptr) { cgValue found = cg_find_procedure_value_from_entity(m, e); GB_ASSERT(are_types_identical(type, found.type)); + GB_ASSERT(found.kind == cgValue_Symbol); + if (p) { + return cg_flatten_value(p, found); + } return found; } GB_PANIC("TODO(bill): cg_const_value ExactValue_Procedure"); @@ -796,10 +812,12 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac switch (value.kind) { case ExactValue_Bool: + GB_ASSERT(p != nullptr); GB_ASSERT(!TB_IS_VOID_TYPE(dt)); return cg_value(tb_inst_uint(p->func, dt, value.value_bool), type); case ExactValue_Integer: + GB_ASSERT(p != nullptr); GB_ASSERT(!TB_IS_VOID_TYPE(dt)); // GB_ASSERT(dt.raw != TB_TYPE_I128.raw); if (is_type_unsigned(type)) { @@ -812,6 +830,7 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac break; case ExactValue_Float: + GB_ASSERT(p != nullptr); GB_ASSERT(!TB_IS_VOID_TYPE(dt)); GB_ASSERT(dt.raw != TB_TYPE_F16.raw); GB_ASSERT(!is_type_different_to_arch_endianness(type)); -- cgit v1.2.3 From 4654b41c3e6a01118e28e6297b2de97bd0a8cd42 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 22 Jul 2023 09:06:44 +0100 Subject: Implement call expressions --- src/array.cpp | 11 ++++ src/tilde.hpp | 9 ++- src/tilde_const.cpp | 2 +- src/tilde_proc.cpp | 185 +++++++++++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 201 insertions(+), 6 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/array.cpp b/src/array.cpp index d8e25d25d..5d602cebc 100644 --- a/src/array.cpp +++ b/src/array.cpp @@ -168,6 +168,17 @@ gb_internal gb_inline Slice slice(Slice const &array, isize lo, isize hi) } return out; } +template +gb_internal gb_inline Slice slice(Array const &array, isize lo, isize hi) { + GB_ASSERT(0 <= lo && lo <= hi && hi <= array.count); + Slice out = {}; + isize len = hi-lo; + if (len > 0) { + out.data = array.data+lo; + out.count = len; + } + return out; +} template diff --git a/src/tilde.hpp b/src/tilde.hpp index d548de78e..45eceeb7b 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -42,8 +42,9 @@ struct cgValue { cgValueKind kind; Type * type; union { - TB_Symbol *symbol; - TB_Node * node; + // NOTE: any value in this union must be a pointer + TB_Symbol * symbol; + TB_Node * node; cgValueMulti *multi; }; }; @@ -308,4 +309,6 @@ gb_internal cgValue cg_emit_arith(cgProcedure *p, TokenKind op, cgValue lhs, cgV gb_internal bool cg_emit_goto(cgProcedure *p, TB_Node *control_region); -gb_internal TB_Node *cg_control_region(cgProcedure *p, char const *name); \ No newline at end of file +gb_internal TB_Node *cg_control_region(cgProcedure *p, char const *name); + +gb_internal isize cg_append_tuple_values(cgProcedure *p, Array *dst_values, cgValue src_value); \ No newline at end of file diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 6e3979637..e066c72a3 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -126,7 +126,7 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty if (global == nullptr) { global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_global, type_size_of(type), type_align_of(type), 2); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, type_size_of(type), type_align_of(type), 2); } tb_global_add_symbol_reloc(m->mod, global, offset+0, cast(TB_Symbol *)str_global); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 8f7b1972e..0deb4af45 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -355,7 +355,7 @@ gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr) { return res; } -gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice args) { +gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice const &args) { if (value.kind == cgValue_Symbol) { value = cg_value(tb_inst_get_symbol_address(p->func, value.symbol), value.type); } @@ -540,6 +540,43 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice return cg_value_multi(multi, pt->results); } + +gb_internal cgValue cg_handle_param_value(cgProcedure *p, Type *parameter_type, ParameterValue const ¶m_value, TokenPos const &pos) { + switch (param_value.kind) { + case ParameterValue_Constant: + if (is_type_constant_type(parameter_type)) { + auto res = cg_const_value(p, parameter_type, param_value.value); + return res; + } else { + ExactValue ev = param_value.value; + cgValue arg = {}; + Type *type = type_of_expr(param_value.original_ast_expr); + if (type != nullptr) { + arg = cg_const_value(p, type, ev); + } else { + arg = cg_const_value(p, parameter_type, param_value.value); + } + return cg_emit_conv(p, arg, parameter_type); + } + + case ParameterValue_Nil: + return cg_const_nil(p, parameter_type); + case ParameterValue_Location: + { + String proc_name = {}; + if (p->entity != nullptr) { + proc_name = p->entity->token.string; + } + GB_PANIC("TODO(bill): cg_emit_source_code_location_as_global"); + // return cg_emit_source_code_location_as_global(p, proc_name, pos); + break; + } + case ParameterValue_Value: + return cg_build_expr(p, param_value.ast_value); + } + return cg_const_nil(p, parameter_type); +} + gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { ast_node(ce, CallExpr, expr); @@ -611,7 +648,151 @@ gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { value = cg_emit_load(p, value); } GB_ASSERT(value.kind == cgValue_Value); + GB_ASSERT(value.node != nullptr); GB_ASSERT(is_type_proc(value.type)); - return cg_emit_call(p, value, {}); + TEMPORARY_ALLOCATOR_GUARD(); + + Type *proc_type_ = base_type(value.type); + GB_ASSERT(proc_type_->kind == Type_Proc); + TypeProc *pt = &proc_type_->Proc; + + GB_ASSERT(ce->split_args != nullptr); + + auto args = array_make(temporary_allocator(), 0, pt->param_count); + + bool vari_expand = (ce->ellipsis.pos.line != 0); + bool is_c_vararg = pt->c_vararg; + + for_array(i, ce->split_args->positional) { + Entity *e = pt->params->Tuple.variables[i]; + if (e->kind == Entity_TypeName) { + continue; + } else if (e->kind == Entity_Constant) { + continue; + } + + GB_ASSERT(e->kind == Entity_Variable); + + if (pt->variadic && pt->variadic_index == i) { + cgValue variadic_args = cg_const_nil(p, e->type); + auto variadic = slice(ce->split_args->positional, pt->variadic_index, ce->split_args->positional.count); + if (variadic.count != 0) { + // variadic call argument generation + Type *slice_type = e->type; + GB_ASSERT(slice_type->kind == Type_Slice); + + if (is_c_vararg) { + GB_ASSERT(!vari_expand); + + Type *elem_type = slice_type->Slice.elem; + + for (Ast *var_arg : variadic) { + cgValue arg = cg_build_expr(p, var_arg); + if (is_type_any(elem_type)) { + array_add(&args, cg_emit_conv(p, arg, default_type(arg.type))); + } else { + array_add(&args, cg_emit_conv(p, arg, elem_type)); + } + } + break; + } else if (vari_expand) { + GB_ASSERT(variadic.count == 1); + variadic_args = cg_build_expr(p, variadic[0]); + variadic_args = cg_emit_conv(p, variadic_args, slice_type); + } else { + Type *elem_type = slice_type->Slice.elem; + + auto var_args = array_make(temporary_allocator(), 0, variadic.count); + for (Ast *var_arg : variadic) { + cgValue v = cg_build_expr(p, var_arg); + cg_append_tuple_values(p, &var_args, v); + } + isize slice_len = var_args.count; + if (slice_len > 0) { + cgAddr slice = cg_add_local(p, slice_type, nullptr, true); + cgAddr base_array = cg_add_local(p, alloc_type_array(elem_type, slice_len), nullptr, true); + + for (isize i = 0; i < var_args.count; i++) { + cgValue addr = cg_emit_array_epi(p, base_array.addr, cast(i32)i); + cgValue var_arg = var_args[i]; + var_arg = cg_emit_conv(p, var_arg, elem_type); + cg_emit_store(p, addr, var_arg); + } + + cgValue base_elem = cg_emit_array_epi(p, base_array.addr, 0); + cgValue len = cg_const_int(p, t_int, slice_len); + GB_PANIC("TODO(bill): cg_fill_slice"); + // cg_fill_slice(p, slice, base_elem, len); + + variadic_args = cg_addr_load(p, slice); + } + } + } + array_add(&args, variadic_args); + + break; + } else { + cgValue value = cg_build_expr(p, ce->split_args->positional[i]); + cg_append_tuple_values(p, &args, value); + } + } + + if (!is_c_vararg) { + array_resize(&args, pt->param_count); + } + + for (Ast *arg : ce->split_args->named) { + ast_node(fv, FieldValue, arg); + GB_ASSERT(fv->field->kind == Ast_Ident); + String name = fv->field->Ident.token.string; + gb_unused(name); + isize param_index = lookup_procedure_parameter(pt, name); + GB_ASSERT(param_index >= 0); + + cgValue value = cg_build_expr(p, fv->value); + GB_ASSERT(!is_type_tuple(value.type)); + args[param_index] = value; + } + + TokenPos pos = ast_token(ce->proc).pos; + + + if (pt->params != nullptr) { + isize min_count = pt->params->Tuple.variables.count; + if (is_c_vararg) { + min_count -= 1; + } + GB_ASSERT(args.count >= min_count); + for_array(arg_index, pt->params->Tuple.variables) { + Entity *e = pt->params->Tuple.variables[arg_index]; + if (pt->variadic && arg_index == pt->variadic_index) { + if (!is_c_vararg && args[arg_index].node == nullptr) { + args[arg_index] = cg_const_nil(p, e->type); + } + continue; + } + + cgValue arg = args[arg_index]; + if (arg.node == nullptr) { + switch (e->kind) { + case Entity_TypeName: + case Entity_Constant: + break; + case Entity_Variable: + args[arg_index] = cg_handle_param_value(p, e->type, e->Variable.param_value, pos); + break; + default: + GB_PANIC("Unknown entity kind %.*s\n", LIT(entity_strings[e->kind])); + } + } else { + args[arg_index] = cg_emit_conv(p, arg, e->type); + } + } + } + + isize final_count = is_c_vararg ? args.count : pt->param_count; + auto call_args = slice(args, 0, final_count); + + return cg_emit_call(p, value, call_args); } -- cgit v1.2.3 From 6c12156b1a47cb3c39e5c12d443e482af2a218bb Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 22 Jul 2023 11:16:29 +0100 Subject: Simplify procedure argument handling --- src/tilde.cpp | 1 + src/tilde.hpp | 5 +-- src/tilde/tb.h | 3 +- src/tilde/tb.lib | Bin 4162738 -> 4157412 bytes src/tilde_const.cpp | 2 +- src/tilde_expr.cpp | 2 +- src/tilde_proc.cpp | 113 +++++++++++++++++++++++++++++++++++++++------------- src/tilde_stmt.cpp | 5 ++- 8 files changed, 95 insertions(+), 36 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 1969deaec..26bd69f4f 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -75,6 +75,7 @@ gb_internal TB_DataType cg_data_type(Type *t) { case Basic_f32be: return TB_TYPE_F32; case Basic_f64be: return TB_TYPE_F64; } + break; case Type_Pointer: case Type_MultiPointer: diff --git a/src/tilde.hpp b/src/tilde.hpp index f0e45bb97..0e5b3b551 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -166,9 +166,6 @@ struct cgProcedure { TB_FunctionPrototype *proto; TB_Symbol *symbol; - // includes parameters, pointers to return values, and context ptr - Slice param_nodes; - Entity * entity; cgModule *module; String name; @@ -309,11 +306,11 @@ gb_internal cgValue cg_emit_arith(cgProcedure *p, TokenKind op, cgValue lhs, cgV gb_internal bool cg_emit_goto(cgProcedure *p, TB_Node *control_region); - gb_internal TB_Node *cg_control_region(cgProcedure *p, char const *name); gb_internal isize cg_append_tuple_values(cgProcedure *p, Array *dst_values, cgValue src_value); +gb_internal cgValue cg_handle_param_value(cgProcedure *p, Type *parameter_type, ParameterValue const ¶m_value, TokenPos const &pos); gb_internal cgValue cg_builtin_len(cgProcedure *p, cgValue value); gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &x); \ No newline at end of file diff --git a/src/tilde/tb.h b/src/tilde/tb.h index 8e5bc5567..abe3c5a1a 100644 --- a/src/tilde/tb.h +++ b/src/tilde/tb.h @@ -83,7 +83,6 @@ typedef enum TB_ABI { typedef enum TB_OutputFlavor { TB_FLAVOR_OBJECT, // .o .obj - TB_FLAVOR_ASSEMBLY, // .s .asm TB_FLAVOR_SHARED, // .so .dll TB_FLAVOR_STATIC, // .a .lib TB_FLAVOR_EXECUTABLE, // .exe @@ -951,7 +950,7 @@ TB_API TB_Node* tb_inst_sint(TB_Function* f, TB_DataType dt, int64_t imm); TB_API TB_Node* tb_inst_uint(TB_Function* f, TB_DataType dt, uint64_t imm); TB_API TB_Node* tb_inst_float32(TB_Function* f, float imm); TB_API TB_Node* tb_inst_float64(TB_Function* f, double imm); -TB_API TB_Node* tb_inst_cstring(TB_Function* f, const char* srt); +TB_API TB_Node* tb_inst_cstring(TB_Function* f, const char* str); TB_API TB_Node* tb_inst_string(TB_Function* f, size_t len, const char* str); // write 'val' over 'count' bytes on 'dst' diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index b9b9dbd44..a3c6ba044 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index e066c72a3..6b1fb5c92 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -851,7 +851,7 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); return cg_lvalue_addr(node, type); } else { - return cg_value(symbol, type); + return cg_value(symbol, alloc_type_pointer(type)); } } diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index c0ddc4e70..3d9054803 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -179,7 +179,7 @@ gb_internal cgValue cg_emit_transmute(cgProcedure *p, cgValue value, Type *type) TB_DataType dt = cg_data_type(type); switch (value.kind) { case cgValue_Value: - GB_ASSERT_MSG(!TB_IS_VOID_TYPE(dt), "%s", type_to_string(type)); + GB_ASSERT_MSG(!TB_IS_VOID_TYPE(dt), "%d %s -> %s", dt.type, type_to_string(value.type), type_to_string(type)); value.type = type; if (value.node->dt.raw != dt.raw) { value.node = tb_inst_bitcast(p->func, value.node, dt); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 8016e4dba..7c7bda197 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -89,11 +89,9 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i if (p->symbol == nullptr) { p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - size_t out_param_count = 0; p->debug_type = cg_debug_type_for_proc(m, p->type); - TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, cg_arena(), &out_param_count); - p->param_nodes = {params, cast(isize)out_param_count}; - p->proto = tb_function_get_prototype(p->func); + p->proto = tb_prototype_from_dbg(m->mod, p->debug_type); + tb_function_set_prototype(p->func, p->proto, cg_arena()); p->symbol = cast(TB_Symbol *)p->func; } @@ -142,12 +140,9 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); - size_t out_param_count = 0; p->debug_type = cg_debug_type_for_proc(m, p->type); - TB_Node **params = tb_function_set_prototype_from_dbg(p->func, p->debug_type, cg_arena(), &out_param_count); - p->param_nodes = {params, cast(isize)out_param_count}; - p->proto = tb_function_get_prototype(p->func); - + p->proto = tb_prototype_from_dbg(m->mod, p->debug_type); + tb_function_set_prototype(p->func, p->proto, cg_arena()); p->symbol = cast(TB_Symbol *)p->func; @@ -179,25 +174,59 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { GB_ASSERT(p->type->kind == Type_Proc); TypeProc *pt = &p->type->Proc; + bool is_odin_like_cc = is_calling_convention_odin(pt->calling_convention); int param_index = 0; + int param_count = p->proto->param_count; + + if (pt->results) { + Type *result_type = nullptr; + if (is_odin_like_cc) { + result_type = pt->results->Tuple.variables[pt->results->Tuple.variables.count-1]->type; + } else { + result_type = pt->results; + } + TB_DebugType *debug_type = cg_debug_type(p->module, result_type); + TB_PassingRule rule = tb_get_passing_rule_from_dbg(p->module->mod, debug_type, true); + if (rule == TB_PASSING_INDIRECT) { + param_index++; + } + } + if (pt->params != nullptr) for (Entity *e : pt->params->Tuple.variables) { if (e->kind != Entity_Variable) { continue; } - if (param_index >= p->param_nodes.count) { + GB_ASSERT_MSG(param_index < param_count, "%d < %d %.*s :: %s", param_index, param_count, LIT(p->name), type_to_string(p->type)); + + TB_Node *param_ptr = nullptr; + + TB_CharUnits size = cast(TB_CharUnits)type_size_of(e->type); + TB_CharUnits align = cast(TB_CharUnits)type_align_of(e->type); + TB_DebugType *debug_type = cg_debug_type(p->module, e->type); + TB_PassingRule rule = tb_get_passing_rule_from_dbg(p->module->mod, debug_type, false); + switch (rule) { + case TB_PASSING_DIRECT: { + TB_Node *param = tb_inst_param(p->func, param_index++); + param_ptr = tb_inst_local(p->func, size, align); + tb_inst_store(p->func, param->dt, param_ptr, param, align, false); + } break; + case TB_PASSING_INDIRECT: + // TODO(bill): does this need a copy? for non-odin calling convention stuff? + param_ptr = tb_inst_param(p->func, param_index++); break; + case TB_PASSING_IGNORE: + continue; } - TB_Node *param = p->param_nodes[param_index++]; - cgValue local = cg_value(param, alloc_type_pointer(e->type)); + GB_ASSERT(param_ptr->dt.type == TB_PTR); + + cgValue local = cg_value(param_ptr, alloc_type_pointer(e->type)); if (e != nullptr && e->token.string.len > 0 && e->token.string != "_") { // NOTE(bill): for debugging purposes only String name = e->token.string; - TB_DebugType *debug_type = cg_debug_type(p->module, e->type); - tb_node_append_attrib(param, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); - + tb_node_append_attrib(param_ptr, tb_function_attrib_variable(p->func, name.len, cast(char const *)name.text, debug_type)); } cgAddr addr = cg_addr(local); if (e) { @@ -243,7 +272,9 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { // } } - if (p->type->Proc.calling_convention == ProcCC_Odin) { + // isize split_offset = param_index; + + if (pt->calling_convention == ProcCC_Odin) { // NOTE(bill): Push context on to stack from implicit parameter String name = str_lit("__.context_ptr"); @@ -251,10 +282,8 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { Entity *e = alloc_entity_param(nullptr, make_token_ident(name), t_context_ptr, false, false); e->flags |= EntityFlag_NoAlias; - TB_Node *param = p->param_nodes[p->param_nodes.count-1]; - param = tb_inst_load(p->func, TB_TYPE_PTR, param, cast(TB_CharUnits)build_context.ptr_size, false); - - cgValue local = cg_value(param, t_context_ptr); + TB_Node *param_ptr = tb_inst_param(p->func, param_count-1); + cgValue local = cg_value(param_ptr, t_context_ptr); cgAddr addr = cg_addr(local); map_set(&p->variable_map, e, addr); @@ -264,6 +293,26 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { cd->scope_index = -1; cd->uses = +1; // make sure it has been used already } + + if (pt->has_named_results) { + auto const &results = pt->results->Tuple.variables; + for_array(i, results) { + Entity *e = results[i]; + GB_ASSERT(e->kind == Entity_Variable); + + if (e->token.string == "") { + continue; + } + GB_ASSERT(!is_blank_ident(e->token)); + + cgAddr res = cg_add_local(p, e->type, e, true); + + if (e->Variable.param_value.kind != ParameterValue_Invalid) { + cgValue c = cg_handle_param_value(p, e->type, e->Variable.param_value, e->token.pos); + cg_addr_store(p, res, c); + } + } + } } gb_internal void cg_procedure_end(cgProcedure *p) { @@ -276,7 +325,8 @@ gb_internal void cg_procedure_end(cgProcedure *p) { bool emit_asm = false; // if (p->name == "main") { if ( - p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || + p->name == "runtime" ABI_PKG_NAME_SEPARATOR "print_string" || + // p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || // p->name == "main" || false ) { @@ -301,18 +351,27 @@ gb_internal void cg_procedure_end(cgProcedure *p) { } } +gb_global String procedures_to_generate_list[] = { + str_lit("bug" ABI_PKG_NAME_SEPARATOR "main"), + str_lit("main"), +}; + gb_internal void cg_procedure_generate(cgProcedure *p) { if (p->body == nullptr) { return; } - cg_procedure_begin(p); - defer (cg_procedure_end(p)); - if (p->name != "bug" ABI_PKG_NAME_SEPARATOR "main" && - p->name != "main") { - return; + if ( + p->name == "runtime" ABI_PKG_NAME_SEPARATOR "print_string" || + // p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || + // p->name == "main" || + false + ) { + cg_procedure_begin(p); + cg_build_stmt(p, p->body); } - cg_build_stmt(p, p->body); + + cg_procedure_end(p); } diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index f0203e724..4fc00dd28 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -914,7 +914,10 @@ gb_internal void cg_build_assignment(cgProcedure *p, Array const &lvals, } Type *type = cg_addr_type(lval); - GB_ASSERT(are_types_identical(type, init.type)); + if (!cg_addr_is_empty(lval)) { + GB_ASSERT_MSG(are_types_identical(init.type, type), "%s = %s", type_to_string(init.type), type_to_string(type)); + } + if (init.kind == cgValue_Addr && !cg_addr_is_empty(lval)) { // NOTE(bill): This is needed for certain constructs such as this: -- cgit v1.2.3 From 99c812b02d31d8f827e299ff7bb4a5d0c59bed4b Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 23 Jul 2023 12:21:27 +0100 Subject: Begin working on a minimum build --- src/checker.cpp | 3 + src/tilde.cpp | 44 ++- src/tilde.hpp | 9 +- src/tilde/tb.lib | Bin 4162054 -> 4163308 bytes src/tilde_builtin.cpp | 133 +++++++ src/tilde_const.cpp | 109 ++++-- src/tilde_debug.cpp | 6 +- src/tilde_expr.cpp | 932 +++++++++++++++++++++++++++++++++++++++++++------- src/tilde_proc.cpp | 102 ++++-- src/tilde_stmt.cpp | 273 ++++++++++++--- 10 files changed, 1355 insertions(+), 256 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/checker.cpp b/src/checker.cpp index 01b8b6b2a..21fa80d9f 100644 --- a/src/checker.cpp +++ b/src/checker.cpp @@ -1046,6 +1046,7 @@ gb_internal void init_universal(void) { add_global_bool_constant("ODIN_NO_RTTI", bc->no_rtti); add_global_bool_constant("ODIN_VALGRIND_SUPPORT", bc->ODIN_VALGRIND_SUPPORT); + add_global_bool_constant("ODIN_TILDE", bc->tilde_backend); add_global_constant("ODIN_COMPILE_TIMESTAMP", t_untyped_integer, exact_value_i64(odin_compile_timestamp())); @@ -2311,7 +2312,9 @@ gb_internal void generate_minimum_dependency_set(Checker *c, Entity *start) { str_lit("memory_equal"), str_lit("memory_compare"), str_lit("memory_compare_zero"), + ); + FORCE_ADD_RUNTIME_ENTITIES(!build_context.tilde_backend, // Extended data type internal procedures str_lit("umodti3"), str_lit("udivti3"), diff --git a/src/tilde.cpp b/src/tilde.cpp index 26bd69f4f..ff2a540f5 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -126,6 +126,19 @@ gb_internal cgValue cg_lvalue_addr(TB_Node *node, Type *type) { return v; } +gb_internal cgValue cg_lvalue_addr_to_value(cgValue v) { + if (v.kind == cgValue_Value) { + GB_ASSERT(is_type_pointer(v.type)); + GB_ASSERT(v.node->dt.type == TB_PTR); + } else { + GB_ASSERT(v.kind == cgValue_Addr); + GB_ASSERT(v.node->dt.type == TB_PTR); + v.kind = cgValue_Value; + v.type = alloc_type_pointer(v.type); + } + return v; +} + gb_internal cgValue cg_value_multi(cgValueMulti *multi, Type *type) { GB_ASSERT(type->kind == Type_Tuple); GB_ASSERT(multi != nullptr); @@ -138,6 +151,24 @@ gb_internal cgValue cg_value_multi(cgValueMulti *multi, Type *type) { return v; } +gb_internal cgValue cg_value_multi(Slice const &values, Type *type) { + cgValueMulti *multi = gb_alloc_item(permanent_allocator(), cgValueMulti); + multi->values = values; + return cg_value_multi(multi, type); +} + + +gb_internal cgValue cg_value_multi2(cgValue const &x, cgValue const &y, Type *type) { + GB_ASSERT(type->kind == Type_Tuple); + GB_ASSERT(type->Tuple.variables.count == 2); + cgValueMulti *multi = gb_alloc_item(permanent_allocator(), cgValueMulti); + multi->values = slice_make(permanent_allocator(), 2); + multi->values[0] = x; + multi->values[1] = y; + return cg_value_multi(multi, type); +} + + gb_internal cgAddr cg_addr(cgValue const &value) { GB_ASSERT(value.kind != cgValue_Multi); cgAddr addr = {}; @@ -151,10 +182,21 @@ gb_internal cgAddr cg_addr(cgValue const &value) { return addr; } +gb_internal void cg_set_debug_pos_from_node(cgProcedure *p, Ast *node) { + if (node) { + TokenPos pos = ast_token(node).pos; + TB_FileID *file_id = map_get(&p->module->file_id_map, cast(uintptr)pos.file_id); + if (file_id) { + tb_inst_set_location(p->func, *file_id, pos.line); + } + } +} + gb_internal void cg_add_entity(cgModule *m, Entity *e, cgValue const &val) { if (e) { rw_mutex_lock(&m->values_mutex); + GB_ASSERT(val.node != nullptr); map_set(&m->values, e, val); rw_mutex_unlock(&m->values_mutex); } @@ -744,7 +786,7 @@ gb_internal bool cg_generate_code(Checker *c) { } TB_DebugFormat debug_format = TB_DEBUGFMT_NONE; - if (build_context.ODIN_DEBUG) { + if (build_context.ODIN_DEBUG || true) { switch (build_context.metrics.os) { case TargetOs_windows: debug_format = TB_DEBUGFMT_CODEVIEW; diff --git a/src/tilde.hpp b/src/tilde.hpp index b8434ce4b..8a29d4c90 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -272,6 +272,7 @@ gb_internal void cg_build_when_stmt(cgProcedure *p, AstWhenStmt *ws); gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr); gb_internal cgAddr cg_build_addr(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_addr_ptr(cgProcedure *p, Ast *expr); +gb_internal cgValue cg_build_cond(cgProcedure *p, Ast *cond, TB_Node *true_block, TB_Node *false_block); gb_internal Type * cg_addr_type(cgAddr const &addr); gb_internal cgValue cg_addr_load(cgProcedure *p, cgAddr addr); @@ -279,13 +280,15 @@ gb_internal void cg_addr_store(cgProcedure *p, cgAddr addr, cgValue value); gb_internal cgValue cg_addr_get_ptr(cgProcedure *p, cgAddr const &addr); gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_volatile=false); -gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, bool is_volatile=false); +gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue src, bool is_volatile=false); gb_internal cgAddr cg_add_local(cgProcedure *p, Type *type, Entity *e, bool zero_init); gb_internal cgValue cg_address_from_load_or_generate_local(cgProcedure *p, cgValue value); gb_internal cgValue cg_copy_value_to_ptr(cgProcedure *p, cgValue value, Type *original_type, isize min_alignment); gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr); +gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return_results); +gb_internal void cg_build_return_stmt_internal(cgProcedure *p, Slice const &results); gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e); @@ -300,6 +303,7 @@ gb_internal cgValue cg_emit_array_ep(cgProcedure *p, cgValue s, cgValue index); gb_internal cgValue cg_emit_array_epi(cgProcedure *p, cgValue s, i64 index); gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index); gb_internal cgValue cg_emit_deep_field_gep(cgProcedure *p, cgValue e, Selection const &sel); +gb_internal cgValue cg_emit_struct_ev(cgProcedure *p, cgValue s, i64 index); gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *t); gb_internal cgValue cg_emit_comp_against_nil(cgProcedure *p, TokenKind op_kind, cgValue x); @@ -315,4 +319,5 @@ gb_internal isize cg_append_tuple_values(cgProcedure *p, Array *dst_val gb_internal cgValue cg_handle_param_value(cgProcedure *p, Type *parameter_type, ParameterValue const ¶m_value, TokenPos const &pos); gb_internal cgValue cg_builtin_len(cgProcedure *p, cgValue value); -gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &x); \ No newline at end of file +gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &x); + diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index f50666cff..936675fda 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_builtin.cpp b/src/tilde_builtin.cpp index d6e161ec3..c55cfbb75 100644 --- a/src/tilde_builtin.cpp +++ b/src/tilde_builtin.cpp @@ -61,6 +61,7 @@ gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &value) { cgValue ptr = cg_value(value.node, alloc_type_pointer(value.type)); cgValue data_ptr = cg_emit_struct_ep(p, ptr, 0); res = cg_emit_load(p, data_ptr); + GB_ASSERT(is_type_multi_pointer(res.type)); } break; case Type_DynamicArray: @@ -82,7 +83,12 @@ gb_internal cgValue cg_builtin_raw_data(cgProcedure *p, cgValue const &value) { } break; case Type_Pointer: + GB_ASSERT(is_type_array_like(t->Pointer.elem)); + GB_ASSERT(value.kind == cgValue_Value); + res = cg_value(value.node, alloc_type_multi_pointer(base_array_type(t->Pointer.elem))); + break; case Type_MultiPointer: + GB_PANIC("TODO(bill) %s", type_to_string(value.type)); // res = cg_emit_conv(p, value, tv.type); break; @@ -102,6 +108,37 @@ gb_internal cgValue cg_builtin_max(cgProcedure *p, Type *t, cgValue x, cgValue y return cg_emit_select(p, cg_emit_comp(p, Token_Gt, x, y), x, y); } +gb_internal cgValue cg_builtin_abs(cgProcedure *p, cgValue x) { + if (is_type_unsigned(x.type)) { + return x; + } + + if (is_type_quaternion(x.type)) { + GB_PANIC("TODO(bill): abs quaternion"); + } else if (is_type_complex(x.type)) { + GB_PANIC("TODO(bill): abs complex"); + } + + TB_DataType dt = cg_data_type(x.type); + GB_ASSERT(!TB_IS_VOID_TYPE(dt)); + TB_Node *zero = nullptr; + if (dt.type == TB_FLOAT) { + if (dt.data == 32) { + zero = tb_inst_float32(p->func, 0); + } else if (dt.data == 64) { + zero = tb_inst_float64(p->func, 0); + } + } else { + zero = tb_inst_uint(p->func, dt, 0); + } + GB_ASSERT(zero != nullptr); + + cgValue cond = cg_emit_comp(p, Token_Lt, x, cg_value(zero, x.type)); + cgValue neg = cg_emit_unary_arith(p, Token_Sub, x, x.type); + return cg_emit_select(p, cond, neg, x); +} + + gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr) { ast_node(ce, CallExpr, expr); @@ -149,6 +186,12 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr return cg_builtin_len(p, v); } + case BuiltinProc_raw_data: + { + cgValue v = cg_build_expr(p, ce->args[0]); + return cg_builtin_raw_data(p, v); + } + case BuiltinProc_min: if (ce->args.count == 2) { Type *t = type_of_expr(expr); @@ -176,6 +219,96 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr } break; + case BuiltinProc_abs: + { + cgValue x = cg_build_expr(p, ce->args[0]); + return cg_builtin_abs(p, x); + } + + case BuiltinProc_debug_trap: + tb_inst_debugbreak(p->func); + return {}; + case BuiltinProc_trap: + tb_inst_trap(p->func); + return {}; + + case BuiltinProc_mem_zero: + { + cgValue ptr = cg_build_expr(p, ce->args[0]); + cgValue len = cg_build_expr(p, ce->args[1]); + GB_ASSERT(ptr.kind == cgValue_Value); + GB_ASSERT(len.kind == cgValue_Value); + tb_inst_memzero(p->func, ptr.node, len.node, 1, false); + return {}; + } + + case BuiltinProc_mem_copy: + { + cgValue dst = cg_build_expr(p, ce->args[0]); + cgValue src = cg_build_expr(p, ce->args[1]); + cgValue len = cg_build_expr(p, ce->args[2]); + GB_ASSERT(dst.kind == cgValue_Value); + GB_ASSERT(src.kind == cgValue_Value); + GB_ASSERT(len.kind == cgValue_Value); + // TODO(bill): This needs to be memmove + tb_inst_memcpy(p->func, dst.node, src.node, len.node, 1, false); + return {}; + } + + case BuiltinProc_mem_copy_non_overlapping: + { + cgValue dst = cg_build_expr(p, ce->args[0]); + cgValue src = cg_build_expr(p, ce->args[1]); + cgValue len = cg_build_expr(p, ce->args[2]); + GB_ASSERT(dst.kind == cgValue_Value); + GB_ASSERT(src.kind == cgValue_Value); + GB_ASSERT(len.kind == cgValue_Value); + tb_inst_memcpy(p->func, dst.node, src.node, len.node, 1, false); + return {}; + } + + + case BuiltinProc_overflow_add: + { + Type *res_type = type_of_expr(expr); + GB_ASSERT(res_type->kind == Type_Tuple); + GB_ASSERT(res_type->Tuple.variables.count == 2); + // TODO(bill): do a proper overflow add + Type *type = res_type->Tuple.variables[0]->type; + Type *ok_type = res_type->Tuple.variables[1]->type; + cgValue x = cg_build_expr(p, ce->args[0]); + cgValue y = cg_build_expr(p, ce->args[1]); + x = cg_emit_conv(p, x, type); + y = cg_emit_conv(p, y, type); + cgValue res = cg_emit_arith(p, Token_Add, x, y, type); + cgValue ok = cg_const_int(p, ok_type, false); + + return cg_value_multi2(res, ok, res_type); + } + + + case BuiltinProc_ptr_offset: + { + cgValue ptr = cg_build_expr(p, ce->args[0]); + cgValue len = cg_build_expr(p, ce->args[1]); + len = cg_emit_conv(p, len, t_int); + return cg_emit_ptr_offset(p, ptr, len); + } + case BuiltinProc_ptr_sub: + { + Type *elem0 = type_deref(type_of_expr(ce->args[0])); + Type *elem1 = type_deref(type_of_expr(ce->args[1])); + GB_ASSERT(are_types_identical(elem0, elem1)); + Type *elem = elem0; + + cgValue ptr0 = cg_emit_conv(p, cg_build_expr(p, ce->args[0]), t_uintptr); + cgValue ptr1 = cg_emit_conv(p, cg_build_expr(p, ce->args[1]), t_uintptr); + + cgValue diff = cg_emit_arith(p, Token_Sub, ptr0, ptr1, t_uintptr); + diff = cg_emit_conv(p, diff, t_int); + return cg_emit_arith(p, Token_Quo, diff, cg_const_int(p, t_int, type_size_of(elem)), t_int); + } + } diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 6b1fb5c92..bb4a294a5 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -52,6 +52,13 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { } +gb_internal cgValue cg_emit_source_code_location_as_global(cgProcedure *p, String const &proc_name, TokenPos pos) { + // TODO(bill): cg_emit_source_code_location_as_global + return cg_const_nil(p, t_source_code_location); +} + + + gb_internal void cg_write_big_int_at_ptr(void *dst, BigInt const *a, Type *original_type) { GB_ASSERT(build_context.endian_kind == TargetEndian_Little); size_t sz = cast(size_t)type_size_of(original_type); @@ -109,7 +116,6 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty char name[32] = {}; gb_snprintf(name, 31, "csb$%u", 1+m->const_nil_guid.fetch_add(1)); - TB_Global *str_global = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); i64 size = str.len+1; tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_global, size, 1, 1); @@ -125,6 +131,7 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty } if (global == nullptr) { + gb_snprintf(name, 31, "cstr$%u", 1+m->const_nil_guid.fetch_add(1)); global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, type_size_of(type), type_align_of(type), 2); } @@ -778,18 +785,47 @@ gb_internal TB_Global *cg_global_const_comp_literal(cgModule *m, Type *original_ } -gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, ExactValue const &value) { +gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value) { + GB_ASSERT(p != nullptr); TB_Node *node = nullptr; + if (is_type_untyped(type)) { + // TODO(bill): THIS IS A COMPLETE HACK, WHY DOES THIS NOT A TYPE? + GB_ASSERT(type->kind == Type_Basic); + switch (type->Basic.kind) { + case Basic_UntypedBool: + type = t_bool; + break; + case Basic_UntypedInteger: + type = t_i64; + break; + case Basic_UntypedFloat: + type = t_f64; + break; + case Basic_UntypedComplex: + type = t_complex128; + break; + case Basic_UntypedQuaternion: + type = t_quaternion256; + break; + case Basic_UntypedString: + type = t_string; + break; + case Basic_UntypedRune: + type = t_rune; + break; + case Basic_UntypedNil: + case Basic_UntypedUninit: + return cg_value(cast(TB_Node *)nullptr, type); + } + } TB_DataType dt = cg_data_type(type); switch (value.kind) { case ExactValue_Invalid: - GB_ASSERT(p != nullptr); return cg_const_nil(p, type); case ExactValue_Typeid: - GB_ASSERT(p != nullptr); return cg_typeid(p, value.value_typeid); case ExactValue_Procedure: @@ -797,13 +833,13 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac Ast *expr = unparen_expr(value.value_procedure); Entity *e = entity_of_node(expr); if (e != nullptr) { - cgValue found = cg_find_procedure_value_from_entity(m, e); - GB_ASSERT(are_types_identical(type, found.type)); + cgValue found = cg_find_procedure_value_from_entity(p->module, e); + GB_ASSERT_MSG(are_types_identical(type, found.type), + "%.*s %s == %s", + LIT(p->name), + type_to_string(type), type_to_string(found.type)); GB_ASSERT(found.kind == cgValue_Symbol); - if (p) { - return cg_flatten_value(p, found); - } - return found; + return cg_flatten_value(p, found); } GB_PANIC("TODO(bill): cg_const_value ExactValue_Procedure"); } @@ -812,12 +848,10 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac switch (value.kind) { case ExactValue_Bool: - GB_ASSERT(p != nullptr); GB_ASSERT(!TB_IS_VOID_TYPE(dt)); return cg_value(tb_inst_uint(p->func, dt, value.value_bool), type); case ExactValue_Integer: - GB_ASSERT(p != nullptr); GB_ASSERT(!TB_IS_VOID_TYPE(dt)); // GB_ASSERT(dt.raw != TB_TYPE_I128.raw); if (is_type_unsigned(type)) { @@ -830,7 +864,6 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac break; case ExactValue_Float: - GB_ASSERT(p != nullptr); GB_ASSERT(!TB_IS_VOID_TYPE(dt)); GB_ASSERT(dt.raw != TB_TYPE_F16.raw); GB_ASSERT(!is_type_different_to_arch_endianness(type)); @@ -846,13 +879,36 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac case ExactValue_String: { - TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_string(m, value.value_string, type, nullptr, 0); - if (p) { - TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); - return cg_lvalue_addr(node, type); - } else { - return cg_value(symbol, alloc_type_pointer(type)); + GB_ASSERT(is_type_string(type)); + cgModule *m = p->module; + + String str = value.value_string; + + char name[32] = {}; + gb_snprintf(name, 31, "csb$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *cstr_global = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + i64 size = str.len+1; + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), cstr_global, size, 1, 1); + u8 *data = cast(u8 *)tb_global_add_region(m->mod, cstr_global, 0, size); + gb_memcopy(data, str.text, str.len); + data[str.len] = 0; + + if (is_type_cstring(type)) { + cgValue s = cg_value(cstr_global, type); + return cg_flatten_value(p, s); } + + gb_snprintf(name, 31, "str$%u", 1+m->const_nil_guid.fetch_add(1)); + TB_Global *str_global = tb_global_create(m->mod, -1, name, cg_debug_type(m, type), TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), str_global, type_size_of(type), type_align_of(type), 2); + + tb_global_add_symbol_reloc(m->mod, str_global, 0, cast(TB_Symbol *)cstr_global); + void *len_ptr = tb_global_add_region(m->mod, str_global, build_context.int_size, build_context.int_size); + cg_write_int_at_ptr(len_ptr, str.len, t_int); + + TB_Node *s = tb_inst_get_symbol_address(p->func, cast(TB_Symbol *)str_global); + return cg_lvalue_addr(s, type); + } case ExactValue_Pointer: @@ -860,13 +916,9 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac case ExactValue_Compound: { - TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_comp_literal(m, type, value, nullptr, 0); - if (p) { - TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); - return cg_lvalue_addr(node, type); - } else { - return cg_value(symbol, type); - } + TB_Symbol *symbol = cast(TB_Symbol *)cg_global_const_comp_literal(p->module, type, value, nullptr, 0); + TB_Node *node = tb_inst_get_symbol_address(p->func, symbol); + return cg_lvalue_addr(node, type); } break; } @@ -876,11 +928,6 @@ gb_internal cgValue cg_const_value(cgModule *m, cgProcedure *p, Type *type, Exac return cg_value(node, type); } -gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const &value) { - GB_ASSERT(p != nullptr); - return cg_const_value(p->module, p, type, value); -} - gb_internal cgValue cg_const_int(cgProcedure *p, Type *type, i64 i) { return cg_const_value(p, type, exact_value_i64(i)); } diff --git a/src/tilde_debug.cpp b/src/tilde_debug.cpp index 21594ef07..e6e60be96 100644 --- a/src/tilde_debug.cpp +++ b/src/tilde_debug.cpp @@ -368,7 +368,11 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { param_count += 1; } - TB_DebugType *func = tb_debug_create_func(m->mod, TB_CDECL, param_count, return_count, pt->c_vararg); + TB_CallingConv tb_cc = TB_CDECL; + if (pt->calling_convention == ProcCC_StdCall) { + tb_cc = TB_STDCALL; + } + TB_DebugType *func = tb_debug_create_func(m->mod, tb_cc, param_count, return_count, pt->c_vararg); map_set(&m->proc_debug_type_map, original_type, func); map_set(&m->proc_debug_type_map, type, func); diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index b6dbce181..822c637ca 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -648,21 +648,22 @@ gb_internal cgValue cg_emit_comp_against_nil(cgProcedure *p, TokenKind op_kind, break; case Basic_any: { - GB_PANIC("TODO(bill): cg_emit_struct_ev"); + GB_ASSERT(x.kind == cgValue_Addr); // // TODO(bill): is this correct behaviour for nil comparison for any? - // cgValue data = cg_emit_struct_ev(p, x, 0); - // cgValue ti = cg_emit_struct_ev(p, x, 1); - // if (op_kind == Token_CmpEq) { - // LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, ""); - // LLVMValueRef b = LLVMBuildIsNull(p->builder, ti.value, ""); - // res.value = LLVMBuildOr(p->builder, a, b, ""); - // return res; - // } else if (op_kind == Token_NotEq) { - // LLVMValueRef a = LLVMBuildIsNotNull(p->builder, data.value, ""); - // LLVMValueRef b = LLVMBuildIsNotNull(p->builder, ti.value, ""); - // res.value = LLVMBuildAnd(p->builder, a, b, ""); - // return res; - // } + cgValue data = cg_emit_struct_ev(p, x, 0); + cgValue id = cg_emit_struct_ev(p, x, 1); + + if (op_kind == Token_CmpEq) { + TB_Node *a = tb_inst_cmp_eq(p->func, data.node, tb_inst_uint(p->func, data.node->dt, 0)); + TB_Node *b = tb_inst_cmp_eq(p->func, id.node, tb_inst_uint(p->func, id.node->dt, 0)); + TB_Node *c = tb_inst_or(p->func, a, b); + return cg_value(c, t_bool); + } else if (op_kind == Token_NotEq) { + TB_Node *a = tb_inst_cmp_ne(p->func, data.node, tb_inst_uint(p->func, data.node->dt, 0)); + TB_Node *b = tb_inst_cmp_ne(p->func, id.node, tb_inst_uint(p->func, id.node->dt, 0)); + TB_Node *c = tb_inst_and(p->func, a, b); + return cg_value(c, t_bool); + } } break; case Basic_typeid: @@ -685,64 +686,33 @@ gb_internal cgValue cg_emit_comp_against_nil(cgProcedure *p, TokenKind op_kind, break; case Type_Slice: - { - GB_PANIC("TODO(bill): cg_emit_struct_ev"); - // cgValue data = cg_emit_struct_ev(p, x, 0); - // if (op_kind == Token_CmpEq) { - // res.value = LLVMBuildIsNull(p->builder, data.value, ""); - // return res; - // } else if (op_kind == Token_NotEq) { - // res.value = LLVMBuildIsNotNull(p->builder, data.value, ""); - // return res; - // } - } - break; - case Type_DynamicArray: - { - GB_PANIC("TODO(bill): cg_emit_struct_ev"); - // cgValue data = cg_emit_struct_ev(p, x, 0); - // if (op_kind == Token_CmpEq) { - // res.value = LLVMBuildIsNull(p->builder, data.value, ""); - // return res; - // } else if (op_kind == Token_NotEq) { - // res.value = LLVMBuildIsNotNull(p->builder, data.value, ""); - // return res; - // } - } - break; - case Type_Map: { - GB_PANIC("TODO(bill): cg_emit_struct_ev"); - // cgValue data_ptr = cg_emit_struct_ev(p, x, 0); - - // if (op_kind == Token_CmpEq) { - // res.value = LLVMBuildIsNull(p->builder, data_ptr.value, ""); - // return res; - // } else { - // res.value = LLVMBuildIsNotNull(p->builder, data_ptr.value, ""); - // return res; - // } + // NOTE(bill): all of their data "pointer-like" fields are at the 0-index + cgValue data = cg_emit_struct_ev(p, x, 0); + if (op_kind == Token_CmpEq) { + TB_Node *a = tb_inst_cmp_eq(p->func, data.node, tb_inst_uint(p->func, data.node->dt, 0)); + return cg_value(a, t_bool); + } else if (op_kind == Token_NotEq) { + TB_Node *a = tb_inst_cmp_ne(p->func, data.node, tb_inst_uint(p->func, data.node->dt, 0)); + return cg_value(a, t_bool); + } } break; case Type_Union: { - GB_PANIC("TODO(bill): cg_emit_struct_ev"); - // if (type_size_of(t) == 0) { - // if (op_kind == Token_CmpEq) { - // return cg_const_bool(p->module, t_bool, true); - // } else if (op_kind == Token_NotEq) { - // return cg_const_bool(p->module, t_bool, false); - // } - // } else if (is_type_union_maybe_pointer(t)) { - // cgValue tag = cg_emit_transmute(p, x, t_rawptr); - // return cg_emit_comp_against_nil(p, op_kind, tag); - // } else { - // cgValue tag = cg_emit_union_tag_value(p, x); - // return cg_emit_comp(p, op_kind, tag, cg_zero(p->module, tag.type)); - // } + if (type_size_of(t) == 0) { + return cg_const_bool(p, t_bool, op_kind == Token_CmpEq); + } else if (is_type_union_maybe_pointer(t)) { + cgValue tag = cg_emit_transmute(p, x, t_rawptr); + return cg_emit_comp_against_nil(p, op_kind, tag); + } else { + GB_ASSERT("TODO(bill): cg_emit_union_tag_value"); + // cgValue tag = cg_emit_union_tag_value(p, x); + // return cg_emit_comp(p, op_kind, tag, cg_zero(p->module, tag.type)); + } } break; case Type_Struct: @@ -1311,6 +1281,17 @@ handle_op:; } +gb_internal void cg_fill_slice(cgProcedure *p, cgAddr const &slice, cgValue data, cgValue len) { + cgValue slice_ptr = cg_addr_get_ptr(p, slice); + cgValue data_ptr = cg_emit_struct_ep(p, slice_ptr, 0); + cgValue len_ptr = cg_emit_struct_ep(p, slice_ptr, 1); + + data = cg_emit_conv(p, data, type_deref(data_ptr.type)); + len = cg_emit_conv(p, len, t_int); + cg_emit_store(p, data_ptr, data); + cg_emit_store(p, len_ptr, len); +} + gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { ast_node(se, SliceExpr, expr); @@ -1338,23 +1319,28 @@ gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { } switch (type->kind) { + case Type_Basic: case Type_Slice: { - // Type *slice_type = type; - // cgValue len = cg_slice_len(p, base); - // if (high.value == nullptr) high = len; + if (type->kind == Type_Basic) { + GB_ASSERT(type->Basic.kind == Basic_string); + } - // if (!no_indices) { - // cg_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); - // } + Type *slice_type = type; + if (high.node == nullptr) { + cgValue len = cg_builtin_len(p, base); + high = len; + } - // cgValue elem = cg_emit_ptr_offset(p, cg_slice_elem(p, base), low); - // cgValue new_len = cg_emit_arith(p, Token_Sub, high, low, t_int); + if (!no_indices) { + // cg_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); + } - // cgAddr slice = cg_add_local_generated(p, slice_type, false); - // cg_fill_slice(p, slice, elem, new_len); - // return slice; - GB_PANIC("cg_build_addr_slice_expr Type_Slice"); - break; + cgValue elem = cg_emit_ptr_offset(p, cg_builtin_raw_data(p, base), low); + cgValue new_len = cg_emit_arith(p, Token_Sub, high, low, t_int); + + cgAddr slice = cg_add_local(p, slice_type, nullptr, true); + cg_fill_slice(p, slice, elem, new_len); + return slice; } case Type_RelativeSlice: @@ -1414,46 +1400,24 @@ gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { } case Type_Array: { - // Type *slice_type = alloc_type_slice(type->Array.elem); - // lbValue len = lb_const_int(p->module, t_int, type->Array.count); - - // if (high.value == nullptr) high = len; + Type *slice_type = type_of_expr(expr); + GB_ASSERT(is_type_slice(slice_type)); + cgValue len = cg_const_int(p, t_int, type->Array.count); + if (high.node == nullptr) high = len; // bool low_const = type_and_value_of_expr(se->low).mode == Addressing_Constant; // bool high_const = type_and_value_of_expr(se->high).mode == Addressing_Constant; - // if (!low_const || !high_const) { // if (!no_indices) { // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); // } // } - // lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, lb_addr_get_ptr(p, addr)), low); - // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + cgValue elem = cg_emit_ptr_offset(p, cg_builtin_raw_data(p, cg_addr_get_ptr(p, addr)), low); + cgValue new_len = cg_emit_arith(p, Token_Sub, high, low, t_int); - // lbAddr slice = lb_add_local_generated(p, slice_type, false); - // lb_fill_slice(p, slice, elem, new_len); - // return slice; - GB_PANIC("cg_build_addr_slice_expr Type_Array"); - break; - } - - case Type_Basic: { - // GB_ASSERT(type == t_string); - // lbValue len = lb_string_len(p, base); - // if (high.value == nullptr) high = len; - - // if (!no_indices) { - // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); - // } - - // lbValue elem = lb_emit_ptr_offset(p, lb_string_elem(p, base), low); - // lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); - - // lbAddr str = lb_add_local_generated(p, t_string, false); - // lb_fill_string(p, str, elem, new_len); - // return str; - GB_PANIC("cg_build_addr_slice_expr Type_Basic"); - break; + cgAddr slice = cg_add_local(p, slice_type, nullptr, true); + cg_fill_slice(p, slice, elem, new_len); + return slice; } @@ -1685,6 +1649,207 @@ gb_internal cgValue cg_emit_unary_arith(cgProcedure *p, TokenKind op, cgValue x, return res; } +gb_internal void cg_emit_if(cgProcedure *p, cgValue const &cond, TB_Node *true_region, TB_Node *false_region) { + GB_ASSERT(cond.kind == cgValue_Value); + tb_inst_if(p->func, cond.node, true_region, false_region); +} + +gb_internal void cg_build_try_lhs_rhs(cgProcedure *p, Ast *arg, Type *final_type, cgValue *lhs_, cgValue *rhs_) { + cgValue lhs = {}; + cgValue rhs = {}; + + cgValue value = cg_build_expr(p, arg); + if (value.kind == cgValue_Multi) { + auto const &values = value.multi->values; + if (values.count == 2) { + lhs = values[0]; + rhs = values[1]; + } else { + rhs = values[values.count-1]; + if (values.count > 1) { + lhs = cg_value_multi(slice(values, 0, values.count-1), final_type); + } + } + } else { + rhs = value; + } + + GB_ASSERT(rhs.node != nullptr); + + if (lhs_) *lhs_ = lhs; + if (rhs_) *rhs_ = rhs; +} + +gb_internal cgValue cg_emit_try_has_value(cgProcedure *p, cgValue rhs) { + cgValue has_value = {}; + if (is_type_boolean(rhs.type)) { + has_value = rhs; + } else { + GB_ASSERT_MSG(type_has_nil(rhs.type), "%s", type_to_string(rhs.type)); + has_value = cg_emit_comp_against_nil(p, Token_CmpEq, rhs); + } + GB_ASSERT(has_value.node != nullptr); + return has_value; +} + +gb_internal cgValue cg_build_or_return(cgProcedure *p, Ast *arg, Type *final_type) { + cgValue lhs = {}; + cgValue rhs = {}; + cg_build_try_lhs_rhs(p, arg, final_type, &lhs, &rhs); + + TB_Node *return_region = cg_control_region(p, "or_return_return"); + TB_Node *continue_region = cg_control_region(p, "or_return_continue"); + + cgValue cond = cg_emit_try_has_value(p, rhs); + cg_emit_if(p, cond, continue_region, return_region); + tb_inst_set_control(p->func, return_region); + { + Type *proc_type = base_type(p->type); + Type *results = proc_type->Proc.results; + GB_ASSERT(results != nullptr && results->kind == Type_Tuple); + TypeTuple *tuple = &results->Tuple; + + GB_ASSERT(tuple->variables.count != 0); + + Entity *end_entity = tuple->variables[tuple->variables.count-1]; + rhs = cg_emit_conv(p, rhs, end_entity->type); + if (p->type->Proc.has_named_results) { + GB_ASSERT(end_entity->token.string.len != 0); + + // NOTE(bill): store the named values before returning + cgAddr found = map_must_get(&p->variable_map, end_entity); + cg_addr_store(p, found, rhs); + + cg_build_return_stmt(p, {}); + } else { + GB_ASSERT(tuple->variables.count == 1); + Slice results = {}; + results.data = &rhs; + results.count = 1;; + cg_build_return_stmt_internal(p, results); + } + } + tb_inst_set_control(p->func, continue_region); + if (final_type != nullptr && !is_type_tuple(final_type)) { + return cg_emit_conv(p, lhs, final_type); + } + return {}; +} + +gb_internal cgValue cg_build_or_else(cgProcedure *p, Ast *arg, Ast *else_expr, Type *final_type) { + if (arg->state_flags & StateFlag_DirectiveWasFalse) { + return cg_build_expr(p, else_expr); + } + + cgValue lhs = {}; + cgValue rhs = {}; + cg_build_try_lhs_rhs(p, arg, final_type, &lhs, &rhs); + + GB_ASSERT(else_expr != nullptr); + + if (is_diverging_expr(else_expr)) { + TB_Node *then = cg_control_region(p, "or_else_then"); + TB_Node *else_ = cg_control_region(p, "or_else_else"); + + cg_emit_if(p, cg_emit_try_has_value(p, rhs), then, else_); + // NOTE(bill): else block needs to be straight afterwards to make sure that the actual value is used + // from the then block + tb_inst_set_control(p->func, else_); + + cg_build_expr(p, else_expr); + + tb_inst_set_control(p->func, then); + return cg_emit_conv(p, lhs, final_type); + } else { + TB_Node *incoming_values[2] = {}; + TB_Node *incoming_regions[2] = {}; + + TB_Node *then = cg_control_region(p, "or_else_then"); + TB_Node *done = cg_control_region(p, "or_else_done"); // NOTE(bill): Append later + TB_Node *else_ = cg_control_region(p, "or_else_else"); + + cg_emit_if(p, cg_emit_try_has_value(p, rhs), then, else_); + tb_inst_set_control(p->func, then); + + cgValue x = cg_emit_conv(p, lhs, final_type); + incoming_values[0] = x.node; + incoming_regions[0] = tb_inst_get_control(p->func); + + tb_inst_goto(p->func, done); + tb_inst_set_control(p->func, else_); + + cgValue y = cg_emit_conv(p, cg_build_expr(p, else_expr), final_type); + incoming_values[1] = y.node; + incoming_regions[1] = tb_inst_get_control(p->func); + + tb_inst_goto(p->func, done); + tb_inst_set_control(p->func, done); + + GB_ASSERT(x.kind == y.kind); + GB_ASSERT(incoming_values[0]->dt.raw == incoming_values[1]->dt.raw); + cgValue res = {}; + res.kind = x.kind; + res.type = final_type; + + res.node = tb_inst_incomplete_phi(p->func, incoming_values[0]->dt, done, 2); + tb_inst_add_phi_operand(p->func, res.node, incoming_regions[0], incoming_values[0]); + tb_inst_add_phi_operand(p->func, res.node, incoming_regions[1], incoming_values[1]); + return res; + } +} + + +gb_internal isize cg_control_region_pred_count(TB_Node *region) { + GB_ASSERT(region->type == TB_REGION); + GB_ASSERT(region->input_count > 0); + return region->input_count; +} + +gb_internal cgValue cg_build_logical_binary_expr(cgProcedure *p, TokenKind op, Ast *left, Ast *right, Type *final_type) { + TB_Node *rhs = cg_control_region(p, "logical_cmp_rhs"); + TB_Node *done = cg_control_region(p, "logical_cmp_done"); + + cgValue short_circuit = {}; + if (op == Token_CmpAnd) { + cg_build_cond(p, left, rhs, done); + short_circuit = cg_const_bool(p, t_bool, false); + } else if (op == Token_CmpOr) { + cg_build_cond(p, left, done, rhs); + short_circuit = cg_const_bool(p, t_bool, true); + } + + if (rhs->input_count == 0) { + tb_inst_set_control(p->func, done); + return cg_emit_conv(p, short_circuit, final_type); + } + + if (done->input_count == 0) { + tb_inst_set_control(p->func, rhs); + return cg_build_expr(p, right); + } + + tb_inst_set_control(p->func, rhs); + cgValue edge = cg_build_expr(p, right); + TB_Node *edge_region = tb_inst_get_control(p->func); + + tb_inst_goto(p->func, done); + tb_inst_set_control(p->func, done); + + TB_DataType dt = edge.node->dt; + TB_Node *phi = tb_inst_incomplete_phi(p->func, dt, done, done->input_count); + for (size_t i = 0; i < done->input_count; i++) { + TB_Node *val = short_circuit.node; + TB_Node *region = done->inputs[i]; + if (region == edge_region) { + val = edge.node; + } + tb_inst_add_phi_operand(p->func, phi, region, val); + } + return cg_emit_conv(p, cg_value(phi, t_bool), final_type); +} + + + gb_internal cgValue cg_build_binary_expr(cgProcedure *p, Ast *expr) { ast_node(be, BinaryExpr, expr); @@ -1786,8 +1951,7 @@ gb_internal cgValue cg_build_binary_expr(cgProcedure *p, Ast *expr) { case Token_CmpAnd: case Token_CmpOr: - GB_PANIC("TODO(bill): cg_emit_logical_binary_expr"); - // return cg_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type); + return cg_build_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type); case Token_in: case Token_not_in: @@ -1896,15 +2060,14 @@ gb_internal cgValue cg_build_cond(cgProcedure *p, Ast *cond, TB_Node *true_block } else { v = cg_build_expr(p, cond); } - - GB_ASSERT(v.kind == cgValue_Value); - tb_inst_if(p->func, v.node, true_block, false_block); - + cg_emit_if(p, v, true_block, false_block); return v; } gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr); gb_internal cgValue cg_build_expr(cgProcedure *p, Ast *expr) { + cg_set_debug_pos_from_node(p, expr); + u16 prev_state_flags = p->state_flags; defer (p->state_flags = prev_state_flags); @@ -2003,6 +2166,468 @@ gb_internal cgValue cg_find_ident(cgProcedure *p, Entity *e, Ast *expr) { return {}; } +cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { + struct cgCompoundLitElemTempData { + Ast * expr; + cgValue value; + i64 elem_index; + i64 elem_length; + cgValue gep; + }; + + + auto const &populate = [](cgProcedure *p, Slice const &elems, Array *temp_data, Type *compound_type) { + Type *bt = base_type(compound_type); + Type *et = nullptr; + switch (bt->kind) { + case Type_Array: et = bt->Array.elem; break; + case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break; + case Type_Slice: et = bt->Slice.elem; break; + case Type_BitSet: et = bt->BitSet.elem; break; + case Type_DynamicArray: et = bt->DynamicArray.elem; break; + case Type_SimdVector: et = bt->SimdVector.elem; break; + case Type_Matrix: et = bt->Matrix.elem; break; + } + GB_ASSERT(et != nullptr); + + + // NOTE(bill): Separate value, gep, store into their own chunks + for_array(i, elems) { + Ast *elem = elems[i]; + if (elem->kind == Ast_FieldValue) { + ast_node(fv, FieldValue, elem); + if (is_ast_range(fv->field)) { + ast_node(ie, BinaryExpr, fv->field); + TypeAndValue lo_tav = ie->left->tav; + TypeAndValue hi_tav = ie->right->tav; + GB_ASSERT(lo_tav.mode == Addressing_Constant); + GB_ASSERT(hi_tav.mode == Addressing_Constant); + + TokenKind op = ie->op.kind; + i64 lo = exact_value_to_i64(lo_tav.value); + i64 hi = exact_value_to_i64(hi_tav.value); + if (op != Token_RangeHalf) { + hi += 1; + } + + cgValue value = cg_emit_conv(p, cg_build_expr(p, fv->value), et); + + GB_ASSERT((hi-lo) > 0); + + if (bt->kind == Type_Matrix) { + GB_PANIC("TODO(bill): Type_Matrix"); + // for (i64 k = lo; k < hi; k++) { + // cgCompoundLitElemTempData data = {}; + // data.value = value; + + // data.elem_index = matrix_row_major_index_to_offset(bt, k); + // array_add(temp_data, data); + // } + } else { + enum {MAX_ELEMENT_AMOUNT = 32}; + if ((hi-lo) <= MAX_ELEMENT_AMOUNT) { + for (i64 k = lo; k < hi; k++) { + cgCompoundLitElemTempData data = {}; + data.value = value; + data.elem_index = k; + array_add(temp_data, data); + } + } else { + cgCompoundLitElemTempData data = {}; + data.value = value; + data.elem_index = lo; + data.elem_length = hi-lo; + array_add(temp_data, data); + } + } + } else { + auto tav = fv->field->tav; + GB_ASSERT(tav.mode == Addressing_Constant); + i64 index = exact_value_to_i64(tav.value); + + cgValue value = cg_emit_conv(p, cg_build_expr(p, fv->value), et); + GB_ASSERT(!is_type_tuple(value.type)); + + cgCompoundLitElemTempData data = {}; + data.value = value; + data.expr = fv->value; + if (bt->kind == Type_Matrix) { + GB_PANIC("TODO(bill): Type_Matrix"); + // data.elem_index = matrix_row_major_index_to_offset(bt, index); + } else { + data.elem_index = index; + } + array_add(temp_data, data); + } + + } else { + // if (bt->kind != Type_DynamicArray && lb_is_elem_const(elem, et)) { + // continue; + // } + + cgValue field_expr = cg_build_expr(p, elem); + GB_ASSERT(!is_type_tuple(field_expr.type)); + + cgValue ev = cg_emit_conv(p, field_expr, et); + + cgCompoundLitElemTempData data = {}; + data.value = ev; + if (bt->kind == Type_Matrix) { + GB_PANIC("TODO(bill): Type_Matrix"); + // data.elem_index = matrix_row_major_index_to_offset(bt, i); + } else { + data.elem_index = i; + } + array_add(temp_data, data); + } + } + }; + + auto const &assign_array = [](cgProcedure *p, Array const &temp_data) { + for (auto const &td : temp_data) if (td.value.node != nullptr) { + if (td.elem_length > 0) { + GB_PANIC("TODO(bill): range"); + // auto loop_data = cg_loop_start(p, cast(isize)td.elem_length, t_i32); + // { + // cgValue dst = td.gep; + // dst = cg_emit_ptr_offset(p, dst, loop_data.idx); + // cg_emit_store(p, dst, td.value); + // } + // cg_loop_end(p, loop_data); + } else { + cg_emit_store(p, td.gep, td.value); + } + } + }; + + + + ast_node(cl, CompoundLit, expr); + + Type *type = type_of_expr(expr); + Type *bt = base_type(type); + + cgAddr v = cg_add_local(p, type, nullptr, true); + + if (cl->elems.count == 0) { + // No need to create it + return v; + } + + TEMPORARY_ALLOCATOR_GUARD(); + + Type *et = nullptr; + switch (bt->kind) { + case Type_Array: et = bt->Array.elem; break; + case Type_EnumeratedArray: et = bt->EnumeratedArray.elem; break; + case Type_Slice: et = bt->Slice.elem; break; + case Type_BitSet: et = bt->BitSet.elem; break; + case Type_SimdVector: et = bt->SimdVector.elem; break; + case Type_Matrix: et = bt->Matrix.elem; break; + } + + String proc_name = {}; + if (p->entity) { + proc_name = p->entity->token.string; + } + TokenPos pos = ast_token(expr).pos; + + if (cl->elems.count == 0) { + } + + switch (bt->kind) { + default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break; + + case Type_Struct: { + TypeStruct *st = &bt->Struct; + cgValue comp_lit_ptr = cg_addr_get_ptr(p, v); + + for_array(field_index, cl->elems) { + Ast *elem = cl->elems[field_index]; + + cgValue field_expr = {}; + Entity *field = nullptr; + isize index = field_index; + + if (elem->kind == Ast_FieldValue) { + ast_node(fv, FieldValue, elem); + String name = fv->field->Ident.token.string; + Selection sel = lookup_field(bt, name, false); + GB_ASSERT(!sel.indirect); + + elem = fv->value; + if (sel.index.count > 1) { + cgValue dst = cg_emit_deep_field_gep(p, comp_lit_ptr, sel); + field_expr = cg_build_expr(p, elem); + field_expr = cg_emit_conv(p, field_expr, sel.entity->type); + cg_emit_store(p, dst, field_expr); + continue; + } + + index = sel.index[0]; + } else { + Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_index); + GB_ASSERT(sel.index.count == 1); + GB_ASSERT(!sel.indirect); + index = sel.index[0]; + } + + field = st->fields[index]; + Type *ft = field->type; + + field_expr = cg_build_expr(p, elem); + + cgValue gep = {}; + if (st->is_raw_union) { + gep = cg_emit_conv(p, comp_lit_ptr, alloc_type_pointer(ft)); + } else { + gep = cg_emit_struct_ep(p, comp_lit_ptr, cast(i32)index); + } + + Type *fet = field_expr.type; + GB_ASSERT(fet->kind != Type_Tuple); + + // HACK TODO(bill): THIS IS A MASSIVE HACK!!!! + if (is_type_union(ft) && !are_types_identical(fet, ft) && !is_type_untyped(fet)) { + GB_ASSERT_MSG(union_variant_index(ft, fet) >= 0, "%s", type_to_string(fet)); + + GB_PANIC("TODO(bill): cg_emit_store_union_variant"); + // cg_emit_store_union_variant(p, gep, field_expr, fet); + } else { + cgValue fv = cg_emit_conv(p, field_expr, ft); + cg_emit_store(p, gep, fv); + } + } + return v; + } + + // case Type_Map: { + // GB_ASSERT(!build_context.no_dynamic_literals); + + // cgValue err = cg_dynamic_map_reserve(p, v.addr, 2*cl->elems.count, pos); + // gb_unused(err); + + // for (Ast *elem : cl->elems) { + // ast_node(fv, FieldValue, elem); + + // cgValue key = cg_build_expr(p, fv->field); + // cgValue value = cg_build_expr(p, fv->value); + // cg_internal_dynamic_map_set(p, v.addr, type, key, value, elem); + // } + // break; + // } + + // case Type_Array: { + // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); + + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + + // populate(p, cl->elems, &temp_data, type); + + // cgValue dst_ptr = cg_addr_get_ptr(p, v); + // for_array(i, temp_data) { + // i32 index = cast(i32)(temp_data[i].elem_index); + // temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, index); + // } + + // assign_array(p, temp_data); + // break; + // } + // case Type_EnumeratedArray: { + // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); + + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + + // populate(p, cl->elems, &temp_data, type); + + // cgValue dst_ptr = cg_addr_get_ptr(p, v); + // i64 index_offset = exact_value_to_i64(*bt->EnumeratedArray.min_value); + // for_array(i, temp_data) { + // i32 index = cast(i32)(temp_data[i].elem_index - index_offset); + // temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, index); + // } + + // assign_array(p, temp_data); + // break; + // } + case Type_Slice: { + isize count = gb_max(cl->elems.count, cl->max_count); + + TB_CharUnits backing_size = cast(TB_CharUnits)(type_size_of(bt->Slice.elem) * count); + TB_CharUnits align = cast(TB_CharUnits)type_align_of(bt->Slice.elem); + TB_Node *backing = tb_inst_local(p->func, backing_size, align); + + cgValue data = cg_value(backing, alloc_type_multi_pointer(bt->Slice.elem)); + + auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + populate(p, cl->elems, &temp_data, type); + + + for_array(i, temp_data) { + temp_data[i].gep = cg_emit_ptr_offset(p, data, cg_const_int(p, t_int, temp_data[i].elem_index)); + } + + assign_array(p, temp_data); + cg_fill_slice(p, v, data, cg_const_int(p, t_int, cl->max_count)); + return v; + } + + // case Type_DynamicArray: { + // GB_ASSERT(!build_context.no_dynamic_literals); + + // Type *et = bt->DynamicArray.elem; + // cgValue size = cg_const_int(p->module, t_int, type_size_of(et)); + // cgValue align = cg_const_int(p->module, t_int, type_align_of(et)); + + // i64 item_count = gb_max(cl->max_count, cl->elems.count); + // { + + // auto args = array_make(temporary_allocator(), 5); + // args[0] = cg_emit_conv(p, cg_addr_get_ptr(p, v), t_rawptr); + // args[1] = size; + // args[2] = align; + // args[3] = cg_const_int(p->module, t_int, item_count); + // args[4] = cg_emit_source_code_location_as_global(p, proc_name, pos); + // cg_emit_runtime_call(p, "__dynamic_array_reserve", args); + // } + + // cgValue items = cg_generate_local_array(p, et, item_count); + + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + // populate(p, cl->elems, &temp_data, type); + + // for_array(i, temp_data) { + // temp_data[i].gep = cg_emit_array_epi(p, items, temp_data[i].elem_index); + // } + // assign_array(p, temp_data); + + // { + // auto args = array_make(temporary_allocator(), 6); + // args[0] = cg_emit_conv(p, v.addr, t_rawptr); + // args[1] = size; + // args[2] = align; + // args[3] = cg_emit_conv(p, items, t_rawptr); + // args[4] = cg_const_int(p->module, t_int, item_count); + // args[5] = cg_emit_source_code_location_as_global(p, proc_name, pos); + // cg_emit_runtime_call(p, "__dynamic_array_append", args); + // } + // break; + // } + + // case Type_Basic: { + // GB_ASSERT(is_type_any(bt)); + // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); + // String field_names[2] = { + // str_lit("data"), + // str_lit("id"), + // }; + // Type *field_types[2] = { + // t_rawptr, + // t_typeid, + // }; + + // for_array(field_index, cl->elems) { + // Ast *elem = cl->elems[field_index]; + + // cgValue field_expr = {}; + // isize index = field_index; + + // if (elem->kind == Ast_FieldValue) { + // ast_node(fv, FieldValue, elem); + // Selection sel = lookup_field(bt, fv->field->Ident.token.string, false); + // index = sel.index[0]; + // elem = fv->value; + // } else { + // TypeAndValue tav = type_and_value_of_expr(elem); + // Selection sel = lookup_field(bt, field_names[field_index], false); + // index = sel.index[0]; + // } + + // field_expr = cg_build_expr(p, elem); + + // GB_ASSERT(field_expr.type->kind != Type_Tuple); + + // Type *ft = field_types[index]; + // cgValue fv = cg_emit_conv(p, field_expr, ft); + // cgValue gep = cg_emit_struct_ep(p, cg_addr_get_ptr(p, v), cast(i32)index); + // cg_emit_store(p, gep, fv); + // } + // break; + // } + + case Type_BitSet: { + i64 sz = type_size_of(type); + if (sz == 0) { + return v; + } + cgValue lower = cg_const_value(p, t_int, exact_value_i64(bt->BitSet.lower)); + Type *it = bit_set_to_int(bt); + cgValue one = cg_const_value(p, it, exact_value_i64(1)); + for (Ast *elem : cl->elems) { + GB_ASSERT(elem->kind != Ast_FieldValue); + + cgValue expr = cg_build_expr(p, elem); + GB_ASSERT(expr.type->kind != Type_Tuple); + + cgValue e = cg_emit_conv(p, expr, it); + e = cg_emit_arith(p, Token_Sub, e, lower, it); + e = cg_emit_arith(p, Token_Shl, one, e, it); + + cgValue old_value = cg_emit_transmute(p, cg_addr_load(p, v), it); + cgValue new_value = cg_emit_arith(p, Token_Or, old_value, e, it); + new_value = cg_emit_transmute(p, new_value, type); + cg_addr_store(p, v, new_value); + } + return v; + } + + // case Type_Matrix: { + // cg_addr_store(p, v, cg_const_value(p->module, type, exact_value_compound(expr))); + + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + + // populate(p, cl->elems, &temp_data, type); + + // cgValue dst_ptr = cg_addr_get_ptr(p, v); + // for_array(i, temp_data) { + // temp_data[i].gep = cg_emit_array_epi(p, dst_ptr, temp_data[i].elem_index); + // } + + // assign_array(p, temp_data); + // break; + // } + + // case Type_SimdVector: { + // cgValue vector_value = cg_const_value(p->module, type, exact_value_compound(expr)); + // defer (cg_addr_store(p, v, vector_value)); + + // auto temp_data = array_make(temporary_allocator(), 0, cl->elems.count); + + // populate(p, cl->elems, &temp_data, type); + + // // TODO(bill): reduce the need for individual `insertelement` if a `shufflevector` + // // might be a better option + // for (auto const &td : temp_data) { + // if (td.value.value != nullptr) { + // if (td.elem_length > 0) { + // for (i64 k = 0; k < td.elem_length; k++) { + // LLVMValueRef index = cg_const_int(p->module, t_u32, td.elem_index + k).value; + // vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, ""); + // } + // } else { + // LLVMValueRef index = cg_const_int(p->module, t_u32, td.elem_index).value; + // vector_value.value = LLVMBuildInsertElement(p->builder, vector_value.value, td.value.value, index, ""); + + // } + // } + // } + // break; + // } + } + + return v; +} + gb_internal cgValue cg_build_unary_and(cgProcedure *p, Ast *expr) { ast_node(ue, UnaryExpr, expr); auto tv = type_and_value_of_expr(expr); @@ -2020,12 +2645,12 @@ gb_internal cgValue cg_build_unary_and(cgProcedure *p, Ast *expr) { // GB_ASSERT(t->kind == Type_Map); // ast_node(ie, IndexExpr, ue_expr); - // lbValue map_val = lb_build_addr_ptr(p, ie->expr); + // cgValue map_val = cg_build_addr_ptr(p, ie->expr); // if (deref) { - // map_val = lb_emit_load(p, map_val); + // map_val = cg_emit_load(p, map_val); // } - // lbValue key = lb_build_expr(p, ie->index); + // cgValue key = lb_build_expr(p, ie->index); // key = lb_emit_conv(p, key, t->Map.key); // lbAddr addr = lb_addr_map(map_val, key, t, alloc_type_pointer(t->Map.value)); @@ -2053,18 +2678,8 @@ gb_internal cgValue cg_build_unary_and(cgProcedure *p, Ast *expr) { // return lb_make_soa_pointer(p, tv.type, addr, index); } else if (ue_expr->kind == Ast_CompoundLit) { - cgValue v = cg_build_expr(p, ue->expr); - - Type *type = v.type; - cgAddr addr = {}; - // if (p->is_startup) { - // addr = cg_add_global_generated(p->module, type, v); - // } else { - addr = cg_add_local(p, type, nullptr, false); - // } - cg_addr_store(p, addr, v); + cgAddr addr = cg_build_addr_compound_lit(p, expr); return addr.addr; - } else if (ue_expr->kind == Ast_TypeAssertion) { GB_PANIC("TODO(bill): &v.(T)"); // if (is_type_tuple(tv.type)) { @@ -2225,7 +2840,8 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { Type *type = type_of_expr(expr); GB_ASSERT_MSG(tv.mode != Addressing_Invalid, "invalid expression '%s' (tv.mode = %d, tv.type = %s) @ %s\n Current Proc: %.*s : %s", expr_to_string(expr), tv.mode, type_to_string(tv.type), token_pos_to_string(expr_pos), LIT(p->name), type_to_string(p->type)); - if (tv.value.kind != ExactValue_Invalid) { + if (tv.value.kind != ExactValue_Invalid && + expr->kind != Ast_CompoundLit) { // NOTE(bill): The commented out code below is just for debug purposes only // if (is_type_untyped(type)) { // gb_printf_err("%s %s : %s @ %p\n", token_pos_to_string(expr_pos), expr_to_string(expr), type_to_string(expr->tav.type), expr); @@ -2314,6 +2930,11 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { return cg_build_call_expr(p, expr); case_end; + case_ast_node(cl, CompoundLit, expr); + cgAddr addr = cg_build_addr_compound_lit(p, expr); + return cg_addr_load(p, addr); + case_end; + case_ast_node(te, TernaryIfExpr, expr); cgValue incoming_values[2] = {}; @@ -2413,6 +3034,14 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { case_ast_node(be, BinaryExpr, expr); return cg_build_binary_expr(p, expr); case_end; + + case_ast_node(oe, OrReturnExpr, expr); + return cg_build_or_return(p, oe->expr, tv.type); + case_end; + + case_ast_node(oe, OrElseExpr, expr); + return cg_build_or_else(p, oe->x, oe->y, tv.type); + case_end; } GB_PANIC("TODO(bill): cg_build_expr_internal %.*s", LIT(ast_strings[expr->kind])); return {}; @@ -2580,6 +3209,7 @@ gb_internal cgAddr cg_build_addr_index_expr(cgProcedure *p, Ast *expr) { // cgValue len = cg_builtin_len(p, slice); // cg_emit_bounds_check(p, ast_token(ie->index), index, len); cgValue v = cg_emit_ptr_offset(p, elem, index); + v.type = alloc_type_pointer(type_deref(v.type, true)); return cg_addr(v); } @@ -2592,7 +3222,9 @@ gb_internal cgAddr cg_build_addr_index_expr(cgProcedure *p, Ast *expr) { cgValue index = cg_build_expr(p, ie->index); index = cg_emit_conv(p, index, t_int); - return cg_addr(cg_emit_ptr_offset(p, multi_ptr, index)); + cgValue v = cg_emit_ptr_offset(p, multi_ptr, index); + v.type = alloc_type_pointer(type_deref(v.type, true)); + return cg_addr(v); } case Type_RelativeSlice: { @@ -2624,6 +3256,7 @@ gb_internal cgAddr cg_build_addr_index_expr(cgProcedure *p, Ast *expr) { // cgValue len = cg_dynamic_array_len(p, dynamic_array); // cg_emit_bounds_check(p, ast_token(ie->index), index, len); cgValue v = cg_emit_ptr_offset(p, elem, index); + v.type = alloc_type_pointer(type_deref(v.type, true)); return cg_addr(v); } @@ -2664,7 +3297,9 @@ gb_internal cgAddr cg_build_addr_index_expr(cgProcedure *p, Ast *expr) { index = cg_emit_conv(p, cg_build_expr(p, ie->index), t_int); // cg_emit_bounds_check(p, ast_token(ie->index), index, len); - return cg_addr(cg_emit_ptr_offset(p, elem, index)); + cgValue v = cg_emit_ptr_offset(p, elem, index); + v.type = alloc_type_pointer(type_deref(v.type, true)); + return cg_addr(v); } } return {}; @@ -2694,6 +3329,23 @@ gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { return cg_build_addr_from_entity(p, e, expr); case_end; + case_ast_node(de, DerefExpr, expr); + Type *t = type_of_expr(de->expr); + if (is_type_relative_pointer(t)) { + cgAddr addr = cg_build_addr(p, de->expr); + addr.relative.deref = true; + return addr; + } else if (is_type_soa_pointer(t)) { + cgValue value = cg_build_expr(p, de->expr); + cgValue ptr = cg_emit_struct_ev(p, value, 0); + cgValue idx = cg_emit_struct_ev(p, value, 1); + GB_PANIC("TODO(bill): cg_addr_soa_variable"); + // return cg_addr_soa_variable(ptr, idx, nullptr); + } + cgValue addr = cg_build_expr(p, de->expr); + return cg_addr(addr); + case_end; + case_ast_node(ie, IndexExpr, expr); return cg_build_addr_index_expr(p, expr); case_end; @@ -2804,6 +3456,7 @@ gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { if (sub_sel.index.count > 0) { item = cg_emit_deep_field_gep(p, item, sub_sel); } + item.type = alloc_type_pointer(type_deref(item.type, true)); return cg_addr(item); } else if (addr.kind == cgAddr_Swizzle) { GB_ASSERT(sel.index.count > 0); @@ -2821,6 +3474,23 @@ gb_internal cgAddr cg_build_addr_internal(cgProcedure *p, Ast *expr) { } case_end; + case_ast_node(ce, CallExpr, expr); + cgValue res = cg_build_expr(p, expr); + switch (res.kind) { + case cgValue_Value: + return cg_addr(cg_address_from_load_or_generate_local(p, res)); + case cgValue_Addr: + return cg_addr(res); + case cgValue_Multi: + GB_PANIC("cannot address a multi-valued expression"); + break; + } + case_end; + + case_ast_node(cl, CompoundLit, expr); + return cg_build_addr_compound_lit(p, expr); + case_end; + } TokenPos token_pos = ast_token(expr).pos; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 41c185dc6..610d715ae 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -86,6 +86,10 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i } p->symbol = cast(TB_Symbol *)tb_extern_create(m->mod, link_name.len, cast(char const *)link_name.text, TB_EXTERNAL_SO_LOCAL); } + if (p->name == "main") { + // TODO(bill): figure out when this should be public or not + linkage = TB_LINKAGE_PUBLIC; + } if (p->symbol == nullptr) { p->func = tb_function_create(m->mod, link_name.len, cast(char const *)link_name.text, linkage, TB_COMDAT_NONE); @@ -97,9 +101,9 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i p->symbol = cast(TB_Symbol *)p->func; } - cgValue proc_value = cg_value(p->symbol, p->type); - cg_add_entity(m, entity, proc_value); - cg_add_member(m, p->name, proc_value); + p->value = cg_value(p->symbol, p->type); + cg_add_entity(m, entity, p->value); + cg_add_member(m, p->name, p->value); cg_add_procedure_value(m, p); @@ -275,7 +279,9 @@ gb_internal void cg_procedure_begin(cgProcedure *p) { // } } - p->split_returns_index = param_index; + if (is_odin_like_cc) { + p->split_returns_index = param_index; + } if (pt->calling_convention == ProcCC_Odin) { // NOTE(bill): Push context on to stack from implicit parameter @@ -323,9 +329,15 @@ gb_internal void cg_procedure_end(cgProcedure *p) { return; } if (tb_inst_get_control(p->func)) { + GB_ASSERT(p->type->Proc.result_count == 0); tb_inst_ret(p->func, 0, nullptr); } bool emit_asm = false; + + if (string_starts_with(p->name, str_lit("bug@main"))) { + // emit_asm = true; + } + TB_FunctionOutput *output = tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST, emit_asm); if (emit_asm) { TB_Assembly *assembly = tb_output_get_asm(output); @@ -336,47 +348,70 @@ gb_internal void cg_procedure_end(cgProcedure *p) { } } -gb_global String procedures_to_generate_list[] = { - str_lit("bug" ABI_PKG_NAME_SEPARATOR "main"), - str_lit("main"), -}; - gb_internal void cg_procedure_generate(cgProcedure *p) { if (p->body == nullptr) { return; } - bool build_body = false; - - if ( - string_starts_with(p->name, str_lit("runtime" ABI_PKG_NAME_SEPARATOR "_os_write")) || - // p->name == "bug" ABI_PKG_NAME_SEPARATOR "main" || - // p->name == "main" || - false - ) { - build_body = true; - } - - if (build_body) { - cg_procedure_begin(p); - cg_build_stmt(p, p->body); - } + cg_procedure_begin(p); + cg_build_stmt(p, p->body); cg_procedure_end(p); - if (build_body) { + if (string_starts_with(p->name, str_lit("bug@main"))) { // IR Printing TB_Arena *arena = tb_default_arena(); defer (arena->free(arena)); TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); defer (tb_funcopt_exit(opt)); tb_funcopt_print(opt); + fprintf(stdout, "\n"); + } + if (false) { // GraphViz printing + tb_function_print(p->func, tb_default_print_callback, stdout); + } +} + +gb_internal void cg_build_nested_proc(cgProcedure *p, AstProcLit *pd, Entity *e) { + GB_ASSERT(pd->body != nullptr); + cgModule *m = p->module; + auto *min_dep_set = &m->info->minimum_dependency_set; + + if (ptr_set_exists(min_dep_set, e) == false) { + // NOTE(bill): Nothing depends upon it so doesn't need to be built + return; + } - // GraphViz printing - // tb_function_print(p->func, tb_default_print_callback, stdout); + // NOTE(bill): Generate a new name + // parent.name-guid + String original_name = e->token.string; + String pd_name = original_name; + if (e->Procedure.link_name.len > 0) { + pd_name = e->Procedure.link_name; } + + + isize name_len = p->name.len + 1 + pd_name.len + 1 + 10 + 1; + char *name_text = gb_alloc_array(permanent_allocator(), char, name_len); + + i32 guid = cast(i32)p->children.count; + name_len = gb_snprintf(name_text, name_len, "%.*s" ABI_PKG_NAME_SEPARATOR "%.*s-%d", LIT(p->name), LIT(pd_name), guid); + String name = make_string(cast(u8 *)name_text, name_len-1); + + e->Procedure.link_name = name; + + cgProcedure *nested_proc = cg_procedure_create(p->module, e); + e->cg_procedure = nested_proc; + + cgValue value = nested_proc->value; + + cg_add_entity(m, e, value); + array_add(&p->children, nested_proc); + array_add(&m->procedures_to_generate, nested_proc); } + + gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e) { GB_ASSERT(is_type_proc(e->type)); e = strip_entity_wrapping(e); @@ -388,6 +423,7 @@ gb_internal cgValue cg_find_procedure_value_from_entity(cgModule *m, Entity *e) found = map_get(&m->values, e); rw_mutex_shared_unlock(&m->values_mutex); if (found) { + GB_ASSERT(found->node != nullptr); return *found; } @@ -408,9 +444,6 @@ gb_internal cgValue cg_build_call_expr(cgProcedure *p, Ast *expr) { GB_ASSERT(res.kind == cgValue_Multi); GB_ASSERT(res.multi->values.count == 2); return res.multi->values[0]; - // GB_ASSERT(is_type_tuple(res.type)); - // GB_ASSERT(res.type->Tuple.variables.count == 2); - // return cg_emit_struct_ev(p, res, 0); } return res; } @@ -470,8 +503,9 @@ gb_internal cgValue cg_emit_call(cgProcedure * p, cgValue value, Slice params[param_index++] = local; } } - for (cgValue arg : args) { - Type *param_type = param_entities[param_index]->type; + for_array(i, args) { + Type *param_type = param_entities[i]->type; + cgValue arg = args[i]; arg = cg_emit_conv(p, arg, param_type); arg = cg_flatten_value(p, arg); @@ -629,9 +663,7 @@ gb_internal cgValue cg_handle_param_value(cgProcedure *p, Type *parameter_type, if (p->entity != nullptr) { proc_name = p->entity->token.string; } - GB_PANIC("TODO(bill): cg_emit_source_code_location_as_global"); - // return cg_emit_source_code_location_as_global(p, proc_name, pos); - break; + return cg_emit_source_code_location_as_global(p, proc_name, pos); } case ParameterValue_Value: return cg_build_expr(p, param_value.ast_value); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 074d2674c..b25be089d 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -65,7 +65,7 @@ gb_internal cgValue cg_emit_load(cgProcedure *p, cgValue const &ptr, bool is_vol return cg_value(tb_inst_load(p->func, dt, the_ptr, alignment, is_volatile), type); } -gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, bool is_volatile) { +gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue src, bool is_volatile) { GB_ASSERT_MSG(dst.kind != cgValue_Multi, "cannot store to multiple values at once"); if (dst.kind == cgValue_Addr) { @@ -122,10 +122,14 @@ gb_internal void cg_emit_store(cgProcedure *p, cgValue dst, cgValue const &src, return; } + switch (dst.kind) { case cgValue_Value: - switch (dst.kind) { + switch (src.kind) { case cgValue_Value: + if (src.node->dt.type == TB_INT && src.node->dt.data == 1) { + src.node = tb_inst_zxt(p->func, src.node, dt); + } tb_inst_store(p->func, dt, dst.node, src.node, alignment, is_volatile); return; case cgValue_Addr: @@ -367,8 +371,7 @@ gb_internal cgValue cg_emit_ptr_offset(cgProcedure *p, cgValue ptr, cgValue inde Type *elem = type_deref(ptr.type, true); i64 stride = type_size_of(elem); - ptr.node = tb_inst_array_access(p->func, ptr.node, index.node, stride); - return ptr; + return cg_value(tb_inst_array_access(p->func, ptr.node, index.node, stride), alloc_type_pointer(elem)); } gb_internal cgValue cg_emit_array_ep(cgProcedure *p, cgValue s, cgValue index) { GB_ASSERT(s.kind == cgValue_Value); @@ -383,8 +386,7 @@ gb_internal cgValue cg_emit_array_ep(cgProcedure *p, cgValue s, cgValue index) { Type *elem = base_array_type(st); i64 stride = type_size_of(elem); - s.node = tb_inst_array_access(p->func, s.node, index.node, stride); - return s; + return cg_value(tb_inst_array_access(p->func, s.node, index.node, stride), alloc_type_pointer(elem)); } gb_internal cgValue cg_emit_array_epi(cgProcedure *p, cgValue s, i64 index) { return cg_emit_array_ep(p, s, cg_const_int(p, t_int, index)); @@ -425,7 +427,7 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { case Type_Slice: switch (index) { case 0: - result_type = alloc_type_pointer(t->Slice.elem); + result_type = alloc_type_multi_pointer(t->Slice.elem); offset = 0; break; case 1: @@ -439,7 +441,7 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { case Basic_string: switch (index) { case 0: - result_type = t_u8_ptr; + result_type = t_u8_multi_ptr; offset = 0; break; case 1: @@ -494,7 +496,7 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { case Type_DynamicArray: switch (index) { case 0: - result_type = alloc_type_pointer(t->DynamicArray.elem); + result_type = alloc_type_multi_pointer(t->DynamicArray.elem); offset = index*int_size; break; case 1: case 2: @@ -564,6 +566,14 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { ); } + +gb_internal cgValue cg_emit_struct_ev(cgProcedure *p, cgValue s, i64 index) { + s = cg_address_from_load_or_generate_local(p, s); + cgValue ptr = cg_emit_struct_ep(p, s, index); + return cg_flatten_value(p, cg_emit_load(p, ptr)); +} + + gb_internal cgValue cg_emit_deep_field_gep(cgProcedure *p, cgValue e, Selection const &sel) { GB_ASSERT(sel.index.count > 0); Type *type = type_deref(e.type); @@ -1008,7 +1018,7 @@ gb_internal void cg_build_assign_stmt(cgProcedure *p, AstAssignStmt *as) { } } -gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return_results) { +gb_internal void cg_build_return_stmt_internal(cgProcedure *p, Slice const &results) { TypeTuple *tuple = &p->type->Proc.results->Tuple; isize return_count = p->type->Proc.result_count; @@ -1016,38 +1026,6 @@ gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return tb_inst_ret(p->func, 0, nullptr); return; } - TEMPORARY_ALLOCATOR_GUARD(); - - auto results = array_make(temporary_allocator(), 0, return_count); - - if (return_results.count != 0) { - for (isize i = 0; i < return_results.count; i++) { - cgValue res = cg_build_expr(p, return_results[i]); - cg_append_tuple_values(p, &results, res); - } - } else { - for_array(i, tuple->variables) { - Entity *e = tuple->variables[i]; - cgAddr addr = map_must_get(&p->variable_map, e); - cgValue res = cg_addr_load(p, addr); - array_add(&results, res); - } - } - GB_ASSERT(results.count == return_count); - - if (return_results.count != 0 && p->type->Proc.has_named_results) { - // NOTE(bill): store the named values before returning - for_array(i, tuple->variables) { - Entity *e = tuple->variables[i]; - cgAddr addr = map_must_get(&p->variable_map, e); - cg_addr_store(p, addr, results[i]); - } - } - for_array(i, tuple->variables) { - Entity *e = tuple->variables[i]; - results[i] = cg_emit_conv(p, results[i], e->type); - } - if (p->split_returns_index >= 0) { GB_ASSERT(is_calling_convention_odin(p->type->Proc.calling_convention)); @@ -1071,15 +1049,20 @@ gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return GB_ASSERT(p->proto->return_count == 1); TB_DataType dt = TB_PROTOTYPE_RETURNS(p->proto)->dt; - cgValue result = cg_flatten_value(p, results[0]); + cgValue result = results[return_count-1]; + result = cg_flatten_value(p, result); TB_Node *final_res = nullptr; if (result.kind == cgValue_Addr) { TB_CharUnits align = cast(TB_CharUnits)type_align_of(result.type); final_res = tb_inst_load(p->func, dt, result.node, align, false); } else { GB_ASSERT(result.kind == cgValue_Value); - if (result.node->dt.raw == dt.raw) { + TB_DataType st = result.node->dt; + GB_ASSERT(st.type == dt.type); + if (st.raw == dt.raw) { final_res = result.node; + } else if (st.type == TB_INT && st.data == 1) { + final_res = tb_inst_zxt(p->func, result.node, dt); } else { final_res = tb_inst_bitcast(p->func, result.node, dt); } @@ -1092,10 +1075,94 @@ gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return } else { GB_ASSERT(!is_calling_convention_odin(p->type->Proc.calling_convention)); + + if (p->return_by_ptr) { + Entity *e = tuple->variables[return_count-1]; + TB_Node *ret_ptr = tb_inst_param(p->func, 0); + cgValue ptr = cg_value(ret_ptr, alloc_type_pointer(e->type)); + cg_emit_store(p, ptr, results[return_count-1]); + + tb_inst_ret(p->func, 0, nullptr); + return; + } else { + GB_ASSERT(p->proto->return_count == 1); + TB_DataType dt = TB_PROTOTYPE_RETURNS(p->proto)->dt; + if (results.count == 1) { + cgValue result = results[0]; + result = cg_flatten_value(p, result); + + TB_Node *final_res = nullptr; + if (result.kind == cgValue_Addr) { + TB_CharUnits align = cast(TB_CharUnits)type_align_of(result.type); + final_res = tb_inst_load(p->func, dt, result.node, align, false); + } else { + GB_ASSERT(result.kind == cgValue_Value); + TB_DataType st = result.node->dt; + GB_ASSERT(st.type == dt.type); + if (st.raw == dt.raw) { + final_res = result.node; + } else if (st.type == TB_INT && st.data == 1) { + final_res = tb_inst_zxt(p->func, result.node, dt); + } else { + final_res = tb_inst_bitcast(p->func, result.node, dt); + } + } + + GB_ASSERT(final_res != nullptr); + + tb_inst_ret(p->func, 1, &final_res); + return; + } else { + GB_ASSERT_MSG(results.count == 1, "TODO(bill): multi-return values for the return"); + return; + } + } + } +} + + +gb_internal void cg_build_return_stmt(cgProcedure *p, Slice const &return_results) { + TypeTuple *tuple = &p->type->Proc.results->Tuple; + isize return_count = p->type->Proc.result_count; + if (return_count == 0) { + tb_inst_ret(p->func, 0, nullptr); + return; + } + TEMPORARY_ALLOCATOR_GUARD(); - GB_PANIC("TODO(bill): %.*s MUTLIPLE RETURN VALUES %td %td", LIT(p->name), results.count, return_results.count); + auto results = array_make(temporary_allocator(), 0, return_count); + + if (return_results.count != 0) { + for (isize i = 0; i < return_results.count; i++) { + cgValue res = cg_build_expr(p, return_results[i]); + cg_append_tuple_values(p, &results, res); + } + } else { + for_array(i, tuple->variables) { + Entity *e = tuple->variables[i]; + cgAddr addr = map_must_get(&p->variable_map, e); + cgValue res = cg_addr_load(p, addr); + array_add(&results, res); + } + } + GB_ASSERT(results.count == return_count); + + if (return_results.count != 0 && p->type->Proc.has_named_results) { + // NOTE(bill): store the named values before returning + for_array(i, tuple->variables) { + Entity *e = tuple->variables[i]; + cgAddr addr = map_must_get(&p->variable_map, e); + cg_addr_store(p, addr, results[i]); + } + } + for_array(i, tuple->variables) { + Entity *e = tuple->variables[i]; + results[i] = cg_emit_conv(p, results[i], e->type); + } + + cg_build_return_stmt_internal(p, slice_from_array(results)); } gb_internal void cg_build_if_stmt(cgProcedure *p, Ast *node) { @@ -1673,13 +1740,7 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { // TODO(bill): check if last instruction was a terminating one or not - { - TokenPos pos = ast_token(node).pos; - TB_FileID *file_id = map_get(&p->module->file_id_map, cast(uintptr)pos.file_id); - if (file_id) { - tb_inst_set_location(p->func, *file_id, pos.line); - } - } + cg_set_debug_pos_from_node(p, node); u16 prev_state_flags = p->state_flags; defer (p->state_flags = prev_state_flags); @@ -1838,7 +1899,7 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { case_end; case_ast_node(rs, RangeStmt, node); - GB_PANIC("TODO(bill): cg_build_range_stmt"); + GB_PANIC("TODO(bill): cg_build_range_stmt %.*s", LIT(p->name)); // cg_build_range_stmt(p, rs, rs->scope); case_end; @@ -1879,13 +1940,115 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { } } +gb_internal void cg_build_constant_value_decl(cgProcedure *p, AstValueDecl *vd) { + if (vd == nullptr || vd->is_mutable) { + return; + } + + auto *min_dep_set = &p->module->info->minimum_dependency_set; + + static i32 global_guid = 0; + + for (Ast *ident : vd->names) { + GB_ASSERT(ident->kind == Ast_Ident); + Entity *e = entity_of_node(ident); + GB_ASSERT(e != nullptr); + if (e->kind != Entity_TypeName) { + continue; + } + + bool polymorphic_struct = false; + if (e->type != nullptr && e->kind == Entity_TypeName) { + Type *bt = base_type(e->type); + if (bt->kind == Type_Struct) { + polymorphic_struct = bt->Struct.is_polymorphic; + } + } + + if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) { + continue; + } + + if (e->TypeName.ir_mangled_name.len != 0) { + // NOTE(bill): Already set + continue; + } + + cg_set_nested_type_name_ir_mangled_name(e, p); + } + + for_array(i, vd->names) { + Ast *ident = vd->names[i]; + GB_ASSERT(ident->kind == Ast_Ident); + Entity *e = entity_of_node(ident); + GB_ASSERT(e != nullptr); + if (e->kind != Entity_Procedure) { + continue; + } + GB_ASSERT (vd->values[i] != nullptr); + + Ast *value = unparen_expr(vd->values[i]); + if (value->kind != Ast_ProcLit) { + continue; // It's an alias + } + + DeclInfo *decl = decl_info_of_entity(e); + ast_node(pl, ProcLit, decl->proc_lit); + if (pl->body != nullptr) { + GenProcsData *gpd = e->Procedure.gen_procs; + if (gpd) { + rw_mutex_shared_lock(&gpd->mutex); + for (Entity *e : gpd->procs) { + if (!ptr_set_exists(min_dep_set, e)) { + continue; + } + DeclInfo *d = decl_info_of_entity(e); + cg_build_nested_proc(p, &d->proc_lit->ProcLit, e); + } + rw_mutex_shared_unlock(&gpd->mutex); + } else { + cg_build_nested_proc(p, pl, e); + } + } else { + + // FFI - Foreign function interace + String original_name = e->token.string; + String name = original_name; + + if (e->Procedure.is_foreign) { + GB_PANIC("cg_add_foreign_library_path"); + // cg_add_foreign_library_path(p->module, e->Procedure.foreign_library); + } + + if (e->Procedure.link_name.len > 0) { + name = e->Procedure.link_name; + } + + cgValue *prev_value = string_map_get(&p->module->members, name); + if (prev_value != nullptr) { + // NOTE(bill): Don't do mutliple declarations in the IR + return; + } + + e->Procedure.link_name = name; + + cgProcedure *nested_proc = cg_procedure_create(p->module, e); + + cgValue value = p->value; + + array_add(&p->module->procedures_to_generate, nested_proc); + array_add(&p->children, nested_proc); + string_map_set(&p->module->members, name, value); + } + } +} + gb_internal void cg_build_stmt_list(cgProcedure *p, Slice const &stmts) { for (Ast *stmt : stmts) { switch (stmt->kind) { case_ast_node(vd, ValueDecl, stmt); - // TODO(bill) - // cg_build_constant_value_decl(p, vd); + cg_build_constant_value_decl(p, vd); case_end; case_ast_node(fb, ForeignBlockDecl, stmt); ast_node(block, BlockStmt, fb->body); -- cgit v1.2.3 From 241a939c2985b0d9ad65dd305af6e84c82554e39 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 10:27:55 +0100 Subject: Update Tilde --- core/runtime/error_checks.odin | 18 +++++++++--------- core/runtime/internal.odin | 13 +++++++++++-- core/runtime/print.odin | 12 ++++++------ core/runtime/procs.odin | 4 ++-- src/tilde/tb.h | 1 - src/tilde/tb.lib | Bin 4163308 -> 4161458 bytes src/tilde_const.cpp | 1 + src/tilde_proc.cpp | 9 ++++++--- 8 files changed, 35 insertions(+), 23 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/core/runtime/error_checks.odin b/core/runtime/error_checks.odin index c189642af..9d484979a 100644 --- a/core/runtime/error_checks.odin +++ b/core/runtime/error_checks.odin @@ -235,7 +235,7 @@ make_slice_error_loc :: #force_inline proc "contextless" (loc := #caller_locatio handle_error(loc, len) } -make_dynamic_array_error_loc :: #force_inline proc "contextless" (using loc := #caller_location, len, cap: int) { +make_dynamic_array_error_loc :: #force_inline proc "contextless" (loc := #caller_location, len, cap: int) { if 0 <= len && len <= cap { return } @@ -271,18 +271,18 @@ make_map_expr_error_loc :: #force_inline proc "contextless" (loc := #caller_loca -bounds_check_error_loc :: #force_inline proc "contextless" (using loc := #caller_location, index, count: int) { - bounds_check_error(file_path, line, column, index, count) +bounds_check_error_loc :: #force_inline proc "contextless" (loc := #caller_location, index, count: int) { + bounds_check_error(loc.file_path, loc.line, loc.column, index, count) } -slice_expr_error_hi_loc :: #force_inline proc "contextless" (using loc := #caller_location, hi: int, len: int) { - slice_expr_error_hi(file_path, line, column, hi, len) +slice_expr_error_hi_loc :: #force_inline proc "contextless" (loc := #caller_location, hi: int, len: int) { + slice_expr_error_hi(loc.file_path, loc.line, loc.column, hi, len) } -slice_expr_error_lo_hi_loc :: #force_inline proc "contextless" (using loc := #caller_location, lo, hi: int, len: int) { - slice_expr_error_lo_hi(file_path, line, column, lo, hi, len) +slice_expr_error_lo_hi_loc :: #force_inline proc "contextless" (loc := #caller_location, lo, hi: int, len: int) { + slice_expr_error_lo_hi(loc.file_path, loc.line, loc.column, lo, hi, len) } -dynamic_array_expr_error_loc :: #force_inline proc "contextless" (using loc := #caller_location, low, high, max: int) { - dynamic_array_expr_error(file_path, line, column, low, high, max) +dynamic_array_expr_error_loc :: #force_inline proc "contextless" (loc := #caller_location, low, high, max: int) { + dynamic_array_expr_error(loc.file_path, loc.line, loc.column, low, high, max) } diff --git a/core/runtime/internal.odin b/core/runtime/internal.odin index ad8a40acf..4d166bef0 100644 --- a/core/runtime/internal.odin +++ b/core/runtime/internal.odin @@ -11,7 +11,7 @@ RUNTIME_LINKAGE :: "strong" when ( ODIN_BUILD_MODE == .Dynamic || !ODIN_NO_CRT) && !IS_WASM) else "internal" -RUNTIME_REQUIRE :: true +RUNTIME_REQUIRE :: !ODIN_TILDE @(private) @@ -218,10 +218,18 @@ memory_equal :: proc "contextless" (x, y: rawptr, n: int) -> bool { case n == 0: return true case x == y: return true } - a, b := ([^]byte)(x), ([^]byte)(y) length := uint(n) + + for i := uint(0); i < length; i += 1 { + if a[i] != b[i] { + return false + } + } + return true +/* + when size_of(uint) == 8 { if word_length := length >> 3; word_length != 0 { for _ in 0.. bool { return true } +*/ } memory_compare :: proc "contextless" (a, b: rawptr, n: int) -> int #no_bounds_check { diff --git a/core/runtime/print.odin b/core/runtime/print.odin index 732ed9c12..20788b66f 100644 --- a/core/runtime/print.odin +++ b/core/runtime/print.odin @@ -215,19 +215,19 @@ print_uint :: proc "contextless" (x: uint) { print_u64(u64(x)) } print_uintptr :: proc "contextless" (x: uintptr) { print_u64(u64(x)) } print_int :: proc "contextless" (x: int) { print_i64(i64(x)) } -print_caller_location :: proc "contextless" (using loc: Source_Code_Location) { - print_string(file_path) +print_caller_location :: proc "contextless" (loc: Source_Code_Location) { + print_string(loc.file_path) when ODIN_ERROR_POS_STYLE == .Default { print_byte('(') - print_u64(u64(line)) + print_u64(u64(loc.line)) print_byte(':') - print_u64(u64(column)) + print_u64(u64(loc.column)) print_byte(')') } else when ODIN_ERROR_POS_STYLE == .Unix { print_byte(':') - print_u64(u64(line)) + print_u64(u64(loc.line)) print_byte(':') - print_u64(u64(column)) + print_u64(u64(loc.column)) print_byte(':') } else { #panic("unhandled ODIN_ERROR_POS_STYLE") diff --git a/core/runtime/procs.odin b/core/runtime/procs.odin index 3a433c3bf..1592c608b 100644 --- a/core/runtime/procs.odin +++ b/core/runtime/procs.odin @@ -31,7 +31,7 @@ when ODIN_NO_CRT && ODIN_OS == .Windows { if ptr != nil && len != 0 { b := byte(val) p := ([^]byte)(ptr) - for i in 0..const_nil_guid.fetch_add(1)); TB_Global *cstr_global = tb_global_create(m->mod, -1, name, nullptr, TB_LINKAGE_PRIVATE); + i64 size = str.len+1; tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), cstr_global, size, 1, 1); u8 *data = cast(u8 *)tb_global_add_region(m->mod, cstr_global, 0, size); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 610d715ae..e75c621ee 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -334,8 +334,8 @@ gb_internal void cg_procedure_end(cgProcedure *p) { } bool emit_asm = false; - if (string_starts_with(p->name, str_lit("bug@main"))) { - // emit_asm = true; + if (string_starts_with(p->name, str_lit("bug@"))) { + emit_asm = true; } TB_FunctionOutput *output = tb_module_compile_function(p->module->mod, p->func, TB_ISEL_FAST, emit_asm); @@ -357,7 +357,10 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { cg_build_stmt(p, p->body); cg_procedure_end(p); - if (string_starts_with(p->name, str_lit("bug@main"))) { // IR Printing + if ( + // string_starts_with(p->name, str_lit("bug@")) || + false + ) { // IR Printing TB_Arena *arena = tb_default_arena(); defer (arena->free(arena)); TB_FuncOpt *opt = tb_funcopt_enter(p->func, arena); -- cgit v1.2.3 From 28c97a94670b2b1cad801e9e9d3b5d465f9435d8 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 24 Jul 2023 17:12:23 +0100 Subject: Begin work on setting up type information table --- src/tilde.cpp | 28 ++++- src/tilde.hpp | 2 + src/tilde_const.cpp | 72 ++++++++++++- src/tilde_proc.cpp | 2 + src/tilde_type_info.cpp | 281 +++++++++++++++++++++++++++++++++++++++++++++--- 5 files changed, 366 insertions(+), 19 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 7574ea6b9..82d30215e 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -199,6 +199,13 @@ gb_internal void cg_set_debug_pos_from_node(cgProcedure *p, Ast *node) { } } +gb_internal void cg_add_symbol(cgModule *m, Entity *e, TB_Symbol *symbol) { + if (e) { + rw_mutex_lock(&m->values_mutex); + map_set(&m->symbols, e, symbol); + rw_mutex_unlock(&m->values_mutex); + } +} gb_internal void cg_add_entity(cgModule *m, Entity *e, cgValue const &val) { if (e) { @@ -221,12 +228,27 @@ gb_internal void cg_add_procedure_value(cgModule *m, cgProcedure *p) { rw_mutex_lock(&m->values_mutex); if (p->entity != nullptr) { map_set(&m->procedure_values, p->func, p->entity); + if (p->symbol != nullptr) { + map_set(&m->symbols, p->entity, p->symbol); + } } string_map_set(&m->procedures, p->name, p); rw_mutex_unlock(&m->values_mutex); } +gb_internal TB_Symbol *cg_find_symbol_from_entity(cgModule *m, Entity *e) { + if (e) { + rw_mutex_lock(&m->values_mutex); + defer (rw_mutex_unlock(&m->values_mutex)); + TB_Symbol **found = map_get(&m->symbols, e); + if (found) { + return *found; + } + } + return nullptr; +} + gb_internal isize cg_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) { auto *set = &info->minimum_dependency_type_info_set; isize index = type_info_index(info, type, err_on_not_found); @@ -449,11 +471,13 @@ gb_internal bool cg_global_variables_create(cgModule *m) { var.is_initialized = true; } } else { - tb_global_set_storage(m->mod, section, global, type_size_of(e->type), type_align_of(e->type), 0); + i64 max_regions = cg_global_const_calculate_region_count_from_basic_type(e->type); + tb_global_set_storage(m->mod, section, global, type_size_of(e->type), type_align_of(e->type), max_regions); } array_add(&global_variables, var); + cg_add_symbol(m, e, cast(TB_Symbol *)global); cg_add_entity(m, e, g); cg_add_member(m, name, g); } @@ -478,6 +502,7 @@ gb_internal cgModule *cg_module_create(Checker *c) { tb_module_set_tls_index(m->mod, 10, "_tls_index"); map_init(&m->values); + map_init(&m->symbols); map_init(&m->file_id_map); @@ -500,6 +525,7 @@ gb_internal cgModule *cg_module_create(Checker *c) { gb_internal void cg_module_destroy(cgModule *m) { map_destroy(&m->values); + map_destroy(&m->symbols); map_destroy(&m->file_id_map); map_destroy(&m->debug_type_map); map_destroy(&m->proc_debug_type_map); diff --git a/src/tilde.hpp b/src/tilde.hpp index 2d7b2e1c3..e4f047017 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -214,6 +214,7 @@ struct cgModule { RwMutex values_mutex; PtrMap values; + PtrMap symbols; StringMap members; StringMap procedures; PtrMap procedure_values; @@ -257,6 +258,7 @@ gb_internal void cg_add_procedure_to_queue(cgProcedure *p); gb_internal void cg_setup_type_info_data(cgModule *m); gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value, Type *type); +gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *type); gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value, Type *type, TB_Global *global, i64 offset); gb_internal cgValue cg_value(TB_Global * g, Type *type); diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 11126e07a..60f8e636b 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -143,6 +143,33 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty return global; } +gb_internal void cg_global_source_code_location_const(cgModule *m, String const &proc_name, TokenPos pos, TB_Global *global, i64 offset) { + // Source_Code_Location :: struct { + // file_path: string, + // line, column: i32, + // procedure: string, + // } + + i64 file_path_offset = type_offset_of(t_source_code_location, 0); + i64 line_offset = type_offset_of(t_source_code_location, 1); + i64 column_offset = type_offset_of(t_source_code_location, 2); + i64 procedure_offset = type_offset_of(t_source_code_location, 3); + + String file_path = get_file_path_string(pos.file_id); + if (file_path.len != 0) { + cg_global_const_string(m, file_path, t_string, global, offset+file_path_offset); + } + + void *line_ptr = tb_global_add_region(m->mod, global, offset+line_offset, 4); + void *column_ptr = tb_global_add_region(m->mod, global, offset+column_offset, 4); + cg_write_int_at_ptr(line_ptr, pos.line, t_i32); + cg_write_int_at_ptr(column_ptr, pos.column, t_i32); + + if (proc_name.len != 0) { + cg_global_const_string(m, proc_name, t_string, global, offset+procedure_offset); + } +} + gb_internal bool cg_elem_type_can_be_constant(Type *t) { t = base_type(t); if (t == t_invalid) { @@ -201,10 +228,11 @@ gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *typ return 1; case Type_Pointer: case Type_MultiPointer: + return 2; // allows for offsets case Type_Proc: - return true; + return 1; case Type_Slice: - return 2; + return 3; // alows for offsets case Type_DynamicArray: return 5; case Type_Map: @@ -221,6 +249,46 @@ gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *typ case Type_Matrix: return 1; + case Type_Array: + { + Type *elem = type->Array.elem; + i64 count = cg_global_const_calculate_region_count_from_basic_type(elem); + return count*type->Array.count; + } + case Type_EnumeratedArray: + { + Type *elem = type->EnumeratedArray.elem; + i64 count = cg_global_const_calculate_region_count_from_basic_type(elem); + return count*type->EnumeratedArray.count; + } + + case Type_Struct: + if (type->Struct.is_raw_union) { + i64 max_count = 0; + for (Entity *f : type->Struct.fields) { + i64 count = cg_global_const_calculate_region_count_from_basic_type(f->type); + max_count = gb_max(count, max_count); + } + return max_count; + } else { + i64 max_count = 0; + for (Entity *f : type->Struct.fields) { + max_count += cg_global_const_calculate_region_count_from_basic_type(f->type); + } + return max_count; + } + break; + case Type_Union: + { + i64 max_count = 0; + for (Type *t : type->Union.variants) { + i64 count = cg_global_const_calculate_region_count_from_basic_type(t); + max_count = gb_max(count, max_count); + } + return max_count+1; + } + break; + default: GB_PANIC("TODO(bill): %s", type_to_string(type)); break; diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index acc31ce67..a805b2985 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -103,6 +103,8 @@ gb_internal cgProcedure *cg_procedure_create(cgModule *m, Entity *entity, bool i } p->value = cg_value(p->symbol, p->type); + + cg_add_symbol(m, entity, p->symbol); cg_add_entity(m, entity, p->value); cg_add_member(m, p->name, p->value); cg_add_procedure_value(m, p); diff --git a/src/tilde_type_info.cpp b/src/tilde_type_info.cpp index d3613cde8..1e86f6644 100644 --- a/src/tilde_type_info.cpp +++ b/src/tilde_type_info.cpp @@ -1,3 +1,16 @@ +gb_internal void cg_global_const_type_info_ptr(cgModule *m, TB_Global *type_info_array, Type *type, TB_Global *global, i64 offset) { + i64 index_in_bytes = cast(i64)cg_type_info_index(m->info, type); + index_in_bytes *= type_size_of(t_type_info); + + void *ti_ptr_ptr = tb_global_add_region(m->mod, global, offset, build_context.ptr_size); + // NOTE(bill): define the byte offset for the pointer + cg_write_int_at_ptr(ti_ptr_ptr, index_in_bytes, t_uintptr); + + // NOTE(bill): this will add to the byte offset set previously + tb_global_add_symbol_reloc(m->mod, global, offset, cast(TB_Symbol *)type_info_array); +} + + gb_internal void cg_setup_type_info_data(cgModule *m) { if (build_context.no_rtti) { return; @@ -9,11 +22,14 @@ gb_internal void cg_setup_type_info_data(cgModule *m) { // gb_printf_err("max_type_info_count: %td\n", max_type_info_count); Type *t = alloc_type_array(t_type_info, max_type_info_count); + i64 max_objects = cast(i64)max_type_info_count * cg_global_const_calculate_region_count_from_basic_type(t_type_info); + TB_Global *g = tb_global_create(m->mod, -1, CG_TYPE_INFO_DATA_NAME, nullptr, TB_LINKAGE_PRIVATE); - tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, max_type_info_count); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), g, type_size_of(t), 16, max_objects); cgValue value = cg_value(g, alloc_type_pointer(t)); cg_global_type_info_data_entity = alloc_entity_variable(nullptr, make_token_ident(CG_TYPE_INFO_DATA_NAME), t, EntityState_Resolved); + cg_add_symbol(m, cg_global_type_info_data_entity, cast(TB_Symbol *)g); cg_add_entity(m, cg_global_type_info_data_entity, value); } @@ -83,22 +99,255 @@ gb_internal void cg_setup_type_info_data(cgModule *m) { gb_unused(info); - // i64 global_type_info_data_entity_count = 0; - // { - // // NOTE(bill): Set the type_table slice with the global backing array - // cgValue global_type_table = cg_find_runtime_value(m, str_lit("type_table")); - // Type *type = base_type(cg_global_type_info_data_entity->type); - // GB_ASSERT(is_type_array(type)); - // global_type_info_data_entity_count = type->Array.count; + i64 global_type_info_data_entity_count = 0; + + // NOTE(bill): Set the type_table slice with the global backing array + TB_Global *type_table_slice = cast(TB_Global *)cg_find_symbol_from_entity(m, scope_lookup_current(m->info->runtime_package->scope, str_lit("type_table"))); + GB_ASSERT(type_table_slice != nullptr); + + TB_Global *type_table_array = cast(TB_Global *)cg_find_symbol_from_entity(m, cg_global_type_info_data_entity); + GB_ASSERT(type_table_array != nullptr); + + Type *type = base_type(cg_global_type_info_data_entity->type); + GB_ASSERT(is_type_array(type)); + global_type_info_data_entity_count = type->Array.count; + + tb_global_add_symbol_reloc(m->mod, type_table_slice, 0, cast(TB_Symbol *)type_table_array); + + void *len_ptr = tb_global_add_region(m->mod, type_table_slice, build_context.int_size, build_context.int_size); + cg_write_int_at_ptr(len_ptr, type->Array.count, t_int); + + // Useful types + Entity *type_info_flags_entity = find_core_entity(info->checker, str_lit("Type_Info_Flags")); + Type *t_type_info_flags = type_info_flags_entity->type; + GB_ASSERT(type_size_of(t_type_info_flags) == 4); + + auto entries_handled = slice_make(heap_allocator(), cast(isize)global_type_info_data_entity_count); + defer (gb_free(heap_allocator(), entries_handled.data)); + entries_handled[0] = true; + + + i64 type_info_size = type_size_of(t_type_info); + i64 size_offset = type_offset_of(t_type_info, 0); + i64 align_offset = type_offset_of(t_type_info, 1); + i64 flags_offset = type_offset_of(t_type_info, 2); + i64 id_offset = type_offset_of(t_type_info, 3); + i64 variant_offset = type_offset_of(t_type_info, 4); + + Type *type_info_union = base_type(t_type_info)->Struct.fields[4]->type; + GB_ASSERT(type_info_union->kind == Type_Union); + + i64 union_tag_offset = type_info_union->Union.variant_block_size; + Type *ti_union_tag_type = union_tag_type(type_info_union); + u64 union_tag_type_size = type_size_of(ti_union_tag_type); + + for_array(type_info_type_index, info->type_info_types) { + Type *t = info->type_info_types[type_info_type_index]; + if (t == nullptr || t == t_invalid) { + continue; + } + + isize entry_index = cg_type_info_index(info, t, false); + if (entry_index <= 0) { + continue; + } + + if (entries_handled[entry_index]) { + continue; + } + entries_handled[entry_index] = true; + + TB_Global *global = type_table_array; + + i64 offset = entry_index * type_info_size; + + i64 size = type_size_of(t); + i64 align = type_align_of(t); + u32 flags = type_info_flags_of_type(t); + u64 id = cg_typeid_as_u64(m, t); + + void *size_ptr = tb_global_add_region(m->mod, global, offset+size_offset, build_context.int_size); + void *align_ptr = tb_global_add_region(m->mod, global, offset+align_offset, build_context.int_size); + void *flags_ptr = tb_global_add_region(m->mod, global, offset+flags_offset, 4); + void *id_ptr = tb_global_add_region(m->mod, global, offset+id_offset, build_context.ptr_size); + cg_write_int_at_ptr (size_ptr, size, t_int); + cg_write_int_at_ptr (align_ptr, align, t_int); + cg_write_int_at_ptr (flags_ptr, flags, t_u32); + cg_write_uint_at_ptr(id_ptr, id, t_typeid); + + + // add data to the offset to make it easier to deal with later on + offset += variant_offset; + + Type *tag_type = nullptr; + + switch (t->kind) { + case Type_Named: { + // Type_Info_Named :: struct { + // name: string, + // base: ^Type_Info, + // pkg: string, + // loc: Source_Code_Location, + // } + tag_type = t_type_info_named; + + if (t->Named.type_name->pkg) { + i64 pkg_offset = type_offset_of(tag_type, 2); + String pkg_name = t->Named.type_name->pkg->name; + cg_global_const_string(m, pkg_name, t_string, global, offset+pkg_offset); + } + + String proc_name = {}; + if (t->Named.type_name->parent_proc_decl) { + DeclInfo *decl = t->Named.type_name->parent_proc_decl; + if (decl->entity && decl->entity->kind == Entity_Procedure) { + i64 name_offset = type_offset_of(tag_type, 0); + proc_name = decl->entity->token.string; + cg_global_const_string(m, proc_name, t_string, global, offset+name_offset); + } + } + + i64 loc_offset = type_offset_of(tag_type, 3); + TokenPos pos = t->Named.type_name->token.pos; + cg_global_source_code_location_const(m, proc_name, pos, global, offset+loc_offset); + + i64 base_offset = type_offset_of(tag_type, 1); + cg_global_const_type_info_ptr(m, type_table_array, t->Named.base, global, offset+base_offset); + break; + } + + case Type_Basic: + switch (t->Basic.kind) { + case Basic_bool: + case Basic_b8: + case Basic_b16: + case Basic_b32: + case Basic_b64: + tag_type = t_type_info_boolean; + break; + + case Basic_i8: + case Basic_u8: + case Basic_i16: + case Basic_u16: + case Basic_i32: + case Basic_u32: + case Basic_i64: + case Basic_u64: + case Basic_i128: + case Basic_u128: + + case Basic_i16le: + case Basic_u16le: + case Basic_i32le: + case Basic_u32le: + case Basic_i64le: + case Basic_u64le: + case Basic_i128le: + case Basic_u128le: + case Basic_i16be: + case Basic_u16be: + case Basic_i32be: + case Basic_u32be: + case Basic_i64be: + case Basic_u64be: + case Basic_i128be: + case Basic_u128be: + + case Basic_int: + case Basic_uint: + case Basic_uintptr: { + tag_type = t_type_info_integer; + + bool is_signed = (t->Basic.flags & BasicFlag_Unsigned) == 0; + // NOTE(bill): This is matches the runtime layout + u8 endianness_value = 0; + if (t->Basic.flags & BasicFlag_EndianLittle) { + endianness_value = 1; + } else if (t->Basic.flags & BasicFlag_EndianBig) { + endianness_value = 2; + } + u8 *signed_ptr = cast(u8 *)tb_global_add_region(m->mod, global, offset+0, 1); + u8 *endianness_ptr = cast(u8 *)tb_global_add_region(m->mod, global, offset+1, 1); + *signed_ptr = is_signed; + *endianness_ptr = endianness_value; + break; + } + + case Basic_rune: + tag_type = t_type_info_rune; + break; + + case Basic_f16: + case Basic_f32: + case Basic_f64: + case Basic_f16le: + case Basic_f32le: + case Basic_f64le: + case Basic_f16be: + case Basic_f32be: + case Basic_f64be: + { + tag_type = t_type_info_float; + + // // NOTE(bill): This is matches the runtime layout + u8 endianness_value = 0; + if (t->Basic.flags & BasicFlag_EndianLittle) { + endianness_value = 1; + } else if (t->Basic.flags & BasicFlag_EndianBig) { + endianness_value = 2; + } + + u8 *ptr = cast(u8 *)tb_global_add_region(m->mod, global, offset+0, 1); + *ptr = endianness_value; + } + break; + + case Basic_complex32: + case Basic_complex64: + case Basic_complex128: + tag_type = t_type_info_complex; + break; - // LLVMValueRef indices[2] = {llvm_zero(m), llvm_zero(m)}; - // LLVMValueRef data = LLVMConstInBoundsGEP2(cg_type(m, cg_global_type_info_data_entity->type), cg_global_type_info_data_ptr(m).value, indices, gb_count_of(indices)); - // LLVMValueRef len = LLVMConstInt(cg_type(m, t_int), type->Array.count, true); - // Type *t = type_deref(global_type_table.type); - // GB_ASSERT(is_type_slice(t)); - // LLVMValueRef slice = llvm_const_slice_internal(m, data, len); + case Basic_quaternion64: + case Basic_quaternion128: + case Basic_quaternion256: + tag_type = t_type_info_quaternion; + break; - // LLVMSetInitializer(global_type_table.value, slice); - // } + case Basic_rawptr: + tag_type = t_type_info_pointer; + break; + case Basic_string: + tag_type = t_type_info_string; + break; + + case Basic_cstring: + { + tag_type = t_type_info_string; + bool *b = cast(bool *)tb_global_add_region(m->mod, global, offset+0, 1); + *b = true; + } + break; + + case Basic_any: + tag_type = t_type_info_any; + break; + + case Basic_typeid: + tag_type = t_type_info_typeid; + break; + } + break; + } + + if (tag_type != nullptr) { + i64 union_index = union_variant_index(type_info_union, tag_type); + GB_ASSERT(union_index != 0); + void *tag_ptr = tb_global_add_region(m->mod, global, offset+union_tag_offset, union_tag_type_size); + cg_write_int_at_ptr(tag_ptr, union_index, ti_union_tag_type); + } + + } } \ No newline at end of file -- cgit v1.2.3 From b934e4b564e58c62b8c6848a71fe99b02c588a94 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 25 Jul 2023 00:33:43 +0100 Subject: Implement basic runtime type information This allows for `runtime.println_any` to work! --- src/tilde.cpp | 2 +- src/tilde/tb.lib | Bin 4164088 -> 4164640 bytes src/tilde_builtin.cpp | 3 +- src/tilde_const.cpp | 81 ++++++++++------- src/tilde_expr.cpp | 229 +++++++++++++++++++++++++++++++++++++++++++++--- src/tilde_proc.cpp | 5 +- src/tilde_stmt.cpp | 43 ++++----- src/tilde_type_info.cpp | 167 +++++++++++++++++++++++++++++++++++ 8 files changed, 459 insertions(+), 71 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 82d30215e..729b8fa1e 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -260,7 +260,7 @@ gb_internal isize cg_type_info_index(CheckerInfo *info, Type *type, bool err_on_ } } if (err_on_not_found) { - GB_PANIC("NOT FOUND lb_type_info_index %s @ index %td", type_to_string(type), index); + GB_PANIC("NOT FOUND lb_type_info_index '%s' @ index %td", type_to_string(type), index); } return -1; } diff --git a/src/tilde/tb.lib b/src/tilde/tb.lib index 7ec145bda..78e661bf8 100644 Binary files a/src/tilde/tb.lib and b/src/tilde/tb.lib differ diff --git a/src/tilde_builtin.cpp b/src/tilde_builtin.cpp index e30ff1cb0..edf436424 100644 --- a/src/tilde_builtin.cpp +++ b/src/tilde_builtin.cpp @@ -267,8 +267,7 @@ gb_internal cgValue cg_build_builtin(cgProcedure *p, BuiltinProcId id, Ast *expr pos = e->token.pos; } - GB_PANIC("TODO(bill): cg_emit_source_code_location_as_global"); - // return cg_emit_source_code_location_as_global(p, procedure, pos); + return cg_emit_source_code_location_as_global(p, procedure, pos); } break; case BuiltinProc_len: { diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 60f8e636b..30038cfdf 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -31,7 +31,7 @@ gb_internal cgValue cg_const_nil(cgModule *m, cgProcedure *p, Type *type) { if (is_type_internally_pointer_like(type)) { return cg_value(tb_inst_uint(p->func, dt, 0), type); - } else if (is_type_integer(type) || is_type_boolean(type) || is_type_bit_set(type)) { + } else if (is_type_integer(type) || is_type_boolean(type) || is_type_bit_set(type) || is_type_typeid(type)) { return cg_value(tb_inst_uint(p->func, dt, 0), type); } else if (is_type_float(type)) { switch (size) { @@ -51,10 +51,49 @@ gb_internal cgValue cg_const_nil(cgProcedure *p, Type *type) { return cg_const_nil(p->module, p, type); } +gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Type *type, TB_Global *global, i64 offset); +gb_internal void cg_write_int_at_ptr(void *dst, i64 i, Type *original_type); + +gb_internal void cg_global_source_code_location_const(cgModule *m, String const &proc_name, TokenPos pos, TB_Global *global, i64 offset) { + // Source_Code_Location :: struct { + // file_path: string, + // line, column: i32, + // procedure: string, + // } + + i64 file_path_offset = type_offset_of(t_source_code_location, 0); + i64 line_offset = type_offset_of(t_source_code_location, 1); + i64 column_offset = type_offset_of(t_source_code_location, 2); + i64 procedure_offset = type_offset_of(t_source_code_location, 3); + + String file_path = get_file_path_string(pos.file_id); + if (file_path.len != 0) { + cg_global_const_string(m, file_path, t_string, global, offset+file_path_offset); + } + + void *line_ptr = tb_global_add_region(m->mod, global, offset+line_offset, 4); + void *column_ptr = tb_global_add_region(m->mod, global, offset+column_offset, 4); + cg_write_int_at_ptr(line_ptr, pos.line, t_i32); + cg_write_int_at_ptr(column_ptr, pos.column, t_i32); + + if (proc_name.len != 0) { + cg_global_const_string(m, proc_name, t_string, global, offset+procedure_offset); + } +} + gb_internal cgValue cg_emit_source_code_location_as_global(cgProcedure *p, String const &proc_name, TokenPos pos) { - // TODO(bill): cg_emit_source_code_location_as_global - return cg_const_nil(p, t_source_code_location); + cgModule *m = p->module; + char name[32] = {}; + gb_snprintf(name, 31, "scl$%u", 1+m->const_nil_guid.fetch_add(1)); + + TB_Global *global = tb_global_create(m->mod, -1, name, cg_debug_type(m, t_source_code_location), TB_LINKAGE_PRIVATE); + tb_global_set_storage(m->mod, tb_module_get_rdata(m->mod), global, type_size_of(t_source_code_location), type_align_of(t_source_code_location), 6); + + cg_global_source_code_location_const(m, proc_name, pos, global, 0); + + TB_Node *ptr = tb_inst_get_symbol_address(p->func, cast(TB_Symbol *)global); + return cg_lvalue_addr(ptr, t_source_code_location); } @@ -143,33 +182,6 @@ gb_internal TB_Global *cg_global_const_string(cgModule *m, String const &str, Ty return global; } -gb_internal void cg_global_source_code_location_const(cgModule *m, String const &proc_name, TokenPos pos, TB_Global *global, i64 offset) { - // Source_Code_Location :: struct { - // file_path: string, - // line, column: i32, - // procedure: string, - // } - - i64 file_path_offset = type_offset_of(t_source_code_location, 0); - i64 line_offset = type_offset_of(t_source_code_location, 1); - i64 column_offset = type_offset_of(t_source_code_location, 2); - i64 procedure_offset = type_offset_of(t_source_code_location, 3); - - String file_path = get_file_path_string(pos.file_id); - if (file_path.len != 0) { - cg_global_const_string(m, file_path, t_string, global, offset+file_path_offset); - } - - void *line_ptr = tb_global_add_region(m->mod, global, offset+line_offset, 4); - void *column_ptr = tb_global_add_region(m->mod, global, offset+column_offset, 4); - cg_write_int_at_ptr(line_ptr, pos.line, t_i32); - cg_write_int_at_ptr(column_ptr, pos.column, t_i32); - - if (proc_name.len != 0) { - cg_global_const_string(m, proc_name, t_string, global, offset+procedure_offset); - } -} - gb_internal bool cg_elem_type_can_be_constant(Type *t) { t = base_type(t); if (t == t_invalid) { @@ -1003,3 +1015,12 @@ gb_internal cgValue cg_const_int(cgProcedure *p, Type *type, i64 i) { gb_internal cgValue cg_const_bool(cgProcedure *p, Type *type, bool v) { return cg_value(tb_inst_bool(p->func, v), type); } + +gb_internal cgValue cg_const_string(cgProcedure *p, Type *type, String const &str) { + return cg_const_value(p, type, exact_value_string(str)); +} + +gb_internal cgValue cg_const_union_tag(cgProcedure *p, Type *u, Type *v) { + return cg_const_value(p, union_tag_type(u), exact_value_i64(union_variant_index(u, v))); +} + diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 8737e75cd..551ffbfbb 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -267,7 +267,8 @@ gb_internal cgValue cg_emit_byte_swap(cgProcedure *p, cgValue value, Type *end_t GB_ASSERT(value.kind == cgValue_Value); - value.node = tb_inst_bswap(p->func, value.node); + // TODO(bill): bswap + // value.node = tb_inst_bswap(p->func, value.node); return cg_emit_transmute(p, value, end_type); } @@ -913,13 +914,12 @@ gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *t) { if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) { - GB_PANIC("TODO(bill): cstring_to_string call"); - // TEMPORARY_ALLOCATOR_GUARD(); - // lbValue c = lb_emit_conv(p, value, t_cstring); - // auto args = array_make(temporary_allocator(), 1); - // args[0] = c; - // lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args); - // return lb_emit_conv(p, s, dst); + TEMPORARY_ALLOCATOR_GUARD(); + cgValue c = cg_emit_conv(p, value, t_cstring); + auto args = slice_make(temporary_allocator(), 1); + args[0] = c; + cgValue s = cg_emit_runtime_call(p, "cstring_to_string", args); + return cg_emit_conv(p, s, dst); } // float -> float @@ -1115,7 +1115,29 @@ gb_internal cgValue cg_emit_conv(cgProcedure *p, cgValue value, Type *t) { } if (is_type_any(dst)) { - GB_PANIC("TODO(bill): ? -> any"); + if (is_type_untyped_nil(src) || + is_type_untyped_uninit(src)) { + return cg_const_nil(p, t); + } + + cgAddr result = cg_add_local(p, t, nullptr, false); + + Type *st = default_type(src_type); + + cgValue data = cg_address_from_load_or_generate_local(p, value); + GB_ASSERT(is_type_pointer(data.type)); + GB_ASSERT(is_type_typed(st)); + + data = cg_emit_conv(p, data, t_rawptr); + + cgValue id = cg_typeid(p, st); + cgValue data_ptr = cg_emit_struct_ep(p, result.addr, 0); + cgValue id_ptr = cg_emit_struct_ep(p, result.addr, 1); + + cg_emit_store(p, data_ptr, data); + cg_emit_store(p, id_ptr, id); + + return cg_addr_load(p, result); } i64 src_sz = type_size_of(src); @@ -2868,6 +2890,190 @@ gb_internal cgValue cg_build_unary_and(cgProcedure *p, Ast *expr) { return cg_build_addr_ptr(p, ue->expr); } +gb_internal cgValue cg_emit_cast_union(cgProcedure *p, cgValue value, Type *type, TokenPos pos) { + Type *src_type = value.type; + bool is_ptr = is_type_pointer(src_type); + + bool is_tuple = true; + Type *tuple = type; + if (type->kind != Type_Tuple) { + is_tuple = false; + tuple = make_optional_ok_type(type); + } + + + if (is_ptr) { + value = cg_emit_load(p, value); + } + Type *src = base_type(type_deref(src_type)); + GB_ASSERT_MSG(is_type_union(src), "%s", type_to_string(src_type)); + Type *dst = tuple->Tuple.variables[0]->type; + + cgValue value_ = cg_address_from_load_or_generate_local(p, value); + + if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) { + // just do a bit cast of the data at the front + cgValue ptr = cg_emit_conv(p, value_, alloc_type_pointer(type)); + return cg_emit_load(p, ptr); + } + + + cgValue tag = {}; + cgValue dst_tag = {}; + cgValue cond = {}; + cgValue data = {}; + + cgValue gep0 = cg_add_local(p, tuple->Tuple.variables[0]->type, nullptr, true).addr; + cgValue gep1 = cg_add_local(p, tuple->Tuple.variables[1]->type, nullptr, true).addr; + + if (is_type_union_maybe_pointer(src)) { + data = cg_emit_load(p, cg_emit_conv(p, value_, gep0.type)); + } else { + tag = cg_emit_load(p, cg_emit_union_tag_ptr(p, value_)); + dst_tag = cg_const_union_tag(p, src, dst); + } + + TB_Node *ok_block = cg_control_region(p, "union_cast_ok"); + TB_Node *end_block = cg_control_region(p, "union_cast_end"); + + if (data.node != nullptr) { + GB_ASSERT(is_type_union_maybe_pointer(src)); + cond = cg_emit_comp_against_nil(p, Token_NotEq, data); + } else { + cond = cg_emit_comp(p, Token_CmpEq, tag, dst_tag); + } + + cg_emit_if(p, cond, ok_block, end_block); + tb_inst_set_control(p->func, ok_block); + + if (data.node == nullptr) { + data = cg_emit_load(p, cg_emit_conv(p, value_, gep0.type)); + } + cg_emit_store(p, gep0, data); + cg_emit_store(p, gep1, cg_const_bool(p, t_bool, true)); + + cg_emit_goto(p, end_block); + tb_inst_set_control(p->func, end_block); + + if (!is_tuple) { + GB_ASSERT((p->state_flags & StateFlag_no_type_assert) == 0); + // NOTE(bill): Panic on invalid conversion + Type *dst_type = tuple->Tuple.variables[0]->type; + + isize arg_count = 7; + if (build_context.no_rtti) { + arg_count = 4; + } + + cgValue ok = cg_emit_load(p, gep1); + auto args = slice_make(permanent_allocator(), arg_count); + args[0] = ok; + + args[1] = cg_const_string(p, t_string, get_file_path_string(pos.file_id)); + args[2] = cg_const_int(p, t_i32, pos.line); + args[3] = cg_const_int(p, t_i32, pos.column); + + if (!build_context.no_rtti) { + args[4] = cg_typeid(p, src_type); + args[5] = cg_typeid(p, dst_type); + args[6] = cg_emit_conv(p, value_, t_rawptr); + } + cg_emit_runtime_call(p, "type_assertion_check2", args); + + return cg_emit_load(p, gep0); + } + + return cg_value_multi2(cg_emit_load(p, gep0), cg_emit_load(p, gep1), tuple); +} + +gb_internal cgValue cg_emit_cast_any(cgProcedure *p, cgValue value, Type *type, TokenPos pos) { + Type *src_type = value.type; + + if (is_type_pointer(src_type)) { + value = cg_emit_load(p, value); + } + + bool is_tuple = true; + Type *tuple = type; + if (type->kind != Type_Tuple) { + is_tuple = false; + tuple = make_optional_ok_type(type); + } + Type *dst_type = tuple->Tuple.variables[0]->type; + + if ((p->state_flags & StateFlag_no_type_assert) != 0 && !is_tuple) { + // just do a bit cast of the data at the front + cgValue ptr = cg_emit_struct_ev(p, value, 0); + ptr = cg_emit_conv(p, ptr, alloc_type_pointer(type)); + return cg_emit_load(p, ptr); + } + + cgValue dst_typeid = cg_typeid(p, dst_type); + cgValue any_typeid = cg_emit_struct_ev(p, value, 1); + + + TB_Node *ok_block = cg_control_region(p, "any_cast_ok"); + TB_Node *end_block = cg_control_region(p, "any_cast_end"); + cgValue cond = cg_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid); + cg_emit_if(p, cond, ok_block, end_block); + tb_inst_set_control(p->func, ok_block); + + cgValue gep0 = cg_add_local(p, tuple->Tuple.variables[0]->type, nullptr, true).addr; + cgValue gep1 = cg_add_local(p, tuple->Tuple.variables[1]->type, nullptr, true).addr; + + cgValue any_data = cg_emit_struct_ev(p, value, 0); + cgValue ptr = cg_emit_conv(p, any_data, alloc_type_pointer(dst_type)); + cg_emit_store(p, gep0, cg_emit_load(p, ptr)); + cg_emit_store(p, gep1, cg_const_bool(p, t_bool, true)); + + cg_emit_goto(p, end_block); + tb_inst_set_control(p->func, end_block); + + if (!is_tuple) { + // NOTE(bill): Panic on invalid conversion + cgValue ok = cg_emit_load(p, gep1); + + isize arg_count = 7; + if (build_context.no_rtti) { + arg_count = 4; + } + auto args = slice_make(permanent_allocator(), arg_count); + args[0] = ok; + + args[1] = cg_const_string(p, t_string, get_file_path_string(pos.file_id)); + args[2] = cg_const_int(p, t_i32, pos.line); + args[3] = cg_const_int(p, t_i32, pos.column); + + if (!build_context.no_rtti) { + args[4] = any_typeid; + args[5] = dst_typeid; + args[6] = cg_emit_struct_ev(p, value, 0); + } + cg_emit_runtime_call(p, "type_assertion_check2", args); + + return cg_emit_load(p, gep0); + } + + return cg_value_multi2(cg_emit_load(p, gep0), cg_emit_load(p, gep1), tuple); +} + + +gb_internal cgValue cg_build_type_assertion(cgProcedure *p, Ast *expr, Type *type) { + ast_node(ta, TypeAssertion, expr); + + TokenPos pos = ast_token(expr).pos; + cgValue e = cg_build_expr(p, ta->expr); + Type *t = type_deref(e.type); + + if (is_type_union(t)) { + return cg_emit_cast_union(p, e, type, pos); + } else if (is_type_any(t)) { + return cg_emit_cast_any(p, e, type, pos); + } + GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type)); + return {}; +} + gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { expr = unparen_expr(expr); @@ -3079,8 +3285,11 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { case_ast_node(oe, OrElseExpr, expr); return cg_build_or_else(p, oe->x, oe->y, tv.type); case_end; + + case_ast_node(ta, TypeAssertion, expr); + return cg_build_type_assertion(p, expr, tv.type); + case_end; } - GB_PANIC("TODO(bill): cg_build_expr_internal %.*s", LIT(ast_strings[expr->kind])); return {}; } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index a805b2985..398148965 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -352,7 +352,7 @@ gb_internal WORKER_TASK_PROC(cg_procedure_compile_worker_proc) { bool emit_asm = false; if ( - // string_starts_with(p->name, str_lit("runtime@_os_write")) || + // string_starts_with(p->name, str_lit("bug@main")) || false ) { emit_asm = true; @@ -866,8 +866,7 @@ gb_internal cgValue cg_build_call_expr_internal(cgProcedure *p, Ast *expr) { cgValue base_elem = cg_emit_array_epi(p, base_array.addr, 0); cgValue len = cg_const_int(p, t_int, slice_len); - GB_PANIC("TODO(bill): cg_fill_slice"); - // cg_fill_slice(p, slice, base_elem, len); + cg_fill_slice(p, slice, base_elem, len); variadic_args = cg_addr_load(p, slice); } diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 8b577dfeb..a663a401d 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -409,11 +409,9 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { switch (t->kind) { case Type_Struct: - { - type_set_offsets(t); - result_type = t->Struct.fields[index]->type; - offset = t->Struct.offsets[index]; - } + type_set_offsets(t); + result_type = t->Struct.fields[index]->type; + offset = t->Struct.offsets[index]; break; case Type_Union: GB_ASSERT(index == -1); @@ -421,7 +419,10 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { break; // return cg_emit_union_tag_ptr(p, s); case Type_Tuple: - GB_PANIC("TODO(bill): cg_emit_tuple_ep"); + type_set_offsets(t); + result_type = t->Tuple.variables[index]->type; + offset = t->Tuple.offsets[index]; + GB_PANIC("TODO(bill): cg_emit_tuple_ep %d", s.kind); break; // return cg_emit_tuple_ep(p, s, index); case Type_Slice: @@ -1799,8 +1800,11 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { expr = unparen_expr(expr); GB_ASSERT(!is_ast_range(expr)); if (expr->tav.mode == Addressing_Type) { - GB_PANIC("TODO(bill): cg_typeid as i64"); - // key = cg_typeid(p, expr->tav.value.value_typeid); + Type *type = expr->tav.value.value_typeid; + if (type == nullptr || type == t_invalid) { + type = expr->tav.type; + } + key = cg_typeid_as_u64(p->module, type); } else { auto tv = type_and_value_of_expr(expr); GB_ASSERT(tv.mode == Addressing_Constant); @@ -1912,21 +1916,16 @@ gb_internal void cg_build_switch_stmt(cgProcedure *p, Ast *node) { cg_scope_close(p, cgDeferExit_Default, done); } -gb_internal void cg_type_case_body(cgProcedure *p, Ast *label, Ast *clause, TB_Node *body_region, TB_Node *done_region) { - // ast_node(cc, CaseClause, clause); - - // cg_push_target_list(p, label, done, nullptr, nullptr); - // cg_build_stmt_list(p, cc->stmts); - // cg_scope_close(p, cgDeferExit_Default, body_region); - // cg_pop_target_list(p); - - // cg_emit_goto(p, done_region); -} - gb_internal void cg_build_type_switch_stmt(cgProcedure *p, Ast *node) { ast_node(ss, TypeSwitchStmt, node); + TB_Node *done_region = cg_control_region(p, "typeswitch_done"); + TB_Node *else_region = done_region; + TB_Node *default_region = nullptr; + isize num_cases = 0; + cg_scope_open(p, ss->scope); + defer (cg_scope_close(p, cgDeferExit_Default, done_region)); ast_node(as, AssignStmt, ss->tag); GB_ASSERT(as->lhs.count == 1); @@ -1969,11 +1968,6 @@ gb_internal void cg_build_type_switch_stmt(cgProcedure *p, Ast *node) { ast_node(body, BlockStmt, ss->body); - TB_Node *done_region = cg_control_region(p, "typeswitch_done"); - TB_Node *else_region = done_region; - TB_Node *default_region = nullptr; - isize num_cases = 0; - for (Ast *clause : body->stmts) { ast_node(cc, CaseClause, clause); num_cases += cc->list.count; @@ -2158,7 +2152,6 @@ gb_internal void cg_build_type_switch_stmt(cgProcedure *p, Ast *node) { cg_emit_goto(p, done_region); tb_inst_set_control(p->func, done_region); - cg_scope_close(p, cgDeferExit_Default, done_region); } diff --git a/src/tilde_type_info.cpp b/src/tilde_type_info.cpp index 1e86f6644..adad2cace 100644 --- a/src/tilde_type_info.cpp +++ b/src/tilde_type_info.cpp @@ -340,6 +340,173 @@ gb_internal void cg_setup_type_info_data(cgModule *m) { break; } break; + + case Type_Pointer: + tag_type = t_type_info_pointer; + cg_global_const_type_info_ptr(m, type_table_array, t->Pointer.elem, global, offset+0); + break; + case Type_MultiPointer: + tag_type = t_type_info_multi_pointer; + cg_global_const_type_info_ptr(m, type_table_array, t->MultiPointer.elem, global, offset+0); + break; + case Type_SoaPointer: + tag_type = t_type_info_soa_pointer; + cg_global_const_type_info_ptr(m, type_table_array, t->SoaPointer.elem, global, offset+0); + break; + + case Type_Array: + { + tag_type = t_type_info_array; + + cg_global_const_type_info_ptr(m, type_table_array, t->Array.elem, global, offset+0); + void *elem_size_ptr = tb_global_add_region(m->mod, global, offset+1*build_context.int_size, build_context.int_size); + void *count_ptr = tb_global_add_region(m->mod, global, offset+2*build_context.int_size, build_context.int_size); + + cg_write_int_at_ptr(elem_size_ptr, type_size_of(t->Array.elem), t_int); + cg_write_int_at_ptr(count_ptr, t->Array.count, t_int); + } + break; + + case Type_EnumeratedArray: + { + tag_type = t_type_info_enumerated_array; + + i64 elem_offset = type_offset_of(tag_type, 0); + i64 index_offset = type_offset_of(tag_type, 1); + i64 elem_size_offset = type_offset_of(tag_type, 2); + i64 count_offset = type_offset_of(tag_type, 3); + i64 min_value_offset = type_offset_of(tag_type, 4); + i64 max_value_offset = type_offset_of(tag_type, 5); + i64 is_sparse_offset = type_offset_of(tag_type, 6); + + cg_global_const_type_info_ptr(m, type_table_array, t->EnumeratedArray.elem, global, offset+elem_offset); + cg_global_const_type_info_ptr(m, type_table_array, t->EnumeratedArray.index, global, offset+index_offset); + + void *elem_size_ptr = tb_global_add_region(m->mod, global, offset+elem_size_offset, build_context.int_size); + void *count_ptr = tb_global_add_region(m->mod, global, offset+count_offset, build_context.int_size); + + void *min_value_ptr = tb_global_add_region(m->mod, global, offset+min_value_offset, type_size_of(t_type_info_enum_value)); + void *max_value_ptr = tb_global_add_region(m->mod, global, offset+max_value_offset, type_size_of(t_type_info_enum_value)); + void *is_sparse_ptr = tb_global_add_region(m->mod, global, offset+is_sparse_offset, 1); + + cg_write_int_at_ptr(elem_size_ptr, type_size_of(t->EnumeratedArray.elem), t_int); + cg_write_int_at_ptr(count_ptr, t->EnumeratedArray.count, t_int); + + cg_write_int_at_ptr(min_value_ptr, exact_value_to_i64(*t->EnumeratedArray.min_value), t_type_info_enum_value); + cg_write_int_at_ptr(max_value_ptr, exact_value_to_i64(*t->EnumeratedArray.max_value), t_type_info_enum_value); + *(bool *)is_sparse_ptr = t->EnumeratedArray.is_sparse; + } + break; + + case Type_DynamicArray: + { + tag_type = t_type_info_dynamic_array; + + cg_global_const_type_info_ptr(m, type_table_array, t->DynamicArray.elem, global, offset+0); + void *elem_size_ptr = tb_global_add_region(m->mod, global, offset+1*build_context.int_size, build_context.int_size); + cg_write_int_at_ptr(elem_size_ptr, type_size_of(t->DynamicArray.elem), t_int); + } + break; + case Type_Slice: + { + tag_type = t_type_info_slice; + + cg_global_const_type_info_ptr(m, type_table_array, t->Slice.elem, global, offset+0); + void *elem_size_ptr = tb_global_add_region(m->mod, global, offset+1*build_context.int_size, build_context.int_size); + cg_write_int_at_ptr(elem_size_ptr, type_size_of(t->Slice.elem), t_int); + } + break; + + case Type_Proc: + { + tag_type = t_type_info_procedure; + + i64 params_offset = type_offset_of(tag_type, 0); + i64 results_offset = type_offset_of(tag_type, 1); + i64 variadic_offset = type_offset_of(tag_type, 2); + i64 convention_offset = type_offset_of(tag_type, 3); + + if (t->Proc.params) { + cg_global_const_type_info_ptr(m, type_table_array, t->Proc.params, global, offset+params_offset); + } + if (t->Proc.results) { + cg_global_const_type_info_ptr(m, type_table_array, t->Proc.results, global, offset+results_offset); + } + + bool *variadic_ptr = cast(bool *)tb_global_add_region(m->mod, global, offset+variadic_offset, 1); + u8 * convention_ptr = cast(u8 *) tb_global_add_region(m->mod, global, offset+convention_offset, 1); + + *variadic_ptr = t->Proc.variadic; + *convention_ptr = cast(u8)t->Proc.calling_convention; + } + break; + + case Type_Tuple: + { + tag_type = t_type_info_parameters; + + // TODO(bill): Type_Info_Parameters + } + break; + + case Type_Enum: + { + tag_type = t_type_info_enum; + + // TODO(bill): Type_Info_Enum + } + break; + case Type_Struct: + { + tag_type = t_type_info_struct; + + // TODO(bill): Type_Info_Struct + } + break; + case Type_Union: + { + tag_type = t_type_info_union; + + // TODO(bill): Type_Info_Union + } + break; + case Type_Map: + { + tag_type = t_type_info_map; + + // TODO(bill): Type_Info_Map + } + break; + case Type_BitSet: + { + tag_type = t_type_info_bit_set; + + // TODO(bill): Type_Info_Bit_Set + } + break; + case Type_SimdVector: + { + tag_type = t_type_info_simd_vector; + + // TODO(bill): Type_Info_Simd_Vector + } + break; + + case Type_RelativePointer: + { + tag_type = t_type_info_relative_pointer; + } + break; + case Type_RelativeSlice: + { + tag_type = t_type_info_relative_slice; + } + break; + case Type_Matrix: + { + tag_type = t_type_info_matrix; + } + break; } if (tag_type != nullptr) { -- cgit v1.2.3 From baea6a1da88444db322f83b8300b5d64d117cfd1 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 25 Jul 2023 13:31:22 +0100 Subject: Generate anonymous procedure literals --- src/tilde.cpp | 24 +++++++++++++++------- src/tilde.hpp | 7 +++++++ src/tilde_const.cpp | 23 +++++++++++++-------- src/tilde_expr.cpp | 16 ++++++++++++++- src/tilde_proc.cpp | 59 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 5 files changed, 112 insertions(+), 17 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index a7f37dc6f..9550374e8 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -238,14 +238,21 @@ gb_internal void cg_add_procedure_value(cgModule *m, cgProcedure *p) { } gb_internal TB_Symbol *cg_find_symbol_from_entity(cgModule *m, Entity *e) { - if (e) { - rw_mutex_lock(&m->values_mutex); - defer (rw_mutex_unlock(&m->values_mutex)); - TB_Symbol **found = map_get(&m->symbols, e); - if (found) { - return *found; - } + GB_ASSERT(e != nullptr); + + rw_mutex_lock(&m->values_mutex); + defer (rw_mutex_unlock(&m->values_mutex)); + TB_Symbol **found = map_get(&m->symbols, e); + if (found) { + return *found; + } + + String link_name = cg_get_entity_name(m, e); + cgProcedure **proc_found = string_map_get(&m->procedures, link_name); + if (proc_found) { + return (*proc_found)->symbol; } + GB_PANIC("could not find entity's symbol %.*s", LIT(e->token.string)); return nullptr; } @@ -397,6 +404,8 @@ gb_internal cgModule *cg_module_create(Checker *c) { map_init(&m->proc_debug_type_map); map_init(&m->proc_proto_map); + map_init(&m->anonymous_proc_lits_map); + array_init(&m->single_threaded_procedure_queue, heap_allocator()); @@ -417,6 +426,7 @@ gb_internal void cg_module_destroy(cgModule *m) { map_destroy(&m->debug_type_map); map_destroy(&m->proc_debug_type_map); map_destroy(&m->proc_proto_map); + map_destroy(&m->anonymous_proc_lits_map); array_free(&m->single_threaded_procedure_queue); diff --git a/src/tilde.hpp b/src/tilde.hpp index 857247305..087655d83 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -227,6 +227,10 @@ struct cgModule { RecursiveMutex proc_proto_mutex; PtrMap proc_proto_map; + BlockingMutex anonymous_proc_lits_mutex; + PtrMap anonymous_proc_lits_map; + + // NOTE(bill): no need to protect this with a mutex PtrMap file_id_map; // Key: AstFile.id (i32 cast to uintptr) @@ -259,11 +263,14 @@ gb_internal TB_Arena *cg_arena(void); gb_internal void cg_add_procedure_to_queue(cgProcedure *p); gb_internal void cg_setup_type_info_data(cgModule *m); +gb_internal cgProcedure *cg_procedure_generate_anonymous(cgModule *m, Ast *expr, cgProcedure *parent); gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value, Type *type); gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *type); gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value, Type *type, TB_Global *global, i64 offset); +gb_internal String cg_get_entity_name(cgModule *m, Entity *e); + gb_internal cgValue cg_value(TB_Global * g, Type *type); gb_internal cgValue cg_value(TB_External *e, Type *type); gb_internal cgValue cg_value(TB_Function *f, Type *type); diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 30038cfdf..05b57a97a 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -911,17 +911,24 @@ gb_internal cgValue cg_const_value(cgProcedure *p, Type *type, ExactValue const case ExactValue_Procedure: { Ast *expr = unparen_expr(value.value_procedure); + if (expr->kind == Ast_ProcLit) { + cgProcedure *anon = cg_procedure_generate_anonymous(p->module, expr, p); + TB_Node *ptr = tb_inst_get_symbol_address(p->func, anon->symbol); + GB_ASSERT(are_types_identical(type, anon->type)); + return cg_value(ptr, type); + } + Entity *e = entity_of_node(expr); if (e != nullptr) { - cgValue found = cg_find_procedure_value_from_entity(p->module, e); - GB_ASSERT_MSG(are_types_identical(type, found.type), - "%.*s %s == %s", - LIT(p->name), - type_to_string(type), type_to_string(found.type)); - GB_ASSERT(found.kind == cgValue_Symbol); - return cg_flatten_value(p, found); + TB_Symbol *found = cg_find_symbol_from_entity(p->module, e); + GB_ASSERT_MSG(found != nullptr, "could not find '%.*s'", LIT(e->token.string)); + TB_Node *ptr = tb_inst_get_symbol_address(p->func, found); + GB_ASSERT(type != nullptr); + GB_ASSERT(are_types_identical(type, e->type)); + return cg_value(ptr, type); } - GB_PANIC("TODO(bill): cg_const_value ExactValue_Procedure"); + + GB_PANIC("TODO(bill): cg_const_value ExactValue_Procedure %s", expr_to_string(expr)); } break; } diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 551ffbfbb..4caf33ccf 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -3090,7 +3090,6 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { // gb_printf_err("%s %s : %s @ %p\n", token_pos_to_string(expr_pos), expr_to_string(expr), type_to_string(expr->tav.type), expr); // GB_PANIC("%s\n", type_to_string(tv.type)); // } - // NOTE(bill): Short on constant values return cg_const_value(p, type, tv.value); } else if (tv.mode == Addressing_Type) { @@ -3289,7 +3288,22 @@ gb_internal cgValue cg_build_expr_internal(cgProcedure *p, Ast *expr) { case_ast_node(ta, TypeAssertion, expr); return cg_build_type_assertion(p, expr, tv.type); case_end; + + case_ast_node(pl, ProcLit, expr); + cgProcedure *anon = cg_procedure_generate_anonymous(p->module, expr, p); + GB_ASSERT(anon != nullptr); + GB_ASSERT(anon->symbol != nullptr); + return cg_value(tb_inst_get_symbol_address(p->func, anon->symbol), type); + case_end; + } + TokenPos token_pos = ast_token(expr).pos; + GB_PANIC("Unexpected expression\n" + "\tAst: %.*s @ " + "%s\n", + LIT(ast_strings[expr->kind]), + token_pos_to_string(token_pos)); + return {}; } diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 08cbcc631..3a0624583 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -161,6 +161,63 @@ gb_internal cgProcedure *cg_procedure_create_dummy(cgModule *m, String const &li return p; } +gb_internal cgProcedure *cg_procedure_generate_anonymous(cgModule *m, Ast *expr, cgProcedure *parent) { + expr = unparen_expr(expr); + ast_node(pl, ProcLit, expr); + + mutex_lock(&m->anonymous_proc_lits_mutex); + defer (mutex_unlock(&m->anonymous_proc_lits_mutex)); + + cgProcedure **found = map_get(&m->anonymous_proc_lits_map, expr); + if (found) { + return *found; + } + + TokenPos pos = ast_token(expr).pos; + + // NOTE(bill): Generate a new name + // parent$count + + String prefix_name = str_lit("proc_lit"); + if (parent) { + prefix_name = parent->name; + } + + isize name_len = prefix_name.len + 6 + 11; + char *name_text = gb_alloc_array(permanent_allocator(), char, name_len); + + static std::atomic name_id; + name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), 1+name_id.fetch_add(1)); + String name = make_string((u8 *)name_text, name_len-1); + + Type *type = type_of_expr(expr); + + GB_ASSERT(pl->decl->entity == nullptr); + Token token = {}; + token.pos = ast_token(expr).pos; + token.kind = Token_Ident; + token.string = name; + Entity *e = alloc_entity_procedure(nullptr, token, type, pl->tags); + e->file = expr->file(); + + // NOTE(bill): this is to prevent a race condition since these procedure literals can be created anywhere at any time + e->decl_info = pl->decl; + pl->decl->entity = e; + e->flags |= EntityFlag_ProcBodyChecked; + + cgProcedure *p = cg_procedure_create(m, e); + + map_set(&m->anonymous_proc_lits_map, expr, p); + + if (parent != nullptr) { + array_add(&parent->children, p); + } + + cg_add_procedure_to_queue(p); + return p; + +} + gb_internal void cg_procedure_begin(cgProcedure *p) { if (p == nullptr || p->func == nullptr) { return; @@ -374,7 +431,7 @@ gb_internal void cg_procedure_generate(cgProcedure *p) { if ( - string_starts_with(p->name, str_lit("bug@main")) || + // string_starts_with(p->name, str_lit("bug@main")) || false ) { // IR Printing TB_Arena *arena = tb_default_arena(); -- cgit v1.2.3 From ab398f37042af66069e746f4f1bf5b214da1b371 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 25 Jul 2023 13:46:40 +0100 Subject: Implement `@(static)` local variables --- src/tilde.cpp | 4 +++- src/tilde_const.cpp | 11 +++++----- src/tilde_stmt.cpp | 60 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 68 insertions(+), 7 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 9550374e8..a8c398a69 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -250,7 +250,9 @@ gb_internal TB_Symbol *cg_find_symbol_from_entity(cgModule *m, Entity *e) { String link_name = cg_get_entity_name(m, e); cgProcedure **proc_found = string_map_get(&m->procedures, link_name); if (proc_found) { - return (*proc_found)->symbol; + TB_Symbol *symbol = (*proc_found)->symbol; + map_set(&m->symbols, e, symbol); + return symbol; } GB_PANIC("could not find entity's symbol %.*s", LIT(e->token.string)); return nullptr; diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 05b57a97a..d37edb89a 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -347,22 +347,23 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value case ExactValue_Bool: case ExactValue_Integer: case ExactValue_Float: - case ExactValue_Pointer: case ExactValue_Typeid: case ExactValue_Complex: case ExactValue_Quaternion: return 1; + case ExactValue_Pointer: + return 2; case ExactValue_Procedure: return 1; case ExactValue_String: if (is_type_string(type)) { - return 2; + return 3; } else if (is_type_cstring(type) || is_type_array_like(type)) { - return 1; + return 2; } - return 2; + return 3; case ExactValue_Compound: { ast_node(cl, CompoundLit, value.value_compound); @@ -455,7 +456,7 @@ gb_internal isize cg_global_const_calculate_region_count(ExactValue const &value return 1; case Type_Slice: - return 2; + return 3; default: GB_PANIC("TODO(bill): %s", type_to_string(type)); diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 794061335..caa622b4d 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -2240,7 +2240,65 @@ gb_internal void cg_build_stmt(cgProcedure *p, Ast *node) { } } if (is_static) { - GB_PANIC("TODO(bill): build static variables"); + for_array(i, vd->names) { + Ast *ident = vd->names[i]; + GB_ASSERT(!is_blank_ident(ident)); + Entity *e = entity_of_node(ident); + GB_ASSERT(e->flags & EntityFlag_Static); + String name = e->token.string; + + String mangled_name = {}; + { + gbString str = gb_string_make_length(permanent_allocator(), p->name.text, p->name.len); + str = gb_string_appendc(str, "-"); + str = gb_string_append_fmt(str, ".%.*s-%llu", LIT(name), cast(long long)e->id); + mangled_name.text = cast(u8 *)str; + mangled_name.len = gb_string_length(str); + } + + cgModule *m = p->module; + + TB_DebugType *debug_type = cg_debug_type(m, e->type); + TB_Global *global = tb_global_create(m->mod, mangled_name.len, cast(char const *)mangled_name.text, debug_type, TB_LINKAGE_PRIVATE); + + TB_ModuleSection *section = tb_module_get_data(m->mod); + if (e->Variable.thread_local_model != "") { + section = tb_module_get_tls(m->mod); + String model = e->Variable.thread_local_model; + if (model == "default") { + // TODO(bill): Thread Local Storage models + } else if (model == "localdynamic") { + // TODO(bill): Thread Local Storage models + } else if (model == "initialexec") { + // TODO(bill): Thread Local Storage models + } else if (model == "localexec") { + // TODO(bill): Thread Local Storage models + } else { + GB_PANIC("Unhandled thread local mode %.*s", LIT(model)); + } + } + + i64 max_objects = 0; + ExactValue value = {}; + + if (vd->values.count > 0) { + GB_ASSERT(vd->names.count == vd->values.count); + Ast *ast_value = vd->values[i]; + GB_ASSERT(ast_value->tav.mode == Addressing_Constant || + ast_value->tav.mode == Addressing_Invalid); + + value = ast_value->tav.value; + max_objects = cg_global_const_calculate_region_count(value, e->type); + } + tb_global_set_storage(m->mod, section, global, type_size_of(e->type), type_align_of(e->type), max_objects); + + cg_global_const_add_region(m, value, e->type, global, 0); + + TB_Node *node = tb_inst_get_symbol_address(p->func, cast(TB_Symbol *)global); + cgValue global_val = cg_value(node, alloc_type_pointer(e->type)); + cg_add_entity(p->module, e, global_val); + cg_add_member(p->module, mangled_name, global_val); + } return; } -- cgit v1.2.3 From c4033c215e01343709a0d7928c277a6425f53524 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 25 Jul 2023 14:37:19 +0100 Subject: Support non-constant global slices --- src/tilde.cpp | 25 ++++++++++++++---------- src/tilde.hpp | 3 +++ src/tilde_const.cpp | 8 +++++++- src/tilde_expr.cpp | 55 +++++++++++++++++++++++++++++++++++++++++++++-------- src/tilde_proc.cpp | 7 +++++-- 5 files changed, 77 insertions(+), 21 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/src/tilde.cpp b/src/tilde.cpp index 6cd8a42af..64fe70ec4 100644 --- a/src/tilde.cpp +++ b/src/tilde.cpp @@ -694,22 +694,14 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin); cgProcedure *p = cg_procedure_create_dummy(m, str_lit(CG_STARTUP_RUNTIME_PROC_NAME), proc_type); p->is_startup = true; - - cg_procedure_begin(p); - cg_global_variables_initialize(p, &global_variables); - - tb_inst_ret(p->func, 0, nullptr); - cg_procedure_end(p); + cg_startup_runtime_proc = p; } if (true) { Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_Odin); cgProcedure *p = cg_procedure_create_dummy(m, str_lit(CG_CLEANUP_RUNTIME_PROC_NAME), proc_type); p->is_startup = true; - - cg_procedure_begin(p); - tb_inst_ret(p->func, 0, nullptr); - cg_procedure_end(p); + cg_cleanup_runtime_proc = p; } auto *min_dep_set = &info->minimum_dependency_set; @@ -741,6 +733,19 @@ gb_internal bool cg_generate_code(Checker *c, LinkerData *linker_data) { array_add(&procedures_to_generate, p); } } + { + cgProcedure *p = cg_startup_runtime_proc; + cg_procedure_begin(p); + cg_global_variables_initialize(p, &global_variables); + tb_inst_ret(p->func, 0, nullptr); + cg_procedure_end(p); + } + { + cgProcedure *p = cg_cleanup_runtime_proc; + cg_procedure_begin(p); + tb_inst_ret(p->func, 0, nullptr); + cg_procedure_end(p); + } for (cgProcedure *p : procedures_to_generate) { cg_add_procedure_to_queue(p); diff --git a/src/tilde.hpp b/src/tilde.hpp index 087655d83..72d5048bb 100644 --- a/src/tilde.hpp +++ b/src/tilde.hpp @@ -257,6 +257,9 @@ gb_global GlobalTypeInfoData cg_global_type_info_member_usings = {}; gb_global GlobalTypeInfoData cg_global_type_info_member_tags = {}; gb_global GlobalTypeInfoData cg_global_type_info_member_enum_values = {}; +gb_global cgProcedure *cg_startup_runtime_proc = nullptr; +gb_global cgProcedure *cg_cleanup_runtime_proc = nullptr; + gb_internal TB_Arena *cg_arena(void); diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index d37edb89a..5b34480f4 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -555,11 +555,11 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value return true; } - GB_ASSERT(!is_type_array_like(bt)); switch (value.kind) { case ExactValue_Bool: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); bool *res = cast(bool *)tb_global_add_region(m->mod, global, offset, size); *res = !!value.value_bool; } @@ -567,6 +567,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value case ExactValue_Integer: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); void *res = tb_global_add_region(m->mod, global, offset, size); cg_write_big_int_at_ptr(res, &value.value_integer, type); } @@ -574,6 +575,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value case ExactValue_Float: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); f64 f = exact_value_to_f64(value); void *res = tb_global_add_region(m->mod, global, offset, size); switch (size) { @@ -586,6 +588,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value case ExactValue_Pointer: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); void *res = tb_global_add_region(m->mod, global, offset, size); *(u64 *)res = exact_value_to_u64(value); } @@ -603,6 +606,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value case ExactValue_Typeid: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); void *dst = tb_global_add_region(m->mod, global, offset, size); u64 id = cg_typeid_as_u64(m, value.value_typeid); cg_write_uint_at_ptr(dst, id, t_typeid); @@ -621,6 +625,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value break; case ExactValue_Complex: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); Complex128 c = {}; if (value.value_complex) { c = *value.value_complex; @@ -644,6 +649,7 @@ gb_internal bool cg_global_const_add_region(cgModule *m, ExactValue const &value break; case ExactValue_Quaternion: { + GB_ASSERT_MSG(!is_type_array_like(bt), "%s", type_to_string(type)); // @QuaternionLayout Quaternion256 q = {}; if (value.value_quaternion) { diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index 4caf33ccf..96f17bfcf 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -86,6 +86,39 @@ gb_internal cgValue cg_find_value_from_entity(cgModule *m, Entity *e) { return {}; } +gb_internal cgValue cg_get_using_variable(cgProcedure *p, Entity *e) { + GB_ASSERT(e->kind == Entity_Variable && e->flags & EntityFlag_Using); + String name = e->token.string; + Entity *parent = e->using_parent; + Selection sel = lookup_field(parent->type, name, false); + GB_ASSERT(sel.entity != nullptr); + cgValue *pv = map_get(&p->module->values, parent); + + cgValue v = {}; + + if (pv == nullptr && parent->flags & EntityFlag_SoaPtrField) { + // NOTE(bill): using SOA value (probably from for-in statement) + GB_PANIC("TODO(bill): cg_get_soa_variable_addr"); + // cgAddr parent_addr = cg_get_soa_variable_addr(p, parent); + // v = cg_addr_get_ptr(p, parent_addr); + } else if (pv != nullptr) { + v = *pv; + } else { + GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s %.*s", LIT(e->token.string), LIT(name)); + v = cg_build_addr_ptr(p, e->using_expr); + } + GB_ASSERT(v.node != nullptr); + GB_ASSERT_MSG(parent->type == type_deref(v.type), "%s %s", type_to_string(parent->type), type_to_string(v.type)); + cgValue ptr = cg_emit_deep_field_gep(p, v, sel); + // if (parent->scope) { + // if ((parent->scope->flags & (ScopeFlag_File|ScopeFlag_Pkg)) == 0) { + // cg_add_debug_local_variable(p, ptr.value, e->type, e->token); + // } + // } else { + // cg_add_debug_local_variable(p, ptr.value, e->type, e->token); + // } + return ptr; +} gb_internal cgAddr cg_build_addr_from_entity(cgProcedure *p, Entity *e, Ast *expr) { GB_ASSERT(e != nullptr); if (e->kind == Entity_Constant) { @@ -111,9 +144,8 @@ gb_internal cgAddr cg_build_addr_from_entity(cgProcedure *p, Entity *e, Ast *exp if (found) { v = *found; } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) { - GB_PANIC("TODO(bill): cg_get_using_variable"); // NOTE(bill): Calculate the using variable every time - // v = cg_get_using_variable(p, e); + v = cg_get_using_variable(p, e); } else if (e->flags & EntityFlag_SoaPtrField) { GB_PANIC("TODO(bill): cg_get_soa_variable_addr"); // return cg_get_soa_variable_addr(p, e); @@ -434,11 +466,10 @@ gb_internal cgValue cg_emit_comp(cgProcedure *p, TokenKind op_kind, cgValue left } GB_ASSERT(runtime_procedure != nullptr); - GB_PANIC("TODO(bill): cg_emit_runtime_call"); - // auto args = array_make(permanent_allocator(), 2); - // args[0] = left; - // args[1] = right; - // return cg_emit_runtime_call(p, runtime_procedure, args); + auto args = slice_make(permanent_allocator(), 2); + args[0] = left; + args[1] = right; + return cg_emit_runtime_call(p, runtime_procedure, args); } if (is_type_complex(a)) { @@ -2514,7 +2545,15 @@ cgAddr cg_build_addr_compound_lit(cgProcedure *p, Ast *expr) { TB_CharUnits backing_size = cast(TB_CharUnits)(type_size_of(bt->Slice.elem) * count); TB_CharUnits align = cast(TB_CharUnits)type_align_of(bt->Slice.elem); - TB_Node *backing = tb_inst_local(p->func, backing_size, align); + + TB_Node *backing = nullptr; + if (p->is_startup) { + TB_Global *global = tb_global_create(p->module->mod, 0, "", nullptr, TB_LINKAGE_PRIVATE); + tb_global_set_storage(p->module->mod, tb_module_get_data(p->module->mod), global, backing_size, align, 0); + backing = tb_inst_get_symbol_address(p->func, cast(TB_Symbol *)global); + } else { + backing = tb_inst_local(p->func, backing_size, align); + } cgValue data = cg_value(backing, alloc_type_multi_pointer(bt->Slice.elem)); diff --git a/src/tilde_proc.cpp b/src/tilde_proc.cpp index 3a0624583..80948adea 100644 --- a/src/tilde_proc.cpp +++ b/src/tilde_proc.cpp @@ -408,8 +408,11 @@ gb_internal void cg_procedure_end(cgProcedure *p) { return; } if (tb_inst_get_control(p->func)) { - GB_ASSERT(p->type->Proc.result_count == 0); - tb_inst_ret(p->func, 0, nullptr); + if (p->type->Proc.result_count == 0) { + tb_inst_ret(p->func, 0, nullptr); + } else { + tb_inst_unreachable(p->func); + } } if (p->module->do_threading) { -- cgit v1.2.3 From c91898a8889604617140ad15c70f4d68494fa0a1 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 5 Aug 2023 16:05:39 +0100 Subject: Remove #relative slices; Replace with #relative multi-pointers --- core/encoding/json/marshal.odin | 2 +- core/fmt/fmt.odin | 27 +---- core/odin/doc-format/doc_format.odin | 50 ++++----- core/reflect/reflect.odin | 119 ++++++++++---------- core/reflect/types.odin | 15 ++- core/runtime/core.odin | 10 +- core/runtime/print.odin | 4 +- src/check_builtin.cpp | 2 +- src/check_expr.cpp | 43 ++++---- src/check_type.cpp | 8 +- src/checker.cpp | 16 +-- src/docs_format.cpp | 50 ++++----- src/docs_writer.cpp | 8 +- src/error.cpp | 4 +- src/llvm_backend.hpp | 1 - src/llvm_backend_debug.cpp | 17 +-- src/llvm_backend_expr.cpp | 39 ++++--- src/llvm_backend_general.cpp | 203 +++++++++++++++-------------------- src/llvm_backend_proc.cpp | 4 +- src/llvm_backend_type.cpp | 12 ++- src/llvm_backend_utility.cpp | 7 +- src/parser.cpp | 6 +- src/tilde_builtin.cpp | 4 - src/tilde_const.cpp | 6 +- src/tilde_debug.cpp | 16 +-- src/tilde_expr.cpp | 32 +++--- src/tilde_stmt.cpp | 15 --- src/tilde_type_info.cpp | 46 ++++---- src/types.cpp | 55 +++++----- 29 files changed, 368 insertions(+), 453 deletions(-) (limited to 'src/tilde_const.cpp') diff --git a/core/encoding/json/marshal.odin b/core/encoding/json/marshal.odin index d25015ac7..77a5bf8df 100644 --- a/core/encoding/json/marshal.odin +++ b/core/encoding/json/marshal.odin @@ -207,7 +207,7 @@ marshal_to_writer :: proc(w: io.Writer, v: any, opt: ^Marshal_Options) -> (err: case runtime.Type_Info_Relative_Pointer: return .Unsupported_Type - case runtime.Type_Info_Relative_Slice: + case runtime.Type_Info_Relative_Multi_Pointer: return .Unsupported_Type case runtime.Type_Info_Matrix: diff --git a/core/fmt/fmt.odin b/core/fmt/fmt.odin index e64b621bf..b380cac18 100644 --- a/core/fmt/fmt.odin +++ b/core/fmt/fmt.odin @@ -2535,32 +2535,11 @@ fmt_value :: proc(fi: ^Info, v: any, verb: rune) { fmt_value(fi, absolute_ptr, verb) - case runtime.Type_Info_Relative_Slice: + case runtime.Type_Info_Relative_Multi_Pointer: ptr := reflect.relative_pointer_to_absolute_raw(v.data, info.base_integer.id) + absolute_ptr := any{ptr, info.pointer.id} - if verb == 'p' { - fmt_pointer(fi, ptr, 'p') - } else if ptr == nil { - io.write_string(fi.writer, "[]", &fi.n) - } else { - len_ptr := uintptr(v.data) + uintptr(info.base_integer.size) - len_any := any{rawptr(len_ptr), info.base_integer.id} - len, _ := reflect.as_int(len_any) - slice_type := reflect.type_info_base(info.slice).variant.(runtime.Type_Info_Slice) - - fi.record_level += 1 - defer fi.record_level -= 1 - - io.write_byte(fi.writer, '[', &fi.n) - defer io.write_byte(fi.writer, ']', &fi.n) - - for i in 0.. 0 { io.write_string(fi.writer, ", ", &fi.n) } - - data := uintptr(ptr) + uintptr(i*slice_type.elem_size) - fmt_arg(fi, any{rawptr(data), slice_type.elem.id}, verb) - } - } + fmt_value(fi, absolute_ptr, verb) case runtime.Type_Info_Matrix: fmt_matrix(fi, v, verb, info) diff --git a/core/odin/doc-format/doc_format.odin b/core/odin/doc-format/doc_format.odin index 895fcf70d..d22dafd27 100644 --- a/core/odin/doc-format/doc_format.odin +++ b/core/odin/doc-format/doc_format.odin @@ -162,31 +162,31 @@ Attribute :: struct { } Type_Kind :: enum u32le { - Invalid = 0, - Basic = 1, - Named = 2, - Generic = 3, - Pointer = 4, - Array = 5, - Enumerated_Array = 6, - Slice = 7, - Dynamic_Array = 8, - Map = 9, - Struct = 10, - Union = 11, - Enum = 12, - Tuple = 13, - Proc = 14, - Bit_Set = 15, - Simd_Vector = 16, - SOA_Struct_Fixed = 17, - SOA_Struct_Slice = 18, - SOA_Struct_Dynamic = 19, - Relative_Pointer = 20, - Relative_Slice = 21, - Multi_Pointer = 22, - Matrix = 23, - Soa_Pointer = 24, + Invalid = 0, + Basic = 1, + Named = 2, + Generic = 3, + Pointer = 4, + Array = 5, + Enumerated_Array = 6, + Slice = 7, + Dynamic_Array = 8, + Map = 9, + Struct = 10, + Union = 11, + Enum = 12, + Tuple = 13, + Proc = 14, + Bit_Set = 15, + Simd_Vector = 16, + SOA_Struct_Fixed = 17, + SOA_Struct_Slice = 18, + SOA_Struct_Dynamic = 19, + Relative_Pointer = 20, + Relative_Multi_Pointer = 21, + Multi_Pointer = 22, + Matrix = 23, + Soa_Pointer = 24, } Type_Elems_Cap :: 4 diff --git a/core/reflect/reflect.odin b/core/reflect/reflect.odin index a88557e0e..24a826f04 100644 --- a/core/reflect/reflect.odin +++ b/core/reflect/reflect.odin @@ -8,35 +8,35 @@ _ :: intrinsics Type_Info :: runtime.Type_Info -Type_Info_Named :: runtime.Type_Info_Named -Type_Info_Integer :: runtime.Type_Info_Integer -Type_Info_Rune :: runtime.Type_Info_Rune -Type_Info_Float :: runtime.Type_Info_Float -Type_Info_Complex :: runtime.Type_Info_Complex -Type_Info_Quaternion :: runtime.Type_Info_Quaternion -Type_Info_String :: runtime.Type_Info_String -Type_Info_Boolean :: runtime.Type_Info_Boolean -Type_Info_Any :: runtime.Type_Info_Any -Type_Info_Type_Id :: runtime.Type_Info_Type_Id -Type_Info_Pointer :: runtime.Type_Info_Pointer -Type_Info_Multi_Pointer :: runtime.Type_Info_Multi_Pointer -Type_Info_Procedure :: runtime.Type_Info_Procedure -Type_Info_Array :: runtime.Type_Info_Array -Type_Info_Enumerated_Array :: runtime.Type_Info_Enumerated_Array -Type_Info_Dynamic_Array :: runtime.Type_Info_Dynamic_Array -Type_Info_Slice :: runtime.Type_Info_Slice -Type_Info_Parameters :: runtime.Type_Info_Parameters -Type_Info_Tuple :: runtime.Type_Info_Parameters -Type_Info_Struct :: runtime.Type_Info_Struct -Type_Info_Union :: runtime.Type_Info_Union -Type_Info_Enum :: runtime.Type_Info_Enum -Type_Info_Map :: runtime.Type_Info_Map -Type_Info_Bit_Set :: runtime.Type_Info_Bit_Set -Type_Info_Simd_Vector :: runtime.Type_Info_Simd_Vector -Type_Info_Relative_Pointer :: runtime.Type_Info_Relative_Pointer -Type_Info_Relative_Slice :: runtime.Type_Info_Relative_Slice -Type_Info_Matrix :: runtime.Type_Info_Matrix -Type_Info_Soa_Pointer :: runtime.Type_Info_Soa_Pointer +Type_Info_Named :: runtime.Type_Info_Named +Type_Info_Integer :: runtime.Type_Info_Integer +Type_Info_Rune :: runtime.Type_Info_Rune +Type_Info_Float :: runtime.Type_Info_Float +Type_Info_Complex :: runtime.Type_Info_Complex +Type_Info_Quaternion :: runtime.Type_Info_Quaternion +Type_Info_String :: runtime.Type_Info_String +Type_Info_Boolean :: runtime.Type_Info_Boolean +Type_Info_Any :: runtime.Type_Info_Any +Type_Info_Type_Id :: runtime.Type_Info_Type_Id +Type_Info_Pointer :: runtime.Type_Info_Pointer +Type_Info_Multi_Pointer :: runtime.Type_Info_Multi_Pointer +Type_Info_Procedure :: runtime.Type_Info_Procedure +Type_Info_Array :: runtime.Type_Info_Array +Type_Info_Enumerated_Array :: runtime.Type_Info_Enumerated_Array +Type_Info_Dynamic_Array :: runtime.Type_Info_Dynamic_Array +Type_Info_Slice :: runtime.Type_Info_Slice +Type_Info_Parameters :: runtime.Type_Info_Parameters +Type_Info_Tuple :: runtime.Type_Info_Parameters +Type_Info_Struct :: runtime.Type_Info_Struct +Type_Info_Union :: runtime.Type_Info_Union +Type_Info_Enum :: runtime.Type_Info_Enum +Type_Info_Map :: runtime.Type_Info_Map +Type_Info_Bit_Set :: runtime.Type_Info_Bit_Set +Type_Info_Simd_Vector :: runtime.Type_Info_Simd_Vector +Type_Info_Relative_Pointer :: runtime.Type_Info_Relative_Pointer +Type_Info_Relative_Multi_Pointer :: runtime.Type_Info_Relative_Multi_Pointer +Type_Info_Matrix :: runtime.Type_Info_Matrix +Type_Info_Soa_Pointer :: runtime.Type_Info_Soa_Pointer Type_Info_Enum_Value :: runtime.Type_Info_Enum_Value @@ -69,7 +69,7 @@ Type_Kind :: enum { Bit_Set, Simd_Vector, Relative_Pointer, - Relative_Slice, + Relative_Multi_Pointer, Matrix, Soa_Pointer, } @@ -80,34 +80,34 @@ type_kind :: proc(T: typeid) -> Type_Kind { ti := type_info_of(T) if ti != nil { switch _ in ti.variant { - case Type_Info_Named: return .Named - case Type_Info_Integer: return .Integer - case Type_Info_Rune: return .Rune - case Type_Info_Float: return .Float - case Type_Info_Complex: return .Complex - case Type_Info_Quaternion: return .Quaternion - case Type_Info_String: return .String - case Type_Info_Boolean: return .Boolean - case Type_Info_Any: return .Any - case Type_Info_Type_Id: return .Type_Id - case Type_Info_Pointer: return .Pointer - case Type_Info_Multi_Pointer: return .Multi_Pointer - case Type_Info_Procedure: return .Procedure - case Type_Info_Array: return .Array - case Type_Info_Enumerated_Array: return .Enumerated_Array - case Type_Info_Dynamic_Array: return .Dynamic_Array - case Type_Info_Slice: return .Slice - case Type_Info_Parameters: return .Tuple - case Type_Info_Struct: return .Struct - case Type_Info_Union: return .Union - case Type_Info_Enum: return .Enum - case Type_Info_Map: return .Map - case Type_Info_Bit_Set: return .Bit_Set - case Type_Info_Simd_Vector: return .Simd_Vector - case Type_Info_Relative_Pointer: return .Relative_Pointer - case Type_Info_Relative_Slice: return .Relative_Slice - case Type_Info_Matrix: return .Matrix - case Type_Info_Soa_Pointer: return .Soa_Pointer + case Type_Info_Named: return .Named + case Type_Info_Integer: return .Integer + case Type_Info_Rune: return .Rune + case Type_Info_Float: return .Float + case Type_Info_Complex: return .Complex + case Type_Info_Quaternion: return .Quaternion + case Type_Info_String: return .String + case Type_Info_Boolean: return .Boolean + case Type_Info_Any: return .Any + case Type_Info_Type_Id: return .Type_Id + case Type_Info_Pointer: return .Pointer + case Type_Info_Multi_Pointer: return .Multi_Pointer + case Type_Info_Procedure: return .Procedure + case Type_Info_Array: return .Array + case Type_Info_Enumerated_Array: return .Enumerated_Array + case Type_Info_Dynamic_Array: return .Dynamic_Array + case Type_Info_Slice: return .Slice + case Type_Info_Parameters: return .Tuple + case Type_Info_Struct: return .Struct + case Type_Info_Union: return .Union + case Type_Info_Enum: return .Enum + case Type_Info_Map: return .Map + case Type_Info_Bit_Set: return .Bit_Set + case Type_Info_Simd_Vector: return .Simd_Vector + case Type_Info_Relative_Pointer: return .Relative_Pointer + case Type_Info_Relative_Multi_Pointer: return .Relative_Multi_Pointer + case Type_Info_Matrix: return .Matrix + case Type_Info_Soa_Pointer: return .Soa_Pointer } } @@ -1457,8 +1457,6 @@ equal :: proc(a, b: any, including_indirect_array_recursion := false, recursion_ return equal(va, vb, including_indirect_array_recursion, recursion_level+1) case Type_Info_Map: return false - case Type_Info_Relative_Slice: - return false case Type_Info_Boolean, Type_Info_Integer, @@ -1474,6 +1472,7 @@ equal :: proc(a, b: any, including_indirect_array_recursion := false, recursion_ Type_Info_Enum, Type_Info_Simd_Vector, Type_Info_Relative_Pointer, + Type_Info_Relative_Multi_Pointer, Type_Info_Soa_Pointer, Type_Info_Matrix: return runtime.memory_compare(a.data, b.data, t.size) == 0 diff --git a/core/reflect/types.odin b/core/reflect/types.odin index cad9b1f66..21f75580c 100644 --- a/core/reflect/types.odin +++ b/core/reflect/types.odin @@ -165,9 +165,9 @@ are_types_identical :: proc(a, b: ^Type_Info) -> bool { y := b.variant.(Type_Info_Relative_Pointer) or_return return x.base_integer == y.base_integer && x.pointer == y.pointer - case Type_Info_Relative_Slice: - y := b.variant.(Type_Info_Relative_Slice) or_return - return x.base_integer == y.base_integer && x.slice == y.slice + case Type_Info_Relative_Multi_Pointer: + y := b.variant.(Type_Info_Relative_Multi_Pointer) or_return + return x.base_integer == y.base_integer && x.pointer == y.pointer case Type_Info_Matrix: y := b.variant.(Type_Info_Matrix) or_return @@ -383,9 +383,9 @@ is_relative_pointer :: proc(info: ^Type_Info) -> bool { return ok } @(require_results) -is_relative_slice :: proc(info: ^Type_Info) -> bool { +is_relative_multi_pointer :: proc(info: ^Type_Info) -> bool { if info == nil { return false } - _, ok := type_info_base(info).variant.(Type_Info_Relative_Slice) + _, ok := type_info_base(info).variant.(Type_Info_Relative_Multi_Pointer) return ok } @@ -395,7 +395,6 @@ is_relative_slice :: proc(info: ^Type_Info) -> bool { - write_typeid_builder :: proc(buf: ^strings.Builder, id: typeid, n_written: ^int = nil) -> (n: int, err: io.Error) { return write_type_writer(strings.to_writer(buf), type_info_of(id)) } @@ -652,11 +651,11 @@ write_type_writer :: proc(w: io.Writer, ti: ^Type_Info, n_written: ^int = nil) - io.write_string(w, ") ", &n) or_return write_type(w, info.pointer, &n) or_return - case Type_Info_Relative_Slice: + case Type_Info_Relative_Multi_Pointer: io.write_string(w, "#relative(", &n) or_return write_type(w, info.base_integer, &n) or_return io.write_string(w, ") ", &n) or_return - write_type(w, info.slice, &n) or_return + write_type(w, info.pointer, &n) or_return case Type_Info_Matrix: io.write_string(w, "matrix[", &n) or_return diff --git a/core/runtime/core.odin b/core/runtime/core.odin index 83504c9ee..f76c77581 100644 --- a/core/runtime/core.odin +++ b/core/runtime/core.odin @@ -162,11 +162,11 @@ Type_Info_Simd_Vector :: struct { count: int, } Type_Info_Relative_Pointer :: struct { - pointer: ^Type_Info, + pointer: ^Type_Info, // ^T base_integer: ^Type_Info, } -Type_Info_Relative_Slice :: struct { - slice: ^Type_Info, +Type_Info_Relative_Multi_Pointer :: struct { + pointer: ^Type_Info, // [^]T base_integer: ^Type_Info, } Type_Info_Matrix :: struct { @@ -219,7 +219,7 @@ Type_Info :: struct { Type_Info_Bit_Set, Type_Info_Simd_Vector, Type_Info_Relative_Pointer, - Type_Info_Relative_Slice, + Type_Info_Relative_Multi_Pointer, Type_Info_Matrix, Type_Info_Soa_Pointer, }, @@ -252,7 +252,7 @@ Typeid_Kind :: enum u8 { Bit_Set, Simd_Vector, Relative_Pointer, - Relative_Slice, + Relative_Multi_Pointer, Matrix, } #assert(len(Typeid_Kind) < 32) diff --git a/core/runtime/print.odin b/core/runtime/print.odin index 035d47f15..6b1555f52 100644 --- a/core/runtime/print.odin +++ b/core/runtime/print.odin @@ -471,11 +471,11 @@ print_type :: proc "contextless" (ti: ^Type_Info) { print_string(") ") print_type(info.pointer) - case Type_Info_Relative_Slice: + case Type_Info_Relative_Multi_Pointer: print_string("#relative(") print_type(info.base_integer) print_string(") ") - print_type(info.slice) + print_type(info.pointer) case Type_Info_Matrix: print_string("matrix[") diff --git a/src/check_builtin.cpp b/src/check_builtin.cpp index 7f9f4ab13..2e65c5750 100644 --- a/src/check_builtin.cpp +++ b/src/check_builtin.cpp @@ -1748,7 +1748,7 @@ gb_internal bool check_builtin_procedure(CheckerContext *c, Operand *operand, As mode = Addressing_Constant; value = exact_value_i64(at->EnumeratedArray.count); type = t_untyped_integer; - } else if ((is_type_slice(op_type) || is_type_relative_slice(op_type)) && id == BuiltinProc_len) { + } else if (is_type_slice(op_type) && id == BuiltinProc_len) { mode = Addressing_Value; } else if (is_type_dynamic_array(op_type)) { mode = Addressing_Value; diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 5b6e8be3d..14a4eebc8 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -856,8 +856,8 @@ gb_internal i64 check_distance_between_types(CheckerContext *c, Operand *operand } } - if (is_type_relative_slice(dst)) { - i64 score = check_distance_between_types(c, operand, dst->RelativeSlice.slice_type); + if (is_type_relative_multi_pointer(dst)) { + i64 score = check_distance_between_types(c, operand, dst->RelativeMultiPointer.pointer_type); if (score >= 0) { return score+2; } @@ -1005,8 +1005,8 @@ gb_internal AstPackage *get_package_of_type(Type *type) { case Type_RelativePointer: type = type->RelativePointer.pointer_type; continue; - case Type_RelativeSlice: - type = type->RelativeSlice.slice_type; + case Type_RelativeMultiPointer: + type = type->RelativeMultiPointer.pointer_type; continue; } return nullptr; @@ -7366,11 +7366,11 @@ gb_internal bool check_set_index_data(Operand *o, Type *t, bool indirection, i64 } return true; - case Type_RelativeSlice: + case Type_RelativeMultiPointer: { - Type *slice_type = base_type(t->RelativeSlice.slice_type); - GB_ASSERT(slice_type->kind == Type_Slice); - o->type = slice_type->Slice.elem; + Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type); + GB_ASSERT(pointer_type->kind == Type_MultiPointer); + o->type = pointer_type->MultiPointer.elem; if (o->mode != Addressing_Constant) { o->mode = Addressing_Variable; } @@ -9502,14 +9502,14 @@ gb_internal ExprKind check_index_expr(CheckerContext *c, Operand *o, Ast *node, if (is_const) { if (is_type_array(t)) { - // OKay + // Okay } else if (is_type_slice(t)) { // Okay } else if (is_type_enumerated_array(t)) { // Okay } else if (is_type_string(t)) { // Okay - } else if (is_type_relative_slice(t)) { + } else if (is_type_relative_multi_pointer(t)) { // Okay } else if (is_type_matrix(t)) { // Okay @@ -9647,17 +9647,9 @@ gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, } break; - case Type_RelativeSlice: + case Type_RelativeMultiPointer: valid = true; - o->type = t->RelativeSlice.slice_type; - if (o->mode != Addressing_Variable) { - gbString str = expr_to_string(node); - error(node, "Cannot relative slice '%s', as value is not addressable", str); - gb_string_free(str); - o->mode = Addressing_Invalid; - o->expr = node; - return kind; - } + o->type = type_deref(o->type); break; case Type_EnumeratedArray: @@ -9736,8 +9728,19 @@ gb_internal ExprKind check_slice_expr(CheckerContext *c, Operand *o, Ast *node, x[i:n] -> []T */ o->type = alloc_type_slice(t->MultiPointer.elem); + } else if (t->kind == Type_RelativeMultiPointer && se->high != nullptr) { + /* + x[:] -> [^]T + x[i:] -> [^]T + x[:n] -> []T + x[i:n] -> []T + */ + Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type); + GB_ASSERT(pointer_type->kind == Type_MultiPointer); + o->type = alloc_type_slice(pointer_type->MultiPointer.elem); } + o->mode = Addressing_Value; if (is_type_string(t) && max_count >= 0) { diff --git a/src/check_type.cpp b/src/check_type.cpp index 4704f8b9b..cae3ba22e 100644 --- a/src/check_type.cpp +++ b/src/check_type.cpp @@ -2778,16 +2778,16 @@ gb_internal bool check_type_internal(CheckerContext *ctx, Ast *e, Type **type, T Type *relative_type = nullptr; Type *base_type = check_type(ctx, rt->type); - if (!is_type_pointer(base_type) && !is_type_slice(base_type)) { - error(rt->type, "#relative types can only be a pointer or slice"); + if (!is_type_pointer(base_type) && !is_type_multi_pointer(base_type)) { + error(rt->type, "#relative types can only be a pointer or multi-pointer"); relative_type = base_type; } else if (base_integer == nullptr) { relative_type = base_type; } else { if (is_type_pointer(base_type)) { relative_type = alloc_type_relative_pointer(base_type, base_integer); - } else if (is_type_slice(base_type)) { - relative_type = alloc_type_relative_slice(base_type, base_integer); + } else if (is_type_multi_pointer(base_type)) { + relative_type = alloc_type_relative_multi_pointer(base_type, base_integer); } } GB_ASSERT(relative_type != nullptr); diff --git a/src/checker.cpp b/src/checker.cpp index e1860b1fe..7fa7a9c36 100644 --- a/src/checker.cpp +++ b/src/checker.cpp @@ -1969,9 +1969,9 @@ gb_internal void add_type_info_type_internal(CheckerContext *c, Type *t) { add_type_info_type_internal(c, bt->RelativePointer.base_integer); break; - case Type_RelativeSlice: - add_type_info_type_internal(c, bt->RelativeSlice.slice_type); - add_type_info_type_internal(c, bt->RelativeSlice.base_integer); + case Type_RelativeMultiPointer: + add_type_info_type_internal(c, bt->RelativeMultiPointer.pointer_type); + add_type_info_type_internal(c, bt->RelativeMultiPointer.base_integer); break; case Type_Matrix: @@ -2210,9 +2210,9 @@ gb_internal void add_min_dep_type_info(Checker *c, Type *t) { add_min_dep_type_info(c, bt->RelativePointer.base_integer); break; - case Type_RelativeSlice: - add_min_dep_type_info(c, bt->RelativeSlice.slice_type); - add_min_dep_type_info(c, bt->RelativeSlice.base_integer); + case Type_RelativeMultiPointer: + add_min_dep_type_info(c, bt->RelativeMultiPointer.pointer_type); + add_min_dep_type_info(c, bt->RelativeMultiPointer.base_integer); break; case Type_Matrix: @@ -2800,7 +2800,7 @@ gb_internal void init_core_type_info(Checker *c) { t_type_info_bit_set = find_core_type(c, str_lit("Type_Info_Bit_Set")); t_type_info_simd_vector = find_core_type(c, str_lit("Type_Info_Simd_Vector")); t_type_info_relative_pointer = find_core_type(c, str_lit("Type_Info_Relative_Pointer")); - t_type_info_relative_slice = find_core_type(c, str_lit("Type_Info_Relative_Slice")); + t_type_info_relative_multi_pointer = find_core_type(c, str_lit("Type_Info_Relative_Multi_Pointer")); t_type_info_matrix = find_core_type(c, str_lit("Type_Info_Matrix")); t_type_info_soa_pointer = find_core_type(c, str_lit("Type_Info_Soa_Pointer")); @@ -2829,7 +2829,7 @@ gb_internal void init_core_type_info(Checker *c) { t_type_info_bit_set_ptr = alloc_type_pointer(t_type_info_bit_set); t_type_info_simd_vector_ptr = alloc_type_pointer(t_type_info_simd_vector); t_type_info_relative_pointer_ptr = alloc_type_pointer(t_type_info_relative_pointer); - t_type_info_relative_slice_ptr = alloc_type_pointer(t_type_info_relative_slice); + t_type_info_relative_multi_pointer_ptr = alloc_type_pointer(t_type_info_relative_multi_pointer); t_type_info_matrix_ptr = alloc_type_pointer(t_type_info_matrix); t_type_info_soa_pointer_ptr = alloc_type_pointer(t_type_info_soa_pointer); } diff --git a/src/docs_format.cpp b/src/docs_format.cpp index 34114f08e..d0bca214b 100644 --- a/src/docs_format.cpp +++ b/src/docs_format.cpp @@ -59,31 +59,31 @@ struct OdinDocPosition { }; enum OdinDocTypeKind : u32 { - OdinDocType_Invalid = 0, - OdinDocType_Basic = 1, - OdinDocType_Named = 2, - OdinDocType_Generic = 3, - OdinDocType_Pointer = 4, - OdinDocType_Array = 5, - OdinDocType_EnumeratedArray = 6, - OdinDocType_Slice = 7, - OdinDocType_DynamicArray = 8, - OdinDocType_Map = 9, - OdinDocType_Struct = 10, - OdinDocType_Union = 11, - OdinDocType_Enum = 12, - OdinDocType_Tuple = 13, - OdinDocType_Proc = 14, - OdinDocType_BitSet = 15, - OdinDocType_SimdVector = 16, - OdinDocType_SOAStructFixed = 17, - OdinDocType_SOAStructSlice = 18, - OdinDocType_SOAStructDynamic = 19, - OdinDocType_RelativePointer = 20, - OdinDocType_RelativeSlice = 21, - OdinDocType_MultiPointer = 22, - OdinDocType_Matrix = 23, - OdinDocType_SoaPointer = 24, + OdinDocType_Invalid = 0, + OdinDocType_Basic = 1, + OdinDocType_Named = 2, + OdinDocType_Generic = 3, + OdinDocType_Pointer = 4, + OdinDocType_Array = 5, + OdinDocType_EnumeratedArray = 6, + OdinDocType_Slice = 7, + OdinDocType_DynamicArray = 8, + OdinDocType_Map = 9, + OdinDocType_Struct = 10, + OdinDocType_Union = 11, + OdinDocType_Enum = 12, + OdinDocType_Tuple = 13, + OdinDocType_Proc = 14, + OdinDocType_BitSet = 15, + OdinDocType_SimdVector = 16, + OdinDocType_SOAStructFixed = 17, + OdinDocType_SOAStructSlice = 18, + OdinDocType_SOAStructDynamic = 19, + OdinDocType_RelativePointer = 20, + OdinDocType_RelativeMultiPointer = 21, + OdinDocType_MultiPointer = 22, + OdinDocType_Matrix = 23, + OdinDocType_SoaPointer = 24, }; enum OdinDocTypeFlag_Basic : u32 { diff --git a/src/docs_writer.cpp b/src/docs_writer.cpp index 2dd2f338b..6b42d2e7a 100644 --- a/src/docs_writer.cpp +++ b/src/docs_writer.cpp @@ -771,12 +771,12 @@ gb_internal OdinDocTypeIndex odin_doc_type(OdinDocWriter *w, Type *type) { doc_type.types = odin_write_slice(w, types, gb_count_of(types)); } break; - case Type_RelativeSlice: - doc_type.kind = OdinDocType_RelativeSlice; + case Type_RelativeMultiPointer: + doc_type.kind = OdinDocType_RelativeMultiPointer; { OdinDocTypeIndex types[2] = {}; - types[0] = odin_doc_type(w, type->RelativeSlice.slice_type); - types[1] = odin_doc_type(w, type->RelativeSlice.base_integer); + types[0] = odin_doc_type(w, type->RelativeMultiPointer.pointer_type); + types[1] = odin_doc_type(w, type->RelativeMultiPointer.base_integer); doc_type.types = odin_write_slice(w, types, gb_count_of(types)); } break; diff --git a/src/error.cpp b/src/error.cpp index eb010eb36..6a039006b 100644 --- a/src/error.cpp +++ b/src/error.cpp @@ -411,7 +411,7 @@ gb_internal void error_line_va(char const *fmt, va_list va) { gb_internal void error_no_newline_va(TokenPos const &pos, char const *fmt, va_list va) { mutex_lock(&global_error_collector.mutex); - global_error_collector.count++; + global_error_collector.count.fetch_add(1); // NOTE(bill): Duplicate error, skip it if (pos.line == 0) { error_out_coloured("Error: ", TerminalStyle_Normal, TerminalColour_Red); @@ -425,7 +425,7 @@ gb_internal void error_no_newline_va(TokenPos const &pos, char const *fmt, va_li error_out_va(fmt, va); } mutex_unlock(&global_error_collector.mutex); - if (global_error_collector.count > MAX_ERROR_COLLECTOR_COUNT()) { + if (global_error_collector.count.load() > MAX_ERROR_COLLECTOR_COUNT()) { gb_exit(1); } } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index e05bf8025..3178ac9db 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -69,7 +69,6 @@ enum lbAddrKind { lbAddr_SoaVariable, lbAddr_RelativePointer, - lbAddr_RelativeSlice, lbAddr_Swizzle, lbAddr_SwizzleLarge, diff --git a/src/llvm_backend_debug.cpp b/src/llvm_backend_debug.cpp index b9c6c606e..e053c5b40 100644 --- a/src/llvm_backend_debug.cpp +++ b/src/llvm_backend_debug.cpp @@ -442,19 +442,12 @@ gb_internal LLVMMetadataRef lb_debug_type_internal(lbModule *m, Type *type) { gbString name = type_to_string(type, temporary_allocator()); return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type))); } + case Type_RelativeMultiPointer: { + LLVMMetadataRef base_integer = lb_debug_type(m, type->RelativeMultiPointer.base_integer); + gbString name = type_to_string(type, temporary_allocator()); + return LLVMDIBuilderCreateTypedef(m->debug_builder, base_integer, name, gb_string_length(name), nullptr, 0, nullptr, cast(u32)(8*type_align_of(type))); + } - case Type_RelativeSlice: - { - unsigned element_count = 0; - LLVMMetadataRef elements[2] = {}; - Type *base_integer = type->RelativeSlice.base_integer; - unsigned base_bits = cast(unsigned)(8*type_size_of(base_integer)); - elements[0] = lb_debug_struct_field(m, str_lit("data_offset"), base_integer, 0); - elements[1] = lb_debug_struct_field(m, str_lit("len"), base_integer, base_bits); - gbString name = type_to_string(type, temporary_allocator()); - return LLVMDIBuilderCreateStructType(m->debug_builder, nullptr, name, gb_string_length(name), nullptr, 0, 2*base_bits, base_bits, LLVMDIFlagZero, nullptr, elements, element_count, 0, nullptr, "", 0); - } - case Type_Matrix: { LLVMMetadataRef subscripts[1] = {}; subscripts[0] = LLVMDIBuilderGetOrCreateSubrange(m->debug_builder, diff --git a/src/llvm_backend_expr.cpp b/src/llvm_backend_expr.cpp index 5e6831fc2..33768cc12 100644 --- a/src/llvm_backend_expr.cpp +++ b/src/llvm_backend_expr.cpp @@ -2863,7 +2863,6 @@ gb_internal lbValue lb_build_unary_and(lbProcedure *p, Ast *expr) { ast_node(ue, UnaryExpr, expr); auto tv = type_and_value_of_expr(expr); - Ast *ue_expr = unparen_expr(ue->expr); if (ue_expr->kind == Ast_IndexExpr && tv.mode == Addressing_OptionalOkPtr && is_type_tuple(tv.type)) { Type *tuple = tv.type; @@ -3803,25 +3802,32 @@ gb_internal lbAddr lb_build_addr_index_expr(lbProcedure *p, Ast *expr) { lbValue v = {}; LLVMValueRef indices[1] = {index.value}; - v.value = LLVMBuildGEP2(p->builder, lb_type(p->module, t->MultiPointer.elem), multi_ptr.value, indices, 1, "foo"); + v.value = LLVMBuildGEP2(p->builder, lb_type(p->module, t->MultiPointer.elem), multi_ptr.value, indices, 1, ""); v.type = alloc_type_pointer(t->MultiPointer.elem); return lb_addr(v); } - case Type_RelativeSlice: { - lbAddr slice_addr = {}; + case Type_RelativeMultiPointer: { + lbAddr rel_ptr_addr = {}; if (deref) { - slice_addr = lb_addr(lb_build_expr(p, ie->expr)); + lbValue rel_ptr_ptr = lb_build_expr(p, ie->expr); + rel_ptr_addr = lb_addr(rel_ptr_ptr); } else { - slice_addr = lb_build_addr(p, ie->expr); + rel_ptr_addr = lb_build_addr(p, ie->expr); } - lbValue slice = lb_addr_load(p, slice_addr); + lbValue rel_ptr = lb_relative_pointer_to_pointer(p, rel_ptr_addr); - lbValue elem = lb_slice_elem(p, slice); - lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int); - lbValue len = lb_slice_len(p, slice); - lb_emit_bounds_check(p, ast_token(ie->index), index, len); - lbValue v = lb_emit_ptr_offset(p, elem, index); + lbValue index = lb_build_expr(p, ie->index); + index = lb_emit_conv(p, index, t_int); + lbValue v = {}; + + Type *pointer_type = base_type(t->RelativeMultiPointer.pointer_type); + GB_ASSERT(pointer_type->kind == Type_MultiPointer); + Type *elem = pointer_type->MultiPointer.elem; + + LLVMValueRef indices[1] = {index.value}; + v.value = LLVMBuildGEP2(p->builder, lb_type(p->module, elem), rel_ptr.value, indices, 1, ""); + v.type = alloc_type_pointer(elem); return lb_addr(v); } @@ -3925,8 +3931,11 @@ gb_internal lbAddr lb_build_addr_slice_expr(lbProcedure *p, Ast *expr) { return slice; } - case Type_RelativeSlice: - GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the lb_addr_load"); + case Type_RelativePointer: + GB_PANIC("TODO(bill): Type_RelativePointer should be handled above already on the lb_addr_load"); + break; + case Type_RelativeMultiPointer: + GB_PANIC("TODO(bill): Type_RelativeMultiPointer should be handled above already on the lb_addr_load"); break; case Type_DynamicArray: { @@ -3996,7 +4005,7 @@ gb_internal lbAddr lb_build_addr_slice_expr(lbProcedure *p, Ast *expr) { } case Type_Basic: { - GB_ASSERT(type == t_string); + GB_ASSERT_MSG(type == t_string, "got %s", type_to_string(type)); lbValue len = lb_string_len(p, base); if (high.value == nullptr) high = len; diff --git a/src/llvm_backend_general.cpp b/src/llvm_backend_general.cpp index cd8041661..5dfc7aff9 100644 --- a/src/llvm_backend_general.cpp +++ b/src/llvm_backend_general.cpp @@ -349,9 +349,10 @@ gb_internal lbAddr lb_addr(lbValue addr) { if (addr.type != nullptr && is_type_relative_pointer(type_deref(addr.type))) { GB_ASSERT(is_type_pointer(addr.type)); v.kind = lbAddr_RelativePointer; - } else if (addr.type != nullptr && is_type_relative_slice(type_deref(addr.type))) { - GB_ASSERT(is_type_pointer(addr.type)); - v.kind = lbAddr_RelativeSlice; + } else if (addr.type != nullptr && is_type_relative_multi_pointer(type_deref(addr.type))) { + GB_ASSERT(is_type_pointer(addr.type) || + is_type_multi_pointer(addr.type)); + v.kind = lbAddr_RelativePointer; } return v; } @@ -424,6 +425,43 @@ gb_internal Type *lb_addr_type(lbAddr const &addr) { return type_deref(addr.addr.type); } + +gb_internal lbValue lb_relative_pointer_to_pointer(lbProcedure *p, lbAddr const &addr) { + GB_ASSERT(addr.kind == lbAddr_RelativePointer); + + Type *t = base_type(lb_addr_type(addr)); + GB_ASSERT(is_type_relative_pointer(t) || is_type_relative_multi_pointer(t)); + + Type *pointer_type = nullptr; + Type *base_integer = nullptr; + if (t->kind == Type_RelativePointer) { + pointer_type = t->RelativePointer.pointer_type; + base_integer = t->RelativePointer.base_integer; + } else if (t->kind == Type_RelativeMultiPointer) { + pointer_type = t->RelativeMultiPointer.pointer_type; + base_integer = t->RelativeMultiPointer.base_integer; + } + + lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr); + lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(base_integer)); + offset = lb_emit_load(p, offset); + + if (!is_type_unsigned(base_integer)) { + offset = lb_emit_conv(p, offset, t_i64); + } + offset = lb_emit_conv(p, offset, t_uintptr); + lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr); + absolute_ptr = lb_emit_conv(p, absolute_ptr, pointer_type); + + lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, base_integer)); + + // NOTE(bill): nil check + lbValue nil_ptr = lb_const_nil(p->module, pointer_type); + lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr); + return final_ptr; +} + + gb_internal lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) { if (addr.addr.value == nullptr) { GB_PANIC("Illegal addr -> nullptr"); @@ -434,28 +472,8 @@ gb_internal lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) { case lbAddr_Map: return lb_internal_dynamic_map_get_ptr(p, addr.addr, addr.map.key); - case lbAddr_RelativePointer: { - Type *rel_ptr = base_type(lb_addr_type(addr)); - GB_ASSERT(rel_ptr->kind == Type_RelativePointer); - - lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr); - lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer)); - offset = lb_emit_load(p, offset); - - if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) { - offset = lb_emit_conv(p, offset, t_i64); - } - offset = lb_emit_conv(p, offset, t_uintptr); - lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr); - absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type); - - lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer)); - - // NOTE(bill): nil check - lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type); - lbValue final_ptr = lb_emit_select(p, cond, nil_ptr, absolute_ptr); - return final_ptr; - } + case lbAddr_RelativePointer: + return lb_relative_pointer_to_pointer(p, addr); case lbAddr_SoaVariable: // TODO(bill): FIX THIS HACK @@ -477,6 +495,9 @@ gb_internal lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) { gb_internal lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) { lbAddr addr = lb_build_addr(p, expr); + if (addr.kind == lbAddr_RelativePointer) { + return addr.addr; + } return lb_addr_get_ptr(p, addr); } @@ -685,9 +706,20 @@ gb_internal void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) { if (addr.kind == lbAddr_RelativePointer) { Type *rel_ptr = base_type(lb_addr_type(addr)); - GB_ASSERT(rel_ptr->kind == Type_RelativePointer); + GB_ASSERT(rel_ptr->kind == Type_RelativePointer || + rel_ptr->kind == Type_RelativeMultiPointer); + Type *pointer_type = nullptr; + Type *base_integer = nullptr; - value = lb_emit_conv(p, value, rel_ptr->RelativePointer.pointer_type); + if (rel_ptr->kind == Type_RelativePointer) { + pointer_type = rel_ptr->RelativePointer.pointer_type; + base_integer = rel_ptr->RelativePointer.base_integer; + } else if (rel_ptr->kind == Type_RelativeMultiPointer) { + pointer_type = rel_ptr->RelativeMultiPointer.pointer_type; + base_integer = rel_ptr->RelativeMultiPointer.base_integer; + } + + value = lb_emit_conv(p, value, pointer_type); GB_ASSERT(is_type_pointer(addr.addr.type)); lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr); @@ -696,54 +728,20 @@ gb_internal void lb_addr_store(lbProcedure *p, lbAddr addr, lbValue value) { offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, ""); offset.type = t_uintptr; - if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) { + if (!is_type_unsigned(base_integer)) { offset = lb_emit_conv(p, offset, t_i64); } - offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer); + offset = lb_emit_conv(p, offset, base_integer); - lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer)); + lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(base_integer)); offset = lb_emit_select(p, lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)), - lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer), + lb_const_nil(p->module, base_integer), offset ); LLVMBuildStore(p->builder, offset.value, offset_ptr.value); return; - } else if (addr.kind == lbAddr_RelativeSlice) { - Type *rel_ptr = base_type(lb_addr_type(addr)); - GB_ASSERT(rel_ptr->kind == Type_RelativeSlice); - - value = lb_emit_conv(p, value, rel_ptr->RelativeSlice.slice_type); - - GB_ASSERT(is_type_pointer(addr.addr.type)); - lbValue ptr = lb_emit_conv(p, lb_emit_struct_ep(p, addr.addr, 0), t_uintptr); - lbValue val_ptr = lb_emit_conv(p, lb_slice_elem(p, value), t_uintptr); - lbValue offset = {}; - offset.value = LLVMBuildSub(p->builder, val_ptr.value, ptr.value, ""); - offset.type = t_uintptr; - - if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) { - offset = lb_emit_conv(p, offset, t_i64); - } - offset = lb_emit_conv(p, offset, rel_ptr->RelativePointer.base_integer); - - - lbValue offset_ptr = lb_emit_conv(p, addr.addr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer)); - offset = lb_emit_select(p, - lb_emit_comp(p, Token_CmpEq, val_ptr, lb_const_nil(p->module, t_uintptr)), - lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer), - offset - ); - LLVMBuildStore(p->builder, offset.value, offset_ptr.value); - - lbValue len = lb_slice_len(p, value); - len = lb_emit_conv(p, len, rel_ptr->RelativePointer.base_integer); - - lbValue len_ptr = lb_emit_struct_ep(p, addr.addr, 1); - LLVMBuildStore(p->builder, len.value, len_ptr.value); - - return; } else if (addr.kind == lbAddr_Map) { lb_internal_dynamic_map_set(p, addr.addr, addr.map.type, addr.map.key, value, p->curr_stmt); return; @@ -1020,67 +1018,43 @@ gb_internal lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) { if (addr.kind == lbAddr_RelativePointer) { Type *rel_ptr = base_type(lb_addr_type(addr)); - GB_ASSERT(rel_ptr->kind == Type_RelativePointer); + Type *base_integer = nullptr; + Type *pointer_type = nullptr; + GB_ASSERT(rel_ptr->kind == Type_RelativePointer || + rel_ptr->kind == Type_RelativeMultiPointer); + + if (rel_ptr->kind == Type_RelativePointer) { + base_integer = rel_ptr->RelativePointer.base_integer; + pointer_type = rel_ptr->RelativePointer.pointer_type; + } else if (rel_ptr->kind == Type_RelativeMultiPointer) { + base_integer = rel_ptr->RelativeMultiPointer.base_integer; + pointer_type = rel_ptr->RelativeMultiPointer.pointer_type; + } lbValue ptr = lb_emit_conv(p, addr.addr, t_uintptr); - lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(rel_ptr->RelativePointer.base_integer)); + lbValue offset = lb_emit_conv(p, ptr, alloc_type_pointer(base_integer)); offset = lb_emit_load(p, offset); - if (!is_type_unsigned(rel_ptr->RelativePointer.base_integer)) { + if (!is_type_unsigned(base_integer)) { offset = lb_emit_conv(p, offset, t_i64); } offset = lb_emit_conv(p, offset, t_uintptr); lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr); - absolute_ptr = lb_emit_conv(p, absolute_ptr, rel_ptr->RelativePointer.pointer_type); + absolute_ptr = lb_emit_conv(p, absolute_ptr, pointer_type); - lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativePointer.base_integer)); + lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, base_integer)); // NOTE(bill): nil check - lbValue nil_ptr = lb_const_nil(p->module, rel_ptr->RelativePointer.pointer_type); + lbValue nil_ptr = lb_const_nil(p->module, pointer_type); lbValue final_ptr = {}; final_ptr.type = absolute_ptr.type; final_ptr.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, ""); - return lb_emit_load(p, final_ptr); - - } else if (addr.kind == lbAddr_RelativeSlice) { - Type *rel_ptr = base_type(lb_addr_type(addr)); - GB_ASSERT(rel_ptr->kind == Type_RelativeSlice); - - lbValue offset_ptr = lb_emit_struct_ep(p, addr.addr, 0); - lbValue ptr = lb_emit_conv(p, offset_ptr, t_uintptr); - lbValue offset = lb_emit_load(p, offset_ptr); - - - if (!is_type_unsigned(rel_ptr->RelativeSlice.base_integer)) { - offset = lb_emit_conv(p, offset, t_i64); + if (rel_ptr->kind == Type_RelativeMultiPointer) { + return final_ptr; } - offset = lb_emit_conv(p, offset, t_uintptr); - lbValue absolute_ptr = lb_emit_arith(p, Token_Add, ptr, offset, t_uintptr); - - Type *slice_type = base_type(rel_ptr->RelativeSlice.slice_type); - GB_ASSERT(rel_ptr->RelativeSlice.slice_type->kind == Type_Slice); - Type *slice_elem = slice_type->Slice.elem; - Type *slice_elem_ptr = alloc_type_pointer(slice_elem); - - absolute_ptr = lb_emit_conv(p, absolute_ptr, slice_elem_ptr); - - lbValue cond = lb_emit_comp(p, Token_CmpEq, offset, lb_const_nil(p->module, rel_ptr->RelativeSlice.base_integer)); - - // NOTE(bill): nil check - lbValue nil_ptr = lb_const_nil(p->module, slice_elem_ptr); - lbValue data = {}; - data.type = absolute_ptr.type; - data.value = LLVMBuildSelect(p->builder, cond.value, nil_ptr.value, absolute_ptr.value, ""); - - lbValue len = lb_emit_load(p, lb_emit_struct_ep(p, addr.addr, 1)); - len = lb_emit_conv(p, len, t_int); - - lbAddr slice = lb_add_local_generated(p, slice_type, false); - lb_fill_slice(p, slice, data, len); - return lb_addr_load(p, slice); - + return lb_emit_load(p, final_ptr); } else if (addr.kind == lbAddr_Map) { Type *map_type = base_type(type_deref(addr.addr.type)); @@ -2139,17 +2113,10 @@ gb_internal LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { case Type_RelativePointer: return lb_type_internal(m, type->RelativePointer.base_integer); + case Type_RelativeMultiPointer: + return lb_type_internal(m, type->RelativeMultiPointer.base_integer); - case Type_RelativeSlice: - { - LLVMTypeRef base_integer = lb_type_internal(m, type->RelativeSlice.base_integer); - unsigned field_count = 2; - LLVMTypeRef *fields = gb_alloc_array(permanent_allocator(), LLVMTypeRef, field_count); - fields[0] = base_integer; - fields[1] = base_integer; - return LLVMStructTypeInContext(ctx, fields, field_count, false); - } case Type_Matrix: { diff --git a/src/llvm_backend_proc.cpp b/src/llvm_backend_proc.cpp index 7e3a9133b..66edda825 100644 --- a/src/llvm_backend_proc.cpp +++ b/src/llvm_backend_proc.cpp @@ -1710,7 +1710,7 @@ gb_internal lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValu return lb_string_len(p, v); } else if (is_type_array(t)) { GB_PANIC("Array lengths are constant"); - } else if (is_type_slice(t) || is_type_relative_slice(t)) { + } else if (is_type_slice(t)) { return lb_slice_len(p, v); } else if (is_type_dynamic_array(t)) { return lb_dynamic_array_len(p, v); @@ -1735,7 +1735,7 @@ gb_internal lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValu GB_PANIC("Unreachable"); } else if (is_type_array(t)) { GB_PANIC("Array lengths are constant"); - } else if (is_type_slice(t) || is_type_relative_slice(t)) { + } else if (is_type_slice(t)) { return lb_slice_len(p, v); } else if (is_type_dynamic_array(t)) { return lb_dynamic_array_cap(p, v); diff --git a/src/llvm_backend_type.cpp b/src/llvm_backend_type.cpp index c85840517..62a67f96a 100644 --- a/src/llvm_backend_type.cpp +++ b/src/llvm_backend_type.cpp @@ -57,7 +57,7 @@ gb_internal lbValue lb_typeid(lbModule *m, Type *type) { case Type_BitSet: kind = Typeid_Bit_Set; break; case Type_SimdVector: kind = Typeid_Simd_Vector; break; case Type_RelativePointer: kind = Typeid_Relative_Pointer; break; - case Type_RelativeSlice: kind = Typeid_Relative_Slice; break; + case Type_RelativeMultiPointer: kind = Typeid_Relative_Multi_Pointer; break; case Type_SoaPointer: kind = Typeid_SoaPointer; break; } @@ -857,12 +857,13 @@ gb_internal void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup lb_emit_store(p, tag, res); } break; - case Type_RelativeSlice: + + case Type_RelativeMultiPointer: { - tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_slice_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_relative_multi_pointer_ptr); LLVMValueRef vals[2] = { - lb_type_info(m, t->RelativeSlice.slice_type).value, - lb_type_info(m, t->RelativeSlice.base_integer).value, + lb_type_info(m, t->RelativeMultiPointer.pointer_type).value, + lb_type_info(m, t->RelativeMultiPointer.base_integer).value, }; lbValue res = {}; @@ -871,6 +872,7 @@ gb_internal void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup lb_emit_store(p, tag, res); } break; + case Type_Matrix: { tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_matrix_ptr); diff --git a/src/llvm_backend_utility.cpp b/src/llvm_backend_utility.cpp index 2ecad1703..8dd6b14b6 100644 --- a/src/llvm_backend_utility.cpp +++ b/src/llvm_backend_utility.cpp @@ -1124,11 +1124,6 @@ gb_internal lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { } } else if (is_type_array(t)) { return lb_emit_array_epi(p, s, index); - } else if (is_type_relative_slice(t)) { - switch (index) { - case 0: result_type = t->RelativeSlice.base_integer; break; - case 1: result_type = t->RelativeSlice.base_integer; break; - } } else if (is_type_soa_pointer(t)) { switch (index) { case 0: result_type = alloc_type_pointer(t->SoaPointer.elem); break; @@ -1547,7 +1542,7 @@ gb_internal lbValue lb_slice_elem(lbProcedure *p, lbValue slice) { return lb_emit_struct_ev(p, slice, 0); } gb_internal lbValue lb_slice_len(lbProcedure *p, lbValue slice) { - GB_ASSERT(is_type_slice(slice.type) || is_type_relative_slice(slice.type)); + GB_ASSERT(is_type_slice(slice.type)); return lb_emit_struct_ev(p, slice, 1); } gb_internal lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) { diff --git a/src/parser.cpp b/src/parser.cpp index aa8969103..56d1e2d6c 100644 --- a/src/parser.cpp +++ b/src/parser.cpp @@ -2235,7 +2235,11 @@ gb_internal Ast *parse_operand(AstFile *f, bool lhs) { return parse_check_directive_for_statement(operand, name, StateFlag_no_type_assert); } else if (name.string == "relative") { Ast *tag = ast_basic_directive(f, token, name); - tag = parse_call_expr(f, tag); + if (f->curr_token.kind != Token_OpenParen) { + syntax_error(tag, "expected #relative() "); + } else { + tag = parse_call_expr(f, tag); + } Ast *type = parse_type(f); return ast_relative_type(f, tag, type); } else if (name.string == "force_inline" || diff --git a/src/tilde_builtin.cpp b/src/tilde_builtin.cpp index 9dbc3f7c5..f036ce583 100644 --- a/src/tilde_builtin.cpp +++ b/src/tilde_builtin.cpp @@ -44,8 +44,6 @@ gb_internal cgValue cg_builtin_len(cgProcedure *p, cgValue value) { case Type_Struct: GB_ASSERT(is_type_soa_struct(t)); break; - case Type_RelativeSlice: - break; } GB_PANIC("TODO(bill): cg_builtin_len %s", type_to_string(t)); @@ -106,8 +104,6 @@ gb_internal cgValue cg_builtin_cap(cgProcedure *p, cgValue value) { case Type_Struct: GB_ASSERT(is_type_soa_struct(t)); break; - case Type_RelativeSlice: - break; } GB_PANIC("TODO(bill): cg_builtin_cap %s", type_to_string(t)); diff --git a/src/tilde_const.cpp b/src/tilde_const.cpp index 5b34480f4..f9187e3e1 100644 --- a/src/tilde_const.cpp +++ b/src/tilde_const.cpp @@ -255,9 +255,9 @@ gb_internal i64 cg_global_const_calculate_region_count_from_basic_type(Type *typ return 1; case Type_RelativePointer: - return 1; - case Type_RelativeSlice: - return 1; // technically 1 + case Type_RelativeMultiPointer: + return 2; // allows for offsets + case Type_Matrix: return 1; diff --git a/src/tilde_debug.cpp b/src/tilde_debug.cpp index 708476377..926cf9cd0 100644 --- a/src/tilde_debug.cpp +++ b/src/tilde_debug.cpp @@ -457,20 +457,8 @@ gb_internal TB_DebugType *cg_debug_type_internal(cgModule *m, Type *type) { return tb_debug_create_array(m->mod, cg_debug_type(m, type->SimdVector.elem), type->SimdVector.count); case Type_RelativePointer: return cg_debug_type(m, type->RelativePointer.base_integer); - case Type_RelativeSlice: - { - String name = {}; - TB_DebugType *record = tb_debug_create_struct(m->mod, name.len, cast(char const *)name.text); - - TB_DebugType *base_integer = cg_debug_type(m, type->RelativeSlice.base_integer); - TB_CharUnits bi_size = cast(TB_CharUnits)type_size_of(type->RelativeSlice.base_integer); - TB_DebugType **fields = tb_debug_record_begin(record, 2); - fields[0] = tb_debug_create_field(m->mod, base_integer, -1, "data", 0*bi_size); - fields[1] = tb_debug_create_field(m->mod, base_integer, -1, "len", 1*bi_size); - - tb_debug_record_end(record, size, align); - return record; - } + case Type_RelativeMultiPointer: + return cg_debug_type(m, type->RelativeMultiPointer.base_integer); case Type_Matrix: { i64 count = matrix_type_total_internal_elems(type); diff --git a/src/tilde_expr.cpp b/src/tilde_expr.cpp index b654eb5e9..6ff912dd9 100644 --- a/src/tilde_expr.cpp +++ b/src/tilde_expr.cpp @@ -1469,8 +1469,8 @@ gb_internal cgAddr cg_build_addr_slice_expr(cgProcedure *p, Ast *expr) { return slice; } - case Type_RelativeSlice: - GB_PANIC("TODO(bill): Type_RelativeSlice should be handled above already on the cg_addr_load"); + case Type_RelativeMultiPointer: + GB_PANIC("TODO(bill): Type_RelativeMultiPointer should be handled above already on the cg_addr_load"); break; case Type_DynamicArray: { @@ -3598,22 +3598,18 @@ gb_internal cgAddr cg_build_addr_index_expr(cgProcedure *p, Ast *expr) { return cg_addr(v); } - case Type_RelativeSlice: { - GB_PANIC("TODO(bill): relative slice"); - // lbAddr slice_addr = {}; - // if (deref) { - // slice_addr = lb_addr(lb_build_expr(p, ie->expr)); - // } else { - // slice_addr = lb_build_addr(p, ie->expr); - // } - // lbValue slice = lb_addr_load(p, slice_addr); - - // lbValue elem = lb_slice_elem(p, slice); - // lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int); - // lbValue len = lb_slice_len(p, slice); - // lb_emit_bounds_check(p, ast_token(ie->index), index, len); - // lbValue v = lb_emit_ptr_offset(p, elem, index); - // return lb_addr(v); + case Type_RelativeMultiPointer: { + cgValue multi_ptr = {}; + multi_ptr = cg_build_expr(p, ie->expr); + if (deref) { + multi_ptr = cg_emit_load(p, multi_ptr); + } + cgValue index = cg_build_expr(p, ie->index); + index = cg_emit_conv(p, index, t_int); + + cgValue v = cg_emit_ptr_offset(p, multi_ptr, index); + v.type = alloc_type_pointer(type_deref(v.type, true)); + return cg_addr(v); } case Type_DynamicArray: { diff --git a/src/tilde_stmt.cpp b/src/tilde_stmt.cpp index 382b4c02d..2a2aa31aa 100644 --- a/src/tilde_stmt.cpp +++ b/src/tilde_stmt.cpp @@ -530,21 +530,6 @@ gb_internal cgValue cg_emit_struct_ep(cgProcedure *p, cgValue s, i64 index) { } case Type_Array: return cg_emit_array_epi(p, s, index); - case Type_RelativeSlice: - { - Type *bi = t->RelativeSlice.base_integer; - i64 sz = type_size_of(bi); - switch (index) { - case 0: - case 1: - result_type = bi; - offset = sz * index; - break; - default: - goto error_case; - } - } - break; case Type_SoaPointer: switch (index) { case 0: result_type = alloc_type_pointer(t->SoaPointer.elem); break; diff --git a/src/tilde_type_info.cpp b/src/tilde_type_info.cpp index 0dd014bd1..16fe5fd3e 100644 --- a/src/tilde_type_info.cpp +++ b/src/tilde_type_info.cpp @@ -75,24 +75,24 @@ gb_internal u64 cg_typeid_as_u64(cgModule *m, Type *type) { if (flags & BasicFlag_String) kind = Typeid_String; if (flags & BasicFlag_Rune) kind = Typeid_Rune; } break; - case Type_Pointer: kind = Typeid_Pointer; break; - case Type_MultiPointer: kind = Typeid_Multi_Pointer; break; - case Type_Array: kind = Typeid_Array; break; - case Type_Matrix: kind = Typeid_Matrix; break; - case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break; - case Type_Slice: kind = Typeid_Slice; break; - case Type_DynamicArray: kind = Typeid_Dynamic_Array; break; - case Type_Map: kind = Typeid_Map; break; - case Type_Struct: kind = Typeid_Struct; break; - case Type_Enum: kind = Typeid_Enum; break; - case Type_Union: kind = Typeid_Union; break; - case Type_Tuple: kind = Typeid_Tuple; break; - case Type_Proc: kind = Typeid_Procedure; break; - case Type_BitSet: kind = Typeid_Bit_Set; break; - case Type_SimdVector: kind = Typeid_Simd_Vector; break; - case Type_RelativePointer: kind = Typeid_Relative_Pointer; break; - case Type_RelativeSlice: kind = Typeid_Relative_Slice; break; - case Type_SoaPointer: kind = Typeid_SoaPointer; break; + case Type_Pointer: kind = Typeid_Pointer; break; + case Type_MultiPointer: kind = Typeid_Multi_Pointer; break; + case Type_Array: kind = Typeid_Array; break; + case Type_Matrix: kind = Typeid_Matrix; break; + case Type_EnumeratedArray: kind = Typeid_Enumerated_Array; break; + case Type_Slice: kind = Typeid_Slice; break; + case Type_DynamicArray: kind = Typeid_Dynamic_Array; break; + case Type_Map: kind = Typeid_Map; break; + case Type_Struct: kind = Typeid_Struct; break; + case Type_Enum: kind = Typeid_Enum; break; + case Type_Union: kind = Typeid_Union; break; + case Type_Tuple: kind = Typeid_Tuple; break; + case Type_Proc: kind = Typeid_Procedure; break; + case Type_BitSet: kind = Typeid_Bit_Set; break; + case Type_SimdVector: kind = Typeid_Simd_Vector; break; + case Type_RelativePointer: kind = Typeid_Relative_Pointer; break; + case Type_RelativeMultiPointer: kind = Typeid_Relative_Multi_Pointer; break; + case Type_SoaPointer: kind = Typeid_SoaPointer; break; } if (is_type_cstring(type)) { @@ -935,15 +935,15 @@ gb_internal void cg_setup_type_info_data(cgModule *m) { cg_global_const_type_info_ptr(m, t->RelativePointer.base_integer, global, offset+base_integer_offset); } break; - case Type_RelativeSlice: + case Type_RelativeMultiPointer: { - tag_type = t_type_info_relative_slice; + tag_type = t_type_info_relative_multi_pointer; - i64 slice_offset = type_offset_of(tag_type, 0); + i64 pointer_offset = type_offset_of(tag_type, 0); i64 base_integer_offset = type_offset_of(tag_type, 1); - cg_global_const_type_info_ptr(m, t->RelativeSlice.slice_type, global, offset+slice_offset); - cg_global_const_type_info_ptr(m, t->RelativeSlice.base_integer, global, offset+base_integer_offset); + cg_global_const_type_info_ptr(m, t->RelativePointer.pointer_type, global, offset+pointer_offset); + cg_global_const_type_info_ptr(m, t->RelativePointer.base_integer, global, offset+base_integer_offset); } break; case Type_Matrix: diff --git a/src/types.cpp b/src/types.cpp index a4856f767..22deca1dc 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -267,8 +267,8 @@ struct TypeProc { Type *pointer_type; \ Type *base_integer; \ }) \ - TYPE_KIND(RelativeSlice, struct { \ - Type *slice_type; \ + TYPE_KIND(RelativeMultiPointer, struct { \ + Type *pointer_type; \ Type *base_integer; \ }) \ TYPE_KIND(Matrix, struct { \ @@ -349,7 +349,7 @@ enum Typeid_Kind : u8 { Typeid_Bit_Set, Typeid_Simd_Vector, Typeid_Relative_Pointer, - Typeid_Relative_Slice, + Typeid_Relative_Multi_Pointer, Typeid_Matrix, Typeid_SoaPointer, }; @@ -635,7 +635,7 @@ gb_global Type *t_type_info_map = nullptr; gb_global Type *t_type_info_bit_set = nullptr; gb_global Type *t_type_info_simd_vector = nullptr; gb_global Type *t_type_info_relative_pointer = nullptr; -gb_global Type *t_type_info_relative_slice = nullptr; +gb_global Type *t_type_info_relative_multi_pointer = nullptr; gb_global Type *t_type_info_matrix = nullptr; gb_global Type *t_type_info_soa_pointer = nullptr; @@ -664,7 +664,7 @@ gb_global Type *t_type_info_map_ptr = nullptr; gb_global Type *t_type_info_bit_set_ptr = nullptr; gb_global Type *t_type_info_simd_vector_ptr = nullptr; gb_global Type *t_type_info_relative_pointer_ptr = nullptr; -gb_global Type *t_type_info_relative_slice_ptr = nullptr; +gb_global Type *t_type_info_relative_multi_pointer_ptr = nullptr; gb_global Type *t_type_info_matrix_ptr = nullptr; gb_global Type *t_type_info_soa_pointer_ptr = nullptr; @@ -737,6 +737,7 @@ gb_internal Type * bit_set_to_int(Type *t); gb_internal bool are_types_identical(Type *x, Type *y); gb_internal bool is_type_pointer(Type *t); +gb_internal bool is_type_multi_pointer(Type *t); gb_internal bool is_type_soa_pointer(Type *t); gb_internal bool is_type_proc(Type *t); gb_internal bool is_type_slice(Type *t); @@ -1035,12 +1036,12 @@ gb_internal Type *alloc_type_relative_pointer(Type *pointer_type, Type *base_int return t; } -gb_internal Type *alloc_type_relative_slice(Type *slice_type, Type *base_integer) { - GB_ASSERT(is_type_slice(slice_type)); +gb_internal Type *alloc_type_relative_multi_pointer(Type *pointer_type, Type *base_integer) { + GB_ASSERT(is_type_multi_pointer(pointer_type)); GB_ASSERT(is_type_integer(base_integer)); - Type *t = alloc_type(Type_RelativeSlice); - t->RelativeSlice.slice_type = slice_type; - t->RelativeSlice.base_integer = base_integer; + Type *t = alloc_type(Type_RelativeMultiPointer); + t->RelativeMultiPointer.pointer_type = pointer_type; + t->RelativeMultiPointer.base_integer = base_integer; return t; } @@ -1551,9 +1552,9 @@ gb_internal bool is_type_relative_pointer(Type *t) { t = base_type(t); return t->kind == Type_RelativePointer; } -gb_internal bool is_type_relative_slice(Type *t) { +gb_internal bool is_type_relative_multi_pointer(Type *t) { t = base_type(t); - return t->kind == Type_RelativeSlice; + return t->kind == Type_RelativeMultiPointer; } gb_internal bool is_type_u8_slice(Type *t) { @@ -1970,7 +1971,7 @@ gb_internal bool is_type_indexable(Type *t) { return true; case Type_EnumeratedArray: return true; - case Type_RelativeSlice: + case Type_RelativeMultiPointer: return true; case Type_Matrix: return true; @@ -1989,7 +1990,7 @@ gb_internal bool is_type_sliceable(Type *t) { return true; case Type_EnumeratedArray: return false; - case Type_RelativeSlice: + case Type_RelativeMultiPointer: return true; case Type_Matrix: return false; @@ -2195,12 +2196,12 @@ gb_internal bool is_type_polymorphic(Type *t, bool or_specialized=false) { } break; - case Type_RelativeSlice: - if (is_type_polymorphic(t->RelativeSlice.slice_type, or_specialized)) { + case Type_RelativeMultiPointer: + if (is_type_polymorphic(t->RelativeMultiPointer.pointer_type, or_specialized)) { return true; } - if (t->RelativeSlice.base_integer != nullptr && - is_type_polymorphic(t->RelativeSlice.base_integer, or_specialized)) { + if (t->RelativeMultiPointer.base_integer != nullptr && + is_type_polymorphic(t->RelativeMultiPointer.base_integer, or_specialized)) { return true; } break; @@ -2258,7 +2259,7 @@ gb_internal bool type_has_nil(Type *t) { return false; case Type_RelativePointer: - case Type_RelativeSlice: + case Type_RelativeMultiPointer: return true; } return false; @@ -2425,7 +2426,7 @@ gb_internal bool is_type_load_safe(Type *type) { return true; case Type_RelativePointer: - case Type_RelativeSlice: + case Type_RelativeMultiPointer: return true; case Type_Pointer: @@ -3629,8 +3630,8 @@ gb_internal i64 type_align_of_internal(Type *t, TypePath *path) { case Type_RelativePointer: return type_align_of_internal(t->RelativePointer.base_integer, path); - case Type_RelativeSlice: - return type_align_of_internal(t->RelativeSlice.base_integer, path); + case Type_RelativeMultiPointer: + return type_align_of_internal(t->RelativeMultiPointer.base_integer, path); case Type_SoaPointer: return build_context.int_size; @@ -3912,8 +3913,8 @@ gb_internal i64 type_size_of_internal(Type *t, TypePath *path) { case Type_RelativePointer: return type_size_of_internal(t->RelativePointer.base_integer, path); - case Type_RelativeSlice: - return 2*type_size_of_internal(t->RelativeSlice.base_integer, path); + case Type_RelativeMultiPointer: + return type_size_of_internal(t->RelativeMultiPointer.base_integer, path); } // Catch all @@ -4466,11 +4467,11 @@ gb_internal gbString write_type_to_string(gbString str, Type *type, bool shortha str = gb_string_append_fmt(str, ") "); str = write_type_to_string(str, type->RelativePointer.pointer_type); break; - case Type_RelativeSlice: + case Type_RelativeMultiPointer: str = gb_string_append_fmt(str, "#relative("); - str = write_type_to_string(str, type->RelativeSlice.base_integer); + str = write_type_to_string(str, type->RelativePointer.base_integer); str = gb_string_append_fmt(str, ") "); - str = write_type_to_string(str, type->RelativeSlice.slice_type); + str = write_type_to_string(str, type->RelativePointer.pointer_type); break; case Type_Matrix: -- cgit v1.2.3