From 6ed6a91a6434a944010d8f2c6752e70a372b5296 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 1 Feb 2020 22:50:57 +0000 Subject: Begin LLVM C API integration --- src/llvm_backend.cpp | 831 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 831 insertions(+) create mode 100644 src/llvm_backend.cpp (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp new file mode 100644 index 000000000..b2ab67442 --- /dev/null +++ b/src/llvm_backend.cpp @@ -0,0 +1,831 @@ +#include "llvm-c/Core.h" +#include "llvm-c/ExecutionEngine.h" +#include "llvm-c/Target.h" +#include "llvm-c/Analysis.h" +#include "llvm-c/Object.h" +#include "llvm-c/BitWriter.h" + +struct lbModule { + LLVMModuleRef mod; + + Map values; // Key: Entity * +}; + +struct lbGenerator { + lbModule module; + CheckerInfo *info; + + gbFile output_file; + String output_base; + String output_name; +}; + +enum lbAddrKind { + lbAddr_Default, + lbAddr_Map, + lbAddr_BitField, + lbAddr_Context, + lbAddr_SoaVariable, +}; + +struct lbAddr { + lbAddrKind kind; + LLVMValueRef addr; + union { + struct { + LLVMValueRef key; + Type *type; + Type *result; + } map; + struct { + i32 value_index; + } bit_field; + struct { + Selection sel; + } ctx; + struct { + LLVMValueRef index; + Ast *index_expr; + } soa; + }; +}; + +struct lbBlock { + LLVMBasicBlockRef block; + Scope *scope; + isize scope_index; +}; + +struct lbProcedure { + lbProcedure *parent; + Array children; + + Entity * entity; + lbModule * module; + String name; + Type * type; + Ast * type_expr; + Ast * body; + u64 tags; + ProcInlining inlining; + bool is_foreign; + bool is_export; + bool is_entry_point; + + + LLVMValueRef value; + LLVMBuilderRef builder; + + LLVMValueRef return_ptr; + Array params; + Array blocks; + Scope * curr_scope; + i32 scope_index; + lbBlock * decl_block; + lbBlock * entry_block; + lbBlock * curr_block; +}; + +lbBlock * lb_create_block(lbProcedure *p, char const *name); +LLVMTypeRef lb_type(Type *type); +void lb_build_stmt (lbProcedure *p, Ast *stmt); +LLVMValueRef lb_build_expr (lbProcedure *p, Ast *expr); + +lbAddr lb_addr(LLVMValueRef addr) { + lbAddr v = {lbAddr_Default, addr}; + return v; +} + +LLVMTypeRef lb_addr_type(lbAddr const &addr) { + return LLVMGetElementType(LLVMTypeOf(addr.addr)); +} + +void lb_addr_store(lbProcedure *p, lbAddr const &addr, LLVMValueRef value) { + if (addr.addr == nullptr) { + return; + } + GB_ASSERT(value != nullptr); + LLVMBuildStore(p->builder, value, addr.addr); +} + +LLVMTypeRef lb_type_internal(Type *type) { + switch (type->kind) { + case Type_Basic: + switch (type->Basic.kind) { + case Basic_llvm_bool: return LLVMInt1Type(); + case Basic_bool: return LLVMInt8Type(); + case Basic_b8: return LLVMInt8Type(); + case Basic_b16: return LLVMInt16Type(); + case Basic_b32: return LLVMInt32Type(); + case Basic_b64: return LLVMInt64Type(); + + case Basic_i8: return LLVMInt8Type(); + case Basic_u8: return LLVMInt8Type(); + case Basic_i16: return LLVMInt16Type(); + case Basic_u16: return LLVMInt16Type(); + case Basic_i32: return LLVMInt32Type(); + case Basic_u32: return LLVMInt32Type(); + case Basic_i64: return LLVMInt64Type(); + case Basic_u64: return LLVMInt64Type(); + case Basic_i128: return LLVMInt128Type(); + case Basic_u128: return LLVMInt128Type(); + + case Basic_rune: return LLVMInt32Type(); + + // Basic_f16, + case Basic_f32: return LLVMFloatType(); + case Basic_f64: return LLVMDoubleType(); + + // Basic_complex32, + case Basic_complex64: + { + LLVMTypeRef fields[2] = { + lb_type(t_f32), + lb_type(t_f32), + }; + return LLVMStructType(fields, 2, false); + } + case Basic_complex128: + { + LLVMTypeRef fields[2] = { + lb_type(t_f64), + lb_type(t_f64), + }; + return LLVMStructType(fields, 2, false); + } + + case Basic_quaternion128: + { + LLVMTypeRef fields[4] = { + lb_type(t_f32), + lb_type(t_f32), + lb_type(t_f32), + lb_type(t_f32), + }; + return LLVMStructType(fields, 4, false); + } + case Basic_quaternion256: + { + LLVMTypeRef fields[4] = { + lb_type(t_f64), + lb_type(t_f64), + lb_type(t_f64), + lb_type(t_f64), + }; + return LLVMStructType(fields, 4, false); + } + + case Basic_int: return LLVMIntType(8*cast(unsigned)build_context.word_size); + case Basic_uint: return LLVMIntType(8*cast(unsigned)build_context.word_size); + + case Basic_uintptr: return LLVMIntType(8*cast(unsigned)build_context.word_size); + + case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0); + case Basic_string: + { + LLVMTypeRef fields[2] = { + LLVMPointerType(lb_type(t_u8), 0), + lb_type(t_int), + }; + return LLVMStructType(fields, 2, false); + } + case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0); + case Basic_any: + { + LLVMTypeRef fields[2] = { + LLVMPointerType(lb_type(t_rawptr), 0), + lb_type(t_typeid), + }; + return LLVMStructType(fields, 2, false); + } + + case Basic_typeid: return LLVMIntType(8*cast(unsigned)build_context.word_size); + + // Endian Specific Types + case Basic_i16le: return LLVMInt16Type(); + case Basic_u16le: return LLVMInt16Type(); + case Basic_i32le: return LLVMInt32Type(); + case Basic_u32le: return LLVMInt32Type(); + case Basic_i64le: return LLVMInt64Type(); + case Basic_u64le: return LLVMInt64Type(); + case Basic_i128le: return LLVMInt128Type(); + case Basic_u128le: return LLVMInt128Type(); + + case Basic_i16be: return LLVMInt16Type(); + case Basic_u16be: return LLVMInt16Type(); + case Basic_i32be: return LLVMInt32Type(); + case Basic_u32be: return LLVMInt32Type(); + case Basic_i64be: return LLVMInt64Type(); + case Basic_u64be: return LLVMInt64Type(); + case Basic_i128be: return LLVMInt128Type(); + case Basic_u128be: return LLVMInt128Type(); + + // Untyped types + case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break; + case Basic_UntypedInteger: GB_PANIC("Basic_UntypedInteger"); break; + case Basic_UntypedFloat: GB_PANIC("Basic_UntypedFloat"); break; + case Basic_UntypedComplex: GB_PANIC("Basic_UntypedComplex"); break; + case Basic_UntypedQuaternion: GB_PANIC("Basic_UntypedQuaternion"); break; + case Basic_UntypedString: GB_PANIC("Basic_UntypedString"); break; + case Basic_UntypedRune: GB_PANIC("Basic_UntypedRune"); break; + case Basic_UntypedNil: GB_PANIC("Basic_UntypedNil"); break; + case Basic_UntypedUndef: GB_PANIC("Basic_UntypedUndef"); break; + } + break; + case Type_Named: + GB_PANIC("Type_Named"); + return nullptr; + case Type_Pointer: + return LLVMPointerType(lb_type(type_deref(type)), 0); + case Type_Opaque: + return lb_type(base_type(type)); + case Type_Array: + return LLVMArrayType(lb_type(type->Array.elem), cast(unsigned)type->Array.count); + case Type_EnumeratedArray: + return LLVMArrayType(lb_type(type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count); + case Type_Slice: + { + LLVMTypeRef fields[2] = { + LLVMPointerType(lb_type(type->Slice.elem), 0), // data + lb_type(t_int), // len + }; + return LLVMStructType(fields, 2, false); + } + break; + case Type_DynamicArray: + { + LLVMTypeRef fields[4] = { + LLVMPointerType(lb_type(type->DynamicArray.elem), 0), // data + lb_type(t_int), // len + lb_type(t_int), // cap + lb_type(t_allocator), // allocator + }; + return LLVMStructType(fields, 4, false); + } + break; + case Type_Map: + return lb_type(type->Map.internal_type); + case Type_Struct: + GB_PANIC("Type_Struct"); + break; + case Type_Union: + GB_PANIC("Type_Union"); + break; + case Type_Enum: + return LLVMIntType(8*cast(unsigned)type_size_of(type)); + case Type_Tuple: + GB_PANIC("Type_Tuple"); + break; + case Type_Proc: + set_procedure_abi_types(heap_allocator(), type); + GB_PANIC("Type_Proc"); + break; + case Type_BitFieldValue: + return LLVMIntType(type->BitFieldValue.bits); + case Type_BitField: + GB_PANIC("Type_BitField"); + break; + case Type_BitSet: + return LLVMIntType(8*cast(unsigned)type_size_of(type)); + case Type_SimdVector: + if (type->SimdVector.is_x86_mmx) { + return LLVMX86MMXType(); + } + return LLVMVectorType(lb_type(type->SimdVector.elem), cast(unsigned)type->SimdVector.count); + } + + GB_PANIC("Invalid type"); + return LLVMInt32Type(); +} + +LLVMTypeRef lb_type(Type *type) { + if (type->llvm_type) { + return type->llvm_type; + } + + LLVMTypeRef llvm_type = lb_type_internal(type); + type->llvm_type = llvm_type; + + return llvm_type; +} + +lbProcedure *lb_create_procedure(lbModule *module, Entity *entity) { + lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure); + + p->module = module; + p->entity = entity; + p->name = entity->token.string; + + DeclInfo *decl = entity->decl_info; + + ast_node(pl, ProcLit, decl->proc_lit); + Type *pt = base_type(entity->type); + GB_ASSERT(pt->kind == Type_Proc); + + p->type = entity->type; + p->type_expr = decl->type_expr; + p->body = pl->body; + p->tags = pt->Proc.tags; + p->inlining = ProcInlining_none; + p->is_foreign = false; + p->is_export = false; + p->is_entry_point = false; + + p->children.allocator = heap_allocator(); + p->params.allocator = heap_allocator(); + p->blocks.allocator = heap_allocator(); + + + char *name = alloc_cstring(heap_allocator(), p->name); + LLVMTypeRef ret_type = LLVMFunctionType(LLVMVoidType(), nullptr, 0, false); + + p->value = LLVMAddFunction(module->mod, name, ret_type); + p->builder = LLVMCreateBuilder(); + + p->decl_block = lb_create_block(p, "decls"); + p->entry_block = lb_create_block(p, "entry"); + p->curr_block = p->entry_block; + + set_procedure_abi_types(heap_allocator(), p->type); + + LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); + + return p; +} + +void lb_end_procedure(lbProcedure *p) { + LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block); + LLVMBuildBr(p->builder, p->entry_block->block); + LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); + + LLVMDisposeBuilder(p->builder); +} + + +lbBlock *lb_create_block(lbProcedure *p, char const *name) { + lbBlock *b = gb_alloc_item(heap_allocator(), lbBlock); + b->block = LLVMAppendBasicBlock(p->value, name); + b->scope = p->curr_scope; + b->scope_index = p->scope_index; + array_add(&p->blocks, b); + return b; +} + +lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr) { + LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block); + + LLVMTypeRef llvm_type = lb_type(type); + LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, ""); + LLVMSetAlignment(ptr, 16); + + LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); + + if (e != nullptr) { + map_set(&p->module->values, hash_entity(e), ptr); + } + + return lb_addr(ptr); +} + + +bool lb_init_generator(lbGenerator *gen, Checker *c) { + if (global_error_collector.count != 0) { + return false; + } + + isize tc = c->parser->total_token_count; + if (tc < 2) { + return false; + } + + + String init_fullpath = c->parser->init_fullpath; + + if (build_context.out_filepath.len == 0) { + gen->output_name = remove_directory_from_path(init_fullpath); + gen->output_name = remove_extension_from_path(gen->output_name); + gen->output_base = gen->output_name; + } else { + gen->output_name = build_context.out_filepath; + isize pos = string_extension_position(gen->output_name); + if (pos < 0) { + gen->output_base = gen->output_name; + } else { + gen->output_base = substring(gen->output_name, 0, pos); + } + } + gbAllocator ha = heap_allocator(); + gen->output_base = path_to_full_path(ha, gen->output_base); + + gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len); + output_file_path = gb_string_appendc(output_file_path, ".obj"); + defer (gb_string_free(output_file_path)); + + gbFileError err = gb_file_create(&gen->output_file, output_file_path); + if (err != gbFileError_None) { + gb_printf_err("Failed to create file %s\n", output_file_path); + return false; + } + + gen->info = &c->info; + + return true; +} + + +void lb_build_stmt_list(lbProcedure *p, Array const &stmts) { + for_array(i, stmts) { + Ast *stmt = stmts[i]; + switch (stmt->kind) { + case_ast_node(vd, ValueDecl, stmt); + // lb_build_constant_value_decl(b, vd); + case_end; + case_ast_node(fb, ForeignBlockDecl, stmt); + ast_node(block, BlockStmt, fb->body); + lb_build_stmt_list(p, block->stmts); + case_end; + } + } + for_array(i, stmts) { + lb_build_stmt(p, stmts[i]); + } +} + + +void lb_build_stmt(lbProcedure *p, Ast *node) { + switch (node->kind) { + case_ast_node(bs, EmptyStmt, node); + case_end; + + case_ast_node(us, UsingStmt, node); + case_end; + + case_ast_node(bs, BlockStmt, node); + lb_build_stmt_list(p, bs->stmts); + case_end; + + case_ast_node(vd, ValueDecl, node); + if (!vd->is_mutable) { + return; + } + + bool is_static = false; + if (vd->names.count > 0) { + Entity *e = entity_of_ident(vd->names[0]); + if (e->flags & EntityFlag_Static) { + // NOTE(bill): If one of the entities is static, they all are + is_static = true; + } + } + + GB_ASSERT_MSG(!is_static, "handle static variables"); + + + auto addrs = array_make(heap_allocator(), vd->names.count); + auto values = array_make(heap_allocator(), 0, vd->names.count); + defer (array_free(&addrs)); + defer (array_free(&values)); + + for_array(i, vd->names) { + Ast *name = vd->names[i]; + if (!is_blank_ident(name)) { + Entity *e = entity_of_ident(name); + addrs[i] = lb_add_local(p, e->type, e); + if (vd->values.count == 0) { + lb_addr_store(p, addrs[i], LLVMConstNull(lb_addr_type(addrs[i]))); + } + } + } + + for_array(i, vd->values) { + LLVMValueRef value = lb_build_expr(p, vd->values[i]); + array_add(&values, value); + } + + for_array(i, values) { + lb_addr_store(p, addrs[i], values[i]); + } + + case_end; + } +} + +LLVMValueRef lb_value_constant(Type *type, ExactValue const &value) { + + switch (value.kind) { + case ExactValue_Invalid: + return LLVMConstNull(lb_type(type)); + case ExactValue_Bool: + return LLVMConstInt(lb_type(type), value.value_bool, false); + case ExactValue_String: + return LLVMConstInt(lb_type(type), value.value_bool, false); + case ExactValue_Integer: + return LLVMConstIntOfArbitraryPrecision(lb_type(type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); + case ExactValue_Float: + return LLVMConstReal(lb_type(type), value.value_float); + case ExactValue_Complex: + GB_PANIC("ExactValue_Complex"); + break; + case ExactValue_Quaternion: + GB_PANIC("ExactValue_Quaternion"); + break; + + case ExactValue_Pointer: + return LLVMConstBitCast(LLVMConstInt(lb_type(t_uintptr), value.value_pointer, false), lb_type(type)); + case ExactValue_Compound: + GB_PANIC("ExactValue_Compound"); + break; + case ExactValue_Procedure: + GB_PANIC("ExactValue_Procedure"); + break; + case ExactValue_Typeid: + GB_PANIC("ExactValue_Typeid"); + break; + } + + GB_PANIC("UNKNOWN ExactValue kind"); + return nullptr; +} + +LLVMValueRef lb_add_module_constant(lbModule *m, Type *type, ExactValue const &value) { + gbAllocator a = heap_allocator(); + + if (is_type_slice(type)) { + GB_PANIC("lb_add_module_constant -> slice"); + } + + return lb_value_constant(type, value); +} + +LLVMValueRef lb_emit_arith(lbProcedure *p, TokenKind op, LLVMValueRef lhs, LLVMValueRef rhs, Type *type) { + switch (op) { + case Token_Add: + return LLVMBuildAdd(p->builder, lhs, rhs, ""); + case Token_Sub: + return LLVMBuildSub(p->builder, lhs, rhs, ""); + case Token_Mul: + return LLVMBuildMul(p->builder, lhs, rhs, ""); + case Token_Quo: + case Token_Mod: + case Token_ModMod: + case Token_And: + return LLVMBuildAdd(p->builder, lhs, rhs, ""); + case Token_Or: + return LLVMBuildOr(p->builder, lhs, rhs, ""); + case Token_Xor: + return LLVMBuildXor(p->builder, lhs, rhs, ""); + case Token_Shl: + return LLVMBuildShl(p->builder, lhs, rhs, ""); + case Token_Shr: + + case Token_AndNot: + break; + } + + GB_PANIC("unhandled operator of lb_emit_arith"); + + return nullptr; +} + +LLVMValueRef lb_build_binary_expr(lbProcedure *p, Ast *expr) { + ast_node(be, BinaryExpr, expr); + + TypeAndValue tv = type_and_value_of_expr(expr); + + switch (be->op.kind) { + case Token_Add: + case Token_Sub: + case Token_Mul: + case Token_Quo: + case Token_Mod: + case Token_ModMod: + case Token_And: + case Token_Or: + case Token_Xor: + case Token_AndNot: + case Token_Shl: + case Token_Shr: { + Type *type = default_type(tv.type); + LLVMValueRef left = lb_build_expr(p, be->left); + LLVMValueRef right = lb_build_expr(p, be->right); + return lb_emit_arith(p, be->op.kind, left, right, type); + } + default: + GB_PANIC("Invalid binary expression"); + break; + } + return nullptr; +} + +LLVMValueRef lb_build_expr(lbProcedure *p, Ast *expr) { + expr = unparen_expr(expr); + + TypeAndValue tv = type_and_value_of_expr(expr); + GB_ASSERT(tv.mode != Addressing_Invalid); + GB_ASSERT(tv.mode != Addressing_Type); + + if (tv.value.kind != ExactValue_Invalid) { + // // NOTE(bill): Edge case + // if (tv.value.kind != ExactValue_Compound && + // is_type_array(tv.type)) { + // Type *elem = core_array_type(tv.type); + // ExactValue value = convert_exact_value_for_type(tv.value, elem); + // irValue *x = ir_add_module_constant(proc->module, elem, value); + // return ir_emit_conv(proc, x, tv.type); + // } + + // if (tv.value.kind == ExactValue_Typeid) { + // irValue *v = ir_typeid(proc->module, tv.value.value_typeid); + // return ir_emit_conv(proc, v, tv.type); + // } + + return lb_add_module_constant(p->module, tv.type, tv.value); + } + + + switch (expr->kind) { + case_ast_node(bl, BasicLit, expr); + TokenPos pos = bl->token.pos; + GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, 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(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name)); + case_end; + + // case_ast_node(i, Implicit, expr); + // return ir_addr_load(proc, ir_build_addr(proc, expr)); + // case_end; + + case_ast_node(u, Undef, expr); + return LLVMGetUndef(lb_type(tv.type)); + case_end; + + case_ast_node(i, Ident, expr); + Entity *e = entity_of_ident(expr); + GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr)); + if (e->kind == Entity_Builtin) { + Token token = ast_token(expr); + GB_PANIC("TODO(bill): ir_build_expr Entity_Builtin '%.*s'\n" + "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name), + LIT(token.pos.file), token.pos.line, token.pos.column); + return nullptr; + } else if (e->kind == Entity_Nil) { + return LLVMConstNull(lb_type(tv.type)); + } + + auto *found = map_get(&p->module->values, hash_entity(e)); + if (found) { + LLVMValueRef v = *found; + LLVMTypeKind kind = LLVMGetTypeKind(LLVMTypeOf(v)); + if (kind == LLVMFunctionTypeKind) { + return v; + } + return LLVMBuildLoad2(p->builder, LLVMGetElementType(LLVMTypeOf(v)), v, ""); + // } else if (e != nullptr && e->kind == Entity_Variable) { + // return ir_addr_load(proc, ir_build_addr(proc, expr)); + } + GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr); + return nullptr; + case_end; + + case_ast_node(be, BinaryExpr, expr); + return lb_build_binary_expr(p, expr); + case_end; + } + + return nullptr; +} + + + + +void lb_generate_module(lbGenerator *gen) { + gen->module.mod = LLVMModuleCreateWithName("odin_module"); + map_init(&gen->module.values, heap_allocator()); + + LLVMModuleRef mod = gen->module.mod; + CheckerInfo *info = gen->info; + + Arena temp_arena = {}; + arena_init(&temp_arena, heap_allocator()); + gbAllocator temp_allocator = arena_allocator(&temp_arena); + + Entity *entry_point = info->entry_point; + + auto *min_dep_set = &info->minimum_dependency_set; + + + for_array(i, info->entities) { + arena_free_all(&temp_arena); + gbAllocator a = temp_allocator; + + Entity *e = info->entities[i]; + String name = e->token.string; + DeclInfo *decl = e->decl_info; + Scope * scope = e->scope; + + if ((scope->flags & ScopeFlag_File) == 0) { + continue; + } + + Scope *package_scope = scope->parent; + GB_ASSERT(package_scope->flags & ScopeFlag_Pkg); + + switch (e->kind) { + case Entity_Variable: + // NOTE(bill): Handled above as it requires a specific load order + continue; + case Entity_ProcGroup: + continue; + + case Entity_TypeName: + case Entity_Procedure: + break; + } + + 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 = is_type_polymorphic(bt); + } + } + + if (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) { + // NOTE(bill): Nothing depends upon it so doesn't need to be built + continue; + } + + + if (entry_point == e) { + lbProcedure *p = lb_create_procedure(&gen->module, e); + + if (p->body != nullptr) { // Build Procedure + + lb_build_stmt(p, p->body); + + LLVMBuildRet(p->builder, nullptr); + } + + lb_end_procedure(p); + } + } + + { + LLVMTypeRef ret_type = LLVMFunctionType(LLVMVoidType(), nullptr, 0, false); + + LLVMValueRef p = LLVMAddFunction(mod, "mainCRTStartup", ret_type); + + + LLVMBasicBlockRef entry = LLVMAppendBasicBlock(p, "entry"); + + LLVMBuilderRef b = LLVMCreateBuilder(); + defer (LLVMDisposeBuilder(b)); + + LLVMPositionBuilderAtEnd(b, entry); + + + LLVMBuildRetVoid(b); + // LLVMBuildRet(b, nullptr); + } + + char *llvm_error = nullptr; + defer (LLVMDisposeMessage(llvm_error)); + + LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); + llvm_error = nullptr; + + LLVMDumpModule(mod); + + + LLVMPassManagerRef pass_manager = LLVMCreatePassManager(); + defer (LLVMDisposePassManager(pass_manager)); + + LLVMRunPassManager(pass_manager, mod); + LLVMFinalizeFunctionPassManager(pass_manager); + + LLVMInitializeAllTargetInfos(); + LLVMInitializeAllTargets(); + LLVMInitializeAllTargetMCs(); + LLVMInitializeAllAsmParsers(); + LLVMInitializeAllAsmPrinters(); + + char const *target_triple = "x86_64-pc-windows-msvc"; + char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; + LLVMSetTarget(mod, target_triple); + + LLVMTargetRef target = {}; + LLVMGetTargetFromTriple(target_triple, &target, &llvm_error); + GB_ASSERT(target != nullptr); + + LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault); + defer (LLVMDisposeTargetMachine(target_machine)); + + LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, "llvm_demo.obj", LLVMObjectFile, &llvm_error); + if (ok) { + gb_printf_err("LLVM Error: %s\n", llvm_error); + return; + } +} -- cgit v1.2.3 From 5f1b397a055be3cc58789281abdb7a390e2b18d5 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 1 Feb 2020 23:52:22 +0000 Subject: Use `lbValue` to represent values everywhere --- src/llvm_backend.cpp | 285 +++++++++++++++++++++++++++++++++++---------------- src/main.cpp | 5 + 2 files changed, 203 insertions(+), 87 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index b2ab67442..eb66db696 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -4,11 +4,19 @@ #include "llvm-c/Analysis.h" #include "llvm-c/Object.h" #include "llvm-c/BitWriter.h" +#include "llvm-c/Transforms/AggressiveInstCombine.h" +#include "llvm-c/Transforms/InstCombine.h" +#include "llvm-c/Transforms/IPO.h" + +struct lbValue { + LLVMValueRef value; + Type *type; +}; struct lbModule { LLVMModuleRef mod; - Map values; // Key: Entity * + Map values; // Key: Entity * }; struct lbGenerator { @@ -28,12 +36,14 @@ enum lbAddrKind { lbAddr_SoaVariable, }; + + struct lbAddr { lbAddrKind kind; - LLVMValueRef addr; + lbValue addr; union { struct { - LLVMValueRef key; + lbValue key; Type *type; Type *result; } map; @@ -44,7 +54,7 @@ struct lbAddr { Selection sel; } ctx; struct { - LLVMValueRef index; + lbValue index; Ast *index_expr; } soa; }; @@ -76,36 +86,41 @@ struct lbProcedure { LLVMValueRef value; LLVMBuilderRef builder; - LLVMValueRef return_ptr; - Array params; - Array blocks; - Scope * curr_scope; - i32 scope_index; - lbBlock * decl_block; - lbBlock * entry_block; - lbBlock * curr_block; + lbValue return_ptr; + Array params; + Array blocks; + Scope * curr_scope; + i32 scope_index; + lbBlock * decl_block; + lbBlock * entry_block; + lbBlock * curr_block; }; lbBlock * lb_create_block(lbProcedure *p, char const *name); LLVMTypeRef lb_type(Type *type); void lb_build_stmt (lbProcedure *p, Ast *stmt); -LLVMValueRef lb_build_expr (lbProcedure *p, Ast *expr); +lbValue lb_build_expr (lbProcedure *p, Ast *expr); +lbValue lb_constant_nil(Type *type); + -lbAddr lb_addr(LLVMValueRef addr) { +lbAddr lb_addr(lbValue addr) { lbAddr v = {lbAddr_Default, addr}; return v; } -LLVMTypeRef lb_addr_type(lbAddr const &addr) { - return LLVMGetElementType(LLVMTypeOf(addr.addr)); +Type *lb_addr_type(lbAddr const &addr) { + return type_deref(addr.addr.type); +} +LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) { + return LLVMGetElementType(LLVMTypeOf(addr.addr.value)); } -void lb_addr_store(lbProcedure *p, lbAddr const &addr, LLVMValueRef value) { - if (addr.addr == nullptr) { +void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue const &value) { + if (addr.addr.value == nullptr) { return; } - GB_ASSERT(value != nullptr); - LLVMBuildStore(p->builder, value, addr.addr); + GB_ASSERT(value.value != nullptr); + LLVMBuildStore(p->builder, value.value, addr.addr.value); } LLVMTypeRef lb_type_internal(Type *type) { @@ -380,11 +395,15 @@ lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr) { LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); + lbValue val = {}; + val.value = ptr; + val.type = alloc_type_pointer(type); + if (e != nullptr) { - map_set(&p->module->values, hash_entity(e), ptr); + map_set(&p->module->values, hash_entity(e), val); } - return lb_addr(ptr); + return lb_addr(val); } @@ -482,7 +501,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { auto addrs = array_make(heap_allocator(), vd->names.count); - auto values = array_make(heap_allocator(), 0, vd->names.count); + auto values = array_make(heap_allocator(), 0, vd->names.count); defer (array_free(&addrs)); defer (array_free(&values)); @@ -492,13 +511,13 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { Entity *e = entity_of_ident(name); addrs[i] = lb_add_local(p, e->type, e); if (vd->values.count == 0) { - lb_addr_store(p, addrs[i], LLVMConstNull(lb_addr_type(addrs[i]))); + lb_addr_store(p, addrs[i], lb_constant_nil(lb_addr_type(addrs[i]))); } } } for_array(i, vd->values) { - LLVMValueRef value = lb_build_expr(p, vd->values[i]); + lbValue value = lb_build_expr(p, vd->values[i]); array_add(&values, value); } @@ -510,28 +529,78 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { } } -LLVMValueRef lb_value_constant(Type *type, ExactValue const &value) { +lbValue lb_constant_nil(Type *type) { + LLVMValueRef v = LLVMConstNull(lb_type(type)); + return lbValue{v, type}; +} + +LLVMValueRef llvm_const_f32(f32 f, Type *type=t_f32) { + u32 u = bit_cast(f); + LLVMValueRef i = LLVMConstInt(LLVMInt32Type(), u, false); + return LLVMConstBitCast(i, lb_type(type)); +} + +lbValue lb_constant_value(Type *type, ExactValue const &value) { switch (value.kind) { case ExactValue_Invalid: - return LLVMConstNull(lb_type(type)); + return lbValue{LLVMConstNull(lb_type(type)), type}; case ExactValue_Bool: - return LLVMConstInt(lb_type(type), value.value_bool, false); + return lbValue{LLVMConstInt(lb_type(type), value.value_bool, false), type}; case ExactValue_String: - return LLVMConstInt(lb_type(type), value.value_bool, false); + return lbValue{LLVMConstInt(lb_type(type), value.value_bool, false), type}; case ExactValue_Integer: - return LLVMConstIntOfArbitraryPrecision(lb_type(type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); + return lbValue{LLVMConstIntOfArbitraryPrecision(lb_type(type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)), type}; case ExactValue_Float: - return LLVMConstReal(lb_type(type), value.value_float); + if (type_size_of(type) == 4) { + f32 f = cast(f32)value.value_float; + return lbValue{llvm_const_f32(f, type), type}; + } + return lbValue{LLVMConstReal(lb_type(type), value.value_float), type}; case ExactValue_Complex: - GB_PANIC("ExactValue_Complex"); + { + LLVMValueRef values[2] = {}; + switch (8*type_size_of(type)) { + case 64: + values[0] = llvm_const_f32(cast(f32)value.value_complex.real); + values[1] = llvm_const_f32(cast(f32)value.value_complex.imag); + break; + case 128: + values[0] = LLVMConstReal(lb_type(t_f64), value.value_complex.real); + values[1] = LLVMConstReal(lb_type(t_f64), value.value_complex.imag); + break; + } + + return lbValue{LLVMConstStruct(values, 2, false)}; + } break; case ExactValue_Quaternion: - GB_PANIC("ExactValue_Quaternion"); + { + LLVMValueRef values[4] = {}; + switch (8*type_size_of(type)) { + case 128: + // @QuaternionLayout + values[3] = llvm_const_f32(cast(f32)value.value_quaternion.real); + values[0] = llvm_const_f32(cast(f32)value.value_quaternion.imag); + values[1] = llvm_const_f32(cast(f32)value.value_quaternion.jmag); + values[2] = llvm_const_f32(cast(f32)value.value_quaternion.kmag); + break; + case 256: + // @QuaternionLayout + values[3] = LLVMConstReal(lb_type(t_f64), value.value_quaternion.real); + values[0] = LLVMConstReal(lb_type(t_f64), value.value_quaternion.imag); + values[1] = LLVMConstReal(lb_type(t_f64), value.value_quaternion.jmag); + values[2] = LLVMConstReal(lb_type(t_f64), value.value_quaternion.kmag); + break; + } + + return lbValue{LLVMConstStruct(values, 4, false)}; + } break; case ExactValue_Pointer: - return LLVMConstBitCast(LLVMConstInt(lb_type(t_uintptr), value.value_pointer, false), lb_type(type)); + return lbValue{LLVMConstBitCast(LLVMConstInt(lb_type(t_uintptr), value.value_pointer, false), lb_type(type)), type}; + case ExactValue_Compound: GB_PANIC("ExactValue_Compound"); break; @@ -544,50 +613,88 @@ LLVMValueRef lb_value_constant(Type *type, ExactValue const &value) { } GB_PANIC("UNKNOWN ExactValue kind"); - return nullptr; + return lbValue{nullptr, type}; } -LLVMValueRef lb_add_module_constant(lbModule *m, Type *type, ExactValue const &value) { +lbValue lb_add_module_constant(lbModule *m, Type *type, ExactValue const &value) { gbAllocator a = heap_allocator(); if (is_type_slice(type)) { GB_PANIC("lb_add_module_constant -> slice"); } - return lb_value_constant(type, value); + return lb_constant_value(type, value); } -LLVMValueRef lb_emit_arith(lbProcedure *p, TokenKind op, LLVMValueRef lhs, LLVMValueRef rhs, Type *type) { +lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) { switch (op) { case Token_Add: - return LLVMBuildAdd(p->builder, lhs, rhs, ""); + if (is_type_float(type)) { + return lbValue{LLVMBuildFAdd(p->builder, lhs.value, rhs.value, ""), type}; + } + return lbValue{LLVMBuildAdd(p->builder, lhs.value, rhs.value, ""), type}; case Token_Sub: - return LLVMBuildSub(p->builder, lhs, rhs, ""); + if (is_type_float(type)) { + return lbValue{LLVMBuildFSub(p->builder, lhs.value, rhs.value, ""), type}; + } + return lbValue{LLVMBuildSub(p->builder, lhs.value, rhs.value, ""), type}; case Token_Mul: - return LLVMBuildMul(p->builder, lhs, rhs, ""); + if (is_type_float(type)) { + return lbValue{LLVMBuildFMul(p->builder, lhs.value, rhs.value, ""), type}; + } + return lbValue{LLVMBuildMul(p->builder, lhs.value, rhs.value, ""), type}; case Token_Quo: + if (is_type_float(type)) { + return lbValue{LLVMBuildFDiv(p->builder, lhs.value, rhs.value, ""), type}; + } else if (is_type_unsigned(type)) { + return lbValue{LLVMBuildUDiv(p->builder, lhs.value, rhs.value, ""), type}; + } + return lbValue{LLVMBuildSDiv(p->builder, lhs.value, rhs.value, ""), type}; case Token_Mod: + if (is_type_float(type)) { + return lbValue{LLVMBuildFRem(p->builder, lhs.value, rhs.value, ""), type}; + } else if (is_type_unsigned(type)) { + return lbValue{LLVMBuildURem(p->builder, lhs.value, rhs.value, ""), type}; + } + return lbValue{LLVMBuildSRem(p->builder, lhs.value, rhs.value, ""), type}; case Token_ModMod: + if (is_type_unsigned(type)) { + return lbValue{LLVMBuildURem(p->builder, lhs.value, rhs.value, ""), type}; + } else { + LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, ""); + LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, ""); + LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, ""); + return lbValue{c, type}; + } + case Token_And: - return LLVMBuildAdd(p->builder, lhs, rhs, ""); + return lbValue{LLVMBuildAnd(p->builder, lhs.value, rhs.value, ""), type}; case Token_Or: - return LLVMBuildOr(p->builder, lhs, rhs, ""); + return lbValue{LLVMBuildOr(p->builder, lhs.value, rhs.value, ""), type}; case Token_Xor: - return LLVMBuildXor(p->builder, lhs, rhs, ""); + return lbValue{LLVMBuildXor(p->builder, lhs.value, rhs.value, ""), type}; case Token_Shl: - return LLVMBuildShl(p->builder, lhs, rhs, ""); + return lbValue{LLVMBuildShl(p->builder, lhs.value, rhs.value, ""), type}; case Token_Shr: - + if (is_type_unsigned(type)) { + return lbValue{LLVMBuildLShr(p->builder, lhs.value, rhs.value, ""), type}; + } + return lbValue{LLVMBuildAShr(p->builder, lhs.value, rhs.value, ""), type}; case Token_AndNot: + { + LLVMValueRef all_ones = LLVMConstAllOnes(lb_type(type)); + LLVMValueRef new_rhs = LLVMBuildXor(p->builder, all_ones, rhs.value, ""); + return lbValue{LLVMBuildAnd(p->builder, lhs.value, new_rhs, ""), type}; + } break; } GB_PANIC("unhandled operator of lb_emit_arith"); - return nullptr; + return {}; } -LLVMValueRef lb_build_binary_expr(lbProcedure *p, Ast *expr) { +lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { ast_node(be, BinaryExpr, expr); TypeAndValue tv = type_and_value_of_expr(expr); @@ -606,18 +713,18 @@ LLVMValueRef lb_build_binary_expr(lbProcedure *p, Ast *expr) { case Token_Shl: case Token_Shr: { Type *type = default_type(tv.type); - LLVMValueRef left = lb_build_expr(p, be->left); - LLVMValueRef right = lb_build_expr(p, be->right); + lbValue left = lb_build_expr(p, be->left); + lbValue right = lb_build_expr(p, be->right); return lb_emit_arith(p, be->op.kind, left, right, type); } default: GB_PANIC("Invalid binary expression"); break; } - return nullptr; + return {}; } -LLVMValueRef lb_build_expr(lbProcedure *p, Ast *expr) { +lbValue lb_build_expr(lbProcedure *p, Ast *expr) { expr = unparen_expr(expr); TypeAndValue tv = type_and_value_of_expr(expr); @@ -659,7 +766,7 @@ LLVMValueRef lb_build_expr(lbProcedure *p, Ast *expr) { // case_end; case_ast_node(u, Undef, expr); - return LLVMGetUndef(lb_type(tv.type)); + return lbValue{LLVMGetUndef(lb_type(tv.type)), tv.type}; case_end; case_ast_node(i, Ident, expr); @@ -670,24 +777,24 @@ LLVMValueRef lb_build_expr(lbProcedure *p, Ast *expr) { GB_PANIC("TODO(bill): ir_build_expr Entity_Builtin '%.*s'\n" "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name), LIT(token.pos.file), token.pos.line, token.pos.column); - return nullptr; + return {}; } else if (e->kind == Entity_Nil) { - return LLVMConstNull(lb_type(tv.type)); + return lb_constant_nil(tv.type); } auto *found = map_get(&p->module->values, hash_entity(e)); if (found) { - LLVMValueRef v = *found; - LLVMTypeKind kind = LLVMGetTypeKind(LLVMTypeOf(v)); + auto v = *found; + LLVMTypeKind kind = LLVMGetTypeKind(LLVMTypeOf(v.value)); if (kind == LLVMFunctionTypeKind) { return v; } - return LLVMBuildLoad2(p->builder, LLVMGetElementType(LLVMTypeOf(v)), v, ""); + return lbValue{LLVMBuildLoad2(p->builder, lb_type(type_deref(v.type)), v.value, ""), e->type}; // } else if (e != nullptr && e->kind == Entity_Variable) { // return ir_addr_load(proc, ir_build_addr(proc, expr)); } GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr); - return nullptr; + return {}; case_end; case_ast_node(be, BinaryExpr, expr); @@ -695,7 +802,7 @@ LLVMValueRef lb_build_expr(lbProcedure *p, Ast *expr) { case_end; } - return nullptr; + return {}; } @@ -718,8 +825,8 @@ void lb_generate_module(lbGenerator *gen) { for_array(i, info->entities) { - arena_free_all(&temp_arena); - gbAllocator a = temp_allocator; + // arena_free_all(&temp_arena); + // gbAllocator a = temp_allocator; Entity *e = info->entities[i]; String name = e->token.string; @@ -767,6 +874,7 @@ void lb_generate_module(lbGenerator *gen) { lb_build_stmt(p, p->body); LLVMBuildRet(p->builder, nullptr); + // LLVMBuildRetVoid(p->builder); } lb_end_procedure(p); @@ -794,38 +902,41 @@ void lb_generate_module(lbGenerator *gen) { char *llvm_error = nullptr; defer (LLVMDisposeMessage(llvm_error)); - LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); - llvm_error = nullptr; - LLVMDumpModule(mod); + // LLVMPassManagerRef pass_manager = LLVMCreatePassManager(); + // defer (LLVMDisposePassManager(pass_manager)); + + // LLVMAddAggressiveInstCombinerPass(pass_manager); + // LLVMAddConstantMergePass(pass_manager); + // LLVMAddDeadArgEliminationPass(pass_manager); + // LLVMRunPassManager(pass_manager, mod); - LLVMPassManagerRef pass_manager = LLVMCreatePassManager(); - defer (LLVMDisposePassManager(pass_manager)); + LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); + llvm_error = nullptr; - LLVMRunPassManager(pass_manager, mod); - LLVMFinalizeFunctionPassManager(pass_manager); + LLVMDumpModule(mod); - LLVMInitializeAllTargetInfos(); - LLVMInitializeAllTargets(); - LLVMInitializeAllTargetMCs(); - LLVMInitializeAllAsmParsers(); - LLVMInitializeAllAsmPrinters(); + // LLVMInitializeAllTargetInfos(); + // LLVMInitializeAllTargets(); + // LLVMInitializeAllTargetMCs(); + // LLVMInitializeAllAsmParsers(); + // LLVMInitializeAllAsmPrinters(); - char const *target_triple = "x86_64-pc-windows-msvc"; - char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; - LLVMSetTarget(mod, target_triple); + // char const *target_triple = "x86_64-pc-windows-msvc"; + // char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; + // LLVMSetTarget(mod, target_triple); - LLVMTargetRef target = {}; - LLVMGetTargetFromTriple(target_triple, &target, &llvm_error); - GB_ASSERT(target != nullptr); + // LLVMTargetRef target = {}; + // LLVMGetTargetFromTriple(target_triple, &target, &llvm_error); + // GB_ASSERT(target != nullptr); - LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault); - defer (LLVMDisposeTargetMachine(target_machine)); + // LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault); + // defer (LLVMDisposeTargetMachine(target_machine)); - LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, "llvm_demo.obj", LLVMObjectFile, &llvm_error); - if (ok) { - gb_printf_err("LLVM Error: %s\n", llvm_error); - return; - } + // LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, "llvm_demo.obj", LLVMObjectFile, &llvm_error); + // if (ok) { + // gb_printf_err("LLVM Error: %s\n", llvm_error); + // return; + // } } diff --git a/src/main.cpp b/src/main.cpp index 95bc52d63..bed1935ec 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1275,11 +1275,16 @@ int main(int arg_count, char const **arg_ptr) { } if (build_context.use_llvm_api) { + timings_start_section(timings, str_lit("LLVM API Code Gen")); lbGenerator gen = {}; if (!lb_init_generator(&gen, &checker)) { return 1; } lb_generate_module(&gen); + + if (build_context.show_timings) { + show_timings(&checker, timings); + } return 0; } -- cgit v1.2.3 From 5dc82c2720524b2c99f3b35c3636e0b0f10dcbb7 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 2 Feb 2020 12:34:49 +0000 Subject: Correctly generate LLVM types from Odin types. --- examples/llvm-demo/demo.odin | 23 ++- src/llvm_backend.cpp | 445 ++++++++++++++++++++++++++++++++++++------- 2 files changed, 401 insertions(+), 67 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/examples/llvm-demo/demo.odin b/examples/llvm-demo/demo.odin index 481970ab5..e3727e610 100644 --- a/examples/llvm-demo/demo.odin +++ b/examples/llvm-demo/demo.odin @@ -3,9 +3,28 @@ package demo import "core:os" main :: proc() { - x := 1; - y := 2; + Foo :: struct { + x, y: int, + }; + + x := i32(1); + y := i32(2); z := x + y; w := z - 2; + + + c := 1 + 2i; + q := 1 + 2i + 3j + 4k; + + s := "Hellope"; + + f: Foo; + pc: proc "contextless" (x: i32) -> Foo; + po: proc "odin" (x: i32) -> Foo; + e: enum{A, B, C}; + u: union{i32, bool}; + u1: union{i32}; + um: union #maybe {^int}; + // os.write_string(os.stdout, "Hellope\n"); } diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index eb66db696..fd6d7a983 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -103,6 +103,12 @@ lbValue lb_build_expr (lbProcedure *p, Ast *expr); lbValue lb_constant_nil(Type *type); +gb_internal lbModule *global_module = nullptr; + +gb_internal LLVMValueRef lb_zero32 = nullptr; +gb_internal LLVMValueRef lb_one32 = nullptr; + + lbAddr lb_addr(lbValue addr) { lbAddr v = {lbAddr_Default, addr}; return v; @@ -123,7 +129,36 @@ void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue const &value) { LLVMBuildStore(p->builder, value.value, addr.addr.value); } +void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) { + unsigned field_count = LLVMCountStructElementTypes(src); + LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); + LLVMGetStructElementTypes(src, fields); + LLVMStructSetBody(dst, fields, field_count, LLVMIsPackedStruct(src)); + gb_free(heap_allocator(), fields); +} + +LLVMTypeRef lb_alignment_prefix_type_hack(i64 alignment) { + switch (alignment) { + case 1: + return LLVMArrayType(lb_type(t_u8), 0); + case 2: + return LLVMArrayType(lb_type(t_u16), 0); + case 4: + return LLVMArrayType(lb_type(t_u32), 0); + case 8: + return LLVMArrayType(lb_type(t_u64), 0); + case 16: + return LLVMArrayType(LLVMVectorType(lb_type(t_u32), 4), 0); + default: + GB_PANIC("Invalid alignment %d", cast(i32)alignment); + break; + } + return nullptr; +} + LLVMTypeRef lb_type_internal(Type *type) { + i64 size = type_size_of(type); // Check size + switch (type->kind) { case Type_Basic: switch (type->Basic.kind) { @@ -154,40 +189,48 @@ LLVMTypeRef lb_type_internal(Type *type) { // Basic_complex32, case Basic_complex64: { + LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..complex64"); LLVMTypeRef fields[2] = { lb_type(t_f32), lb_type(t_f32), }; - return LLVMStructType(fields, 2, false); + LLVMStructSetBody(type, fields, 2, false); + return type; } case Basic_complex128: { + LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..complex128"); LLVMTypeRef fields[2] = { lb_type(t_f64), lb_type(t_f64), }; - return LLVMStructType(fields, 2, false); + LLVMStructSetBody(type, fields, 2, false); + return type; } case Basic_quaternion128: { + LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..quaternion128"); LLVMTypeRef fields[4] = { lb_type(t_f32), lb_type(t_f32), lb_type(t_f32), lb_type(t_f32), }; - return LLVMStructType(fields, 4, false); + LLVMStructSetBody(type, fields, 4, false); + return type; } case Basic_quaternion256: { + LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..quaternion256"); LLVMTypeRef fields[4] = { lb_type(t_f64), lb_type(t_f64), lb_type(t_f64), lb_type(t_f64), }; - return LLVMStructType(fields, 4, false); + LLVMStructSetBody(type, fields, 4, false); + return type; } case Basic_int: return LLVMIntType(8*cast(unsigned)build_context.word_size); @@ -198,40 +241,44 @@ LLVMTypeRef lb_type_internal(Type *type) { case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0); case Basic_string: { + LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..string"); LLVMTypeRef fields[2] = { LLVMPointerType(lb_type(t_u8), 0), lb_type(t_int), }; - return LLVMStructType(fields, 2, false); + LLVMStructSetBody(type, fields, 2, false); + return type; } case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0); case Basic_any: { + LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..any"); LLVMTypeRef fields[2] = { LLVMPointerType(lb_type(t_rawptr), 0), lb_type(t_typeid), }; - return LLVMStructType(fields, 2, false); + LLVMStructSetBody(type, fields, 2, false); + return type; } case Basic_typeid: return LLVMIntType(8*cast(unsigned)build_context.word_size); // Endian Specific Types - case Basic_i16le: return LLVMInt16Type(); - case Basic_u16le: return LLVMInt16Type(); - case Basic_i32le: return LLVMInt32Type(); - case Basic_u32le: return LLVMInt32Type(); - case Basic_i64le: return LLVMInt64Type(); - case Basic_u64le: return LLVMInt64Type(); + case Basic_i16le: return LLVMInt16Type(); + case Basic_u16le: return LLVMInt16Type(); + case Basic_i32le: return LLVMInt32Type(); + case Basic_u32le: return LLVMInt32Type(); + case Basic_i64le: return LLVMInt64Type(); + case Basic_u64le: return LLVMInt64Type(); case Basic_i128le: return LLVMInt128Type(); case Basic_u128le: return LLVMInt128Type(); - case Basic_i16be: return LLVMInt16Type(); - case Basic_u16be: return LLVMInt16Type(); - case Basic_i32be: return LLVMInt32Type(); - case Basic_u32be: return LLVMInt32Type(); - case Basic_i64be: return LLVMInt64Type(); - case Basic_u64be: return LLVMInt64Type(); + case Basic_i16be: return LLVMInt16Type(); + case Basic_u16be: return LLVMInt16Type(); + case Basic_i32be: return LLVMInt32Type(); + case Basic_u32be: return LLVMInt32Type(); + case Basic_i64be: return LLVMInt64Type(); + case Basic_u64be: return LLVMInt64Type(); case Basic_i128be: return LLVMInt128Type(); case Basic_u128be: return LLVMInt128Type(); @@ -248,16 +295,74 @@ LLVMTypeRef lb_type_internal(Type *type) { } break; case Type_Named: - GB_PANIC("Type_Named"); - return nullptr; + { + Type *base = base_type(type->Named.base); + + switch (base->kind) { + case Type_Basic: + return lb_type(base); + + case Type_Named: + case Type_Generic: + case Type_BitFieldValue: + GB_PANIC("INVALID TYPE"); + break; + + case Type_Pointer: + case Type_Opaque: + case Type_Array: + case Type_EnumeratedArray: + case Type_Slice: + case Type_DynamicArray: + case Type_Map: + case Type_Enum: + case Type_BitSet: + case Type_SimdVector: + return lb_type(base); + + // TODO(bill): Deal with this correctly. Can this be named? + case Type_Proc: + return lb_type(base); + + case Type_Tuple: + return lb_type(base); + } + + LLVMContextRef ctx = LLVMGetModuleContext(global_module->mod); + + if (base->llvm_type != nullptr) { + LLVMTypeKind kind = LLVMGetTypeKind(base->llvm_type); + if (kind == LLVMStructTypeKind) { + type->llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), type->Named.name)); + lb_clone_struct_type(type->llvm_type, base->llvm_type); + } + } + + switch (base->kind) { + case Type_Struct: + case Type_Union: + case Type_BitField: + type->llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), type->Named.name)); + lb_clone_struct_type(type->llvm_type, lb_type(base)); + return type->llvm_type; + } + + + return lb_type(base); + } + case Type_Pointer: return LLVMPointerType(lb_type(type_deref(type)), 0); + case Type_Opaque: return lb_type(base_type(type)); + case Type_Array: return LLVMArrayType(lb_type(type->Array.elem), cast(unsigned)type->Array.count); + case Type_EnumeratedArray: return LLVMArrayType(lb_type(type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count); + case Type_Slice: { LLVMTypeRef fields[2] = { @@ -267,6 +372,7 @@ LLVMTypeRef lb_type_internal(Type *type) { return LLVMStructType(fields, 2, false); } break; + case Type_DynamicArray: { LLVMTypeRef fields[4] = { @@ -278,27 +384,160 @@ LLVMTypeRef lb_type_internal(Type *type) { return LLVMStructType(fields, 4, false); } break; + case Type_Map: return lb_type(type->Map.internal_type); + case Type_Struct: - GB_PANIC("Type_Struct"); + { + if (type->Struct.is_raw_union) { + unsigned field_count = 2; + LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); + i64 alignment = type_align_of(type); + unsigned size_of_union = cast(unsigned)type_size_of(type); + fields[0] = lb_alignment_prefix_type_hack(alignment); + fields[1] = LLVMArrayType(lb_type(t_u8), size_of_union); + return LLVMStructType(fields, field_count, false); + } + + isize offset = 0; + if (type->Struct.custom_align > 0) { + offset = 1; + } + + unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset); + LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); + defer (gb_free(heap_allocator(), fields)); + + for_array(i, type->Struct.fields) { + Entity *field = type->Struct.fields[i]; + fields[i+offset] = lb_type(field->type); + } + + if (type->Struct.custom_align > 0) { + fields[0] = lb_alignment_prefix_type_hack(type->Struct.custom_align); + } + + return LLVMStructType(fields, field_count, type->Struct.is_packed); + } break; + case Type_Union: - GB_PANIC("Type_Union"); + if (type->Union.variants.count == 0) { + return LLVMStructType(nullptr, 0, false); + } else { + // NOTE(bill): The zero size array is used to fix the alignment used in a structure as + // LLVM takes the first element's alignment as the entire alignment (like C) + i64 align = type_align_of(type); + i64 size = type_size_of(type); + + if (is_type_union_maybe_pointer_original_alignment(type)) { + LLVMTypeRef fields[1] = {lb_type(type->Union.variants[0])}; + return LLVMStructType(fields, 1, false); + } + + unsigned block_size = cast(unsigned)type->Union.variant_block_size; + + LLVMTypeRef fields[3] = {}; + unsigned field_count = 1; + fields[0] = lb_alignment_prefix_type_hack(align); + if (is_type_union_maybe_pointer(type)) { + field_count += 1; + fields[1] = lb_type(type->Union.variants[0]); + } else { + field_count += 2; + fields[1] = LLVMArrayType(lb_type(t_u8), block_size); + fields[2] = lb_type(union_tag_type(type)); + } + + return LLVMStructType(fields, field_count, false); + } break; + case Type_Enum: - return LLVMIntType(8*cast(unsigned)type_size_of(type)); + return lb_type(base_enum_type(type)); + case Type_Tuple: - GB_PANIC("Type_Tuple"); - break; + { + unsigned field_count = cast(unsigned)(type->Tuple.variables.count); + LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); + defer (gb_free(heap_allocator(), fields)); + + for_array(i, type->Tuple.variables) { + Entity *field = type->Tuple.variables[i]; + fields[i] = lb_type(field->type); + } + + return LLVMStructType(fields, field_count, type->Tuple.is_packed); + } + case Type_Proc: - set_procedure_abi_types(heap_allocator(), type); - GB_PANIC("Type_Proc"); + { + set_procedure_abi_types(heap_allocator(), type); + + LLVMTypeRef return_type = LLVMVoidType(); + isize offset = 0; + if (type->Proc.return_by_pointer) { + offset = 1; + } else if (type->Proc.abi_compat_result_type != nullptr) { + return_type = lb_type(type->Proc.abi_compat_result_type); + } + + isize extra_param_count = offset; + if (type->Proc.calling_convention == ProcCC_Odin) { + extra_param_count += 1; + } + + unsigned param_count = cast(unsigned)(type->Proc.abi_compat_params.count + extra_param_count); + LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count); + defer (gb_free(heap_allocator(), param_types)); + + for_array(i, type->Proc.abi_compat_params) { + Type *param = type->Proc.abi_compat_params[i]; + param_types[i+offset] = lb_type(param); + } + if (type->Proc.return_by_pointer) { + param_types[0] = LLVMPointerType(lb_type(type->Proc.abi_compat_result_type), 0); + } + if (type->Proc.calling_convention == ProcCC_Odin) { + param_types[param_count-1] = lb_type(t_context_ptr); + } + + LLVMTypeRef t = LLVMFunctionType(return_type, param_types, param_count, type->Proc.c_vararg); + return LLVMPointerType(t, 0); + } break; case Type_BitFieldValue: return LLVMIntType(type->BitFieldValue.bits); + case Type_BitField: - GB_PANIC("Type_BitField"); + { + LLVMTypeRef internal_type = nullptr; + { + GB_ASSERT(type->BitField.fields.count == type->BitField.sizes.count); + unsigned field_count = cast(unsigned)type->BitField.fields.count; + LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); + defer (gb_free(heap_allocator(), fields)); + + for_array(i, type->BitField.sizes) { + u32 size = type->BitField.sizes[i]; + fields[i] = LLVMIntType(size); + } + + internal_type = LLVMStructType(fields, field_count, true); + } + unsigned field_count = 2; + LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); + + i64 alignment = 1; + if (type->BitField.custom_align > 0) { + alignment = type->BitField.custom_align; + } + fields[0] = lb_alignment_prefix_type_hack(alignment); + fields[1] = internal_type; + + return LLVMStructType(fields, field_count, true); + } break; case Type_BitSet: return LLVMIntType(8*cast(unsigned)type_size_of(type)); @@ -448,6 +687,15 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { gen->info = &c->info; + gen->module.mod = LLVMModuleCreateWithName("odin_module"); + map_init(&gen->module.values, heap_allocator()); + + global_module = &gen->module; + + lb_zero32 = LLVMConstInt(lb_type(t_i32), 0, false); + lb_one32 = LLVMConstInt(lb_type(t_i32), 1, false); + + return true; } @@ -470,6 +718,14 @@ void lb_build_stmt_list(lbProcedure *p, Array const &stmts) { } } +lbValue lb_build_gep(lbProcedure *p, lbValue const &value, i32 index) { + Type *elem_type = nullptr; + + + GB_ASSERT(elem_type != nullptr); + return lbValue{LLVMBuildStructGEP2(p->builder, lb_type(elem_type), value.value, index, ""), elem_type}; +} + void lb_build_stmt(lbProcedure *p, Ast *node) { switch (node->kind) { @@ -517,7 +773,12 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { } for_array(i, vd->values) { - lbValue value = lb_build_expr(p, vd->values[i]); + Ast *expr = vd->values[i]; + lbValue value = lb_build_expr(p, expr); + GB_ASSERT_MSG(value.type != nullptr, "%s", expr_to_string(expr)); + if (is_type_tuple(value.type)) { + + } array_add(&values, value); } @@ -540,23 +801,51 @@ LLVMValueRef llvm_const_f32(f32 f, Type *type=t_f32) { return LLVMConstBitCast(i, lb_type(type)); } -lbValue lb_constant_value(Type *type, ExactValue const &value) { +lbValue lb_constant_value(lbModule *m, Type *type, ExactValue const &value) { + lbValue res = {}; + res.type = type; switch (value.kind) { case ExactValue_Invalid: - return lbValue{LLVMConstNull(lb_type(type)), type}; + res.value = LLVMConstNull(lb_type(type)); + return res; case ExactValue_Bool: - return lbValue{LLVMConstInt(lb_type(type), value.value_bool, false), type}; + res.value = LLVMConstInt(lb_type(type), value.value_bool, false); + return res; case ExactValue_String: - return lbValue{LLVMConstInt(lb_type(type), value.value_bool, false), type}; + { + LLVMValueRef indices[2] = {lb_zero32, lb_zero32}; + LLVMValueRef data = LLVMConstString(cast(char const *)value.value_string.text, + cast(unsigned)value.value_string.len, + false); + LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), "test_string_data"); + LLVMSetInitializer(global_data, data); + + LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); + + if (is_type_cstring(type)) { + res.value = ptr; + return res; + } + + LLVMValueRef len = LLVMConstInt(lb_type(t_int), value.value_string.len, true); + LLVMValueRef values[2] = {ptr, len}; + + res.value = LLVMConstNamedStruct(lb_type(type), values, 2); + return res; + } + case ExactValue_Integer: - return lbValue{LLVMConstIntOfArbitraryPrecision(lb_type(type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)), type}; + res.value = LLVMConstIntOfArbitraryPrecision(lb_type(type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); + return res; case ExactValue_Float: if (type_size_of(type) == 4) { f32 f = cast(f32)value.value_float; - return lbValue{llvm_const_f32(f, type), type}; + res.value = llvm_const_f32(f, type); + return res; } - return lbValue{LLVMConstReal(lb_type(type), value.value_float), type}; + res.value = LLVMConstReal(lb_type(type), value.value_float); + return res; case ExactValue_Complex: { LLVMValueRef values[2] = {}; @@ -571,7 +860,8 @@ lbValue lb_constant_value(Type *type, ExactValue const &value) { break; } - return lbValue{LLVMConstStruct(values, 2, false)}; + res.value = LLVMConstNamedStruct(lb_type(type), values, 2); + return res; } break; case ExactValue_Quaternion: @@ -594,12 +884,14 @@ lbValue lb_constant_value(Type *type, ExactValue const &value) { break; } - return lbValue{LLVMConstStruct(values, 4, false)}; + res.value = LLVMConstNamedStruct(lb_type(type), values, 4); + return res; } break; case ExactValue_Pointer: - return lbValue{LLVMConstBitCast(LLVMConstInt(lb_type(t_uintptr), value.value_pointer, false), lb_type(type)), type}; + res.value = LLVMConstBitCast(LLVMConstInt(lb_type(t_uintptr), value.value_pointer, false), lb_type(type)); + return res; case ExactValue_Compound: GB_PANIC("ExactValue_Compound"); @@ -613,7 +905,7 @@ lbValue lb_constant_value(Type *type, ExactValue const &value) { } GB_PANIC("UNKNOWN ExactValue kind"); - return lbValue{nullptr, type}; + return res; } lbValue lb_add_module_constant(lbModule *m, Type *type, ExactValue const &value) { @@ -623,68 +915,92 @@ lbValue lb_add_module_constant(lbModule *m, Type *type, ExactValue const &value) GB_PANIC("lb_add_module_constant -> slice"); } - return lb_constant_value(type, value); + return lb_constant_value(m, type, value); } lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) { + lbValue res = {}; + res.type = type; + switch (op) { case Token_Add: if (is_type_float(type)) { - return lbValue{LLVMBuildFAdd(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildFAdd(p->builder, lhs.value, rhs.value, ""); + return res; } - return lbValue{LLVMBuildAdd(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildAdd(p->builder, lhs.value, rhs.value, ""); + return res; case Token_Sub: if (is_type_float(type)) { - return lbValue{LLVMBuildFSub(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildFSub(p->builder, lhs.value, rhs.value, ""); + return res; } - return lbValue{LLVMBuildSub(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildSub(p->builder, lhs.value, rhs.value, ""); + return res; case Token_Mul: if (is_type_float(type)) { - return lbValue{LLVMBuildFMul(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildFMul(p->builder, lhs.value, rhs.value, ""); + return res; } - return lbValue{LLVMBuildMul(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildMul(p->builder, lhs.value, rhs.value, ""); + return res; case Token_Quo: if (is_type_float(type)) { - return lbValue{LLVMBuildFDiv(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildFDiv(p->builder, lhs.value, rhs.value, ""); + return res; } else if (is_type_unsigned(type)) { - return lbValue{LLVMBuildUDiv(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildUDiv(p->builder, lhs.value, rhs.value, ""); + return res; } - return lbValue{LLVMBuildSDiv(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildSDiv(p->builder, lhs.value, rhs.value, ""); + return res; case Token_Mod: if (is_type_float(type)) { - return lbValue{LLVMBuildFRem(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildFRem(p->builder, lhs.value, rhs.value, ""); + return res; } else if (is_type_unsigned(type)) { - return lbValue{LLVMBuildURem(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, ""); + return res; } - return lbValue{LLVMBuildSRem(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildSRem(p->builder, lhs.value, rhs.value, ""); + return res; case Token_ModMod: if (is_type_unsigned(type)) { - return lbValue{LLVMBuildURem(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildURem(p->builder, lhs.value, rhs.value, ""); + return res; } else { LLVMValueRef a = LLVMBuildSRem(p->builder, lhs.value, rhs.value, ""); LLVMValueRef b = LLVMBuildAdd(p->builder, a, rhs.value, ""); LLVMValueRef c = LLVMBuildSRem(p->builder, b, rhs.value, ""); - return lbValue{c, type}; + res.value = c; + return res; } case Token_And: - return lbValue{LLVMBuildAnd(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildAnd(p->builder, lhs.value, rhs.value, ""); + return res; case Token_Or: - return lbValue{LLVMBuildOr(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildOr(p->builder, lhs.value, rhs.value, ""); + return res; case Token_Xor: - return lbValue{LLVMBuildXor(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, ""); + return res; case Token_Shl: - return lbValue{LLVMBuildShl(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildShl(p->builder, lhs.value, rhs.value, ""); + return res; case Token_Shr: if (is_type_unsigned(type)) { - return lbValue{LLVMBuildLShr(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildLShr(p->builder, lhs.value, rhs.value, ""); + return res; } - return lbValue{LLVMBuildAShr(p->builder, lhs.value, rhs.value, ""), type}; + res.value = LLVMBuildAShr(p->builder, lhs.value, rhs.value, ""); + return res; case Token_AndNot: { LLVMValueRef all_ones = LLVMConstAllOnes(lb_type(type)); LLVMValueRef new_rhs = LLVMBuildXor(p->builder, all_ones, rhs.value, ""); - return lbValue{LLVMBuildAnd(p->builder, lhs.value, new_rhs, ""), type}; + res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, ""); + return res; } break; } @@ -809,9 +1125,6 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { void lb_generate_module(lbGenerator *gen) { - gen->module.mod = LLVMModuleCreateWithName("odin_module"); - map_init(&gen->module.values, heap_allocator()); - LLVMModuleRef mod = gen->module.mod; CheckerInfo *info = gen->info; @@ -824,6 +1137,8 @@ void lb_generate_module(lbGenerator *gen) { auto *min_dep_set = &info->minimum_dependency_set; + + for_array(i, info->entities) { // arena_free_all(&temp_arena); // gbAllocator a = temp_allocator; -- cgit v1.2.3 From d56807095a2e9a376bcb583a98aa151ecd77120d Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 2 Feb 2020 18:33:13 +0000 Subject: Implement constant value generation from ExactValue --- examples/llvm-demo/demo.odin | 49 +- src/ir.cpp | 28 -- src/ir_print.cpp | 3 +- src/llvm_backend.cpp | 1111 ++++++++++++++++++++++++++++++++++-------- src/types.cpp | 28 ++ 5 files changed, 978 insertions(+), 241 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/examples/llvm-demo/demo.odin b/examples/llvm-demo/demo.odin index e3727e610..3b8953134 100644 --- a/examples/llvm-demo/demo.odin +++ b/examples/llvm-demo/demo.odin @@ -2,29 +2,44 @@ package demo import "core:os" +// Foo :: struct { +// x, y: int, +// }; +// foo :: proc(x: int) -> (f: Foo) { +// return; +// } + main :: proc() { - Foo :: struct { - x, y: int, - }; + Foo :: enum {A=1, B, C, D}; + Foo_Set :: bit_set[Foo]; + x := Foo_Set{.A, .C}; + + y := [4]int{3 = 1, 0 .. 1 = 3, 2 = 9}; + z := []int{1, 2, 3, 4}; + + // @thread_local a: int; + + // x := i32(1); + // y := i32(2); + // z := x + y; + // w := z - 2; - x := i32(1); - y := i32(2); - z := x + y; - w := z - 2; + // foo(123); - c := 1 + 2i; - q := 1 + 2i + 3j + 4k; + // c := 1 + 2i; + // q := 1 + 2i + 3j + 4k; - s := "Hellope"; + // s := "Hellope"; - f: Foo; - pc: proc "contextless" (x: i32) -> Foo; - po: proc "odin" (x: i32) -> Foo; - e: enum{A, B, C}; - u: union{i32, bool}; - u1: union{i32}; - um: union #maybe {^int}; + // f := Foo{1, 2}; + // pc: proc "contextless" (x: i32) -> Foo; + // po: proc "odin" (x: i32) -> Foo; + // e: enum{A, B, C}; + // u: union{i32, bool}; + // u1: union{i32}; + // um: union #maybe {^int}; // os.write_string(os.stdout, "Hellope\n"); + return; } diff --git a/src/ir.cpp b/src/ir.cpp index 2f4d491e7..8171d774d 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -5911,34 +5911,6 @@ irValue *ir_type_info(irProcedure *proc, Type *type) { return ir_emit_array_ep(proc, ir_global_type_info_data, ir_const_i32(id)); } -// IMPORTANT NOTE(bill): This must match the same as the in core.odin -enum Typeid_Kind : u8 { - Typeid_Invalid, - Typeid_Integer, - Typeid_Rune, - Typeid_Float, - Typeid_Complex, - Typeid_Quaternion, - Typeid_String, - Typeid_Boolean, - Typeid_Any, - Typeid_Type_Id, - Typeid_Pointer, - Typeid_Procedure, - Typeid_Array, - Typeid_Enumerated_Array, - Typeid_Dynamic_Array, - Typeid_Slice, - Typeid_Tuple, - Typeid_Struct, - Typeid_Union, - Typeid_Enum, - Typeid_Map, - Typeid_Bit_Field, - Typeid_Bit_Set, -}; - - irValue *ir_typeid(irModule *m, Type *type) { type = default_type(type); diff --git a/src/ir_print.cpp b/src/ir_print.cpp index a3f28c59f..ac4d2469a 100644 --- a/src/ir_print.cpp +++ b/src/ir_print.cpp @@ -1014,8 +1014,7 @@ void ir_print_exact_value(irFileBuffer *f, irModule *m, ExactValue value, Type * } else if (is_type_enumerated_array(type)) { ast_node(cl, CompoundLit, value.value_compound); - Type *index_type = type->EnumeratedArray.elem; - Type *elem_type = type->Array.elem; + Type *elem_type = type->EnumeratedArray.elem; isize elem_count = cl->elems.count; if (elem_count == 0) { ir_write_str_lit(f, "zeroinitializer"); diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index fd6d7a983..c818051d0 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -1,109 +1,6 @@ -#include "llvm-c/Core.h" -#include "llvm-c/ExecutionEngine.h" -#include "llvm-c/Target.h" -#include "llvm-c/Analysis.h" -#include "llvm-c/Object.h" -#include "llvm-c/BitWriter.h" -#include "llvm-c/Transforms/AggressiveInstCombine.h" -#include "llvm-c/Transforms/InstCombine.h" -#include "llvm-c/Transforms/IPO.h" - -struct lbValue { - LLVMValueRef value; - Type *type; -}; - -struct lbModule { - LLVMModuleRef mod; - - Map values; // Key: Entity * -}; - -struct lbGenerator { - lbModule module; - CheckerInfo *info; - - gbFile output_file; - String output_base; - String output_name; -}; - -enum lbAddrKind { - lbAddr_Default, - lbAddr_Map, - lbAddr_BitField, - lbAddr_Context, - lbAddr_SoaVariable, -}; - - - -struct lbAddr { - lbAddrKind kind; - lbValue addr; - union { - struct { - lbValue key; - Type *type; - Type *result; - } map; - struct { - i32 value_index; - } bit_field; - struct { - Selection sel; - } ctx; - struct { - lbValue index; - Ast *index_expr; - } soa; - }; -}; - -struct lbBlock { - LLVMBasicBlockRef block; - Scope *scope; - isize scope_index; -}; - -struct lbProcedure { - lbProcedure *parent; - Array children; - - Entity * entity; - lbModule * module; - String name; - Type * type; - Ast * type_expr; - Ast * body; - u64 tags; - ProcInlining inlining; - bool is_foreign; - bool is_export; - bool is_entry_point; - - - LLVMValueRef value; - LLVMBuilderRef builder; - - lbValue return_ptr; - Array params; - Array blocks; - Scope * curr_scope; - i32 scope_index; - lbBlock * decl_block; - lbBlock * entry_block; - lbBlock * curr_block; -}; - -lbBlock * lb_create_block(lbProcedure *p, char const *name); -LLVMTypeRef lb_type(Type *type); -void lb_build_stmt (lbProcedure *p, Ast *stmt); -lbValue lb_build_expr (lbProcedure *p, Ast *expr); -lbValue lb_constant_nil(Type *type); - - -gb_internal lbModule *global_module = nullptr; +#include "llvm_backend.hpp" + +gb_internal gb_thread_local lbModule *global_module = nullptr; gb_internal LLVMValueRef lb_zero32 = nullptr; gb_internal LLVMValueRef lb_one32 = nullptr; @@ -129,6 +26,20 @@ void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue const &value) { LLVMBuildStore(p->builder, value.value, addr.addr.value); } + +lbValue lb_emit_load(lbProcedure *p, lbValue value) { + GB_ASSERT(value.value != nullptr); + Type *t = type_deref(value.type); + LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(t), value.value, ""); + return lbValue{v, t}; +} + +lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) { + GB_ASSERT(addr.addr.value != nullptr); + return lb_emit_load(p, addr.addr); +} + + void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) { unsigned field_count = LLVMCountStructElementTypes(src); LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); @@ -156,6 +67,60 @@ LLVMTypeRef lb_alignment_prefix_type_hack(i64 alignment) { return nullptr; } +String lb_mangle_name(lbModule *m, Entity *e) { + gbAllocator a = heap_allocator(); + + String name = e->token.string; + + AstPackage *pkg = e->pkg; + GB_ASSERT_MSG(pkg != nullptr, "Missing package for '%.*s'", LIT(name)); + String pkgn = pkg->name; + GB_ASSERT(!rune_is_digit(pkgn[0])); + + + isize max_len = pkgn.len + 1 + name.len + 1; + bool require_suffix_id = is_type_polymorphic(e->type, true); + if (require_suffix_id) { + max_len += 21; + } + + u8 *new_name = gb_alloc_array(a, u8, max_len); + isize new_name_len = gb_snprintf( + cast(char *)new_name, max_len, + "%.*s.%.*s", LIT(pkgn), LIT(name) + ); + if (require_suffix_id) { + char *str = cast(char *)new_name + new_name_len-1; + isize len = max_len-new_name_len; + isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id); + new_name_len += extra-1; + } + + return make_string(new_name, new_name_len-1); +} + +String lb_get_entity_name(lbModule *m, Entity *e, String name) { + if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) { + return e->TypeName.ir_mangled_name; + } + + + bool no_name_mangle = false; + + if (!no_name_mangle) { + name = lb_mangle_name(m, e); + } + if (name.len == 0) { + name = e->token.string; + } + + if (e != nullptr && e->kind == Entity_TypeName) { + e->TypeName.ir_mangled_name = name; + + } + return name; +} + LLVMTypeRef lb_type_internal(Type *type) { i64 size = type_size_of(type); // Check size @@ -333,7 +298,7 @@ LLVMTypeRef lb_type_internal(Type *type) { if (base->llvm_type != nullptr) { LLVMTypeKind kind = LLVMGetTypeKind(base->llvm_type); if (kind == LLVMStructTypeKind) { - type->llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), type->Named.name)); + type->llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), lb_get_entity_name(global_module, type->Named.type_name))); lb_clone_struct_type(type->llvm_type, base->llvm_type); } } @@ -342,7 +307,7 @@ LLVMTypeRef lb_type_internal(Type *type) { case Type_Struct: case Type_Union: case Type_BitField: - type->llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), type->Named.name)); + type->llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), lb_get_entity_name(global_module, type->Named.type_name))); lb_clone_struct_type(type->llvm_type, lb_type(base)); return type->llvm_type; } @@ -407,6 +372,7 @@ LLVMTypeRef lb_type_internal(Type *type) { unsigned field_count = cast(unsigned)(type->Struct.fields.count + offset); LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); + GB_ASSERT(fields != nullptr); defer (gb_free(heap_allocator(), fields)); for_array(i, type->Struct.fields) { @@ -563,12 +529,43 @@ LLVMTypeRef lb_type(Type *type) { return llvm_type; } +void lb_add_entity(lbModule *m, Entity *e, lbValue val) { + if (e != nullptr) { + map_set(&m->values, hash_entity(e), val); + } +} +void lb_add_member(lbModule *m, String const &name, lbValue val) { + if (name.len > 0) { + map_set(&m->members, hash_string(name), val); + } +} +void lb_add_member(lbModule *m, HashKey const &key, lbValue val) { + map_set(&m->members, key, val); +} + + +LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) { + unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name)); + return LLVMCreateEnumAttribute(ctx, kind, value); +} + +void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) { + LLVMContextRef ctx = LLVMGetModuleContext(p->module->mod); + LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, lb_create_enum_attribute(ctx, name, value)); +} + +void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) { + lb_add_proc_attribute_at_index(p, index, name, true); +} + + + lbProcedure *lb_create_procedure(lbModule *module, Entity *entity) { lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure); p->module = module; p->entity = entity; - p->name = entity->token.string; + p->name = lb_get_entity_name(module, entity); DeclInfo *decl = entity->decl_info; @@ -576,6 +573,8 @@ lbProcedure *lb_create_procedure(lbModule *module, Entity *entity) { Type *pt = base_type(entity->type); GB_ASSERT(pt->kind == Type_Proc); + set_procedure_abi_types(heap_allocator(), entity->type); + p->type = entity->type; p->type_expr = decl->type_expr; p->body = pl->body; @@ -588,30 +587,119 @@ lbProcedure *lb_create_procedure(lbModule *module, Entity *entity) { p->children.allocator = heap_allocator(); p->params.allocator = heap_allocator(); p->blocks.allocator = heap_allocator(); + p->branch_blocks.allocator = heap_allocator(); char *name = alloc_cstring(heap_allocator(), p->name); - LLVMTypeRef ret_type = LLVMFunctionType(LLVMVoidType(), nullptr, 0, false); + LLVMTypeRef func_ptr_type = lb_type(p->type); + LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type); + + p->value = LLVMAddFunction(module->mod, name, func_type); + lb_add_entity(module, entity, lbValue{p->value, p->type}); + lb_add_member(module, p->name, lbValue{p->value, p->type}); + + LLVMContextRef ctx = LLVMGetModuleContext(module->mod); + + // NOTE(bill): offset==0 is the return value + isize offset = 1; + if (pt->Proc.return_by_pointer) { + lb_add_proc_attribute_at_index(p, 1, "sret"); + lb_add_proc_attribute_at_index(p, 1, "noalias"); + offset = 2; + } + + isize parameter_index = 0; + if (pt->Proc.param_count) { + TypeTuple *params = &pt->Proc.params->Tuple; + for (isize i = 0; i < pt->Proc.param_count; i++, parameter_index++) { + Entity *e = params->variables[i]; + Type *original_type = e->type; + Type *abi_type = pt->Proc.abi_compat_params[i]; + if (e->kind != Entity_Variable) continue; + + if (i+1 == params->variables.count && pt->Proc.c_vararg) { + continue; + } + if (is_type_tuple(abi_type)) { + for_array(j, abi_type->Tuple.variables) { + Type *tft = abi_type->Tuple.variables[j]->type; + if (e->flags&EntityFlag_NoAlias) { + lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias"); + } + } + parameter_index += abi_type->Tuple.variables.count-1; + } else { + if (e->flags&EntityFlag_NoAlias) { + lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias"); + } + } + } + } + + if (pt->Proc.calling_convention == ProcCC_Odin) { + lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias"); + lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull"); + lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture"); + + } + + + return p; +} + +void lb_begin_procedure_body(lbProcedure *p) { + DeclInfo *decl = decl_info_of_entity(p->entity); + if (decl != nullptr) { + for_array(i, decl->labels) { + BlockLabel bl = decl->labels[i]; + lbBranchBlocks bb = {bl.label, nullptr, nullptr}; + array_add(&p->branch_blocks, bb); + } + } - p->value = LLVMAddFunction(module->mod, name, ret_type); p->builder = LLVMCreateBuilder(); p->decl_block = lb_create_block(p, "decls"); p->entry_block = lb_create_block(p, "entry"); p->curr_block = p->entry_block; - set_procedure_abi_types(heap_allocator(), p->type); - LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); - return p; + GB_ASSERT(p->type != nullptr); + + if (p->type->Proc.return_by_pointer) { + // NOTE(bill): this must be parameter 0 + Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results)); + Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("agg.result")), ptr_type, false, false); + e->flags |= EntityFlag_Sret | EntityFlag_NoAlias; + + lbValue return_ptr_value = {}; + return_ptr_value.value = LLVMGetParam(p->value, 0); + return_ptr_value.type = alloc_type_pointer(p->type->Proc.abi_compat_result_type); + p->return_ptr = lb_addr(return_ptr_value); + + lb_add_entity(p->module, e, return_ptr_value); + } + + } -void lb_end_procedure(lbProcedure *p) { +void lb_end_procedure_body(lbProcedure *p) { LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block); LLVMBuildBr(p->builder, p->entry_block->block); LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); + if (p->type->Proc.result_count == 0) { + LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block); + if (!LLVMIsAReturnInst(instr)) { + LLVMBuildRetVoid(p->builder); + } + } + + p->curr_block = nullptr; + +} +void lb_end_procedure(lbProcedure *p) { LLVMDisposeBuilder(p->builder); } @@ -638,9 +726,7 @@ lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr) { val.value = ptr; val.type = alloc_type_pointer(type); - if (e != nullptr) { - map_set(&p->module->values, hash_entity(e), val); - } + lb_add_entity(p->module, e, val); return lb_addr(val); } @@ -686,9 +772,13 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { } gen->info = &c->info; + gen->module.info = &c->info; gen->module.mod = LLVMModuleCreateWithName("odin_module"); map_init(&gen->module.values, heap_allocator()); + map_init(&gen->module.members, heap_allocator()); + map_init(&gen->module.const_strings, heap_allocator()); + map_init(&gen->module.const_string_byte_slices, heap_allocator()); global_module = &gen->module; @@ -726,6 +816,26 @@ lbValue lb_build_gep(lbProcedure *p, lbValue const &value, i32 index) { return lbValue{LLVMBuildStructGEP2(p->builder, lb_type(elem_type), value.value, index, ""), elem_type}; } +void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) { + TypeAndValue tv = type_and_value_of_expr(ws->cond); + GB_ASSERT(is_type_boolean(tv.type)); + GB_ASSERT(tv.value.kind == ExactValue_Bool); + if (tv.value.value_bool) { + lb_build_stmt_list(p, ws->body->BlockStmt.stmts); + } else if (ws->else_stmt) { + switch (ws->else_stmt->kind) { + case Ast_BlockStmt: + lb_build_stmt_list(p, ws->else_stmt->BlockStmt.stmts); + break; + case Ast_WhenStmt: + lb_build_when_stmt(p, &ws->else_stmt->WhenStmt); + break; + default: + GB_PANIC("Invalid 'else' statement in 'when' statement"); + break; + } + } +} void lb_build_stmt(lbProcedure *p, Ast *node) { switch (node->kind) { @@ -735,6 +845,11 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_ast_node(us, UsingStmt, node); case_end; + case_ast_node(ws, WhenStmt, node); + lb_build_when_stmt(p, ws); + case_end; + + case_ast_node(bs, BlockStmt, node); lb_build_stmt_list(p, bs->stmts); case_end; @@ -753,7 +868,69 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { } } - GB_ASSERT_MSG(!is_static, "handle static variables"); + if (is_static) { + for_array(i, vd->names) { + lbValue 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 = lb_const_value(p->module, ast_value->tav.type, ast_value->tav.value); + } + + Ast *ident = vd->names[i]; + GB_ASSERT(!is_blank_ident(ident)); + Entity *e = entity_of_ident(ident); + GB_ASSERT(e->flags & EntityFlag_Static); + String name = e->token.string; + + String mangled_name = {}; + { + gbString str = gb_string_make_length(heap_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); + } + + char *c_name = alloc_cstring(heap_allocator(), mangled_name); + + LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(e->type), c_name); + if (value.value != nullptr) { + LLVMSetInitializer(global, value.value); + } + if (e->Variable.thread_local_model != "") { + LLVMSetThreadLocal(global, true); + + String m = e->Variable.thread_local_model; + LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel; + if (m == "default") { + mode = LLVMGeneralDynamicTLSModel; + } else if (m == "localdynamic") { + mode = LLVMLocalDynamicTLSModel; + } else if (m == "initialexec") { + mode = LLVMInitialExecTLSModel; + } else if (m == "localexec") { + mode = LLVMLocalExecTLSModel; + } else { + GB_PANIC("Unhandled thread local mode %.*s", LIT(m)); + } + LLVMSetThreadLocalMode(global, mode); + } else { + LLVMSetLinkage(global, LLVMInternalLinkage); + } + + + lbValue global_val = {global, alloc_type_pointer(e->type)}; + lb_add_entity(p->module, e, global_val); + lb_add_member(p->module, mangled_name, global_val); + } + return; + } + + auto addrs = array_make(heap_allocator(), vd->names.count); @@ -765,9 +942,10 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { Ast *name = vd->names[i]; if (!is_blank_ident(name)) { Entity *e = entity_of_ident(name); - addrs[i] = lb_add_local(p, e->type, e); + lbAddr local = lb_add_local(p, e->type, e); + addrs[i] = local; if (vd->values.count == 0) { - lb_addr_store(p, addrs[i], lb_constant_nil(lb_addr_type(addrs[i]))); + lb_addr_store(p, addrs[i], lb_const_nil(lb_addr_type(addrs[i]))); } } } @@ -785,12 +963,80 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { for_array(i, values) { lb_addr_store(p, addrs[i], values[i]); } + case_end; + + case_ast_node(as, AssignStmt, node); + case_end; + + case_ast_node(es, ExprStmt, node); + lb_build_expr(p, es->expr); + case_end; + + case_ast_node(ds, DeferStmt, node); + case_end; + + case_ast_node(rs, ReturnStmt, node); + lbValue res = {}; + + TypeTuple *tuple = &p->type->Proc.results->Tuple; + isize return_count = p->type->Proc.result_count; + isize res_count = rs->results.count; + + if (return_count == 0) { + // No return values + LLVMBuildRetVoid(p->builder); + return; + } else if (return_count == 1) { + Entity *e = tuple->variables[0]; + if (res_count == 0) { + // lbValue *found = map_get(&p->module->values, hash_entity(e)); + // GB_ASSERT(found); + // res = lb_emit_load(p, *found); + } else { + res = lb_build_expr(p, rs->results[0]); + // res = ir_emit_conv(p, v, e->type); + } + } else { + + } + + if (p->type->Proc.return_by_pointer) { + if (res.value != nullptr) { + lb_addr_store(p, p->return_ptr, res); + } else { + lb_addr_store(p, p->return_ptr, lb_const_nil(p->type->Proc.abi_compat_result_type)); + } + LLVMBuildRetVoid(p->builder); + } else { + GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name)); + LLVMBuildRet(p->builder, res.value); + } + case_end; + + case_ast_node(is, IfStmt, node); + case_end; + case_ast_node(fs, ForStmt, node); + case_end; + + case_ast_node(rs, RangeStmt, node); + case_end; + + case_ast_node(rs, InlineRangeStmt, node); + case_end; + + case_ast_node(ss, SwitchStmt, node); + case_end; + + case_ast_node(ss, TypeSwitchStmt, node); + case_end; + + case_ast_node(bs, BranchStmt, node); case_end; } } -lbValue lb_constant_nil(Type *type) { +lbValue lb_const_nil(Type *type) { LLVMValueRef v = LLVMConstNull(lb_type(type)); return lbValue{v, type}; } @@ -801,19 +1047,212 @@ LLVMValueRef llvm_const_f32(f32 f, Type *type=t_f32) { return LLVMConstBitCast(i, lb_type(type)); } -lbValue lb_constant_value(lbModule *m, Type *type, ExactValue const &value) { + +lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) { + HashKey key = hash_string(str); + lbValue *found = map_get(&m->const_strings, key); + if (found != nullptr) { + return *found; + } + lbValue v = lb_const_value(m, t_string, exact_value_string(str)); + map_set(&m->const_strings, key, v); + return v; +} + +lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) { + HashKey key = hash_string(str); + lbValue *found = map_get(&m->const_string_byte_slices, key); + if (found != nullptr) { + return *found; + } + Type *t = t_u8_slice; + lbValue v = lb_const_value(m, t, exact_value_string(str)); + map_set(&m->const_string_byte_slices, key, v); + return v; +} + +isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) { + isize index = type_info_index(info, type, false); + if (index >= 0) { + auto *set = &info->minimum_dependency_type_info_set; + for_array(i, set->entries) { + if (set->entries[i].ptr == index) { + return i+1; + } + } + } + if (err_on_not_found) { + GB_PANIC("NOT FOUND ir_type_info_index %s @ index %td", type_to_string(type), index); + } + return -1; +} + +lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type=t_typeid) { + type = default_type(type); + + u64 id = cast(u64)lb_type_info_index(m->info, type); + GB_ASSERT(id >= 0); + + u64 kind = Typeid_Invalid; + u64 named = is_type_named(type) && type->kind != Type_Basic; + u64 special = 0; + u64 reserved = 0; + + Type *bt = base_type(type); + TypeKind tk = bt->kind; + switch (tk) { + case Type_Basic: { + u32 flags = bt->Basic.flags; + if (flags & BasicFlag_Boolean) kind = Typeid_Boolean; + if (flags & BasicFlag_Integer) kind = Typeid_Integer; + if (flags & BasicFlag_Unsigned) kind = Typeid_Integer; + if (flags & BasicFlag_Float) kind = Typeid_Float; + if (flags & BasicFlag_Complex) kind = Typeid_Complex; + if (flags & BasicFlag_Pointer) kind = Typeid_Pointer; + if (flags & BasicFlag_String) kind = Typeid_String; + if (flags & BasicFlag_Rune) kind = Typeid_Rune; + } break; + case Type_Pointer: kind = Typeid_Pointer; break; + case Type_Array: kind = Typeid_Array; 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_BitField: kind = Typeid_Bit_Field; break; + case Type_BitSet: kind = Typeid_Bit_Set; break; + } + + if (is_type_cstring(type)) { + special = 1; + } else if (is_type_integer(type) && !is_type_unsigned(type)) { + special = 1; + } + + u64 data = 0; + if (build_context.word_size == 4) { + data |= (id &~ (1u<<24)) << 0u; // index + data |= (kind &~ (1u<<5)) << 24u; // kind + data |= (named &~ (1u<<1)) << 29u; // kind + data |= (special &~ (1u<<1)) << 30u; // kind + data |= (reserved &~ (1u<<1)) << 31u; // kind + } else { + GB_ASSERT(build_context.word_size == 8); + data |= (id &~ (1ull<<56)) << 0ul; // index + data |= (kind &~ (1ull<<5)) << 56ull; // kind + data |= (named &~ (1ull<<1)) << 61ull; // kind + data |= (special &~ (1ull<<1)) << 62ull; // kind + data |= (reserved &~ (1ull<<1)) << 63ull; // kind + } + + + lbValue res = {}; + res.value = LLVMConstInt(lb_type(typeid_type), data, false); + res.type = typeid_type; + return res; +} + +lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { + Type *original_type = type; + lbValue res = {}; res.type = type; + type = core_type(type); + value = convert_exact_value_for_type(value, type); + + if (is_type_slice(type)) { + if (value.kind == ExactValue_String) { + GB_ASSERT(is_type_u8_slice(type)); + res.value = lb_find_or_add_entity_string_byte_slice(m, value.value_string).value; + return res; + } else { + ast_node(cl, CompoundLit, value.value_compound); + + isize count = cl->elems.count; + if (count == 0) { + return lb_const_nil(type); + } + count = gb_max(cl->max_count, count); + Type *elem = base_type(type)->Slice.elem; + Type *t = alloc_type_array(elem, count); + lbValue backing_array = lb_const_value(m, t, value); + + + isize max_len = 7+8+1; + u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len); + isize len = gb_snprintf(cast(char *)str, max_len, "csba$%x", m->global_array_index); + m->global_array_index++; + + String name = make_string(str, len-1); + + Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value); + LLVMValueRef global_data = LLVMAddGlobal(m->mod, lb_type(t), cast(char const *)str); + LLVMSetInitializer(global_data, backing_array.value); + + lbValue g = {}; + g.value = global_data; + g.type = t; + + lb_add_entity(m, e, g); + lb_add_member(m, name, g); + + { + LLVMValueRef indices[2] = {lb_zero32, lb_zero32}; + LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); + LLVMValueRef len = LLVMConstInt(lb_type(t_int), count, true); + LLVMValueRef values[2] = {ptr, len}; + + res.value = LLVMConstNamedStruct(lb_type(original_type), values, 2); + return res; + } + + } + } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) { + LLVMValueRef data = LLVMConstString(cast(char const *)value.value_string.text, + cast(unsigned)value.value_string.len, + false); + res.value = data; + return res; + } else if (is_type_array(type) && + value.kind != ExactValue_Invalid && + value.kind != ExactValue_String && + value.kind != ExactValue_Compound) { + + i64 count = type->Array.count; + Type *elem = type->Array.elem; + + + lbValue single_elem = lb_const_value(m, elem, value); + + LLVMValueRef *elems = gb_alloc_array(heap_allocator(), LLVMValueRef, count); + for (i64 i = 0; i < count; i++) { + elems[i] = single_elem.value; + } + + res.value = LLVMConstArray(lb_type(elem), elems, cast(unsigned)count); + return res; + } switch (value.kind) { case ExactValue_Invalid: - res.value = LLVMConstNull(lb_type(type)); + res.value = LLVMConstNull(lb_type(original_type)); return res; case ExactValue_Bool: - res.value = LLVMConstInt(lb_type(type), value.value_bool, false); + res.value = LLVMConstInt(lb_type(original_type), value.value_bool, false); return res; case ExactValue_String: { + HashKey key = hash_string(value.value_string); + lbValue *found = map_get(&m->const_strings, key); + if (found != nullptr) { + res.value = found->value; + return res; + } + LLVMValueRef indices[2] = {lb_zero32, lb_zero32}; LLVMValueRef data = LLVMConstString(cast(char const *)value.value_string.text, cast(unsigned)value.value_string.len, @@ -831,12 +1270,20 @@ lbValue lb_constant_value(lbModule *m, Type *type, ExactValue const &value) { LLVMValueRef len = LLVMConstInt(lb_type(t_int), value.value_string.len, true); LLVMValueRef values[2] = {ptr, len}; - res.value = LLVMConstNamedStruct(lb_type(type), values, 2); + res.value = LLVMConstNamedStruct(lb_type(original_type), values, 2); + + map_set(&m->const_strings, key, res); + return res; } case ExactValue_Integer: - res.value = LLVMConstIntOfArbitraryPrecision(lb_type(type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); + if (is_type_pointer(type)) { + LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); + res.value = LLVMConstBitCast(i, lb_type(original_type)); + } else { + res.value = LLVMConstIntOfArbitraryPrecision(lb_type(original_type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); + } return res; case ExactValue_Float: if (type_size_of(type) == 4) { @@ -844,7 +1291,7 @@ lbValue lb_constant_value(lbModule *m, Type *type, ExactValue const &value) { res.value = llvm_const_f32(f, type); return res; } - res.value = LLVMConstReal(lb_type(type), value.value_float); + res.value = LLVMConstReal(lb_type(original_type), value.value_float); return res; case ExactValue_Complex: { @@ -860,7 +1307,7 @@ lbValue lb_constant_value(lbModule *m, Type *type, ExactValue const &value) { break; } - res.value = LLVMConstNamedStruct(lb_type(type), values, 2); + res.value = LLVMConstNamedStruct(lb_type(original_type), values, 2); return res; } break; @@ -884,38 +1331,335 @@ lbValue lb_constant_value(lbModule *m, Type *type, ExactValue const &value) { break; } - res.value = LLVMConstNamedStruct(lb_type(type), values, 4); + res.value = LLVMConstNamedStruct(lb_type(original_type), values, 4); return res; } break; case ExactValue_Pointer: - res.value = LLVMConstBitCast(LLVMConstInt(lb_type(t_uintptr), value.value_pointer, false), lb_type(type)); + res.value = LLVMConstBitCast(LLVMConstInt(lb_type(t_uintptr), value.value_pointer, false), lb_type(original_type)); return res; case ExactValue_Compound: - GB_PANIC("ExactValue_Compound"); + if (is_type_slice(type)) { + return lb_const_value(m, type, value); + } else if (is_type_array(type)) { + ast_node(cl, CompoundLit, value.value_compound); + Type *elem_type = type->Array.elem; + isize elem_count = cl->elems.count; + if (elem_count == 0) { + return lb_const_nil(original_type); + } + if (cl->elems[0]->kind == Ast_FieldValue) { + // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand + + LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count); + defer (gb_free(heap_allocator(), values)); + + isize value_index = 0; + for (i64 i = 0; i < type->Array.count; i++) { + bool found = false; + + for (isize j = 0; j < elem_count; j++) { + Ast *elem = cl->elems[j]; + 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_Ellipsis) { + hi += 1; + } + if (lo == i) { + TypeAndValue tav = fv->value->tav; + if (tav.mode != Addressing_Constant) { + break; + } + LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value; + for (i64 k = lo; k < hi; k++) { + values[value_index++] = val; + } + + found = true; + i += (hi-lo-1); + break; + } + } else { + TypeAndValue index_tav = fv->field->tav; + GB_ASSERT(index_tav.mode == Addressing_Constant); + i64 index = exact_value_to_i64(index_tav.value); + if (index == i) { + TypeAndValue tav = fv->value->tav; + if (tav.mode != Addressing_Constant) { + break; + } + LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value; + values[value_index++] = val; + found = true; + break; + } + } + } + + if (!found) { + values[value_index++] = LLVMConstNull(lb_type(elem_type)); + } + } + + res.value = LLVMConstArray(lb_type(elem_type), values, cast(unsigned int)type->Array.count); + return res; + } else { + GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count); + + LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->Array.count); + defer (gb_free(heap_allocator(), values)); + + for (isize i = 0; i < elem_count; i++) { + TypeAndValue tav = cl->elems[i]->tav; + GB_ASSERT(tav.mode != Addressing_Invalid); + values[i] = lb_const_value(m, elem_type, tav.value).value; + } + for (isize i = elem_count; i < type->Array.count; i++) { + values[i] = LLVMConstNull(lb_type(elem_type)); + } + + res.value = LLVMConstArray(lb_type(elem_type), values, cast(unsigned int)type->Array.count); + return res; + } + } else if (is_type_enumerated_array(type)) { + ast_node(cl, CompoundLit, value.value_compound); + Type *elem_type = type->EnumeratedArray.elem; + isize elem_count = cl->elems.count; + if (elem_count == 0) { + return lb_const_nil(original_type); + } + if (cl->elems[0]->kind == Ast_FieldValue) { + // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand + + LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count); + defer (gb_free(heap_allocator(), values)); + + isize value_index = 0; + + i64 total_lo = exact_value_to_i64(type->EnumeratedArray.min_value); + i64 total_hi = exact_value_to_i64(type->EnumeratedArray.max_value); + + for (i64 i = total_lo; i <= total_hi; i++) { + bool found = false; + + for (isize j = 0; j < elem_count; j++) { + Ast *elem = cl->elems[j]; + 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_Ellipsis) { + hi += 1; + } + if (lo == i) { + TypeAndValue tav = fv->value->tav; + if (tav.mode != Addressing_Constant) { + break; + } + LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value; + for (i64 k = lo; k < hi; k++) { + values[value_index++] = val; + } + + found = true; + i += (hi-lo-1); + break; + } + } else { + TypeAndValue index_tav = fv->field->tav; + GB_ASSERT(index_tav.mode == Addressing_Constant); + i64 index = exact_value_to_i64(index_tav.value); + if (index == i) { + TypeAndValue tav = fv->value->tav; + if (tav.mode != Addressing_Constant) { + break; + } + LLVMValueRef val = lb_const_value(m, elem_type, tav.value).value; + values[value_index++] = val; + found = true; + break; + } + } + } + + if (!found) { + values[value_index++] = LLVMConstNull(lb_type(elem_type)); + } + } + + res.value = LLVMConstArray(lb_type(elem_type), values, cast(unsigned int)type->EnumeratedArray.count); + return res; + } else { + GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count); + + LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, type->EnumeratedArray.count); + defer (gb_free(heap_allocator(), values)); + + for (isize i = 0; i < elem_count; i++) { + TypeAndValue tav = cl->elems[i]->tav; + GB_ASSERT(tav.mode != Addressing_Invalid); + values[i] = lb_const_value(m, elem_type, tav.value).value; + } + for (isize i = elem_count; i < type->EnumeratedArray.count; i++) { + values[i] = LLVMConstNull(lb_type(elem_type)); + } + + res.value = LLVMConstArray(lb_type(elem_type), values, cast(unsigned int)type->EnumeratedArray.count); + return res; + } + } else if (is_type_simd_vector(type)) { + ast_node(cl, CompoundLit, value.value_compound); + + Type *elem_type = type->SimdVector.elem; + isize elem_count = cl->elems.count; + if (elem_count == 0) { + return lb_const_nil(original_type); + } + + isize total_elem_count = type->SimdVector.count; + LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, total_elem_count); + defer (gb_free(heap_allocator(), values)); + + for (isize i = 0; i < elem_count; i++) { + TypeAndValue tav = cl->elems[i]->tav; + GB_ASSERT(tav.mode != Addressing_Invalid); + values[i] = lb_const_value(m, elem_type, tav.value).value; + } + for (isize i = elem_count; i < type->SimdVector.count; i++) { + values[i] = LLVMConstNull(lb_type(elem_type)); + } + + res.value = LLVMConstVector(values, cast(unsigned)total_elem_count); + return res; + } else if (is_type_struct(type)) { + ast_node(cl, CompoundLit, value.value_compound); + + if (cl->elems.count == 0) { + return lb_const_nil(type); + } + + isize offset = 0; + if (type->Struct.custom_align > 0) { + offset = 1; + } + + isize value_count = type->Struct.fields.count + offset; + LLVMValueRef *values = gb_alloc_array(heap_allocator(), LLVMValueRef, value_count); + bool *visited = gb_alloc_array(heap_allocator(), bool, value_count); + defer (gb_free(heap_allocator(), values)); + defer (gb_free(heap_allocator(), visited)); + + + + 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; + + TypeAndValue tav = fv->value->tav; + GB_ASSERT(tav.mode != Addressing_Invalid); + + Selection sel = lookup_field(type, name, false); + Entity *f = type->Struct.fields[sel.index[0]]; + + values[offset+f->Variable.field_index] = lb_const_value(m, f->type, tav.value).value; + visited[offset+f->Variable.field_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; + } + values[offset+f->Variable.field_index] = lb_const_value(m, f->type, val).value; + visited[offset+f->Variable.field_index] = true; + } + } + } + + for (isize i = 0; i < type->Struct.fields.count; i++) { + if (!visited[offset+i]) { + GB_ASSERT(values[offset+i] == nullptr); + values[offset+i] = lb_const_nil(type->Struct.fields[i]->type).value; + } + } + + if (type->Struct.custom_align > 0) { + values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(type->Struct.custom_align)); + } + + res.value = LLVMConstNamedStruct(lb_type(original_type), values, cast(unsigned)value_count); + return res; + } else if (is_type_bit_set(type)) { + ast_node(cl, CompoundLit, value.value_compound); + if (cl->elems.count == 0) { + return lb_const_nil(original_type); + } + + i64 sz = type_size_of(type); + if (sz == 0) { + return lb_const_nil(original_type); + } + + u64 bits = 0; + 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 = type->BitSet.lower; + bits |= 1ull< slice"); - } - - return lb_constant_value(m, type, value); + return lb_const_nil(original_type); } lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) { @@ -1048,21 +1792,8 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { GB_ASSERT(tv.mode != Addressing_Type); if (tv.value.kind != ExactValue_Invalid) { - // // NOTE(bill): Edge case - // if (tv.value.kind != ExactValue_Compound && - // is_type_array(tv.type)) { - // Type *elem = core_array_type(tv.type); - // ExactValue value = convert_exact_value_for_type(tv.value, elem); - // irValue *x = ir_add_module_constant(proc->module, elem, value); - // return ir_emit_conv(proc, x, tv.type); - // } - - // if (tv.value.kind == ExactValue_Typeid) { - // irValue *v = ir_typeid(proc->module, tv.value.value_typeid); - // return ir_emit_conv(proc, v, tv.type); - // } - - return lb_add_module_constant(p->module, tv.type, tv.value); + // NOTE(bill): Short on constant values + return lb_const_value(p->module, tv.type, tv.value); } @@ -1077,9 +1808,10 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { GB_PANIC("Non-constant basic literal %.*s(%td:%td) - %.*s", LIT(pos.file), pos.line, pos.column, LIT(bd->name)); case_end; - // case_ast_node(i, Implicit, expr); - // return ir_addr_load(proc, ir_build_addr(proc, expr)); - // case_end; + case_ast_node(i, Implicit, expr); + // return ir_addr_load(proc, ir_build_addr(proc, expr)); + GB_PANIC("TODO(bill): Implicit"); + case_end; case_ast_node(u, Undef, expr); return lbValue{LLVMGetUndef(lb_type(tv.type)), tv.type}; @@ -1095,7 +1827,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { LIT(token.pos.file), token.pos.line, token.pos.column); return {}; } else if (e->kind == Entity_Nil) { - return lb_constant_nil(tv.type); + return lb_const_nil(tv.type); } auto *found = map_get(&p->module->values, hash_entity(e)); @@ -1105,7 +1837,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { if (kind == LLVMFunctionTypeKind) { return v; } - return lbValue{LLVMBuildLoad2(p->builder, lb_type(type_deref(v.type)), v.value, ""), e->type}; + return lb_emit_load(p, v); // } else if (e != nullptr && e->kind == Entity_Variable) { // return ir_addr_load(proc, ir_build_addr(proc, expr)); } @@ -1125,6 +1857,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { void lb_generate_module(lbGenerator *gen) { + lbModule *m = &gen->module; LLVMModuleRef mod = gen->module.mod; CheckerInfo *info = gen->info; @@ -1136,9 +1869,6 @@ void lb_generate_module(lbGenerator *gen) { auto *min_dep_set = &info->minimum_dependency_set; - - - for_array(i, info->entities) { // arena_free_all(&temp_arena); // gbAllocator a = temp_allocator; @@ -1180,40 +1910,33 @@ void lb_generate_module(lbGenerator *gen) { continue; } + String mangled_name = lb_get_entity_name(m, e); - if (entry_point == e) { - lbProcedure *p = lb_create_procedure(&gen->module, e); + if (e->pkg->name != "demo") { + continue; + } - if (p->body != nullptr) { // Build Procedure + switch (e->kind) { + case Entity_TypeName: + break; + case Entity_Procedure: + break; + } - lb_build_stmt(p, p->body); - LLVMBuildRet(p->builder, nullptr); - // LLVMBuildRetVoid(p->builder); + if (e->kind == Entity_Procedure) { + lbProcedure *p = lb_create_procedure(m, e); + + if (p->body != nullptr) { // Build Procedure + lb_begin_procedure_body(p); + lb_build_stmt(p, p->body); + lb_end_procedure_body(p); } lb_end_procedure(p); } } - { - LLVMTypeRef ret_type = LLVMFunctionType(LLVMVoidType(), nullptr, 0, false); - - LLVMValueRef p = LLVMAddFunction(mod, "mainCRTStartup", ret_type); - - - LLVMBasicBlockRef entry = LLVMAppendBasicBlock(p, "entry"); - - LLVMBuilderRef b = LLVMCreateBuilder(); - defer (LLVMDisposeBuilder(b)); - - LLVMPositionBuilderAtEnd(b, entry); - - - LLVMBuildRetVoid(b); - // LLVMBuildRet(b, nullptr); - } - char *llvm_error = nullptr; defer (LLVMDisposeMessage(llvm_error)); diff --git a/src/types.cpp b/src/types.cpp index 822583fee..a6f1e2ae5 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -305,6 +305,34 @@ struct Type { bool failure; }; +// IMPORTANT NOTE(bill): This must match the same as the in core.odin +enum Typeid_Kind : u8 { + Typeid_Invalid, + Typeid_Integer, + Typeid_Rune, + Typeid_Float, + Typeid_Complex, + Typeid_Quaternion, + Typeid_String, + Typeid_Boolean, + Typeid_Any, + Typeid_Type_Id, + Typeid_Pointer, + Typeid_Procedure, + Typeid_Array, + Typeid_Enumerated_Array, + Typeid_Dynamic_Array, + Typeid_Slice, + Typeid_Tuple, + Typeid_Struct, + Typeid_Union, + Typeid_Enum, + Typeid_Map, + Typeid_Bit_Field, + Typeid_Bit_Set, +}; + + // TODO(bill): Should I add extra information here specifying the kind of selection? -- cgit v1.2.3 From 0103cedad7b18d2f8ac2337fd4221e874eb2e1ca Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 2 Feb 2020 23:36:15 +0000 Subject: Port code for lb_build_call_expr --- examples/llvm-demo/demo.odin | 56 +++--- src/llvm_backend.cpp | 429 +++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 435 insertions(+), 50 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/examples/llvm-demo/demo.odin b/examples/llvm-demo/demo.odin index 3b8953134..58bb10682 100644 --- a/examples/llvm-demo/demo.odin +++ b/examples/llvm-demo/demo.odin @@ -1,45 +1,39 @@ package demo -import "core:os" - -// Foo :: struct { -// x, y: int, -// }; -// foo :: proc(x: int) -> (f: Foo) { -// return; -// } +BarBar :: struct { + x, y: int, +}; +foo :: proc(x: int) -> (b: BarBar) { + return; +} main :: proc() { Foo :: enum {A=1, B, C, D}; Foo_Set :: bit_set[Foo]; - x := Foo_Set{.A, .C}; + foo_set := Foo_Set{.A, .C}; - y := [4]int{3 = 1, 0 .. 1 = 3, 2 = 9}; - z := []int{1, 2, 3, 4}; + array := [4]int{3 = 1, 0 .. 1 = 3, 2 = 9}; + slice := []int{1, 2, 3, 4}; - // @thread_local a: int; + @thread_local a: int; - // x := i32(1); - // y := i32(2); - // z := x + y; - // w := z - 2; + x := i32(1); + y := i32(2); + z := x + y; + w := z - 2; - // foo(123); + f := foo; + c := 1 + 2i; + q := 1 + 2i + 3j + 4k; - // c := 1 + 2i; - // q := 1 + 2i + 3j + 4k; + s := "Hellope"; - // s := "Hellope"; - - // f := Foo{1, 2}; - // pc: proc "contextless" (x: i32) -> Foo; - // po: proc "odin" (x: i32) -> Foo; - // e: enum{A, B, C}; - // u: union{i32, bool}; - // u1: union{i32}; - // um: union #maybe {^int}; - - // os.write_string(os.stdout, "Hellope\n"); - return; + bb := BarBar{1, 2}; + pc: proc "contextless" (x: i32) -> BarBar; + po: proc "odin" (x: i32) -> BarBar; + e: enum{A, B, C}; + u: union{i32, bool}; + u1: union{i32}; + um: union #maybe {^int}; } diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index c818051d0..a3ac6dcea 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -27,6 +27,11 @@ void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue const &value) { } +void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) { + GB_ASSERT(value.value != nullptr); + LLVMValueRef v = LLVMBuildStore(p->builder, value.value, ptr.value); +} + lbValue lb_emit_load(lbProcedure *p, lbValue value) { GB_ASSERT(value.value != nullptr); Type *t = type_deref(value.type); @@ -99,14 +104,25 @@ String lb_mangle_name(lbModule *m, Entity *e) { return make_string(new_name, new_name_len-1); } -String lb_get_entity_name(lbModule *m, Entity *e, String name) { +String lb_get_entity_name(lbModule *m, Entity *e, String default_name) { if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) { return e->TypeName.ir_mangled_name; } + String name = {}; bool no_name_mangle = false; + if (e->kind == Entity_Variable) { + bool is_foreign = e->Variable.is_foreign; + bool is_export = e->Variable.is_export; + no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export; + } else if (e->kind == Entity_Procedure && e->Procedure.is_export) { + no_name_mangle = true; + } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) { + no_name_mangle = true; + } + if (!no_name_mangle) { name = lb_mangle_name(m, e); } @@ -116,8 +132,10 @@ String lb_get_entity_name(lbModule *m, Entity *e, String name) { if (e != nullptr && e->kind == Entity_TypeName) { e->TypeName.ir_mangled_name = name; - + } else if (e != nullptr && e->kind == Entity_Procedure) { + e->Procedure.link_name = name; } + return name; } @@ -519,6 +537,8 @@ LLVMTypeRef lb_type_internal(Type *type) { } LLVMTypeRef lb_type(Type *type) { + type = default_type(type); + if (type->llvm_type) { return type->llvm_type; } @@ -726,11 +746,20 @@ lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr) { val.value = ptr; val.type = alloc_type_pointer(type); - lb_add_entity(p->module, e, val); + if (e != nullptr) { + lb_add_entity(p->module, e, val); + } return lb_addr(val); } +lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) { + lbAddr addr = lb_add_local(p, type, nullptr); + lb_addr_store(p, addr, lb_const_nil(type)); + return addr; +} + + bool lb_init_generator(lbGenerator *gen, Checker *c) { if (global_error_collector.count != 0) { @@ -994,7 +1023,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { // res = lb_emit_load(p, *found); } else { res = lb_build_expr(p, rs->results[0]); - // res = ir_emit_conv(p, v, e->type); + res = lb_emit_conv(p, res, e->type); } } else { @@ -1041,6 +1070,13 @@ lbValue lb_const_nil(Type *type) { return lbValue{v, type}; } +lbValue lb_const_int(Type *type, u64 value) { + lbValue res = {}; + res.value = LLVMConstInt(lb_type(type), value, !is_type_unsigned(type)); + res.type = type; + return res; +} + LLVMValueRef llvm_const_f32(f32 f, Type *type=t_f32) { u32 u = bit_cast(f); LLVMValueRef i = LLVMConstInt(LLVMInt32Type(), u, false); @@ -1048,6 +1084,8 @@ LLVMValueRef llvm_const_f32(f32 f, Type *type=t_f32) { } + + lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) { HashKey key = hash_string(str); lbValue *found = map_get(&m->const_strings, key); @@ -1662,6 +1700,31 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { return lb_const_nil(original_type); } +u64 lb_generate_source_code_location_hash(TokenPos const &pos) { + u64 h = 0xcbf29ce484222325; + for (isize i = 0; i < pos.file.len; i++) { + h = (h ^ u64(pos.file[i])) * 0x100000001b3; + } + h = h ^ (u64(pos.line) * 0x100000001b3); + h = h ^ (u64(pos.column) * 0x100000001b3); + return h; +} + +lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) { + LLVMValueRef fields[5] = {}; + fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value; + fields[1]/*line*/ = lb_const_int(t_int, pos.line).value; + fields[2]/*column*/ = lb_const_int(t_int, pos.column).value; + fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value; + fields[4]/*hash*/ = lb_const_int(t_u64, lb_generate_source_code_location_hash(pos)).value; + + lbValue res = {}; + res.value = LLVMConstNamedStruct(lb_type(t_source_code_location), fields, 5); + res.type = t_source_code_location; + return res; +} + + lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) { lbValue res = {}; res.type = type; @@ -1784,6 +1847,339 @@ lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { return {}; } +lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { + // TODO(bill): lb_emit_conv + return value; +} + +lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false) { + return {}; +} + +lbValue lb_emit_ev(lbProcedure *p, lbValue value, i32 index) { + return {}; +} + +lbValue lb_emit_array_epi(lbProcedure *p, lbValue value, i32 index){ + return {}; +} + +void lb_fill_slice(lbProcedure *p, lbAddr slice, lbValue base_elem, lbValue len) { + +} + + +lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { + TypeAndValue tv = type_and_value_of_expr(expr); + + ast_node(ce, CallExpr, 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); + lbValue x = lb_build_expr(p, ce->args[0]); + lbValue y = lb_emit_conv(p, x, tv.type); + return y; + } + + Ast *pexpr = unparen_expr(ce->proc); + if (proc_mode == Addressing_Builtin) { + Entity *e = entity_of_node(pexpr); + BuiltinProcId id = BuiltinProc_Invalid; + if (e != nullptr) { + id = cast(BuiltinProcId)e->Builtin.id; + } else { + id = BuiltinProc_DIRECTIVE; + } + GB_PANIC("lb_build_builtin_proc"); + // return lb_build_builtin_proc(p, expr, tv, id); + } + + // NOTE(bill): Regular call + lbValue value = {}; + Ast *proc_expr = unparen_expr(ce->proc); + 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); + lbValue x = {}; + x.value = LLVMConstInt(lb_type(t_uintptr), u, false); + x.type = t_uintptr; + x = lb_emit_conv(p, x, t_rawptr); + value = lb_emit_conv(p, x, proc_expr->tav.type); + break; + } + case ExactValue_Pointer: + { + u64 u = cast(u64)v.value_pointer; + lbValue x = {}; + x.value = LLVMConstInt(lb_type(t_uintptr), u, false); + x.type = t_uintptr; + x = lb_emit_conv(p, x, t_rawptr); + value = lb_emit_conv(p, x, proc_expr->tav.type); + break; + } + } + } + + if (value.value == nullptr) { + value = lb_build_expr(p, proc_expr); + } + + GB_ASSERT(value.value != nullptr); + Type *proc_type_ = base_type(value.type); + GB_ASSERT(proc_type_->kind == Type_Proc); + TypeProc *pt = &proc_type_->Proc; + set_procedure_abi_types(heap_allocator(), proc_type_); + + if (is_call_expr_field_value(ce)) { + auto args = array_make(heap_allocator(), pt->param_count); + + for_array(arg_index, ce->args) { + Ast *arg = ce->args[arg_index]; + ast_node(fv, FieldValue, arg); + GB_ASSERT(fv->field->kind == Ast_Ident); + String name = fv->field->Ident.token.string; + isize index = lookup_procedure_parameter(pt, name); + GB_ASSERT(index >= 0); + TypeAndValue tav = type_and_value_of_expr(fv->value); + if (tav.mode == Addressing_Type) { + args[index] = lb_const_nil(tav.type); + } else { + args[index] = lb_build_expr(p, fv->value); + } + } + TypeTuple *params = &pt->params->Tuple; + for (isize i = 0; i < args.count; i++) { + Entity *e = params->variables[i]; + if (e->kind == Entity_TypeName) { + args[i] = lb_const_nil(e->type); + } else if (e->kind == Entity_Constant) { + continue; + } else { + GB_ASSERT(e->kind == Entity_Variable); + if (args[i].value == nullptr) { + switch (e->Variable.param_value.kind) { + case ParameterValue_Constant: + args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value); + break; + case ParameterValue_Nil: + args[i] = lb_const_nil(e->type); + break; + case ParameterValue_Location: + args[i] = lb_emit_source_code_location(p, p->entity->token.string, ast_token(expr).pos); + break; + case ParameterValue_Value: + args[i] = lb_build_expr(p, e->Variable.param_value.ast_value); + break; + } + } else { + args[i] = lb_emit_conv(p, args[i], e->type); + } + } + } + + return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr); + } + + isize arg_index = 0; + + isize arg_count = 0; + for_array(i, ce->args) { + Ast *arg = ce->args[i]; + TypeAndValue tav = type_and_value_of_expr(arg); + GB_ASSERT_MSG(tav.mode != Addressing_Invalid, "%s %s", expr_to_string(arg), expr_to_string(expr)); + GB_ASSERT_MSG(tav.mode != Addressing_ProcGroup, "%s", expr_to_string(arg)); + Type *at = tav.type; + if (at->kind == Type_Tuple) { + arg_count += at->Tuple.variables.count; + } else { + arg_count++; + } + } + + isize param_count = 0; + if (pt->params) { + GB_ASSERT(pt->params->kind == Type_Tuple); + param_count = pt->params->Tuple.variables.count; + } + + auto args = array_make(heap_allocator(), cast(isize)gb_max(param_count, arg_count)); + isize variadic_index = pt->variadic_index; + bool variadic = pt->variadic && variadic_index >= 0; + bool vari_expand = ce->ellipsis.pos.line != 0; + bool is_c_vararg = pt->c_vararg; + + String proc_name = {}; + if (p->entity != nullptr) { + proc_name = p->entity->token.string; + } + TokenPos pos = ast_token(ce->proc).pos; + + TypeTuple *param_tuple = nullptr; + if (pt->params) { + GB_ASSERT(pt->params->kind == Type_Tuple); + param_tuple = &pt->params->Tuple; + } + + for_array(i, ce->args) { + Ast *arg = ce->args[i]; + TypeAndValue arg_tv = type_and_value_of_expr(arg); + if (arg_tv.mode == Addressing_Type) { + args[arg_index++] = lb_const_nil(arg_tv.type); + } else { + lbValue a = lb_build_expr(p, arg); + Type *at = a.type; + if (at->kind == Type_Tuple) { + for_array(i, at->Tuple.variables) { + Entity *e = at->Tuple.variables[i]; + lbValue v = lb_emit_ev(p, a, cast(i32)i); + args[arg_index++] = v; + } + } else { + args[arg_index++] = a; + } + } + } + + + if (param_count > 0) { + GB_ASSERT_MSG(pt->params != nullptr, "%s %td", expr_to_string(expr), pt->param_count); + GB_ASSERT(param_count < 1000000); + + if (arg_count < param_count) { + isize end = cast(isize)param_count; + if (variadic) { + end = variadic_index; + } + while (arg_index < end) { + Entity *e = param_tuple->variables[arg_index]; + GB_ASSERT(e->kind == Entity_Variable); + + switch (e->Variable.param_value.kind) { + case ParameterValue_Constant: + args[arg_index++] = lb_const_value(p->module, e->type, e->Variable.param_value.value); + break; + case ParameterValue_Nil: + args[arg_index++] = lb_const_nil(e->type); + break; + case ParameterValue_Location: + args[arg_index++] = lb_emit_source_code_location(p, proc_name, pos); + break; + case ParameterValue_Value: + args[arg_index++] = lb_build_expr(p, e->Variable.param_value.ast_value); + break; + } + } + } + + if (is_c_vararg) { + GB_ASSERT(variadic); + GB_ASSERT(!vari_expand); + isize i = 0; + for (; i < variadic_index; i++) { + Entity *e = param_tuple->variables[i]; + if (e->kind == Entity_Variable) { + args[i] = lb_emit_conv(p, args[i], e->type); + } + } + Type *variadic_type = param_tuple->variables[i]->type; + GB_ASSERT(is_type_slice(variadic_type)); + variadic_type = base_type(variadic_type)->Slice.elem; + if (!is_type_any(variadic_type)) { + for (; i < arg_count; i++) { + args[i] = lb_emit_conv(p, args[i], variadic_type); + } + } else { + for (; i < arg_count; i++) { + args[i] = lb_emit_conv(p, args[i], default_type(args[i].type)); + } + } + } else if (variadic) { + isize i = 0; + for (; i < variadic_index; i++) { + Entity *e = param_tuple->variables[i]; + if (e->kind == Entity_Variable) { + args[i] = lb_emit_conv(p, args[i], e->type); + } + } + if (!vari_expand) { + Type *variadic_type = param_tuple->variables[i]->type; + GB_ASSERT(is_type_slice(variadic_type)); + variadic_type = base_type(variadic_type)->Slice.elem; + for (; i < arg_count; i++) { + args[i] = lb_emit_conv(p, args[i], variadic_type); + } + } + } else { + for (isize i = 0; i < param_count; i++) { + Entity *e = param_tuple->variables[i]; + if (e->kind == Entity_Variable) { + GB_ASSERT(args[i].value != nullptr); + args[i] = lb_emit_conv(p, args[i], e->type); + } + } + } + + if (variadic && !vari_expand && !is_c_vararg) { + // variadic call argument generation + gbAllocator allocator = heap_allocator(); + Type *slice_type = param_tuple->variables[variadic_index]->type; + Type *elem_type = base_type(slice_type)->Slice.elem; + lbAddr slice = lb_add_local_generated(p, slice_type, true); + isize slice_len = arg_count+1 - (variadic_index+1); + + if (slice_len > 0) { + lbAddr base_array = lb_add_local_generated(p, alloc_type_array(elem_type, slice_len), true); + + for (isize i = variadic_index, j = 0; i < arg_count; i++, j++) { + lbValue addr = lb_emit_array_epi(p, base_array.addr, cast(i32)j); + lb_emit_store(p, addr, args[i]); + } + + lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0); + lbValue len = lb_const_int(t_int, slice_len); + lb_fill_slice(p, slice, base_elem, len); + } + + arg_count = param_count; + args[variadic_index] = lb_addr_load(p, slice); + } + } + + if (variadic && variadic_index+1 < param_count) { + for (isize i = variadic_index+1; i < param_count; i++) { + Entity *e = param_tuple->variables[i]; + switch (e->Variable.param_value.kind) { + case ParameterValue_Constant: + args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value); + break; + case ParameterValue_Nil: + args[i] = lb_const_nil(e->type); + break; + case ParameterValue_Location: + args[i] = lb_emit_source_code_location(p, proc_name, pos); + break; + case ParameterValue_Value: + args[i] = lb_build_expr(p, e->Variable.param_value.ast_value); + break; + } + } + } + + isize final_count = param_count; + if (is_c_vararg) { + final_count = arg_count; + } + + auto call_args = array_slice(args, 0, final_count); + return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr); +} + + lbValue lb_build_expr(lbProcedure *p, Ast *expr) { expr = unparen_expr(expr); @@ -1809,7 +2205,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { case_end; case_ast_node(i, Implicit, expr); - // return ir_addr_load(proc, ir_build_addr(proc, expr)); + // return ir_addr_load(p, ir_build_addr(p, expr)); GB_PANIC("TODO(bill): Implicit"); case_end; @@ -1822,7 +2218,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { GB_ASSERT_MSG(e != nullptr, "%s", expr_to_string(expr)); if (e->kind == Entity_Builtin) { Token token = ast_token(expr); - GB_PANIC("TODO(bill): ir_build_expr Entity_Builtin '%.*s'\n" + GB_PANIC("TODO(bill): lb_build_expr Entity_Builtin '%.*s'\n" "\t at %.*s(%td:%td)", LIT(builtin_procs[e->Builtin.id].name), LIT(token.pos.file), token.pos.line, token.pos.column); return {}; @@ -1833,13 +2229,13 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { auto *found = map_get(&p->module->values, hash_entity(e)); if (found) { auto v = *found; - LLVMTypeKind kind = LLVMGetTypeKind(LLVMTypeOf(v.value)); - if (kind == LLVMFunctionTypeKind) { + // NOTE(bill): This is because pointers are already pointers in LLVM + if (is_type_proc(v.type)) { return v; } return lb_emit_load(p, v); // } else if (e != nullptr && e->kind == Entity_Variable) { - // return ir_addr_load(proc, ir_build_addr(proc, expr)); + // return ir_addr_load(p, ir_build_addr(p, expr)); } GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr); return {}; @@ -1848,6 +2244,11 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { case_ast_node(be, BinaryExpr, expr); return lb_build_binary_expr(p, expr); case_end; + + + case_ast_node(ce, CallExpr, expr); + return lb_build_call_expr(p, expr); + case_end; } return {}; @@ -1941,17 +2342,7 @@ void lb_generate_module(lbGenerator *gen) { defer (LLVMDisposeMessage(llvm_error)); - // LLVMPassManagerRef pass_manager = LLVMCreatePassManager(); - // defer (LLVMDisposePassManager(pass_manager)); - - // LLVMAddAggressiveInstCombinerPass(pass_manager); - // LLVMAddConstantMergePass(pass_manager); - // LLVMAddDeadArgEliminationPass(pass_manager); - - // LLVMRunPassManager(pass_manager, mod); - LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); - llvm_error = nullptr; LLVMDumpModule(mod); -- cgit v1.2.3 From b555b0083a58856f661c63fb574722f1fc64fee9 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 5 Feb 2020 20:18:19 +0000 Subject: Slowly add more statements and expressions; Add header file --- src/entity.cpp | 3 + src/llvm_backend.cpp | 1093 ++++++++++++++++++++++++++++++++++++-------------- src/llvm_backend.hpp | 231 +++++++++++ src/parser.hpp | 6 +- src/types.cpp | 1 - 5 files changed, 1022 insertions(+), 312 deletions(-) create mode 100644 src/llvm_backend.hpp (limited to 'src/llvm_backend.cpp') diff --git a/src/entity.cpp b/src/entity.cpp index 8273af3f1..a721c6394 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -2,6 +2,7 @@ struct Scope; struct Checker; struct Type; struct DeclInfo; +struct lbModule; #define ENTITY_KINDS \ @@ -104,6 +105,8 @@ struct Entity { Entity * using_parent; Ast * using_expr; + lbModule * code_gen_module; + isize order_in_src; String deprecated_message; diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index a3ac6dcea..c036da85c 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -1,9 +1,12 @@ #include "llvm_backend.hpp" -gb_internal gb_thread_local lbModule *global_module = nullptr; -gb_internal LLVMValueRef lb_zero32 = nullptr; -gb_internal LLVMValueRef lb_one32 = nullptr; +LLVMValueRef lb_zero32(lbModule *m) { + return LLVMConstInt(lb_type(m, t_i32), 0, false); +} +LLVMValueRef lb_one32(lbModule *m) { + return LLVMConstInt(lb_type(m, t_i32), 1, false); +} lbAddr lb_addr(lbValue addr) { @@ -33,9 +36,10 @@ void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) { } lbValue lb_emit_load(lbProcedure *p, lbValue value) { + lbModule *m = p->module; GB_ASSERT(value.value != nullptr); Type *t = type_deref(value.type); - LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(t), value.value, ""); + LLVMValueRef v = LLVMBuildLoad2(p->builder, lb_type(m, t), value.value, ""); return lbValue{v, t}; } @@ -53,18 +57,18 @@ void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) { gb_free(heap_allocator(), fields); } -LLVMTypeRef lb_alignment_prefix_type_hack(i64 alignment) { +LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) { switch (alignment) { case 1: - return LLVMArrayType(lb_type(t_u8), 0); + return LLVMArrayType(lb_type(m, t_u8), 0); case 2: - return LLVMArrayType(lb_type(t_u16), 0); + return LLVMArrayType(lb_type(m, t_u16), 0); case 4: - return LLVMArrayType(lb_type(t_u32), 0); + return LLVMArrayType(lb_type(m, t_u32), 0); case 8: - return LLVMArrayType(lb_type(t_u64), 0); + return LLVMArrayType(lb_type(m, t_u64), 0); case 16: - return LLVMArrayType(LLVMVectorType(lb_type(t_u32), 4), 0); + return LLVMArrayType(LLVMVectorType(lb_type(m, t_u32), 4), 0); default: GB_PANIC("Invalid alignment %d", cast(i32)alignment); break; @@ -139,53 +143,56 @@ String lb_get_entity_name(lbModule *m, Entity *e, String default_name) { return name; } -LLVMTypeRef lb_type_internal(Type *type) { +LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { + LLVMContextRef ctx = m->ctx; i64 size = type_size_of(type); // Check size + GB_ASSERT(type != t_invalid); + switch (type->kind) { case Type_Basic: switch (type->Basic.kind) { - case Basic_llvm_bool: return LLVMInt1Type(); - case Basic_bool: return LLVMInt8Type(); - case Basic_b8: return LLVMInt8Type(); - case Basic_b16: return LLVMInt16Type(); - case Basic_b32: return LLVMInt32Type(); - case Basic_b64: return LLVMInt64Type(); - - case Basic_i8: return LLVMInt8Type(); - case Basic_u8: return LLVMInt8Type(); - case Basic_i16: return LLVMInt16Type(); - case Basic_u16: return LLVMInt16Type(); - case Basic_i32: return LLVMInt32Type(); - case Basic_u32: return LLVMInt32Type(); - case Basic_i64: return LLVMInt64Type(); - case Basic_u64: return LLVMInt64Type(); - case Basic_i128: return LLVMInt128Type(); - case Basic_u128: return LLVMInt128Type(); - - case Basic_rune: return LLVMInt32Type(); + case Basic_llvm_bool: return LLVMInt1TypeInContext(ctx); + case Basic_bool: return LLVMInt8TypeInContext(ctx); + case Basic_b8: return LLVMInt8TypeInContext(ctx); + case Basic_b16: return LLVMInt16TypeInContext(ctx); + case Basic_b32: return LLVMInt32TypeInContext(ctx); + case Basic_b64: return LLVMInt64TypeInContext(ctx); + + case Basic_i8: return LLVMInt8TypeInContext(ctx); + case Basic_u8: return LLVMInt8TypeInContext(ctx); + case Basic_i16: return LLVMInt16TypeInContext(ctx); + case Basic_u16: return LLVMInt16TypeInContext(ctx); + case Basic_i32: return LLVMInt32TypeInContext(ctx); + case Basic_u32: return LLVMInt32TypeInContext(ctx); + case Basic_i64: return LLVMInt64TypeInContext(ctx); + case Basic_u64: return LLVMInt64TypeInContext(ctx); + case Basic_i128: return LLVMInt128TypeInContext(ctx); + case Basic_u128: return LLVMInt128TypeInContext(ctx); + + case Basic_rune: return LLVMInt32TypeInContext(ctx); // Basic_f16, - case Basic_f32: return LLVMFloatType(); - case Basic_f64: return LLVMDoubleType(); + case Basic_f32: return LLVMFloatTypeInContext(ctx); + case Basic_f64: return LLVMDoubleTypeInContext(ctx); // Basic_complex32, case Basic_complex64: { - LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..complex64"); + LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..complex64"); LLVMTypeRef fields[2] = { - lb_type(t_f32), - lb_type(t_f32), + lb_type(m, t_f32), + lb_type(m, t_f32), }; LLVMStructSetBody(type, fields, 2, false); return type; } case Basic_complex128: { - LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..complex128"); + LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..complex128"); LLVMTypeRef fields[2] = { - lb_type(t_f64), - lb_type(t_f64), + lb_type(m, t_f64), + lb_type(m, t_f64), }; LLVMStructSetBody(type, fields, 2, false); return type; @@ -193,41 +200,41 @@ LLVMTypeRef lb_type_internal(Type *type) { case Basic_quaternion128: { - LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..quaternion128"); + LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..quaternion128"); LLVMTypeRef fields[4] = { - lb_type(t_f32), - lb_type(t_f32), - lb_type(t_f32), - lb_type(t_f32), + lb_type(m, t_f32), + lb_type(m, t_f32), + lb_type(m, t_f32), + lb_type(m, t_f32), }; LLVMStructSetBody(type, fields, 4, false); return type; } case Basic_quaternion256: { - LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..quaternion256"); + LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..quaternion256"); LLVMTypeRef fields[4] = { - lb_type(t_f64), - lb_type(t_f64), - lb_type(t_f64), - lb_type(t_f64), + lb_type(m, t_f64), + lb_type(m, t_f64), + lb_type(m, t_f64), + lb_type(m, t_f64), }; LLVMStructSetBody(type, fields, 4, false); return type; } - case Basic_int: return LLVMIntType(8*cast(unsigned)build_context.word_size); - case Basic_uint: return LLVMIntType(8*cast(unsigned)build_context.word_size); + case Basic_int: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size); + case Basic_uint: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size); - case Basic_uintptr: return LLVMIntType(8*cast(unsigned)build_context.word_size); + case Basic_uintptr: return LLVMIntTypeInContext(ctx, 8*cast(unsigned)build_context.word_size); case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0); case Basic_string: { - LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..string"); + LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..string"); LLVMTypeRef fields[2] = { - LLVMPointerType(lb_type(t_u8), 0), - lb_type(t_int), + LLVMPointerType(lb_type(m, t_u8), 0), + lb_type(m, t_int), }; LLVMStructSetBody(type, fields, 2, false); return type; @@ -235,10 +242,10 @@ LLVMTypeRef lb_type_internal(Type *type) { case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0); case Basic_any: { - LLVMTypeRef type = LLVMStructCreateNamed(LLVMGetGlobalContext(), "..any"); + LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..any"); LLVMTypeRef fields[2] = { - LLVMPointerType(lb_type(t_rawptr), 0), - lb_type(t_typeid), + LLVMPointerType(lb_type(m, t_rawptr), 0), + lb_type(m, t_typeid), }; LLVMStructSetBody(type, fields, 2, false); return type; @@ -247,23 +254,23 @@ LLVMTypeRef lb_type_internal(Type *type) { case Basic_typeid: return LLVMIntType(8*cast(unsigned)build_context.word_size); // Endian Specific Types - case Basic_i16le: return LLVMInt16Type(); - case Basic_u16le: return LLVMInt16Type(); - case Basic_i32le: return LLVMInt32Type(); - case Basic_u32le: return LLVMInt32Type(); - case Basic_i64le: return LLVMInt64Type(); - case Basic_u64le: return LLVMInt64Type(); - case Basic_i128le: return LLVMInt128Type(); - case Basic_u128le: return LLVMInt128Type(); - - case Basic_i16be: return LLVMInt16Type(); - case Basic_u16be: return LLVMInt16Type(); - case Basic_i32be: return LLVMInt32Type(); - case Basic_u32be: return LLVMInt32Type(); - case Basic_i64be: return LLVMInt64Type(); - case Basic_u64be: return LLVMInt64Type(); - case Basic_i128be: return LLVMInt128Type(); - case Basic_u128be: return LLVMInt128Type(); + case Basic_i16le: return LLVMInt16TypeInContext(ctx); + case Basic_u16le: return LLVMInt16TypeInContext(ctx); + case Basic_i32le: return LLVMInt32TypeInContext(ctx); + case Basic_u32le: return LLVMInt32TypeInContext(ctx); + case Basic_i64le: return LLVMInt64TypeInContext(ctx); + case Basic_u64le: return LLVMInt64TypeInContext(ctx); + case Basic_i128le: return LLVMInt128TypeInContext(ctx); + case Basic_u128le: return LLVMInt128TypeInContext(ctx); + + case Basic_i16be: return LLVMInt16TypeInContext(ctx); + case Basic_u16be: return LLVMInt16TypeInContext(ctx); + case Basic_i32be: return LLVMInt32TypeInContext(ctx); + case Basic_u32be: return LLVMInt32TypeInContext(ctx); + case Basic_i64be: return LLVMInt64TypeInContext(ctx); + case Basic_u64be: return LLVMInt64TypeInContext(ctx); + case Basic_i128be: return LLVMInt128TypeInContext(ctx); + case Basic_u128be: return LLVMInt128TypeInContext(ctx); // Untyped types case Basic_UntypedBool: GB_PANIC("Basic_UntypedBool"); break; @@ -283,7 +290,7 @@ LLVMTypeRef lb_type_internal(Type *type) { switch (base->kind) { case Type_Basic: - return lb_type(base); + return lb_type(m, base); case Type_Named: case Type_Generic: @@ -301,23 +308,23 @@ LLVMTypeRef lb_type_internal(Type *type) { case Type_Enum: case Type_BitSet: case Type_SimdVector: - return lb_type(base); + return lb_type(m, base); // TODO(bill): Deal with this correctly. Can this be named? case Type_Proc: - return lb_type(base); + return lb_type(m, base); case Type_Tuple: - return lb_type(base); + return lb_type(m, base); } - LLVMContextRef ctx = LLVMGetModuleContext(global_module->mod); - - if (base->llvm_type != nullptr) { - LLVMTypeKind kind = LLVMGetTypeKind(base->llvm_type); + LLVMTypeRef *found = map_get(&m->types, hash_type(base)); + if (found) { + LLVMTypeKind kind = LLVMGetTypeKind(*found); if (kind == LLVMStructTypeKind) { - type->llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), lb_get_entity_name(global_module, type->Named.type_name))); - lb_clone_struct_type(type->llvm_type, base->llvm_type); + LLVMTypeRef llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name))); + map_set(&m->types, hash_type(type), llvm_type); + lb_clone_struct_type(llvm_type, *found); } } @@ -325,51 +332,54 @@ LLVMTypeRef lb_type_internal(Type *type) { case Type_Struct: case Type_Union: case Type_BitField: - type->llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), lb_get_entity_name(global_module, type->Named.type_name))); - lb_clone_struct_type(type->llvm_type, lb_type(base)); - return type->llvm_type; + { + LLVMTypeRef llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name))); + map_set(&m->types, hash_type(type), llvm_type); + lb_clone_struct_type(llvm_type, lb_type(m, base)); + return llvm_type; + } } - return lb_type(base); + return lb_type(m, base); } case Type_Pointer: - return LLVMPointerType(lb_type(type_deref(type)), 0); + return LLVMPointerType(lb_type(m, type_deref(type)), 0); case Type_Opaque: - return lb_type(base_type(type)); + return lb_type(m, base_type(type)); case Type_Array: - return LLVMArrayType(lb_type(type->Array.elem), cast(unsigned)type->Array.count); + return LLVMArrayType(lb_type(m, type->Array.elem), cast(unsigned)type->Array.count); case Type_EnumeratedArray: - return LLVMArrayType(lb_type(type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count); + return LLVMArrayType(lb_type(m, type->EnumeratedArray.elem), cast(unsigned)type->EnumeratedArray.count); case Type_Slice: { LLVMTypeRef fields[2] = { - LLVMPointerType(lb_type(type->Slice.elem), 0), // data - lb_type(t_int), // len + LLVMPointerType(lb_type(m, type->Slice.elem), 0), // data + lb_type(m, t_int), // len }; - return LLVMStructType(fields, 2, false); + return LLVMStructTypeInContext(ctx, fields, 2, false); } break; case Type_DynamicArray: { LLVMTypeRef fields[4] = { - LLVMPointerType(lb_type(type->DynamicArray.elem), 0), // data - lb_type(t_int), // len - lb_type(t_int), // cap - lb_type(t_allocator), // allocator + LLVMPointerType(lb_type(m, type->DynamicArray.elem), 0), // data + lb_type(m, t_int), // len + lb_type(m, t_int), // cap + lb_type(m, t_allocator), // allocator }; - return LLVMStructType(fields, 4, false); + return LLVMStructTypeInContext(ctx, fields, 4, false); } break; case Type_Map: - return lb_type(type->Map.internal_type); + return lb_type(m, type->Map.internal_type); case Type_Struct: { @@ -378,9 +388,9 @@ LLVMTypeRef lb_type_internal(Type *type) { LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); i64 alignment = type_align_of(type); unsigned size_of_union = cast(unsigned)type_size_of(type); - fields[0] = lb_alignment_prefix_type_hack(alignment); - fields[1] = LLVMArrayType(lb_type(t_u8), size_of_union); - return LLVMStructType(fields, field_count, false); + fields[0] = lb_alignment_prefix_type_hack(m, alignment); + fields[1] = LLVMArrayType(lb_type(m, t_u8), size_of_union); + return LLVMStructTypeInContext(ctx, fields, field_count, false); } isize offset = 0; @@ -395,20 +405,20 @@ LLVMTypeRef lb_type_internal(Type *type) { for_array(i, type->Struct.fields) { Entity *field = type->Struct.fields[i]; - fields[i+offset] = lb_type(field->type); + fields[i+offset] = lb_type(m, field->type); } if (type->Struct.custom_align > 0) { - fields[0] = lb_alignment_prefix_type_hack(type->Struct.custom_align); + fields[0] = lb_alignment_prefix_type_hack(m, type->Struct.custom_align); } - return LLVMStructType(fields, field_count, type->Struct.is_packed); + return LLVMStructTypeInContext(ctx, fields, field_count, type->Struct.is_packed); } break; case Type_Union: if (type->Union.variants.count == 0) { - return LLVMStructType(nullptr, 0, false); + return LLVMStructTypeInContext(ctx, nullptr, 0, false); } else { // NOTE(bill): The zero size array is used to fix the alignment used in a structure as // LLVM takes the first element's alignment as the entire alignment (like C) @@ -416,30 +426,30 @@ LLVMTypeRef lb_type_internal(Type *type) { i64 size = type_size_of(type); if (is_type_union_maybe_pointer_original_alignment(type)) { - LLVMTypeRef fields[1] = {lb_type(type->Union.variants[0])}; - return LLVMStructType(fields, 1, false); + LLVMTypeRef fields[1] = {lb_type(m, type->Union.variants[0])}; + return LLVMStructTypeInContext(ctx, fields, 1, false); } unsigned block_size = cast(unsigned)type->Union.variant_block_size; LLVMTypeRef fields[3] = {}; unsigned field_count = 1; - fields[0] = lb_alignment_prefix_type_hack(align); + fields[0] = lb_alignment_prefix_type_hack(m, align); if (is_type_union_maybe_pointer(type)) { field_count += 1; - fields[1] = lb_type(type->Union.variants[0]); + fields[1] = lb_type(m, type->Union.variants[0]); } else { field_count += 2; - fields[1] = LLVMArrayType(lb_type(t_u8), block_size); - fields[2] = lb_type(union_tag_type(type)); + fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size); + fields[2] = lb_type(m, union_tag_type(type)); } - return LLVMStructType(fields, field_count, false); + return LLVMStructTypeInContext(ctx, fields, field_count, false); } break; case Type_Enum: - return lb_type(base_enum_type(type)); + return lb_type(m, base_enum_type(type)); case Type_Tuple: { @@ -449,22 +459,22 @@ LLVMTypeRef lb_type_internal(Type *type) { for_array(i, type->Tuple.variables) { Entity *field = type->Tuple.variables[i]; - fields[i] = lb_type(field->type); + fields[i] = lb_type(m, field->type); } - return LLVMStructType(fields, field_count, type->Tuple.is_packed); + return LLVMStructTypeInContext(ctx, fields, field_count, type->Tuple.is_packed); } case Type_Proc: { set_procedure_abi_types(heap_allocator(), type); - LLVMTypeRef return_type = LLVMVoidType(); + LLVMTypeRef return_type = LLVMVoidTypeInContext(ctx); isize offset = 0; if (type->Proc.return_by_pointer) { offset = 1; } else if (type->Proc.abi_compat_result_type != nullptr) { - return_type = lb_type(type->Proc.abi_compat_result_type); + return_type = lb_type(m, type->Proc.abi_compat_result_type); } isize extra_param_count = offset; @@ -478,13 +488,13 @@ LLVMTypeRef lb_type_internal(Type *type) { for_array(i, type->Proc.abi_compat_params) { Type *param = type->Proc.abi_compat_params[i]; - param_types[i+offset] = lb_type(param); + param_types[i+offset] = lb_type(m, param); } if (type->Proc.return_by_pointer) { - param_types[0] = LLVMPointerType(lb_type(type->Proc.abi_compat_result_type), 0); + param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0); } if (type->Proc.calling_convention == ProcCC_Odin) { - param_types[param_count-1] = lb_type(t_context_ptr); + param_types[param_count-1] = lb_type(m, t_context_ptr); } LLVMTypeRef t = LLVMFunctionType(return_type, param_types, param_count, type->Proc.c_vararg); @@ -508,7 +518,7 @@ LLVMTypeRef lb_type_internal(Type *type) { fields[i] = LLVMIntType(size); } - internal_type = LLVMStructType(fields, field_count, true); + internal_type = LLVMStructTypeInContext(ctx, fields, field_count, true); } unsigned field_count = 2; LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); @@ -517,34 +527,36 @@ LLVMTypeRef lb_type_internal(Type *type) { if (type->BitField.custom_align > 0) { alignment = type->BitField.custom_align; } - fields[0] = lb_alignment_prefix_type_hack(alignment); + fields[0] = lb_alignment_prefix_type_hack(m, alignment); fields[1] = internal_type; - return LLVMStructType(fields, field_count, true); + return LLVMStructTypeInContext(ctx, fields, field_count, true); } break; case Type_BitSet: return LLVMIntType(8*cast(unsigned)type_size_of(type)); case Type_SimdVector: if (type->SimdVector.is_x86_mmx) { - return LLVMX86MMXType(); + return LLVMX86MMXTypeInContext(ctx); } - return LLVMVectorType(lb_type(type->SimdVector.elem), cast(unsigned)type->SimdVector.count); + return LLVMVectorType(lb_type(m, type->SimdVector.elem), cast(unsigned)type->SimdVector.count); } - GB_PANIC("Invalid type"); - return LLVMInt32Type(); + GB_PANIC("Invalid type %s", type_to_string(type)); + return LLVMInt32TypeInContext(ctx); } -LLVMTypeRef lb_type(Type *type) { +LLVMTypeRef lb_type(lbModule *m, Type *type) { type = default_type(type); - if (type->llvm_type) { - return type->llvm_type; + LLVMTypeRef *found = map_get(&m->types, hash_type(type)); + if (found) { + return *found; } - LLVMTypeRef llvm_type = lb_type_internal(type); - type->llvm_type = llvm_type; + LLVMTypeRef llvm_type = lb_type_internal(m, type); + + map_set(&m->types, hash_type(type), llvm_type); return llvm_type; } @@ -580,12 +592,13 @@ void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *nam -lbProcedure *lb_create_procedure(lbModule *module, Entity *entity) { +lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure); - p->module = module; + entity->code_gen_module = m; + p->module = m; p->entity = entity; - p->name = lb_get_entity_name(module, entity); + p->name = lb_get_entity_name(m, entity); DeclInfo *decl = entity->decl_info; @@ -608,17 +621,20 @@ lbProcedure *lb_create_procedure(lbModule *module, Entity *entity) { p->params.allocator = heap_allocator(); p->blocks.allocator = heap_allocator(); p->branch_blocks.allocator = heap_allocator(); + p->context_stack.allocator = heap_allocator(); char *name = alloc_cstring(heap_allocator(), p->name); - LLVMTypeRef func_ptr_type = lb_type(p->type); + LLVMTypeRef func_ptr_type = lb_type(m, p->type); LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type); - p->value = LLVMAddFunction(module->mod, name, func_type); - lb_add_entity(module, entity, lbValue{p->value, p->type}); - lb_add_member(module, p->name, lbValue{p->value, p->type}); + p->value = LLVMAddFunction(m->mod, name, func_type); + LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]); + lbValue proc_value = {p->value, p->type}; + lb_add_entity(m, entity, proc_value); + lb_add_member(m, p->name, proc_value); - LLVMContextRef ctx = LLVMGetModuleContext(module->mod); + LLVMContextRef ctx = LLVMGetModuleContext(m->mod); // NOTE(bill): offset==0 is the return value isize offset = 1; @@ -663,7 +679,6 @@ lbProcedure *lb_create_procedure(lbModule *module, Entity *entity) { } - return p; } @@ -726,7 +741,7 @@ void lb_end_procedure(lbProcedure *p) { lbBlock *lb_create_block(lbProcedure *p, char const *name) { lbBlock *b = gb_alloc_item(heap_allocator(), lbBlock); - b->block = LLVMAppendBasicBlock(p->value, name); + b->block = LLVMAppendBasicBlockInContext(p->module->ctx, p->value, name); b->scope = p->curr_scope; b->scope_index = p->scope_index; array_add(&p->blocks, b); @@ -736,7 +751,7 @@ lbBlock *lb_create_block(lbProcedure *p, char const *name) { lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr) { LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block); - LLVMTypeRef llvm_type = lb_type(type); + LLVMTypeRef llvm_type = lb_type(p->module, type); LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, ""); LLVMSetAlignment(ptr, 16); @@ -755,70 +770,11 @@ lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr) { lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) { lbAddr addr = lb_add_local(p, type, nullptr); - lb_addr_store(p, addr, lb_const_nil(type)); + lb_addr_store(p, addr, lb_const_nil(p->module, type)); return addr; } - -bool lb_init_generator(lbGenerator *gen, Checker *c) { - if (global_error_collector.count != 0) { - return false; - } - - isize tc = c->parser->total_token_count; - if (tc < 2) { - return false; - } - - - String init_fullpath = c->parser->init_fullpath; - - if (build_context.out_filepath.len == 0) { - gen->output_name = remove_directory_from_path(init_fullpath); - gen->output_name = remove_extension_from_path(gen->output_name); - gen->output_base = gen->output_name; - } else { - gen->output_name = build_context.out_filepath; - isize pos = string_extension_position(gen->output_name); - if (pos < 0) { - gen->output_base = gen->output_name; - } else { - gen->output_base = substring(gen->output_name, 0, pos); - } - } - gbAllocator ha = heap_allocator(); - gen->output_base = path_to_full_path(ha, gen->output_base); - - gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len); - output_file_path = gb_string_appendc(output_file_path, ".obj"); - defer (gb_string_free(output_file_path)); - - gbFileError err = gb_file_create(&gen->output_file, output_file_path); - if (err != gbFileError_None) { - gb_printf_err("Failed to create file %s\n", output_file_path); - return false; - } - - gen->info = &c->info; - gen->module.info = &c->info; - - gen->module.mod = LLVMModuleCreateWithName("odin_module"); - map_init(&gen->module.values, heap_allocator()); - map_init(&gen->module.members, heap_allocator()); - map_init(&gen->module.const_strings, heap_allocator()); - map_init(&gen->module.const_string_byte_slices, heap_allocator()); - - global_module = &gen->module; - - lb_zero32 = LLVMConstInt(lb_type(t_i32), 0, false); - lb_one32 = LLVMConstInt(lb_type(t_i32), 1, false); - - - return true; -} - - void lb_build_stmt_list(lbProcedure *p, Array const &stmts) { for_array(i, stmts) { Ast *stmt = stmts[i]; @@ -842,7 +798,7 @@ lbValue lb_build_gep(lbProcedure *p, lbValue const &value, i32 index) { GB_ASSERT(elem_type != nullptr); - return lbValue{LLVMBuildStructGEP2(p->builder, lb_type(elem_type), value.value, index, ""), elem_type}; + return lbValue{LLVMBuildStructGEP2(p->builder, lb_type(p->module, elem_type), value.value, index, ""), elem_type}; } void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) { @@ -926,7 +882,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { char *c_name = alloc_cstring(heap_allocator(), mangled_name); - LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(e->type), c_name); + LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name); if (value.value != nullptr) { LLVMSetInitializer(global, value.value); } @@ -974,7 +930,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { lbAddr local = lb_add_local(p, e->type, e); addrs[i] = local; if (vd->values.count == 0) { - lb_addr_store(p, addrs[i], lb_const_nil(lb_addr_type(addrs[i]))); + lb_addr_store(p, addrs[i], lb_const_nil(p->module, lb_addr_type(addrs[i]))); } } } @@ -1033,7 +989,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { if (res.value != nullptr) { lb_addr_store(p, p->return_ptr, res); } else { - lb_addr_store(p, p->return_ptr, lb_const_nil(p->type->Proc.abi_compat_result_type)); + lb_addr_store(p, p->return_ptr, lb_const_nil(p->module, p->type->Proc.abi_compat_result_type)); } LLVMBuildRetVoid(p->builder); } else { @@ -1065,22 +1021,22 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { } } -lbValue lb_const_nil(Type *type) { - LLVMValueRef v = LLVMConstNull(lb_type(type)); +lbValue lb_const_nil(lbModule *m, Type *type) { + LLVMValueRef v = LLVMConstNull(lb_type(m, type)); return lbValue{v, type}; } -lbValue lb_const_int(Type *type, u64 value) { +lbValue lb_const_int(lbModule *m, Type *type, u64 value) { lbValue res = {}; - res.value = LLVMConstInt(lb_type(type), value, !is_type_unsigned(type)); + res.value = LLVMConstInt(lb_type(m, type), value, !is_type_unsigned(type)); res.type = type; return res; } -LLVMValueRef llvm_const_f32(f32 f, Type *type=t_f32) { +LLVMValueRef llvm_const_f32(lbModule *m, f32 f, Type *type=t_f32) { u32 u = bit_cast(f); - LLVMValueRef i = LLVMConstInt(LLVMInt32Type(), u, false); - return LLVMConstBitCast(i, lb_type(type)); + LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false); + return LLVMConstBitCast(i, lb_type(m, type)); } @@ -1189,12 +1145,14 @@ lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type=t_typeid) { lbValue res = {}; - res.value = LLVMConstInt(lb_type(typeid_type), data, false); + res.value = LLVMConstInt(lb_type(m, typeid_type), data, false); res.type = typeid_type; return res; } lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { + LLVMContextRef ctx = m->ctx; + Type *original_type = type; lbValue res = {}; @@ -1212,7 +1170,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { isize count = cl->elems.count; if (count == 0) { - return lb_const_nil(type); + return lb_const_nil(m, type); } count = gb_max(cl->max_count, count); Type *elem = base_type(type)->Slice.elem; @@ -1228,7 +1186,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { String name = make_string(str, len-1); Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value); - LLVMValueRef global_data = LLVMAddGlobal(m->mod, lb_type(t), cast(char const *)str); + LLVMValueRef global_data = LLVMAddGlobal(m->mod, lb_type(m, t), cast(char const *)str); LLVMSetInitializer(global_data, backing_array.value); lbValue g = {}; @@ -1239,20 +1197,21 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { lb_add_member(m, name, g); { - LLVMValueRef indices[2] = {lb_zero32, lb_zero32}; + LLVMValueRef indices[2] = {lb_zero32(m), lb_zero32(m)}; LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); - LLVMValueRef len = LLVMConstInt(lb_type(t_int), count, true); + LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true); LLVMValueRef values[2] = {ptr, len}; - res.value = LLVMConstNamedStruct(lb_type(original_type), values, 2); + res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); return res; } } } else if (is_type_array(type) && value.kind == ExactValue_String && !is_type_u8(core_array_type(type))) { - LLVMValueRef data = LLVMConstString(cast(char const *)value.value_string.text, - cast(unsigned)value.value_string.len, - false); + LLVMValueRef data = LLVMConstStringInContext(ctx, + cast(char const *)value.value_string.text, + cast(unsigned)value.value_string.len, + false); res.value = data; return res; } else if (is_type_array(type) && @@ -1271,16 +1230,16 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { elems[i] = single_elem.value; } - res.value = LLVMConstArray(lb_type(elem), elems, cast(unsigned)count); + res.value = LLVMConstArray(lb_type(m, elem), elems, cast(unsigned)count); return res; } switch (value.kind) { case ExactValue_Invalid: - res.value = LLVMConstNull(lb_type(original_type)); + res.value = LLVMConstNull(lb_type(m, original_type)); return res; case ExactValue_Bool: - res.value = LLVMConstInt(lb_type(original_type), value.value_bool, false); + res.value = LLVMConstInt(lb_type(m, original_type), value.value_bool, false); return res; case ExactValue_String: { @@ -1291,10 +1250,11 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { return res; } - LLVMValueRef indices[2] = {lb_zero32, lb_zero32}; - LLVMValueRef data = LLVMConstString(cast(char const *)value.value_string.text, - cast(unsigned)value.value_string.len, - false); + LLVMValueRef indices[2] = {lb_zero32(m), lb_zero32(m)}; + LLVMValueRef data = LLVMConstStringInContext(ctx, + cast(char const *)value.value_string.text, + cast(unsigned)value.value_string.len, + false); LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), "test_string_data"); LLVMSetInitializer(global_data, data); @@ -1305,10 +1265,10 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { return res; } - LLVMValueRef len = LLVMConstInt(lb_type(t_int), value.value_string.len, true); + LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true); LLVMValueRef values[2] = {ptr, len}; - res.value = LLVMConstNamedStruct(lb_type(original_type), values, 2); + res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); map_set(&m->const_strings, key, res); @@ -1317,35 +1277,35 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { case ExactValue_Integer: if (is_type_pointer(type)) { - LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); - res.value = LLVMConstBitCast(i, lb_type(original_type)); + LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); + res.value = LLVMConstBitCast(i, lb_type(m, original_type)); } else { - res.value = LLVMConstIntOfArbitraryPrecision(lb_type(original_type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); + res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); } return res; case ExactValue_Float: if (type_size_of(type) == 4) { f32 f = cast(f32)value.value_float; - res.value = llvm_const_f32(f, type); + res.value = llvm_const_f32(m, f, type); return res; } - res.value = LLVMConstReal(lb_type(original_type), value.value_float); + res.value = LLVMConstReal(lb_type(m, original_type), value.value_float); return res; case ExactValue_Complex: { LLVMValueRef values[2] = {}; switch (8*type_size_of(type)) { case 64: - values[0] = llvm_const_f32(cast(f32)value.value_complex.real); - values[1] = llvm_const_f32(cast(f32)value.value_complex.imag); + values[0] = llvm_const_f32(m, cast(f32)value.value_complex.real); + values[1] = llvm_const_f32(m, cast(f32)value.value_complex.imag); break; case 128: - values[0] = LLVMConstReal(lb_type(t_f64), value.value_complex.real); - values[1] = LLVMConstReal(lb_type(t_f64), value.value_complex.imag); + values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real); + values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.imag); break; } - res.value = LLVMConstNamedStruct(lb_type(original_type), values, 2); + res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); return res; } break; @@ -1355,27 +1315,27 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { switch (8*type_size_of(type)) { case 128: // @QuaternionLayout - values[3] = llvm_const_f32(cast(f32)value.value_quaternion.real); - values[0] = llvm_const_f32(cast(f32)value.value_quaternion.imag); - values[1] = llvm_const_f32(cast(f32)value.value_quaternion.jmag); - values[2] = llvm_const_f32(cast(f32)value.value_quaternion.kmag); + values[3] = llvm_const_f32(m, cast(f32)value.value_quaternion.real); + values[0] = llvm_const_f32(m, cast(f32)value.value_quaternion.imag); + values[1] = llvm_const_f32(m, cast(f32)value.value_quaternion.jmag); + values[2] = llvm_const_f32(m, cast(f32)value.value_quaternion.kmag); break; case 256: // @QuaternionLayout - values[3] = LLVMConstReal(lb_type(t_f64), value.value_quaternion.real); - values[0] = LLVMConstReal(lb_type(t_f64), value.value_quaternion.imag); - values[1] = LLVMConstReal(lb_type(t_f64), value.value_quaternion.jmag); - values[2] = LLVMConstReal(lb_type(t_f64), value.value_quaternion.kmag); + values[3] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.real); + values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.imag); + values[1] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.jmag); + values[2] = LLVMConstReal(lb_type(m, t_f64), value.value_quaternion.kmag); break; } - res.value = LLVMConstNamedStruct(lb_type(original_type), values, 4); + res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 4); return res; } break; case ExactValue_Pointer: - res.value = LLVMConstBitCast(LLVMConstInt(lb_type(t_uintptr), value.value_pointer, false), lb_type(original_type)); + res.value = LLVMConstBitCast(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type)); return res; case ExactValue_Compound: @@ -1386,7 +1346,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { Type *elem_type = type->Array.elem; isize elem_count = cl->elems.count; if (elem_count == 0) { - return lb_const_nil(original_type); + return lb_const_nil(m, original_type); } if (cl->elems[0]->kind == Ast_FieldValue) { // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand @@ -1446,11 +1406,11 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { } if (!found) { - values[value_index++] = LLVMConstNull(lb_type(elem_type)); + values[value_index++] = LLVMConstNull(lb_type(m, elem_type)); } } - res.value = LLVMConstArray(lb_type(elem_type), values, cast(unsigned int)type->Array.count); + res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count); return res; } else { GB_ASSERT_MSG(elem_count == type->Array.count, "%td != %td", elem_count, type->Array.count); @@ -1464,10 +1424,10 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { values[i] = lb_const_value(m, elem_type, tav.value).value; } for (isize i = elem_count; i < type->Array.count; i++) { - values[i] = LLVMConstNull(lb_type(elem_type)); + values[i] = LLVMConstNull(lb_type(m, elem_type)); } - res.value = LLVMConstArray(lb_type(elem_type), values, cast(unsigned int)type->Array.count); + res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->Array.count); return res; } } else if (is_type_enumerated_array(type)) { @@ -1475,7 +1435,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { Type *elem_type = type->EnumeratedArray.elem; isize elem_count = cl->elems.count; if (elem_count == 0) { - return lb_const_nil(original_type); + return lb_const_nil(m, original_type); } if (cl->elems[0]->kind == Ast_FieldValue) { // TODO(bill): This is O(N*M) and will be quite slow; it should probably be sorted before hand @@ -1539,11 +1499,11 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { } if (!found) { - values[value_index++] = LLVMConstNull(lb_type(elem_type)); + values[value_index++] = LLVMConstNull(lb_type(m, elem_type)); } } - res.value = LLVMConstArray(lb_type(elem_type), values, cast(unsigned int)type->EnumeratedArray.count); + res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count); return res; } else { GB_ASSERT_MSG(elem_count == type->EnumeratedArray.count, "%td != %td", elem_count, type->EnumeratedArray.count); @@ -1557,10 +1517,10 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { values[i] = lb_const_value(m, elem_type, tav.value).value; } for (isize i = elem_count; i < type->EnumeratedArray.count; i++) { - values[i] = LLVMConstNull(lb_type(elem_type)); + values[i] = LLVMConstNull(lb_type(m, elem_type)); } - res.value = LLVMConstArray(lb_type(elem_type), values, cast(unsigned int)type->EnumeratedArray.count); + res.value = LLVMConstArray(lb_type(m, elem_type), values, cast(unsigned int)type->EnumeratedArray.count); return res; } } else if (is_type_simd_vector(type)) { @@ -1569,7 +1529,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { Type *elem_type = type->SimdVector.elem; isize elem_count = cl->elems.count; if (elem_count == 0) { - return lb_const_nil(original_type); + return lb_const_nil(m, original_type); } isize total_elem_count = type->SimdVector.count; @@ -1582,7 +1542,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { values[i] = lb_const_value(m, elem_type, tav.value).value; } for (isize i = elem_count; i < type->SimdVector.count; i++) { - values[i] = LLVMConstNull(lb_type(elem_type)); + values[i] = LLVMConstNull(lb_type(m, elem_type)); } res.value = LLVMConstVector(values, cast(unsigned)total_elem_count); @@ -1591,7 +1551,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { ast_node(cl, CompoundLit, value.value_compound); if (cl->elems.count == 0) { - return lb_const_nil(type); + return lb_const_nil(m, type); } isize offset = 0; @@ -1640,25 +1600,25 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { for (isize i = 0; i < type->Struct.fields.count; i++) { if (!visited[offset+i]) { GB_ASSERT(values[offset+i] == nullptr); - values[offset+i] = lb_const_nil(type->Struct.fields[i]->type).value; + values[offset+i] = lb_const_nil(m, type->Struct.fields[i]->type).value; } } if (type->Struct.custom_align > 0) { - values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(type->Struct.custom_align)); + values[0] = LLVMConstNull(lb_alignment_prefix_type_hack(m, type->Struct.custom_align)); } - res.value = LLVMConstNamedStruct(lb_type(original_type), values, cast(unsigned)value_count); + res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, cast(unsigned)value_count); return res; } else if (is_type_bit_set(type)) { ast_node(cl, CompoundLit, value.value_compound); if (cl->elems.count == 0) { - return lb_const_nil(original_type); + return lb_const_nil(m, original_type); } i64 sz = type_size_of(type); if (sz == 0) { - return lb_const_nil(original_type); + return lb_const_nil(m, original_type); } u64 bits = 0; @@ -1684,10 +1644,10 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { } } - res.value = LLVMConstInt(lb_type(original_type), bits, false); + res.value = LLVMConstInt(lb_type(m, original_type), bits, false); return res; } else { - return lb_const_nil(original_type); + return lb_const_nil(m, original_type); } break; case ExactValue_Procedure: @@ -1697,7 +1657,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { return lb_typeid(m, value.value_typeid, original_type); } - return lb_const_nil(original_type); + return lb_const_nil(m, original_type); } u64 lb_generate_source_code_location_hash(TokenPos const &pos) { @@ -1711,21 +1671,25 @@ u64 lb_generate_source_code_location_hash(TokenPos const &pos) { } lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, TokenPos const &pos) { + lbModule *m = p->module; + LLVMValueRef fields[5] = {}; fields[0]/*file*/ = lb_find_or_add_entity_string(p->module, pos.file).value; - fields[1]/*line*/ = lb_const_int(t_int, pos.line).value; - fields[2]/*column*/ = lb_const_int(t_int, pos.column).value; + fields[1]/*line*/ = lb_const_int(m, t_int, pos.line).value; + fields[2]/*column*/ = lb_const_int(m, t_int, pos.column).value; fields[3]/*procedure*/ = lb_find_or_add_entity_string(p->module, procedure).value; - fields[4]/*hash*/ = lb_const_int(t_u64, lb_generate_source_code_location_hash(pos)).value; + fields[4]/*hash*/ = lb_const_int(m, t_u64, lb_generate_source_code_location_hash(pos)).value; lbValue res = {}; - res.value = LLVMConstNamedStruct(lb_type(t_source_code_location), fields, 5); + res.value = LLVMConstNamedStruct(lb_type(m, t_source_code_location), fields, 5); res.type = t_source_code_location; return res; } lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) { + lbModule *m = p->module; + lbValue res = {}; res.type = type; @@ -1804,7 +1768,7 @@ lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Ty return res; case Token_AndNot: { - LLVMValueRef all_ones = LLVMConstAllOnes(lb_type(type)); + LLVMValueRef all_ones = LLVMConstAllOnes(lb_type(m, type)); LLVMValueRef new_rhs = LLVMBuildXor(p->builder, all_ones, rhs.value, ""); res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, ""); return res; @@ -1852,10 +1816,344 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { return value; } -lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false) { +lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) { + // TODO(bill): lb_emit_transmute + return value; +} + + +void lb_emit_init_context(lbProcedure *p, lbValue c) { + lbModule *m = p->module; + gbAllocator a = heap_allocator(); + auto args = array_make(a, 1); + args[0] = c.value != nullptr ? c : m->global_default_context.addr; + // ir_emit_runtime_call(p, "__init_context", args); +} + +void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) { + lbContextData cd = {ctx, p->scope_index}; + array_add(&p->context_stack, cd); +} + + +lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) { + if (p->context_stack.count > 0) { + return p->context_stack[p->context_stack.count-1].ctx; + } + + lbBlock *tmp_block = p->curr_block; + p->curr_block = p->blocks[0]; + + defer (p->curr_block = tmp_block); + + lbAddr c = lb_add_local_generated(p, t_context, true); + lb_push_context_onto_stack(p, c); + lb_addr_store(p, c, lb_addr_load(p, p->module->global_default_context)); + lb_emit_init_context(p, c.addr); + return c; +} + +lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) { + if (LLVMIsALoadInst(value.value)) { + lbValue res = {}; + res.value = LLVMGetOperand(value.value, 0); + res.type = alloc_type_pointer(value.type); + return res; + } + + lbAddr res = lb_add_local_generated(p, value.type, false); + lb_addr_store(p, res, value); + return res.addr; +} + +lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 alignment) { + i64 type_alignment = type_align_of(new_type); + if (alignment < type_alignment) { + alignment = type_alignment; + } + GB_ASSERT_MSG(are_types_identical(new_type, val.type), "%s %s", type_to_string(new_type), type_to_string(val.type)); + + lbAddr ptr = lb_add_local_generated(p, new_type, false); + LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment); + lb_addr_store(p, ptr, val); + + return ptr.addr; +} + +lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { return {}; } +lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) { + if (LLVMIsALoadInst(s.value)) { + lbValue res = {}; + res.value = LLVMGetOperand(s.value, 0); + res.type = alloc_type_pointer(s.type); + lbValue ptr = lb_emit_struct_ep(p, res, index); + return lb_emit_load(p, ptr); + } + + gbAllocator a = heap_allocator(); + Type *t = base_type(s.type); + Type *result_type = nullptr; + + switch (t->kind) { + case Type_Basic: + switch (t->Basic.kind) { + case Basic_string: + switch (index) { + case 0: result_type = t_u8_ptr; break; + case 1: result_type = t_int; break; + } + break; + case Basic_any: + switch (index) { + case 0: result_type = t_rawptr; break; + case 1: result_type = t_typeid; break; + } + break; + case Basic_complex64: case Basic_complex128: + { + Type *ft = base_complex_elem_type(t); + switch (index) { + case 0: result_type = ft; break; + case 1: result_type = ft; break; + } + break; + } + case Basic_quaternion128: case Basic_quaternion256: + { + Type *ft = base_complex_elem_type(t); + switch (index) { + case 0: result_type = ft; break; + case 1: result_type = ft; break; + case 2: result_type = ft; break; + case 3: result_type = ft; break; + } + break; + } + } + break; + case Type_Struct: + result_type = t->Struct.fields[index]->type; + break; + case Type_Union: + GB_ASSERT(index == -1); + // return lb_emit_union_tag_value(proc, s); + GB_PANIC("lb_emit_union_tag_value"); + + case Type_Tuple: + GB_ASSERT(t->Tuple.variables.count > 0); + result_type = t->Tuple.variables[index]->type; + break; + case Type_Slice: + switch (index) { + case 0: result_type = alloc_type_pointer(t->Slice.elem); break; + case 1: result_type = t_int; break; + } + break; + case Type_DynamicArray: + switch (index) { + case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break; + case 1: result_type = t_int; break; + case 2: result_type = t_int; break; + case 3: result_type = t_allocator; break; + } + break; + + case Type_Map: + { + init_map_internal_types(t); + Type *gst = t->Map.generated_struct_type; + switch (index) { + case 0: result_type = gst->Struct.fields[0]->type; break; + case 1: result_type = gst->Struct.fields[1]->type; break; + } + } + break; + + case Type_Array: + result_type = t->Array.elem; + break; + + default: + GB_PANIC("TODO(bill): struct_ev type: %s, %d", type_to_string(s.type), index); + break; + } + + GB_ASSERT_MSG(result_type != nullptr, "%s, %d", type_to_string(s.type), index); + + + lbValue res = {}; + res.value = LLVMBuildExtractValue(p->builder, s.value, cast(unsigned)index, ""); + res.type = result_type; + return res; +} + + +lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) { + unsigned arg_count = cast(unsigned)processed_args.count; + if (return_ptr.value != nullptr) { + arg_count += 1; + } + if (context_ptr.addr.value != nullptr) { + arg_count += 1; + } + + LLVMValueRef *args = gb_alloc_array(heap_allocator(), LLVMValueRef, arg_count); + isize arg_index = 0; + if (return_ptr.value != nullptr) { + args[arg_index++] = return_ptr.value; + } + for_array(i, processed_args) { + lbValue arg = processed_args[i]; + args[arg_index++] = arg.value; + } + if (context_ptr.addr.value != nullptr) { + args[arg_index++] = context_ptr.addr.value; + } + + + lbValue res = {}; + res.value = LLVMBuildCall(p->builder, value.value, args, arg_count, ""); + res.type = abi_rt; + return res; +} + +lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false) { + lbModule *m = p->module; + + Type *pt = base_type(value.type); + GB_ASSERT(pt->kind == Type_Proc); + Type *results = pt->Proc.results; + + if (p->entity != nullptr) { + if (p->entity->flags & EntityFlag_Disabled) { + return {}; + } + } + + lbAddr context_ptr = {}; + if (pt->Proc.calling_convention == ProcCC_Odin) { + context_ptr = lb_find_or_generate_context_ptr(p); + } + + set_procedure_abi_types(heap_allocator(), pt); + + bool is_c_vararg = pt->Proc.c_vararg; + isize param_count = pt->Proc.param_count; + if (is_c_vararg) { + GB_ASSERT(param_count-1 <= args.count); + param_count -= 1; + } else { + GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count); + } + + auto processed_args = array_make(heap_allocator(), 0, args.count); + + for (isize i = 0; i < param_count; i++) { + Entity *e = pt->Proc.params->Tuple.variables[i]; + if (e->kind != Entity_Variable) { + array_add(&processed_args, args[i]); + continue; + } + GB_ASSERT(e->flags & EntityFlag_Param); + + Type *original_type = e->type; + Type *new_type = pt->Proc.abi_compat_params[i]; + Type *arg_type = args[i].type; + if (are_types_identical(arg_type, new_type)) { + // NOTE(bill): Done + array_add(&processed_args, args[i]); + } else if (!are_types_identical(original_type, new_type)) { + if (is_type_pointer(new_type) && !is_type_pointer(original_type)) { + if (e->flags&EntityFlag_ImplicitReference) { + array_add(&processed_args, lb_address_from_load_or_generate_local(p, args[i])); + } else if (!is_type_pointer(arg_type)) { + array_add(&processed_args, lb_copy_value_to_ptr(p, args[i], original_type, 16)); + } + } else if (is_type_integer(new_type) || is_type_float(new_type)) { + array_add(&processed_args, lb_emit_transmute(p, args[i], new_type)); + } else if (new_type == t_llvm_bool) { + array_add(&processed_args, lb_emit_conv(p, args[i], new_type)); + } else if (is_type_simd_vector(new_type)) { + array_add(&processed_args, lb_emit_transmute(p, args[i], new_type)); + } else if (is_type_tuple(new_type)) { + Type *abi_type = pt->Proc.abi_compat_params[i]; + Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type); + lbValue x = lb_emit_transmute(p, args[i], st); + for (isize j = 0; j < new_type->Tuple.variables.count; j++) { + lbValue xx = lb_emit_struct_ev(p, x, cast(i32)j); + array_add(&processed_args, xx); + } + } + } else { + lbValue x = lb_emit_conv(p, args[i], new_type); + array_add(&processed_args, x); + } + } + + if (inlining == ProcInlining_none) { + inlining = p->inlining; + } + + lbValue result = {}; + + Type *abi_rt = pt->Proc.abi_compat_result_type; + Type *rt = reduce_tuple_to_single_type(results); + if (pt->Proc.return_by_pointer) { + lbValue return_ptr = {}; + if (use_return_ptr_hint && p->return_ptr_hint_value.value != nullptr) { + if (are_types_identical(type_deref(p->return_ptr_hint_value.type), rt)) { + return_ptr = p->return_ptr_hint_value; + p->return_ptr_hint_used = true; + } + } + if (return_ptr.value == nullptr) { + lbAddr r = lb_add_local_generated(p, rt, true); + return_ptr = r.addr; + } + GB_ASSERT(is_type_pointer(return_ptr.type)); + lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining); + result = lb_emit_load(p, return_ptr); + } else { + lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining); + if (abi_rt != results) { + result = lb_emit_transmute(p, result, rt); + } + } + + // if (value->kind == irValue_Proc) { + // lbProcedure *the_proc = &value->Proc; + // Entity *e = the_proc->entity; + // if (e != nullptr && entity_has_deferred_procedure(e)) { + // DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind; + // Entity *deferred_entity = e->Procedure.deferred_procedure.entity; + // lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity)); + // GB_ASSERT(deferred_found != nullptr); + // lbValue deferred = *deferred_found; + + + // auto in_args = args; + // Array result_as_args = {}; + // switch (kind) { + // case DeferredProcedure_none: + // break; + // case DeferredProcedure_in: + // result_as_args = in_args; + // break; + // case DeferredProcedure_out: + // result_as_args = ir_value_to_array(p, result); + // break; + // } + + // ir_add_defer_proc(p, p->scope_index, deferred, result_as_args); + // } + // } + + return result; +} + lbValue lb_emit_ev(lbProcedure *p, lbValue value, i32 index) { return {}; } @@ -1870,6 +2168,8 @@ void lb_fill_slice(lbProcedure *p, lbAddr slice, lbValue base_elem, lbValue len) lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { + lbModule *m = p->module; + TypeAndValue tv = type_and_value_of_expr(expr); ast_node(ce, CallExpr, expr); @@ -1906,7 +2206,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { { u64 u = big_int_to_u64(&v.value_integer); lbValue x = {}; - x.value = LLVMConstInt(lb_type(t_uintptr), u, false); + x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false); x.type = t_uintptr; x = lb_emit_conv(p, x, t_rawptr); value = lb_emit_conv(p, x, proc_expr->tav.type); @@ -1916,7 +2216,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { { u64 u = cast(u64)v.value_pointer; lbValue x = {}; - x.value = LLVMConstInt(lb_type(t_uintptr), u, false); + x.value = LLVMConstInt(lb_type(m, t_uintptr), u, false); x.type = t_uintptr; x = lb_emit_conv(p, x, t_rawptr); value = lb_emit_conv(p, x, proc_expr->tav.type); @@ -1947,7 +2247,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { GB_ASSERT(index >= 0); TypeAndValue tav = type_and_value_of_expr(fv->value); if (tav.mode == Addressing_Type) { - args[index] = lb_const_nil(tav.type); + args[index] = lb_const_nil(m, tav.type); } else { args[index] = lb_build_expr(p, fv->value); } @@ -1956,7 +2256,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { for (isize i = 0; i < args.count; i++) { Entity *e = params->variables[i]; if (e->kind == Entity_TypeName) { - args[i] = lb_const_nil(e->type); + args[i] = lb_const_nil(m, e->type); } else if (e->kind == Entity_Constant) { continue; } else { @@ -1967,7 +2267,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value); break; case ParameterValue_Nil: - args[i] = lb_const_nil(e->type); + args[i] = lb_const_nil(m, e->type); break; case ParameterValue_Location: args[i] = lb_emit_source_code_location(p, p->entity->token.string, ast_token(expr).pos); @@ -2029,7 +2329,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { Ast *arg = ce->args[i]; TypeAndValue arg_tv = type_and_value_of_expr(arg); if (arg_tv.mode == Addressing_Type) { - args[arg_index++] = lb_const_nil(arg_tv.type); + args[arg_index++] = lb_const_nil(m, arg_tv.type); } else { lbValue a = lb_build_expr(p, arg); Type *at = a.type; @@ -2064,7 +2364,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { args[arg_index++] = lb_const_value(p->module, e->type, e->Variable.param_value.value); break; case ParameterValue_Nil: - args[arg_index++] = lb_const_nil(e->type); + args[arg_index++] = lb_const_nil(m, e->type); break; case ParameterValue_Location: args[arg_index++] = lb_emit_source_code_location(p, proc_name, pos); @@ -2141,7 +2441,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { } lbValue base_elem = lb_emit_array_epi(p, base_array.addr, 0); - lbValue len = lb_const_int(t_int, slice_len); + lbValue len = lb_const_int(m, t_int, slice_len); lb_fill_slice(p, slice, base_elem, len); } @@ -2158,7 +2458,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { args[i] = lb_const_value(p->module, e->type, e->Variable.param_value.value); break; case ParameterValue_Nil: - args[i] = lb_const_nil(e->type); + args[i] = lb_const_nil(m, e->type); break; case ParameterValue_Location: args[i] = lb_emit_source_code_location(p, proc_name, pos); @@ -2181,6 +2481,8 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { lbValue lb_build_expr(lbProcedure *p, Ast *expr) { + lbModule *m = p->module; + expr = unparen_expr(expr); TypeAndValue tv = type_and_value_of_expr(expr); @@ -2210,7 +2512,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { case_end; case_ast_node(u, Undef, expr); - return lbValue{LLVMGetUndef(lb_type(tv.type)), tv.type}; + return lbValue{LLVMGetUndef(lb_type(m, tv.type)), tv.type}; case_end; case_ast_node(i, Ident, expr); @@ -2223,7 +2525,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { LIT(token.pos.file), token.pos.line, token.pos.column); return {}; } else if (e->kind == Entity_Nil) { - return lb_const_nil(tv.type); + return lb_const_nil(m, tv.type); } auto *found = map_get(&p->module->values, hash_entity(e)); @@ -2257,6 +2559,82 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { +bool lb_init_generator(lbGenerator *gen, Checker *c) { + if (global_error_collector.count != 0) { + return false; + } + + isize tc = c->parser->total_token_count; + if (tc < 2) { + return false; + } + + + String init_fullpath = c->parser->init_fullpath; + + if (build_context.out_filepath.len == 0) { + gen->output_name = remove_directory_from_path(init_fullpath); + gen->output_name = remove_extension_from_path(gen->output_name); + gen->output_base = gen->output_name; + } else { + gen->output_name = build_context.out_filepath; + isize pos = string_extension_position(gen->output_name); + if (pos < 0) { + gen->output_base = gen->output_name; + } else { + gen->output_base = substring(gen->output_name, 0, pos); + } + } + gbAllocator ha = heap_allocator(); + gen->output_base = path_to_full_path(ha, gen->output_base); + + gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len); + output_file_path = gb_string_appendc(output_file_path, ".obj"); + defer (gb_string_free(output_file_path)); + + gbFileError err = gb_file_create(&gen->output_file, output_file_path); + if (err != gbFileError_None) { + gb_printf_err("Failed to create file %s\n", output_file_path); + return false; + } + + + gen->info = &c->info; + gen->module.info = &c->info; + + // gen->ctx = LLVMContextCreate(); + gen->module.ctx = LLVMGetGlobalContext(); + gen->module.mod = LLVMModuleCreateWithNameInContext("odin_module", gen->module.ctx); + map_init(&gen->module.types, heap_allocator()); + map_init(&gen->module.values, heap_allocator()); + map_init(&gen->module.members, heap_allocator()); + map_init(&gen->module.const_strings, heap_allocator()); + map_init(&gen->module.const_string_byte_slices, heap_allocator()); + + return true; +} + +lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value={}) { + GB_ASSERT(type != nullptr); + type = default_type(type); + + isize max_len = 7+8+1; + u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len); + isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index); + m->global_generated_index++; + String name = make_string(str, len-1); + + Scope *scope = nullptr; + Entity *e = alloc_entity_variable(scope, make_token_ident(name), type); + lbValue g = {}; + g.type = alloc_type_pointer(type); + g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str); + lb_add_entity(m, e, g); + lb_add_member(m, name, g); + return lb_addr(g); +} + + void lb_generate_module(lbGenerator *gen) { lbModule *m = &gen->module; LLVMModuleRef mod = gen->module.mod; @@ -2266,10 +2644,107 @@ void lb_generate_module(lbGenerator *gen) { arena_init(&temp_arena, heap_allocator()); gbAllocator temp_allocator = arena_allocator(&temp_arena); - Entity *entry_point = info->entry_point; + gen->module.global_default_context = lb_add_global_generated(m, t_context, {}); + auto *min_dep_set = &info->minimum_dependency_set; + + isize global_variable_max_count = 0; + Entity *entry_point = info->entry_point; + bool has_dll_main = false; + bool has_win_main = false; + + for_array(i, info->entities) { + Entity *e = info->entities[i]; + String name = e->token.string; + + bool is_global = e->pkg != nullptr; + + if (e->kind == Entity_Variable) { + global_variable_max_count++; + } else if (e->kind == Entity_Procedure && !is_global) { + if ((e->scope->flags&ScopeFlag_Init) && name == "main") { + GB_ASSERT(e == entry_point); + // entry_point = e; + } + if (e->Procedure.is_export || + (e->Procedure.link_name.len > 0) || + ((e->scope->flags&ScopeFlag_File) && e->Procedure.link_name.len > 0)) { + if (!has_dll_main && name == "DllMain") { + has_dll_main = true; + } else if (!has_win_main && name == "WinMain") { + has_win_main = true; + } + } + } + } + + struct GlobalVariable { + lbValue var; + lbValue init; + DeclInfo *decl; + }; + auto global_variables = array_make(heap_allocator(), 0, global_variable_max_count); + + for_array(i, info->variable_init_order) { + DeclInfo *d = info->variable_init_order[i]; + + 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 = lb_get_entity_name(m, e); + + if (true) { + continue; + } + + lbValue g = {}; + g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(heap_allocator(), name)); + g.type = alloc_type_pointer(e->type); + // lbValue g = ir_value_global(e, nullptr); + // g->Global.name = name; + // g->Global.thread_local_model = e->Variable.thread_local_model; + // g->Global.is_foreign = is_foreign; + // g->Global.is_export = is_export; + + GlobalVariable var = {}; + var.var = g; + var.decl = decl; + + if (decl->init_expr != nullptr && !is_type_any(e->type)) { + TypeAndValue tav = type_and_value_of_expr(decl->init_expr); + 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); + } + } + } + + array_add(&global_variables, var); + + lb_add_entity(m, e, g); + lb_add_member(m, name, g); + } + + for_array(i, info->entities) { // arena_free_all(&temp_arena); // gbAllocator a = temp_allocator; @@ -2311,30 +2786,34 @@ void lb_generate_module(lbGenerator *gen) { continue; } - String mangled_name = lb_get_entity_name(m, e); - - if (e->pkg->name != "demo") { + if (is_type_polymorphic(e->type)) { continue; } + String mangled_name = lb_get_entity_name(m, e); + switch (e->kind) { case Entity_TypeName: + lb_type(m, e->type); break; case Entity_Procedure: - break; - } + { + if (e->pkg->name != "demo") { + continue; + } - if (e->kind == Entity_Procedure) { - lbProcedure *p = lb_create_procedure(m, e); + lbProcedure *p = lb_create_procedure(m, e); - if (p->body != nullptr) { // Build Procedure - lb_begin_procedure_body(p); - lb_build_stmt(p, p->body); - lb_end_procedure_body(p); - } + if (p->body != nullptr) { // Build Procedure + lb_begin_procedure_body(p); + lb_build_stmt(p, p->body); + lb_end_procedure_body(p); + } - lb_end_procedure(p); + lb_end_procedure(p); + } + break; } } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp new file mode 100644 index 000000000..a9fd6de7e --- /dev/null +++ b/src/llvm_backend.hpp @@ -0,0 +1,231 @@ +#include "llvm-c/Core.h" +#include "llvm-c/ExecutionEngine.h" +#include "llvm-c/Target.h" +#include "llvm-c/Analysis.h" +#include "llvm-c/Object.h" +#include "llvm-c/BitWriter.h" +#include "llvm-c/Transforms/AggressiveInstCombine.h" +#include "llvm-c/Transforms/InstCombine.h" +#include "llvm-c/Transforms/IPO.h" + +struct lbValue { + LLVMValueRef value; + Type *type; +}; + + +enum lbAddrKind { + lbAddr_Default, + lbAddr_Map, + lbAddr_BitField, + lbAddr_Context, + lbAddr_SoaVariable, +}; + +struct lbAddr { + lbAddrKind kind; + lbValue addr; + union { + struct { + lbValue key; + Type *type; + Type *result; + } map; + struct { + i32 value_index; + } bit_field; + struct { + Selection sel; + } ctx; + struct { + lbValue index; + Ast *index_expr; + } soa; + }; +}; + +struct lbModule { + LLVMModuleRef mod; + LLVMContextRef ctx; + CheckerInfo *info; + + Map types; // Key: Type * + + Map values; // Key: Entity * + Map members; // Key: String + + Map const_strings; // Key: String + Map const_string_byte_slices; // Key: String + + lbAddr global_default_context; + + u32 global_array_index; + u32 global_generated_index; +}; + +struct lbGenerator { + lbModule module; + CheckerInfo *info; + + gbFile output_file; + String output_base; + String output_name; +}; + + +struct lbBlock { + LLVMBasicBlockRef block; + Scope *scope; + isize scope_index; +}; + +struct lbBranchBlocks { + Ast *label; + lbBlock *break_; + lbBlock *continue_; +}; + +enum lbCallingConventionKind { + lbCallingConvention_C = 0, + lbCallingConvention_Fast = 8, + lbCallingConvention_Cold = 9, + lbCallingConvention_GHC = 10, + lbCallingConvention_HiPE = 11, + lbCallingConvention_WebKit_JS = 12, + lbCallingConvention_AnyReg = 13, + lbCallingConvention_PreserveMost = 14, + lbCallingConvention_PreserveAll = 15, + lbCallingConvention_Swift = 16, + lbCallingConvention_CXX_FAST_TLS = 17, + lbCallingConvention_FirstTargetCC = 64, + lbCallingConvention_X86_StdCall = 64, + lbCallingConvention_X86_FastCall = 65, + lbCallingConvention_ARM_APCS = 66, + lbCallingConvention_ARM_AAPCS = 67, + lbCallingConvention_ARM_AAPCS_VFP = 68, + lbCallingConvention_MSP430_INTR = 69, + lbCallingConvention_X86_ThisCall = 70, + lbCallingConvention_PTX_Kernel = 71, + lbCallingConvention_PTX_Device = 72, + lbCallingConvention_SPIR_FUNC = 75, + lbCallingConvention_SPIR_KERNEL = 76, + lbCallingConvention_Intel_OCL_BI = 77, + lbCallingConvention_X86_64_SysV = 78, + lbCallingConvention_Win64 = 79, + lbCallingConvention_X86_VectorCall = 80, + lbCallingConvention_HHVM = 81, + lbCallingConvention_HHVM_C = 82, + lbCallingConvention_X86_INTR = 83, + lbCallingConvention_AVR_INTR = 84, + lbCallingConvention_AVR_SIGNAL = 85, + lbCallingConvention_AVR_BUILTIN = 86, + lbCallingConvention_AMDGPU_VS = 87, + lbCallingConvention_AMDGPU_GS = 88, + lbCallingConvention_AMDGPU_PS = 89, + lbCallingConvention_AMDGPU_CS = 90, + lbCallingConvention_AMDGPU_KERNEL = 91, + lbCallingConvention_X86_RegCall = 92, + lbCallingConvention_AMDGPU_HS = 93, + lbCallingConvention_MSP430_BUILTIN = 94, + lbCallingConvention_AMDGPU_LS = 95, + lbCallingConvention_AMDGPU_ES = 96, + lbCallingConvention_AArch64_VectorCall = 97, + lbCallingConvention_MaxID = 1023, +}; + +lbCallingConventionKind const lb_calling_convention_map[ProcCC_MAX] = { + lbCallingConvention_C, // ProcCC_Invalid, + lbCallingConvention_C, // ProcCC_Odin, + lbCallingConvention_C, // ProcCC_Contextless, + lbCallingConvention_C, // ProcCC_CDecl, + lbCallingConvention_X86_StdCall, // ProcCC_StdCall, + lbCallingConvention_X86_FastCall, // ProcCC_FastCall, + + lbCallingConvention_C, // ProcCC_None, +}; + +struct lbContextData { + lbAddr ctx; + isize scope_index; +}; + + +struct lbProcedure { + lbProcedure *parent; + Array children; + + Entity * entity; + lbModule * module; + String name; + Type * type; + Ast * type_expr; + Ast * body; + u64 tags; + ProcInlining inlining; + bool is_foreign; + bool is_export; + bool is_entry_point; + + + LLVMValueRef value; + LLVMBuilderRef builder; + + lbAddr return_ptr; + Array params; + Array blocks; + Array branch_blocks; + Scope * curr_scope; + i32 scope_index; + lbBlock * decl_block; + lbBlock * entry_block; + lbBlock * curr_block; + + Array context_stack; + + lbValue return_ptr_hint_value; + Ast * return_ptr_hint_ast; + bool return_ptr_hint_used; +}; + + +bool lb_init_generator(lbGenerator *gen, Checker *c); +void lb_generate_module(lbGenerator *gen); + +String lb_mangle_name(lbModule *m, Entity *e); +String lb_get_entity_name(lbModule *m, Entity *e, String name = {}); + +LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value); +void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value); +void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name); +lbProcedure *lb_create_procedure(lbModule *module, Entity *entity); +void lb_end_procedure(lbProcedure *p); + + +LLVMTypeRef lb_type(lbModule *m, Type *type); + +lbBlock *lb_create_block(lbProcedure *p, char const *name); + +lbValue lb_const_nil(lbModule *m, Type *type); +lbValue lb_const_value(lbModule *m, Type *type, ExactValue value); + + +lbAddr lb_addr(lbValue addr); +Type *lb_addr_type(lbAddr const &addr); +LLVMTypeRef lb_addr_lb_type(lbAddr const &addr); +void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue const &value); +lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr); +lbValue lb_emit_load(lbProcedure *p, lbValue v); + +void lb_build_stmt (lbProcedure *p, Ast *stmt); +lbValue lb_build_expr (lbProcedure *p, Ast *expr); +void lb_build_stmt_list(lbProcedure *p, Array const &stmts); + +lbValue lb_build_gep(lbProcedure *p, lbValue const &value, i32 index) ; + + +lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type); + + + +lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t); +lbValue lb_build_call_expr(lbProcedure *p, Ast *expr); diff --git a/src/parser.hpp b/src/parser.hpp index cdfd4eba1..28c5d880a 100644 --- a/src/parser.hpp +++ b/src/parser.hpp @@ -174,12 +174,10 @@ enum ProcCallingConvention { ProcCC_StdCall, ProcCC_FastCall, - // TODO(bill): Add extra calling conventions - // ProcCC_VectorCall, - // ProcCC_ClrCall, - ProcCC_None, + ProcCC_MAX, + ProcCC_ForeignBlockDefault = -1, }; diff --git a/src/types.cpp b/src/types.cpp index a6f1e2ae5..fde8cd5a5 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -301,7 +301,6 @@ struct Type { i64 cached_size; i64 cached_align; u32 flags; // TypeFlag - LLVMTypeRef llvm_type; bool failure; }; -- cgit v1.2.3 From 992858b687d9ff53b53239864114ff7ece22449d Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 5 Feb 2020 22:39:23 +0000 Subject: Add ReturnStmt --- src/llvm_backend.cpp | 1718 +++++++++++++++++++++++++++++++++++++++++++++++--- src/llvm_backend.hpp | 26 +- src/types.cpp | 14 +- 3 files changed, 1678 insertions(+), 80 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index c036da85c..5d9d0b544 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -452,7 +452,9 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { return lb_type(m, base_enum_type(type)); case Type_Tuple: - { + if (type->Tuple.variables.count == 1) { + return lb_type(m, type->Tuple.variables[0]->type); + } else { unsigned field_count = cast(unsigned)(type->Tuple.variables.count); LLVMTypeRef *fields = gb_alloc_array(heap_allocator(), LLVMTypeRef, field_count); defer (gb_free(heap_allocator(), fields)); @@ -682,6 +684,103 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { return p; } +lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) { + lbParamPasskind kind = lbParamPass_Value; + + if (e != nullptr && abi_type != e->type) { + if (is_type_pointer(abi_type)) { + GB_ASSERT(e->kind == Entity_Variable); + kind = lbParamPass_Pointer; + if (e->flags&EntityFlag_Value) { + kind = lbParamPass_ConstRef; + } + } else if (is_type_integer(abi_type)) { + kind = lbParamPass_Integer; + } else if (abi_type == t_llvm_bool) { + kind = lbParamPass_Value; + } else if (is_type_simd_vector(abi_type)) { + kind = lbParamPass_BitCast; + } else if (is_type_float(abi_type)) { + kind = lbParamPass_BitCast; + } else if (is_type_tuple(abi_type)) { + kind = lbParamPass_Tuple; + } else { + GB_PANIC("Invalid abi type pass kind %s", type_to_string(abi_type)); + } + } + + if (kind_) *kind_ = kind; + lbValue res = {}; + res.value = LLVMGetParam(p->value, cast(unsigned)index); + res.type = abi_type; + return res; +} + +lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 index) { + lbParamPasskind kind = lbParamPass_Value; + lbValue v = lb_value_param(p, e, abi_type, index, &kind); + array_add(&p->params, v); + + lbValue res = {}; + + switch (kind) { + case lbParamPass_Value: { + lbAddr l = lb_add_local(p, e->type, e, false, index); + lbValue x = v; + if (abi_type == t_llvm_bool) { + x = lb_emit_conv(p, x, t_bool); + } + lb_addr_store(p, l, x); + return x; + } + case lbParamPass_Pointer: + lb_add_entity(p->module, e, v); + return lb_emit_load(p, v); + + case lbParamPass_Integer: { + lbAddr l = lb_add_local(p, e->type, e, false, index); + lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(p->type)); + lb_emit_store(p, iptr, v); + return lb_addr_load(p, l); + } + + case lbParamPass_ConstRef: + lb_add_entity(p->module, e, v); + return lb_emit_load(p, v); + + case lbParamPass_BitCast: { + lbAddr l = lb_add_local(p, e->type, e, false, index); + lbValue x = lb_emit_transmute(p, v, e->type); + lb_addr_store(p, l, x); + return x; + } + case lbParamPass_Tuple: { + lbAddr l = lb_add_local(p, e->type, e, true, index); + Type *st = struct_type_from_systemv_distribute_struct_fields(abi_type); + lbValue ptr = lb_emit_transmute(p, l.addr, alloc_type_pointer(st)); + if (abi_type->Tuple.variables.count > 0) { + array_pop(&p->params); + } + for_array(i, abi_type->Tuple.variables) { + Type *t = abi_type->Tuple.variables[i]->type; + + lbParamPasskind elem_kind = lbParamPass_Value; + lbValue elem = lb_value_param(p, nullptr, t, index+cast(i32)i, &elem_kind); + array_add(&p->params, elem); + + lbValue dst = lb_emit_struct_ep(p, ptr, cast(i32)i); + lb_emit_store(p, dst, elem); + } + return lb_addr_load(p, l); + } + + } + + GB_PANIC("Unreachable"); + return {}; +} + + void lb_begin_procedure_body(lbProcedure *p) { DeclInfo *decl = decl_info_of_entity(p->entity); if (decl != nullptr) { @@ -702,6 +801,8 @@ void lb_begin_procedure_body(lbProcedure *p) { GB_ASSERT(p->type != nullptr); + i32 parameter_index = 0; + if (p->type->Proc.return_by_pointer) { // NOTE(bill): this must be parameter 0 Type *ptr_type = alloc_type_pointer(reduce_tuple_to_single_type(p->type->Proc.results)); @@ -714,9 +815,124 @@ void lb_begin_procedure_body(lbProcedure *p) { p->return_ptr = lb_addr(return_ptr_value); lb_add_entity(p->module, e, return_ptr_value); + + parameter_index += 1; + } + + if (p->type->Proc.params != nullptr) { + TypeTuple *params = &p->type->Proc.params->Tuple; + if (p->type_expr != nullptr) { + ast_node(pt, ProcType, p->type_expr); + isize param_index = 0; + isize q_index = 0; + + for_array(i, params->variables) { + ast_node(fl, FieldList, pt->params); + GB_ASSERT(fl->list.count > 0); + GB_ASSERT(fl->list[0]->kind == Ast_Field); + if (q_index == fl->list[param_index]->Field.names.count) { + q_index = 0; + param_index++; + } + ast_node(field, Field, fl->list[param_index]); + Ast *name = field->names[q_index++]; + + Entity *e = params->variables[i]; + if (e->kind != Entity_Variable) { + parameter_index += 1; + continue; + } + + Type *abi_type = p->type->Proc.abi_compat_params[i]; + if (e->token.string != "") { + lb_add_param(p, e, name, abi_type, parameter_index); + } + + if (is_type_tuple(abi_type)) { + parameter_index += cast(i32)abi_type->Tuple.variables.count; + } else { + parameter_index += 1; + } + } + } else { + auto abi_types = p->type->Proc.abi_compat_params; + + for_array(i, params->variables) { + Entity *e = params->variables[i]; + if (e->kind != Entity_Variable) { + parameter_index += 1; + continue; + } + Type *abi_type = e->type; + if (abi_types.count > 0) { + abi_type = abi_types[i]; + } + if (e->token.string != "") { + lb_add_param(p, e, nullptr, abi_type, parameter_index); + } + if (is_type_tuple(abi_type)) { + parameter_index += cast(i32)abi_type->Tuple.variables.count; + } else { + parameter_index += 1; + } + } + } } + if (p->type->Proc.has_named_results) { + GB_ASSERT(p->type->Proc.result_count > 0); + TypeTuple *results = &p->type->Proc.results->Tuple; + LLVMValueRef return_ptr = LLVMGetParam(p->value, 0); + + isize result_index = 0; + + for_array(i, results->variables) { + Entity *e = results->variables[i]; + if (e->kind != Entity_Variable) { + continue; + } + + if (e->token.string != "") { + GB_ASSERT(!is_blank_ident(e->token)); + + lbAddr res = lb_add_local(p, e->type, e); + gb_printf_err("%.*s\n", LIT(e->token.string)); + + lbValue c = {}; + switch (e->Variable.param_value.kind) { + case ParameterValue_Constant: + c = lb_const_value(p->module, e->type, e->Variable.param_value.value); + break; + case ParameterValue_Nil: + c = lb_const_nil(p->module, e->type); + break; + case ParameterValue_Location: + GB_PANIC("ParameterValue_Location"); + break; + } + if (c.value != nullptr) { + lb_addr_store(p, res, c); + } + } + + result_index += 1; + } + } + + if (p->type->Proc.calling_convention == ProcCC_Odin) { + Entity *e = alloc_entity_param(nullptr, make_token_ident(str_lit("__.context_ptr")), t_context_ptr, false, false); + e->flags |= EntityFlag_NoAlias; + lbValue param = {}; + param.value = LLVMGetParam(p->value, LLVMCountParams(p->value)-1); + param.type = e->type; + lb_add_entity(p->module, e, param); + lbAddr ctx_addr = {}; + ctx_addr.kind = lbAddr_Context; + ctx_addr.addr = param; + lbContextData ctx = {ctx_addr, p->scope_index}; + array_add(&p->context_stack, ctx); + } } void lb_end_procedure_body(lbProcedure *p) { @@ -748,13 +964,17 @@ lbBlock *lb_create_block(lbProcedure *p, char const *name) { return b; } -lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr) { +lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) { LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block); LLVMTypeRef llvm_type = lb_type(p->module, type); LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, ""); LLVMSetAlignment(ptr, 16); + if (zero_init) { + LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr); + } + LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); lbValue val = {}; @@ -951,6 +1171,76 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(as, AssignStmt, node); + if (as->op.kind == Token_Eq) { + auto lvals = array_make(heap_allocator(), 0, as->lhs.count); + + for_array(i, as->lhs) { + Ast *lhs = as->lhs[i]; + lbAddr lval = {}; + if (!is_blank_ident(lhs)) { + lval = lb_build_addr(p, lhs); + } + array_add(&lvals, lval); + } + + if (as->lhs.count == as->rhs.count) { + if (as->lhs.count == 1) { + Ast *rhs = as->rhs[0]; + lbValue init = lb_build_expr(p, rhs); + lb_addr_store(p, lvals[0], init); + } else { + auto inits = array_make(heap_allocator(), 0, lvals.count); + + for_array(i, as->rhs) { + lbValue init = lb_build_expr(p, as->rhs[i]); + array_add(&inits, init); + } + + for_array(i, inits) { + auto lval = lvals[i]; + lb_addr_store(p, lval, inits[i]); + } + } + } else { + auto inits = array_make(heap_allocator(), 0, lvals.count); + + for_array(i, as->rhs) { + lbValue init = lb_build_expr(p, as->rhs[i]); + Type *t = init.type; + // TODO(bill): refactor for code reuse as this is repeated a bit + if (t->kind == Type_Tuple) { + for_array(i, t->Tuple.variables) { + Entity *e = t->Tuple.variables[i]; + lbValue v = lb_emit_struct_ev(p, init, cast(i32)i); + array_add(&inits, v); + } + } else { + array_add(&inits, init); + } + } + + for_array(i, inits) { + lb_addr_store(p, lvals[i], inits[i]); + } + } + } else { + // // NOTE(bill): Only 1 += 1 is allowed, no tuples + // // +=, -=, etc + // i32 op = cast(i32)as->op.kind; + // op += Token_Add - Token_AddEq; // Convert += to + + // if (op == Token_CmpAnd || op == Token_CmpOr) { + // Type *type = as->lhs[0]->tav.type; + // lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type); + + // lbAddr lhs = lb_build_addr(p, as->lhs[0]); + // lb_addr_store(p, lhs, new_value); + // } else { + // lbAddr lhs = lb_build_addr(p, as->lhs[0]); + // lbValue value = lb_build_expr(p, as->rhs[0]); + // ir_build_assign_op(p, lhs, value, cast(TokenKind)op); + // } + return; + } case_end; case_ast_node(es, ExprStmt, node); @@ -974,15 +1264,53 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { } else if (return_count == 1) { Entity *e = tuple->variables[0]; if (res_count == 0) { - // lbValue *found = map_get(&p->module->values, hash_entity(e)); - // GB_ASSERT(found); - // res = lb_emit_load(p, *found); + lbValue *found = map_get(&p->module->values, hash_entity(e)); + GB_ASSERT(found); + res = lb_emit_load(p, *found); } else { res = lb_build_expr(p, rs->results[0]); res = lb_emit_conv(p, res, e->type); } } else { + auto results = array_make(heap_allocator(), 0, return_count); + + if (res_count != 0) { + for (isize res_index = 0; res_index < res_count; res_index++) { + lbValue res = lb_build_expr(p, rs->results[res_index]); + Type *t = res.type; + if (t->kind == Type_Tuple) { + for_array(i, t->Tuple.variables) { + Entity *e = t->Tuple.variables[i]; + lbValue v = lb_emit_struct_ev(p, res, cast(i32)i); + array_add(&results, v); + } + } else { + array_add(&results, res); + } + } + } else { + for (isize res_index = 0; res_index < return_count; res_index++) { + Entity *e = tuple->variables[res_index]; + lbValue *found = map_get(&p->module->values, hash_entity(e)); + GB_ASSERT(found); + lbValue res = lb_emit_load(p, *found); + array_add(&results, res); + } + } + GB_ASSERT(results.count == return_count); + + Type *ret_type = p->type->Proc.results; + // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops + res = lb_add_local_generated(p, ret_type, false).addr; + for_array(i, results) { + Entity *e = tuple->variables[i]; + lbValue res = lb_emit_conv(p, results[i], e->type); + lbValue field = lb_emit_struct_ep(p, res, cast(i32)i); + lb_emit_store(p, field, res); + } + + res = lb_emit_load(p, res); } if (p->type->Proc.return_by_pointer) { @@ -1876,12 +2204,88 @@ lbValue lb_copy_value_to_ptr(lbProcedure *p, lbValue val, Type *new_type, i64 al lbAddr ptr = lb_add_local_generated(p, new_type, false); LLVMSetAlignment(ptr.addr.value, cast(unsigned)alignment); lb_addr_store(p, ptr, val); - + ptr.kind = lbAddr_Context; return ptr.addr; } lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { - return {}; + gbAllocator a = heap_allocator(); + GB_ASSERT(is_type_pointer(s.type)); + Type *t = base_type(type_deref(s.type)); + Type *result_type = nullptr; + + if (t->kind == Type_Opaque) { + t = t->Opaque.elem; + } + + if (is_type_struct(t)) { + result_type = alloc_type_pointer(t->Struct.fields[index]->type); + } else if (is_type_union(t)) { + GB_ASSERT(index == -1); + // return ir_emit_union_tag_ptr(proc, s); + GB_PANIC("ir_emit_union_tag_ptr"); + } else if (is_type_tuple(t)) { + GB_ASSERT(t->Tuple.variables.count > 0); + result_type = alloc_type_pointer(t->Tuple.variables[index]->type); + } else if (is_type_complex(t)) { + Type *ft = base_complex_elem_type(t); + switch (index) { + case 0: result_type = alloc_type_pointer(ft); break; + case 1: result_type = alloc_type_pointer(ft); break; + } + } else if (is_type_quaternion(t)) { + Type *ft = base_complex_elem_type(t); + switch (index) { + case 0: result_type = alloc_type_pointer(ft); break; + case 1: result_type = alloc_type_pointer(ft); break; + case 2: result_type = alloc_type_pointer(ft); break; + case 3: result_type = alloc_type_pointer(ft); break; + } + } else if (is_type_slice(t)) { + switch (index) { + case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->Slice.elem)); break; + case 1: result_type = alloc_type_pointer(t_int); break; + } + } else if (is_type_string(t)) { + switch (index) { + case 0: result_type = alloc_type_pointer(t_u8_ptr); break; + case 1: result_type = alloc_type_pointer(t_int); break; + } + } else if (is_type_any(t)) { + switch (index) { + case 0: result_type = alloc_type_pointer(t_rawptr); break; + case 1: result_type = alloc_type_pointer(t_typeid); break; + } + } else if (is_type_dynamic_array(t)) { + switch (index) { + case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->DynamicArray.elem)); break; + case 1: result_type = t_int_ptr; break; + case 2: result_type = t_int_ptr; break; + case 3: result_type = t_allocator_ptr; break; + } + } else if (is_type_map(t)) { + init_map_internal_types(t); + Type *itp = alloc_type_pointer(t->Map.internal_type); + s = lb_emit_transmute(p, s, itp); + + Type *gst = t->Map.internal_type; + GB_ASSERT(gst->kind == Type_Struct); + switch (index) { + case 0: result_type = alloc_type_pointer(gst->Struct.fields[0]->type); break; + case 1: result_type = alloc_type_pointer(gst->Struct.fields[1]->type); break; + } + } else if (is_type_array(t)) { + return lb_emit_array_epi(p, s, index); + } else { + GB_PANIC("TODO(bill): struct_gep type: %s, %d", type_to_string(s.type), index); + } + + GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index); + + lbValue res = {}; + res.value = LLVMBuildStructGEP2(p->builder, lb_type(p->module, result_type), s.value, cast(unsigned)index, ""); + res.type = result_type; + return res; } lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) { @@ -2049,7 +2453,7 @@ lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, GB_ASSERT_MSG(param_count == args.count, "%td == %td", param_count, args.count); } - auto processed_args = array_make(heap_allocator(), 0, args.count); + auto processed_args = array_make(heap_allocator(), 0, args.count); for (isize i = 0; i < param_count; i++) { Entity *e = pt->Proc.params->Tuple.variables[i]; @@ -2135,7 +2539,7 @@ lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, // auto in_args = args; - // Array result_as_args = {}; + // Array result_as_args = {}; // switch (kind) { // case DeferredProcedure_none: // break; @@ -2154,12 +2558,18 @@ lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, return result; } -lbValue lb_emit_ev(lbProcedure *p, lbValue value, i32 index) { - return {}; -} +lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, i32 index) { + Type *t = s.type; + GB_ASSERT(is_type_pointer(t)); + Type *st = base_type(type_deref(t)); + GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st)); -lbValue lb_emit_array_epi(lbProcedure *p, lbValue value, i32 index){ - return {}; + GB_ASSERT(0 <= index); + Type *ptr = base_array_type(st); + lbValue res = {}; + res.value = LLVMBuildStructGEP2(p->builder, lb_type(p->module, ptr), s.value, index, ""); + res.type = alloc_type_pointer(ptr); + return res; } void lb_fill_slice(lbProcedure *p, lbAddr slice, lbValue base_elem, lbValue len) { @@ -2236,7 +2646,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { set_procedure_abi_types(heap_allocator(), proc_type_); if (is_call_expr_field_value(ce)) { - auto args = array_make(heap_allocator(), pt->param_count); + auto args = array_make(heap_allocator(), pt->param_count); for_array(arg_index, ce->args) { Ast *arg = ce->args[arg_index]; @@ -2307,7 +2717,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { param_count = pt->params->Tuple.variables.count; } - auto args = array_make(heap_allocator(), cast(isize)gb_max(param_count, arg_count)); + auto args = array_make(heap_allocator(), cast(isize)gb_max(param_count, arg_count)); isize variadic_index = pt->variadic_index; bool variadic = pt->variadic && variadic_index >= 0; bool vari_expand = ce->ellipsis.pos.line != 0; @@ -2336,7 +2746,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { if (at->kind == Type_Tuple) { for_array(i, at->Tuple.variables) { Entity *e = at->Tuple.variables[i]; - lbValue v = lb_emit_ev(p, a, cast(i32)i); + lbValue v = lb_emit_struct_ev(p, a, cast(i32)i); args[arg_index++] = v; } } else { @@ -2507,7 +2917,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { case_end; case_ast_node(i, Implicit, expr); - // return ir_addr_load(p, ir_build_addr(p, expr)); + // return ir_addr_load(p, lb_build_addr(p, expr)); GB_PANIC("TODO(bill): Implicit"); case_end; @@ -2537,7 +2947,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { } return lb_emit_load(p, v); // } else if (e != nullptr && e->kind == Entity_Variable) { - // return ir_addr_load(p, ir_build_addr(p, expr)); + // return ir_addr_load(p, lb_build_addr(p, expr)); } GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr); return {}; @@ -2557,78 +2967,1244 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { } +lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) { + GB_ASSERT(e != nullptr); + if (e->kind == Entity_Constant) { + Type *t = default_type(type_of_expr(expr)); + lbValue v = lb_const_value(p->module, t, e->Constant.value); + lbAddr g = lb_add_global_generated(p->module, t, v); + return g; + } -bool lb_init_generator(lbGenerator *gen, Checker *c) { - if (global_error_collector.count != 0) { - return false; + lbValue v = {}; + lbValue *found = map_get(&p->module->values, hash_entity(e)); + if (found) { + v = *found; + } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) { + // NOTE(bill): Calculate the using variable every time + GB_PANIC("HERE: using variable"); + // v = lb_get_using_variable(p, e); } - isize tc = c->parser->total_token_count; - if (tc < 2) { - return false; + if (v.value == nullptr) { + error(expr, "%.*s Unknown value: %.*s, entity: %p %.*s", + LIT(p->name), + LIT(e->token.string), e, LIT(entity_strings[e->kind])); + GB_PANIC("Unknown value"); } + return lb_addr(v); +} - String init_fullpath = c->parser->init_fullpath; +lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { + expr = unparen_expr(expr); - if (build_context.out_filepath.len == 0) { - gen->output_name = remove_directory_from_path(init_fullpath); - gen->output_name = remove_extension_from_path(gen->output_name); - gen->output_base = gen->output_name; - } else { - gen->output_name = build_context.out_filepath; - isize pos = string_extension_position(gen->output_name); - if (pos < 0) { - gen->output_base = gen->output_name; + switch (expr->kind) { + case_ast_node(i, Implicit, expr); + lbAddr v = {}; + switch (i->kind) { + case Token_context: + v = lb_find_or_generate_context_ptr(p); + break; + } + + GB_ASSERT(v.addr.value != nullptr); + return v; + case_end; + + case_ast_node(i, Ident, expr); + if (is_blank_ident(expr)) { + lbAddr val = {}; + return val; + } + String name = i->token.string; + Entity *e = entity_of_ident(expr); + // GB_ASSERT(name == e->token.string); + return lb_build_addr_from_entity(p, e, expr); + case_end; + +#if 0 + case_ast_node(se, SelectorExpr, expr); + ir_emit_comment(proc, str_lit("SelectorExpr")); + Ast *sel = unparen_expr(se->selector); + if (sel->kind == Ast_Ident) { + String selector = sel->Ident.token.string; + TypeAndValue tav = type_and_value_of_expr(se->expr); + + if (tav.mode == Addressing_Invalid) { + // NOTE(bill): Imports + Entity *imp = entity_of_ident(se->expr); + if (imp != nullptr) { + GB_ASSERT(imp->kind == Entity_ImportName); + } + return ir_build_addr(proc, unparen_expr(se->selector)); + } + + + Type *type = base_type(tav.type); + if (tav.mode == Addressing_Type) { // Addressing_Type + Selection sel = lookup_field(type, selector, true); + Entity *e = sel.entity; + GB_ASSERT(e->kind == Entity_Variable); + GB_ASSERT(e->flags & EntityFlag_TypeField); + String name = e->token.string; + if (name == "names") { + lbValue ti_ptr = ir_type_info(proc, type); + lbValue variant = ir_emit_struct_ep(proc, ti_ptr, 2); + + lbValue names_ptr = nullptr; + + if (is_type_enum(type)) { + lbValue enum_info = ir_emit_conv(proc, variant, t_type_info_enum_ptr); + names_ptr = ir_emit_struct_ep(proc, enum_info, 1); + } else if (type->kind == Type_Struct) { + lbValue struct_info = ir_emit_conv(proc, variant, t_type_info_struct_ptr); + names_ptr = ir_emit_struct_ep(proc, struct_info, 1); + } + return ir_addr(names_ptr); + } else { + GB_PANIC("Unhandled TypeField %.*s", LIT(name)); + } + GB_PANIC("Unreachable"); + } + + Selection sel = lookup_field(type, selector, false); + GB_ASSERT(sel.entity != nullptr); + + + if (sel.entity->type->kind == Type_BitFieldValue) { + irAddr addr = ir_build_addr(proc, se->expr); + Type *bft = type_deref(ir_addr_type(addr)); + if (sel.index.count == 1) { + GB_ASSERT(is_type_bit_field(bft)); + i32 index = sel.index[0]; + return ir_addr_bit_field(ir_addr_get_ptr(proc, addr), index); + } else { + Selection s = sel; + s.index.count--; + i32 index = s.index[s.index.count-1]; + lbValue a = ir_addr_get_ptr(proc, addr); + a = ir_emit_deep_field_gep(proc, a, s); + return ir_addr_bit_field(a, index); + } + } else { + irAddr addr = ir_build_addr(proc, se->expr); + if (addr.kind == irAddr_Context) { + GB_ASSERT(sel.index.count > 0); + if (addr.ctx.sel.index.count >= 0) { + sel = selection_combine(addr.ctx.sel, sel); + } + addr.ctx.sel = sel; + + return addr; + } else if (addr.kind == irAddr_SoaVariable) { + lbValue index = addr.soa.index; + i32 first_index = sel.index[0]; + Selection sub_sel = sel; + sub_sel.index.data += 1; + sub_sel.index.count -= 1; + + lbValue arr = ir_emit_struct_ep(proc, addr.addr, first_index); + + Type *t = base_type(type_deref(ir_type(addr.addr))); + GB_ASSERT(is_type_soa_struct(t)); + + if (addr.soa.index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) { + lbValue len = ir_soa_struct_len(proc, addr.addr); + ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), addr.soa.index, len); + } + + lbValue item = nullptr; + + if (t->Struct.soa_kind == StructSoa_Fixed) { + item = ir_emit_array_ep(proc, arr, index); + } else { + item = ir_emit_load(proc, ir_emit_ptr_offset(proc, arr, index)); + } + if (sub_sel.index.count > 0) { + item = ir_emit_deep_field_gep(proc, item, sub_sel); + } + return ir_addr(item); + } + lbValue a = ir_addr_get_ptr(proc, addr); + a = ir_emit_deep_field_gep(proc, a, sel); + return ir_addr(a); + } } else { - gen->output_base = substring(gen->output_name, 0, pos); + GB_PANIC("Unsupported selector expression"); } - } - gbAllocator ha = heap_allocator(); - gen->output_base = path_to_full_path(ha, gen->output_base); + case_end; - gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len); - output_file_path = gb_string_appendc(output_file_path, ".obj"); - defer (gb_string_free(output_file_path)); + case_ast_node(ta, TypeAssertion, expr); + gbAllocator a = ir_allocator(); + TokenPos pos = ast_token(expr).pos; + lbValue e = ir_build_expr(proc, ta->expr); + Type *t = type_deref(ir_type(e)); + if (is_type_union(t)) { + Type *type = type_of_expr(expr); + lbValue v = ir_add_local_generated(proc, type, false); + ir_emit_comment(proc, str_lit("cast - union_cast")); + ir_emit_store(proc, v, ir_emit_union_cast(proc, ir_build_expr(proc, ta->expr), type, pos)); + return ir_addr(v); + } else if (is_type_any(t)) { + ir_emit_comment(proc, str_lit("cast - any_cast")); + Type *type = type_of_expr(expr); + return ir_emit_any_cast_addr(proc, ir_build_expr(proc, ta->expr), type, pos); + } else { + GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e))); + } + case_end; - gbFileError err = gb_file_create(&gen->output_file, output_file_path); - if (err != gbFileError_None) { - gb_printf_err("Failed to create file %s\n", output_file_path); - return false; - } + case_ast_node(ue, UnaryExpr, expr); + switch (ue->op.kind) { + case Token_And: { + return ir_build_addr(proc, ue->expr); + } + default: + GB_PANIC("Invalid unary expression for ir_build_addr"); + } + case_end; + case_ast_node(be, BinaryExpr, expr); + lbValue v = ir_build_expr(proc, expr); + Type *t = ir_type(v); + if (is_type_pointer(t)) { + return ir_addr(v); + } + return ir_addr(ir_address_from_load_or_generate_local(proc, v)); + case_end; - gen->info = &c->info; - gen->module.info = &c->info; + case_ast_node(ie, IndexExpr, expr); + ir_emit_comment(proc, str_lit("IndexExpr")); + Type *t = base_type(type_of_expr(ie->expr)); + gbAllocator a = ir_allocator(); + + bool deref = is_type_pointer(t); + t = base_type(type_deref(t)); + if (is_type_soa_struct(t)) { + // SOA STRUCTURES!!!! + lbValue val = ir_build_addr_ptr(proc, ie->expr); + if (deref) { + val = ir_emit_load(proc, val); + } - // gen->ctx = LLVMContextCreate(); - gen->module.ctx = LLVMGetGlobalContext(); - gen->module.mod = LLVMModuleCreateWithNameInContext("odin_module", gen->module.ctx); - map_init(&gen->module.types, heap_allocator()); - map_init(&gen->module.values, heap_allocator()); - map_init(&gen->module.members, heap_allocator()); - map_init(&gen->module.const_strings, heap_allocator()); - map_init(&gen->module.const_string_byte_slices, heap_allocator()); + lbValue index = ir_build_expr(proc, ie->index); + return ir_addr_soa_variable(val, index, ie->index); + } - return true; -} + if (ie->expr->tav.mode == Addressing_SoaVariable) { + // SOA Structures for slices/dynamic arrays + GB_ASSERT(is_type_pointer(type_of_expr(ie->expr))); -lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value={}) { - GB_ASSERT(type != nullptr); - type = default_type(type); + lbValue field = ir_build_expr(proc, ie->expr); + lbValue index = ir_build_expr(proc, ie->index); - isize max_len = 7+8+1; - u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len); - isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index); - m->global_generated_index++; - String name = make_string(str, len-1); - Scope *scope = nullptr; - Entity *e = alloc_entity_variable(scope, make_token_ident(name), type); - lbValue g = {}; - g.type = alloc_type_pointer(type); + if (!build_context.no_bounds_check) { + // TODO HACK(bill): Clean up this hack to get the length for bounds checking + GB_ASSERT(field->kind == irValue_Instr); + irInstr *instr = &field->Instr; + + GB_ASSERT(instr->kind == irInstr_Load); + lbValue a = instr->Load.address; + + GB_ASSERT(a->kind == irValue_Instr); + irInstr *b = &a->Instr; + GB_ASSERT(b->kind == irInstr_StructElementPtr); + lbValue base_struct = b->StructElementPtr.address; + + GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct)))); + lbValue len = ir_soa_struct_len(proc, base_struct); + ir_emit_bounds_check(proc, ast_token(ie->index), index, len); + } + + lbValue val = ir_emit_ptr_offset(proc, field, index); + return ir_addr(val); + } + + GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr)); + + if (is_type_map(t)) { + lbValue map_val = ir_build_addr_ptr(proc, ie->expr); + if (deref) { + map_val = ir_emit_load(proc, map_val); + } + + lbValue key = ir_build_expr(proc, ie->index); + key = ir_emit_conv(proc, key, t->Map.key); + + Type *result_type = type_of_expr(expr); + return ir_addr_map(map_val, key, t, result_type); + } + + lbValue using_addr = nullptr; + + switch (t->kind) { + case Type_Array: { + lbValue array = nullptr; + if (using_addr != nullptr) { + array = using_addr; + } else { + array = ir_build_addr_ptr(proc, ie->expr); + if (deref) { + array = ir_emit_load(proc, array); + } + } + lbValue index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + lbValue elem = ir_emit_array_ep(proc, array, index); + + auto index_tv = type_and_value_of_expr(ie->index); + if (index_tv.mode != Addressing_Constant) { + lbValue len = ir_const_int(t->Array.count); + ir_emit_bounds_check(proc, ast_token(ie->index), index, len); + } + return ir_addr(elem); + } + + case Type_EnumeratedArray: { + lbValue array = nullptr; + if (using_addr != nullptr) { + array = using_addr; + } else { + array = ir_build_addr_ptr(proc, ie->expr); + if (deref) { + array = ir_emit_load(proc, array); + } + } + + Type *index_type = t->EnumeratedArray.index; + + auto index_tv = type_and_value_of_expr(ie->index); + + lbValue index = nullptr; + if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) { + if (index_tv.mode == Addressing_Constant) { + ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value); + index = ir_value_constant(index_type, idx); + } else { + index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + index = ir_emit_arith(proc, Token_Sub, index, ir_value_constant(index_type, t->EnumeratedArray.min_value), index_type); + } + } else { + index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + } + + lbValue elem = ir_emit_array_ep(proc, array, index); + + if (index_tv.mode != Addressing_Constant) { + lbValue len = ir_const_int(t->EnumeratedArray.count); + ir_emit_bounds_check(proc, ast_token(ie->index), index, len); + } + return ir_addr(elem); + } + + case Type_Slice: { + lbValue slice = nullptr; + if (using_addr != nullptr) { + slice = ir_emit_load(proc, using_addr); + } else { + slice = ir_build_expr(proc, ie->expr); + if (deref) { + slice = ir_emit_load(proc, slice); + } + } + lbValue elem = ir_slice_elem(proc, slice); + lbValue index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + lbValue len = ir_slice_len(proc, slice); + ir_emit_bounds_check(proc, ast_token(ie->index), index, len); + lbValue v = ir_emit_ptr_offset(proc, elem, index); + return ir_addr(v); + } + + case Type_DynamicArray: { + lbValue dynamic_array = nullptr; + if (using_addr != nullptr) { + dynamic_array = ir_emit_load(proc, using_addr); + } else { + dynamic_array = ir_build_expr(proc, ie->expr); + if (deref) { + dynamic_array = ir_emit_load(proc, dynamic_array); + } + } + lbValue elem = ir_dynamic_array_elem(proc, dynamic_array); + lbValue len = ir_dynamic_array_len(proc, dynamic_array); + lbValue index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + ir_emit_bounds_check(proc, ast_token(ie->index), index, len); + lbValue v = ir_emit_ptr_offset(proc, elem, index); + return ir_addr(v); + } + + + case Type_Basic: { // Basic_string + lbValue str; + lbValue elem; + lbValue len; + lbValue index; + + if (using_addr != nullptr) { + str = ir_emit_load(proc, using_addr); + } else { + str = ir_build_expr(proc, ie->expr); + if (deref) { + str = ir_emit_load(proc, str); + } + } + elem = ir_string_elem(proc, str); + len = ir_string_len(proc, str); + + index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + ir_emit_bounds_check(proc, ast_token(ie->index), index, len); + + return ir_addr(ir_emit_ptr_offset(proc, elem, index)); + } + } + case_end; + + case_ast_node(se, SliceExpr, expr); + ir_emit_comment(proc, str_lit("SliceExpr")); + gbAllocator a = ir_allocator(); + lbValue low = v_zero; + lbValue high = nullptr; + + if (se->low != nullptr) low = ir_build_expr(proc, se->low); + if (se->high != nullptr) high = ir_build_expr(proc, se->high); + + bool no_indices = se->low == nullptr && se->high == nullptr; + + lbValue addr = ir_build_addr_ptr(proc, se->expr); + lbValue base = ir_emit_load(proc, addr); + Type *type = base_type(ir_type(base)); + + if (is_type_pointer(type)) { + type = base_type(type_deref(type)); + addr = base; + base = ir_emit_load(proc, base); + } + // TODO(bill): Cleanup like mad! + + switch (type->kind) { + case Type_Slice: { + Type *slice_type = type; + lbValue len = ir_slice_len(proc, base); + if (high == nullptr) high = len; + + if (!no_indices) { + ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); + } + + lbValue elem = ir_emit_ptr_offset(proc, ir_slice_elem(proc, base), low); + lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + + lbValue slice = ir_add_local_generated(proc, slice_type, false); + ir_fill_slice(proc, slice, elem, new_len); + return ir_addr(slice); + } + + case Type_DynamicArray: { + Type *elem_type = type->DynamicArray.elem; + Type *slice_type = alloc_type_slice(elem_type); + + lbValue len = ir_dynamic_array_len(proc, base); + if (high == nullptr) high = len; + + if (!no_indices) { + ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); + } + + lbValue elem = ir_emit_ptr_offset(proc, ir_dynamic_array_elem(proc, base), low); + lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + + lbValue slice = ir_add_local_generated(proc, slice_type, false); + ir_fill_slice(proc, slice, elem, new_len); + return ir_addr(slice); + } + + + case Type_Array: { + Type *slice_type = alloc_type_slice(type->Array.elem); + lbValue len = ir_array_len(proc, base); + + if (high == 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) { + ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); + } + } + lbValue elem = ir_emit_ptr_offset(proc, ir_array_elem(proc, addr), low); + lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + + lbValue slice = ir_add_local_generated(proc, slice_type, false); + ir_fill_slice(proc, slice, elem, new_len); + return ir_addr(slice); + } + + case Type_Basic: { + GB_ASSERT(type == t_string); + lbValue len = ir_string_len(proc, base); + if (high == nullptr) high = len; + + if (!no_indices) { + ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); + } + + lbValue elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, base), low); + lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + + lbValue str = ir_add_local_generated(proc, t_string, false); + ir_fill_string(proc, str, elem, new_len); + return ir_addr(str); + } + + + case Type_Struct: + if (is_type_soa_struct(type)) { + lbValue len = ir_soa_struct_len(proc, addr); + if (high == nullptr) high = len; + + if (!no_indices) { + ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); + } + + lbValue dst = ir_add_local_generated(proc, 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 = ir_emit_struct_ep(proc, dst, i); + lbValue field_src = ir_emit_struct_ep(proc, addr, i); + field_src = ir_emit_array_ep(proc, field_src, low); + ir_emit_store(proc, field_dst, field_src); + } + + lbValue len_dst = ir_emit_struct_ep(proc, dst, field_count); + lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + ir_emit_store(proc, len_dst, new_len); + } else if (type->Struct.soa_kind == StructSoa_Slice) { + if (no_indices) { + ir_emit_store(proc, dst, base); + } else { + i32 field_count = cast(i32)type->Struct.fields.count - 1; + for (i32 i = 0; i < field_count; i++) { + lbValue field_dst = ir_emit_struct_ep(proc, dst, i); + lbValue field_src = ir_emit_struct_ev(proc, base, i); + field_src = ir_emit_ptr_offset(proc, field_src, low); + ir_emit_store(proc, field_dst, field_src); + } + + + lbValue len_dst = ir_emit_struct_ep(proc, dst, field_count); + lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + ir_emit_store(proc, 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 = ir_emit_struct_ep(proc, dst, i); + lbValue field_src = ir_emit_struct_ev(proc, base, i); + field_src = ir_emit_ptr_offset(proc, field_src, low); + ir_emit_store(proc, field_dst, field_src); + } + + + lbValue len_dst = ir_emit_struct_ep(proc, dst, field_count); + lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + ir_emit_store(proc, len_dst, new_len); + } + + return ir_addr(dst); + } + break; + + } + + GB_PANIC("Unknown slicable type"); + case_end; + + case_ast_node(de, DerefExpr, expr); + // TODO(bill): Is a ptr copy needed? + lbValue addr = ir_build_expr(proc, de->expr); + addr = ir_emit_ptr_offset(proc, addr, v_zero); + return ir_addr(addr); + case_end; + + case_ast_node(ce, CallExpr, expr); + // NOTE(bill): This is make sure you never need to have an 'array_ev' + lbValue e = ir_build_expr(proc, expr); + lbValue v = ir_add_local_generated(proc, ir_type(e), false); + ir_emit_store(proc, v, e); + return ir_addr(v); + case_end; + + case_ast_node(cl, CompoundLit, expr); + ir_emit_comment(proc, str_lit("CompoundLit")); + Type *type = type_of_expr(expr); + Type *bt = base_type(type); + + lbValue v = ir_add_local_generated(proc, type, true); + + 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; + } + + String proc_name = {}; + if (proc->entity) { + proc_name = proc->entity->token.string; + } + TokenPos pos = ast_token(expr).pos; + + switch (bt->kind) { + default: GB_PANIC("Unknown CompoundLit type: %s", type_to_string(type)); break; + + case Type_Struct: { + + // TODO(bill): "constant" '#raw_union's are not initialized constantly at the moment. + // NOTE(bill): This is due to the layout of the unions when printed to LLVM-IR + bool is_raw_union = is_type_raw_union(bt); + GB_ASSERT(is_type_struct(bt) || is_raw_union); + TypeStruct *st = &bt->Struct; + if (cl->elems.count > 0) { + ir_emit_store(proc, v, lb_const_value(proc->module, type, exact_value_compound(expr))); + for_array(field_index, cl->elems) { + Ast *elem = cl->elems[field_index]; + + lbValue field_expr = nullptr; + 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); + index = sel.index[0]; + elem = fv->value; + TypeAndValue tav = type_and_value_of_expr(elem); + } else { + TypeAndValue tav = type_and_value_of_expr(elem); + Selection sel = lookup_field_from_index(bt, st->fields[field_index]->Variable.field_src_index); + index = sel.index[0]; + } + + field = st->fields[index]; + Type *ft = field->type; + if (!is_raw_union && !is_type_typeid(ft) && ir_is_elem_const(proc->module, elem, ft)) { + continue; + } + + field_expr = ir_build_expr(proc, elem); + + + GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple); + + Type *fet = ir_type(field_expr); + // 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)); + + lbValue gep = ir_emit_struct_ep(proc, v, cast(i32)index); + ir_emit_store_union_variant(proc, gep, field_expr, fet); + } else { + lbValue fv = ir_emit_conv(proc, field_expr, ft); + lbValue gep = ir_emit_struct_ep(proc, v, cast(i32)index); + ir_emit_store(proc, gep, fv); + } + } + } + break; + } + + case Type_Map: { + if (cl->elems.count == 0) { + break; + } + gbAllocator a = ir_allocator(); + { + auto args = array_make(a, 3); + args[0] = ir_gen_map_header(proc, v, type); + args[1] = ir_const_int(2*cl->elems.count); + args[2] = ir_emit_source_code_location(proc, proc_name, pos); + ir_emit_runtime_call(proc, "__dynamic_map_reserve", args); + } + for_array(field_index, cl->elems) { + Ast *elem = cl->elems[field_index]; + ast_node(fv, FieldValue, elem); + + lbValue key = ir_build_expr(proc, fv->field); + lbValue value = ir_build_expr(proc, fv->value); + ir_insert_dynamic_map_key_and_value(proc, v, type, key, value); + } + break; + } + + case Type_Array: { + if (cl->elems.count > 0) { + ir_emit_store(proc, v, lb_const_value(proc->module, type, exact_value_compound(expr))); + + auto temp_data = array_make(heap_allocator(), 0, cl->elems.count); + defer (array_free(&temp_data)); + + // NOTE(bill): Separate value, gep, store into their own chunks + for_array(i, cl->elems) { + Ast *elem = cl->elems[i]; + if (elem->kind == Ast_FieldValue) { + ast_node(fv, FieldValue, elem); + if (ir_is_elem_const(proc->module, fv->value, et)) { + continue; + } + 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_Ellipsis) { + hi += 1; + } + + lbValue value = ir_build_expr(proc, fv->value); + + for (i64 k = lo; k < hi; k++) { + irCompoundLitElemTempData data = {}; + data.value = value; + data.elem_index = cast(i32)k; + 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); + + irCompoundLitElemTempData data = {}; + data.value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et); + data.expr = fv->value; + data.elem_index = cast(i32)index; + array_add(&temp_data, data); + } + + } else { + if (ir_is_elem_const(proc->module, elem, et)) { + continue; + } + irCompoundLitElemTempData data = {}; + data.expr = elem; + data.elem_index = cast(i32)i; + array_add(&temp_data, data); + } + } + + for_array(i, temp_data) { + temp_data[i].gep = ir_emit_array_epi(proc, v, temp_data[i].elem_index); + } + + for_array(i, temp_data) { + auto return_ptr_hint_ast = proc->return_ptr_hint_ast; + auto return_ptr_hint_value = proc->return_ptr_hint_value; + auto return_ptr_hint_used = proc->return_ptr_hint_used; + defer (proc->return_ptr_hint_ast = return_ptr_hint_ast); + defer (proc->return_ptr_hint_value = return_ptr_hint_value); + defer (proc->return_ptr_hint_used = return_ptr_hint_used); + + lbValue field_expr = temp_data[i].value; + Ast *expr = temp_data[i].expr; + + proc->return_ptr_hint_value = temp_data[i].gep; + proc->return_ptr_hint_ast = unparen_expr(expr); + + if (field_expr == nullptr) { + field_expr = ir_build_expr(proc, expr); + } + Type *t = ir_type(field_expr); + GB_ASSERT(t->kind != Type_Tuple); + lbValue ev = ir_emit_conv(proc, field_expr, et); + + if (!proc->return_ptr_hint_used) { + temp_data[i].value = ev; + } + } + + for_array(i, temp_data) { + if (temp_data[i].value != nullptr) { + ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false); + } + } + } + break; + } + case Type_EnumeratedArray: { + if (cl->elems.count > 0) { + ir_emit_store(proc, v, lb_const_value(proc->module, type, exact_value_compound(expr))); + + auto temp_data = array_make(heap_allocator(), 0, cl->elems.count); + defer (array_free(&temp_data)); + + // NOTE(bill): Separate value, gep, store into their own chunks + for_array(i, cl->elems) { + Ast *elem = cl->elems[i]; + if (elem->kind == Ast_FieldValue) { + ast_node(fv, FieldValue, elem); + if (ir_is_elem_const(proc->module, fv->value, et)) { + continue; + } + 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_Ellipsis) { + hi += 1; + } + + lbValue value = ir_build_expr(proc, fv->value); + + for (i64 k = lo; k < hi; k++) { + irCompoundLitElemTempData data = {}; + data.value = value; + data.elem_index = cast(i32)k; + 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); + + irCompoundLitElemTempData data = {}; + data.value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et); + data.expr = fv->value; + data.elem_index = cast(i32)index; + array_add(&temp_data, data); + } + + } else { + if (ir_is_elem_const(proc->module, elem, et)) { + continue; + } + irCompoundLitElemTempData data = {}; + data.expr = elem; + data.elem_index = cast(i32)i; + array_add(&temp_data, data); + } + } + + + i32 index_offset = cast(i32)exact_value_to_i64(bt->EnumeratedArray.min_value); + + for_array(i, temp_data) { + i32 index = temp_data[i].elem_index - index_offset; + temp_data[i].gep = ir_emit_array_epi(proc, v, index); + } + + for_array(i, temp_data) { + auto return_ptr_hint_ast = proc->return_ptr_hint_ast; + auto return_ptr_hint_value = proc->return_ptr_hint_value; + auto return_ptr_hint_used = proc->return_ptr_hint_used; + defer (proc->return_ptr_hint_ast = return_ptr_hint_ast); + defer (proc->return_ptr_hint_value = return_ptr_hint_value); + defer (proc->return_ptr_hint_used = return_ptr_hint_used); + + lbValue field_expr = temp_data[i].value; + Ast *expr = temp_data[i].expr; + + proc->return_ptr_hint_value = temp_data[i].gep; + proc->return_ptr_hint_ast = unparen_expr(expr); + + if (field_expr == nullptr) { + field_expr = ir_build_expr(proc, expr); + } + Type *t = ir_type(field_expr); + GB_ASSERT(t->kind != Type_Tuple); + lbValue ev = ir_emit_conv(proc, field_expr, et); + + if (!proc->return_ptr_hint_used) { + temp_data[i].value = ev; + } + } + + for_array(i, temp_data) { + if (temp_data[i].value != nullptr) { + ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false); + } + } + } + break; + } + case Type_Slice: { + if (cl->elems.count > 0) { + Type *elem_type = bt->Slice.elem; + Type *elem_ptr_type = alloc_type_pointer(elem_type); + Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type); + lbValue slice = lb_const_value(proc->module, type, exact_value_compound(expr)); + GB_ASSERT(slice->kind == irValue_ConstantSlice); + + lbValue data = ir_emit_array_ep(proc, slice->ConstantSlice.backing_array, v_zero32); + + auto temp_data = array_make(heap_allocator(), 0, cl->elems.count); + defer (array_free(&temp_data)); + + for_array(i, cl->elems) { + Ast *elem = cl->elems[i]; + if (elem->kind == Ast_FieldValue) { + ast_node(fv, FieldValue, elem); + + if (ir_is_elem_const(proc->module, fv->value, et)) { + continue; + } + + 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_Ellipsis) { + hi += 1; + } + + lbValue value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et); + + for (i64 k = lo; k < hi; k++) { + irCompoundLitElemTempData data = {}; + data.value = value; + data.elem_index = cast(i32)k; + array_add(&temp_data, data); + } + + } else { + GB_ASSERT(fv->field->tav.mode == Addressing_Constant); + i64 index = exact_value_to_i64(fv->field->tav.value); + + lbValue field_expr = ir_build_expr(proc, fv->value); + GB_ASSERT(!is_type_tuple(ir_type(field_expr))); + + lbValue ev = ir_emit_conv(proc, field_expr, et); + + irCompoundLitElemTempData data = {}; + data.value = ev; + data.elem_index = cast(i32)index; + array_add(&temp_data, data); + } + } else { + if (ir_is_elem_const(proc->module, elem, et)) { + continue; + } + lbValue field_expr = ir_build_expr(proc, elem); + GB_ASSERT(!is_type_tuple(ir_type(field_expr))); + + lbValue ev = ir_emit_conv(proc, field_expr, et); + + irCompoundLitElemTempData data = {}; + data.value = ev; + data.elem_index = cast(i32)i; + array_add(&temp_data, data); + } + } + + for_array(i, temp_data) { + temp_data[i].gep = ir_emit_ptr_offset(proc, data, ir_const_int(temp_data[i].elem_index)); + } + + for_array(i, temp_data) { + ir_emit_store(proc, temp_data[i].gep, temp_data[i].value); + } + + lbValue count = ir_const_int(slice->ConstantSlice.count); + ir_fill_slice(proc, v, data, count); + } + break; + } + + case Type_DynamicArray: { + if (cl->elems.count == 0) { + break; + } + Type *et = bt->DynamicArray.elem; + gbAllocator a = ir_allocator(); + lbValue size = ir_const_int(type_size_of(et)); + lbValue align = ir_const_int(type_align_of(et)); + + i64 item_count = gb_max(cl->max_count, cl->elems.count); + { + + auto args = array_make(a, 5); + args[0] = ir_emit_conv(proc, v, t_rawptr); + args[1] = size; + args[2] = align; + args[3] = ir_const_int(2*item_count); // TODO(bill): Is this too much waste? + args[4] = ir_emit_source_code_location(proc, proc_name, pos); + ir_emit_runtime_call(proc, "__dynamic_array_reserve", args); + } + + lbValue items = ir_generate_array(proc->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr); + + for_array(i, cl->elems) { + Ast *elem = cl->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_Ellipsis) { + hi += 1; + } + + lbValue value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et); + + for (i64 k = lo; k < hi; k++) { + lbValue ep = ir_emit_array_epi(proc, items, cast(i32)k); + ir_emit_store(proc, ep, value); + } + } else { + GB_ASSERT(fv->field->tav.mode == Addressing_Constant); + + i64 field_index = exact_value_to_i64(fv->field->tav.value); + + lbValue ev = ir_build_expr(proc, fv->value); + lbValue value = ir_emit_conv(proc, ev, et); + lbValue ep = ir_emit_array_epi(proc, items, cast(i32)field_index); + ir_emit_store(proc, ep, value); + } + } else { + lbValue value = ir_emit_conv(proc, ir_build_expr(proc, elem), et); + lbValue ep = ir_emit_array_epi(proc, items, cast(i32)i); + ir_emit_store(proc, ep, value); + } + } + + { + auto args = array_make(a, 6); + args[0] = ir_emit_conv(proc, v, t_rawptr); + args[1] = size; + args[2] = align; + args[3] = ir_emit_conv(proc, items, t_rawptr); + args[4] = ir_const_int(item_count); + args[5] = ir_emit_source_code_location(proc, proc_name, pos); + ir_emit_runtime_call(proc, "__dynamic_array_append", args); + } + break; + } + + case Type_Basic: { + GB_ASSERT(is_type_any(bt)); + if (cl->elems.count > 0) { + ir_emit_store(proc, v, lb_const_value(proc->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]; + + lbValue field_expr = nullptr; + 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 = ir_build_expr(proc, elem); + + GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple); + + Type *ft = field_types[index]; + lbValue fv = ir_emit_conv(proc, field_expr, ft); + lbValue gep = ir_emit_struct_ep(proc, v, cast(i32)index); + ir_emit_store(proc, gep, fv); + } + } + + break; + } + + case Type_BitSet: { + i64 sz = type_size_of(type); + if (cl->elems.count > 0 && sz > 0) { + ir_emit_store(proc, v, lb_const_value(proc->module, type, exact_value_compound(expr))); + + lbValue lower = ir_value_constant(t_int, exact_value_i64(bt->BitSet.lower)); + for_array(i, cl->elems) { + Ast *elem = cl->elems[i]; + GB_ASSERT(elem->kind != Ast_FieldValue); + + if (ir_is_elem_const(proc->module, elem, et)) { + continue; + } + + lbValue expr = ir_build_expr(proc, elem); + GB_ASSERT(ir_type(expr)->kind != Type_Tuple); + + Type *it = bit_set_to_int(bt); + lbValue e = ir_emit_conv(proc, expr, it); + e = ir_emit_arith(proc, Token_Sub, e, lower, it); + e = ir_emit_arith(proc, Token_Shl, v_one, e, it); + + lbValue old_value = ir_emit_bitcast(proc, ir_emit_load(proc, v), it); + lbValue new_value = ir_emit_arith(proc, Token_Or, old_value, e, it); + new_value = ir_emit_bitcast(proc, new_value, type); + ir_emit_store(proc, v, new_value); + } + } + break; + } + + } + + return ir_addr(v); + case_end; + + case_ast_node(tc, TypeCast, expr); + Type *type = type_of_expr(expr); + lbValue x = ir_build_expr(proc, tc->expr); + lbValue e = nullptr; + switch (tc->token.kind) { + case Token_cast: + e = ir_emit_conv(proc, x, type); + break; + case Token_transmute: + e = lb_emit_transmute(proc, x, type); + break; + default: + GB_PANIC("Invalid AST TypeCast"); + } + lbValue v = ir_add_local_generated(proc, type, false); + ir_emit_store(proc, v, e); + return ir_addr(v); + case_end; + + case_ast_node(ac, AutoCast, expr); + return ir_build_addr(proc, ac->expr); + case_end; +#endif + } + + TokenPos token_pos = ast_token(expr).pos; + GB_PANIC("Unexpected address expression\n" + "\tAst: %.*s @ " + "%.*s(%td:%td)\n", + LIT(ast_strings[expr->kind]), + LIT(token_pos.file), token_pos.line, token_pos.column); + + + return {}; +} + + + +bool lb_init_generator(lbGenerator *gen, Checker *c) { + if (global_error_collector.count != 0) { + return false; + } + + isize tc = c->parser->total_token_count; + if (tc < 2) { + return false; + } + + + String init_fullpath = c->parser->init_fullpath; + + if (build_context.out_filepath.len == 0) { + gen->output_name = remove_directory_from_path(init_fullpath); + gen->output_name = remove_extension_from_path(gen->output_name); + gen->output_base = gen->output_name; + } else { + gen->output_name = build_context.out_filepath; + isize pos = string_extension_position(gen->output_name); + if (pos < 0) { + gen->output_base = gen->output_name; + } else { + gen->output_base = substring(gen->output_name, 0, pos); + } + } + gbAllocator ha = heap_allocator(); + gen->output_base = path_to_full_path(ha, gen->output_base); + + gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len); + output_file_path = gb_string_appendc(output_file_path, ".obj"); + defer (gb_string_free(output_file_path)); + + gbFileError err = gb_file_create(&gen->output_file, output_file_path); + if (err != gbFileError_None) { + gb_printf_err("Failed to create file %s\n", output_file_path); + return false; + } + + + gen->info = &c->info; + gen->module.info = &c->info; + + // gen->ctx = LLVMContextCreate(); + gen->module.ctx = LLVMGetGlobalContext(); + gen->module.mod = LLVMModuleCreateWithNameInContext("odin_module", gen->module.ctx); + map_init(&gen->module.types, heap_allocator()); + map_init(&gen->module.values, heap_allocator()); + map_init(&gen->module.members, heap_allocator()); + map_init(&gen->module.const_strings, heap_allocator()); + map_init(&gen->module.const_string_byte_slices, heap_allocator()); + + return true; +} + +lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) { + GB_ASSERT(type != nullptr); + type = default_type(type); + + isize max_len = 7+8+1; + u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len); + isize len = gb_snprintf(cast(char *)str, max_len, "ggv$%x", m->global_generated_index); + m->global_generated_index++; + String name = make_string(str, len-1); + + Scope *scope = nullptr; + Entity *e = alloc_entity_variable(scope, make_token_ident(name), type); + lbValue g = {}; + g.type = alloc_type_pointer(type); g.value = LLVMAddGlobal(m->mod, lb_type(m, type), cast(char const *)str); + if (value.value != nullptr) { + GB_ASSERT(LLVMIsConstant(value.value)); + LLVMSetInitializer(g.value, value.value); + } + lb_add_entity(m, e, g); lb_add_member(m, name, g); return lb_addr(g); diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index a9fd6de7e..3046ebfea 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -187,6 +187,16 @@ struct lbProcedure { bool return_ptr_hint_used; }; +enum lbParamPasskind { + lbParamPass_Value, // Pass by value + lbParamPass_Pointer, // Pass as a pointer rather than by value + lbParamPass_Integer, // Pass as an integer of the same size + lbParamPass_ConstRef, // Pass as a pointer but the value is immutable + lbParamPass_BitCast, // Pass by value and bit cast to the correct type + lbParamPass_Tuple, // Pass across multiple parameters (System V AMD64, up to 2) +}; + + bool lb_init_generator(lbGenerator *gen, Checker *c); void lb_generate_module(lbGenerator *gen); @@ -216,12 +226,17 @@ void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue const &value); lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr); lbValue lb_emit_load(lbProcedure *p, lbValue v); -void lb_build_stmt (lbProcedure *p, Ast *stmt); -lbValue lb_build_expr (lbProcedure *p, Ast *expr); +void lb_build_stmt(lbProcedure *p, Ast *stmt); +lbValue lb_build_expr(lbProcedure *p, Ast *expr); +lbAddr lb_build_addr(lbProcedure *p, Ast *expr); void lb_build_stmt_list(lbProcedure *p, Array const &stmts); lbValue lb_build_gep(lbProcedure *p, lbValue const &value, i32 index) ; +lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index); +lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index); +lbValue lb_emit_array_epi(lbProcedure *p, lbValue value, i32 index); + lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type); @@ -229,3 +244,10 @@ lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Ty lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t); lbValue lb_build_call_expr(lbProcedure *p, Ast *expr); + + +lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value={}); + +lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr, bool zero_init=true, i32 param_index=0); + +lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t); diff --git a/src/types.cpp b/src/types.cpp index fde8cd5a5..2afba733c 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -1143,13 +1143,13 @@ bool is_type_simd_vector(Type *t) { } Type *base_array_type(Type *t) { - if (is_type_array(t)) { - t = base_type(t); - return t->Array.elem; - } - if (is_type_simd_vector(t)) { - t = base_type(t); - return t->SimdVector.elem; + Type *bt = base_type(t); + if (is_type_array(bt)) { + return bt->Array.elem; + } else if (is_type_enumerated_array(bt)) { + return bt->EnumeratedArray.elem; + } else if (is_type_simd_vector(bt)) { + return bt->SimdVector.elem; } return t; } -- cgit v1.2.3 From 09e1cf0737e9fd950ca63f94fe3d9da62ef48ef9 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 5 Feb 2020 23:41:10 +0000 Subject: IfStmt --- src/llvm_backend.cpp | 630 ++++++++++++++++++++++++++++++++++++++++++++++++++- src/llvm_backend.hpp | 150 ++++++------ 2 files changed, 710 insertions(+), 70 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 5d9d0b544..41de200e2 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -897,7 +897,6 @@ void lb_begin_procedure_body(lbProcedure *p) { GB_ASSERT(!is_blank_ident(e->token)); lbAddr res = lb_add_local(p, e->type, e); - gb_printf_err("%.*s\n", LIT(e->token.string)); lbValue c = {}; switch (e->Variable.param_value.kind) { @@ -964,6 +963,57 @@ lbBlock *lb_create_block(lbProcedure *p, char const *name) { return b; } +void lb_start_block(lbProcedure *p, lbBlock *b) { + p->curr_block = b; + LLVMPositionBuilderAtEnd(p->builder, b->block); +} + +void lb_emit_jump(lbProcedure *p, lbBlock *target_block) { + if (p->curr_block == nullptr) { + return; + } + LLVMBuildBr(p->builder, target_block->block); + p->curr_block = nullptr; +} + +lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) { + switch (cond->kind) { + case_ast_node(pe, ParenExpr, cond); + return lb_build_cond(p, pe->expr, true_block, false_block); + case_end; + + case_ast_node(ue, UnaryExpr, cond); + if (ue->op.kind == Token_Not) { + return lb_build_cond(p, ue->expr, false_block, true_block); + } + case_end; + + case_ast_node(be, BinaryExpr, cond); + if (be->op.kind == Token_CmpAnd) { + lbBlock *block = lb_create_block(p, "cmp.and"); + lb_build_cond(p, be->left, block, false_block); + lb_start_block(p, block); + return lb_build_cond(p, be->right, true_block, false_block); + } else if (be->op.kind == Token_CmpOr) { + lbBlock *block = lb_create_block(p, "cmp.or"); + lb_build_cond(p, be->left, true_block, block); + lb_start_block(p, block); + return lb_build_cond(p, be->right, true_block, false_block); + } + case_end; + } + + lbValue v = lb_build_expr(p, cond); + // v = lb_emit_conv(p, v, t_bool); + v = lb_emit_conv(p, v, t_llvm_bool); + + LLVMBuildCondBr(p->builder, v.value, true_block->block, false_block->block); + + return v; +} + + + lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) { LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block); @@ -1021,6 +1071,95 @@ lbValue lb_build_gep(lbProcedure *p, lbValue const &value, i32 index) { return lbValue{LLVMBuildStructGEP2(p->builder, lb_type(p->module, elem_type), value.value, index, ""), elem_type}; } + +lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) { + GB_ASSERT(ident->kind == Ast_Ident); + Entity *e = entity_of_ident(ident); + GB_ASSERT(e->kind == Entity_Label); + for_array(i, p->branch_blocks) { + lbBranchBlocks *b = &p->branch_blocks[i]; + if (b->label == e->Label.node) { + return *b; + } + } + + GB_PANIC("Unreachable"); + lbBranchBlocks empty = {}; + return empty; +} + + +lbTargetList *lb_push_target_list(lbProcedure *p, Ast *label, lbBlock *break_, lbBlock *continue_, lbBlock *fallthrough_) { + lbTargetList *tl = gb_alloc_item(heap_allocator(), lbTargetList); + tl->prev = p->target_list; + tl->break_ = break_; + tl->continue_ = continue_; + tl->fallthrough_ = fallthrough_; + p->target_list = tl; + + if (label != nullptr) { // Set label blocks + GB_ASSERT(label->kind == Ast_Label); + + for_array(i, p->branch_blocks) { + lbBranchBlocks *b = &p->branch_blocks[i]; + GB_ASSERT(b->label != nullptr && label != nullptr); + GB_ASSERT(b->label->kind == Ast_Label); + if (b->label == label) { + b->break_ = break_; + b->continue_ = continue_; + return tl; + } + } + + GB_PANIC("Unreachable"); + } + + return tl; +} + +void lb_pop_target_list(lbProcedure *p) { + p->target_list = p->target_list->prev; +} + + + + +void lb_open_scope(lbProcedure *p) { + p->scope_index += 1; +} + +void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) { + GB_ASSERT(p->scope_index > 0); + + // NOTE(bill): Remove `context`s made in that scope + + isize end_idx = p->context_stack.count-1; + isize pop_count = 0; + + for (;;) { + if (end_idx < 0) { + break; + } + lbContextData *end = &p->context_stack[end_idx]; + if (end == nullptr) { + break; + } + if (end->scope_index != p->scope_index) { + break; + } + end_idx -= 1; + pop_count += 1; + } + if (pop_stack) { + for (isize i = 0; i < pop_count; i++) { + array_pop(&p->context_stack); + } + } + + + p->scope_index -= 1; +} + void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) { TypeAndValue tv = type_and_value_of_expr(ws->cond); GB_ASSERT(is_type_boolean(tv.type)); @@ -1056,7 +1195,22 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_ast_node(bs, BlockStmt, node); - lb_build_stmt_list(p, bs->stmts); + if (bs->label != nullptr) { + lbBlock *done = lb_create_block(p, "block.done"); + lbTargetList *tl = lb_push_target_list(p, bs->label, done, nullptr, nullptr); + tl->is_block = true; + + lb_open_scope(p); + lb_build_stmt_list(p, bs->stmts); + lb_close_scope(p, lbDeferExit_Default, nullptr); + + lb_emit_jump(p, done); + lb_start_block(p, done); + } else { + lb_open_scope(p); + lb_build_stmt_list(p, bs->stmts); + lb_close_scope(p, lbDeferExit_Default, nullptr); + } case_end; case_ast_node(vd, ValueDecl, node); @@ -1327,6 +1481,49 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(is, IfStmt, node); + lb_open_scope(p); // Scope #1 + + if (is->init != nullptr) { + // TODO(bill): Should this have a separate block to begin with? + #if 1 + lbBlock *init = lb_create_block(p, "if.init"); + lb_emit_jump(p, init); + lb_start_block(p, init); + #endif + lb_build_stmt(p, is->init); + } + lbBlock *then = lb_create_block(p, "if.then"); + lbBlock *done = lb_create_block(p, "if.done"); + lbBlock *else_ = done; + if (is->else_stmt != nullptr) { + else_ = lb_create_block(p, "if.else"); + } + + lb_build_cond(p, is->cond, then, else_); + lb_start_block(p, then); + + if (is->label != nullptr) { + lbTargetList *tl = lb_push_target_list(p, is->label, done, nullptr, nullptr); + tl->is_block = true; + } + + lb_build_stmt(p, is->body); + + lb_emit_jump(p, done); + + if (is->else_stmt != nullptr) { + lb_start_block(p, else_); + + lb_open_scope(p); + lb_build_stmt(p, is->else_stmt); + lb_close_scope(p, lbDeferExit_Default, nullptr); + + lb_emit_jump(p, done); + } + + + lb_start_block(p, done); + lb_close_scope(p, lbDeferExit_Default, nullptr); case_end; case_ast_node(fs, ForStmt, node); @@ -1345,6 +1542,34 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(bs, BranchStmt, node); + lbBlock *block = nullptr; + + if (bs->label != nullptr) { + lbBranchBlocks bb = lb_lookup_branch_blocks(p, bs->label); + switch (bs->token.kind) { + case Token_break: block = bb.break_; break; + case Token_continue: block = bb.continue_; break; + case Token_fallthrough: + GB_PANIC("fallthrough cannot have a label"); + break; + } + } else { + for (lbTargetList *t = p->target_list; t != nullptr && block == nullptr; t = t->prev) { + if (t->is_block) { + continue; + } + + switch (bs->token.kind) { + case Token_break: block = t->break_; break; + case Token_continue: block = t->continue_; break; + case Token_fallthrough: block = t->fallthrough_; break; + } + } + } + if (block != nullptr) { + // ir_emit_defer_stmts(p, irDeferExit_Branch, block); + } + lb_emit_jump(p, block); case_end; } } @@ -1354,6 +1579,12 @@ lbValue lb_const_nil(lbModule *m, Type *type) { return lbValue{v, type}; } +lbValue lb_const_undef(lbModule *m, Type *type) { + LLVMValueRef v = LLVMGetUndef(lb_type(m, type)); + return lbValue{v, type}; +} + + lbValue lb_const_int(lbModule *m, Type *type, u64 value) { lbValue res = {}; res.value = LLVMConstInt(lb_type(m, type), value, !is_type_unsigned(type)); @@ -2140,8 +2371,397 @@ lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { } lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { - // TODO(bill): lb_emit_conv - return value; + lbModule *m = p->module; + + Type *src_type = value.type; + if (are_types_identical(t, src_type)) { + return value; + } + + Type *src = core_type(src_type); + Type *dst = core_type(t); + + + // if (is_type_untyped_nil(src) && type_has_nil(dst)) { + if (is_type_untyped_nil(src)) { + return lb_const_nil(m, t); + } + if (is_type_untyped_undef(src)) { + return lb_const_undef(m, t); + } + + if (LLVMIsConstant(value.value)) { + if (is_type_any(dst)) { + lbAddr default_value = lb_add_local_generated(p, default_type(src_type), false); + lb_addr_store(p, default_value, value); + return lb_emit_conv(p, lb_addr_load(p, default_value), t_any); + } else if (dst->kind == Type_Basic) { + if (is_type_float(dst)) { + return value; + } else if (is_type_integer(dst)) { + return value; + } + // ExactValue ev = value->Constant.value; + // if (is_type_float(dst)) { + // ev = exact_value_to_float(ev); + // } else if (is_type_complex(dst)) { + // ev = exact_value_to_complex(ev); + // } else if (is_type_quaternion(dst)) { + // ev = exact_value_to_quaternion(ev); + // } else if (is_type_string(dst)) { + // // Handled elsewhere + // GB_ASSERT_MSG(ev.kind == ExactValue_String, "%d", ev.kind); + // } else if (is_type_integer(dst)) { + // ev = exact_value_to_integer(ev); + // } else if (is_type_pointer(dst)) { + // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null' + // lbValue i = ir_add_module_constant(p->module, t_uintptr, ev); + // return ir_emit(p, ir_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst)); + // } + // return lb_const_value(p->module, t, ev); + } + } + + if (are_types_identical(src, dst)) { + if (!are_types_identical(src_type, t)) { + return lb_emit_transmute(p, value, t); + } + return value; + } + + + + // bool <-> llvm bool + if (is_type_boolean(src) && dst == t_llvm_bool) { + lbValue res = {}; + res.value = LLVMBuildTrunc(p->builder, value.value, lb_type(m, dst), ""); + res.type = dst; + return res; + } + if (src == t_llvm_bool && is_type_boolean(dst)) { + lbValue res = {}; + res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, dst), ""); + res.type = dst; + return res; + } + +#if 0 + + // integer -> integer + if (is_type_integer(src) && is_type_integer(dst)) { + GB_ASSERT(src->kind == Type_Basic && + dst->kind == Type_Basic); + i64 sz = type_size_of(default_type(src)); + i64 dz = type_size_of(default_type(dst)); + + if (sz > 1 && is_type_different_to_arch_endianness(src)) { + Type *platform_src_type = integer_endian_type_to_platform_type(src); + value = ir_emit_byte_swap(p, value, platform_src_type); + } + irConvKind kind = irConv_trunc; + + if (dz < sz) { + kind = irConv_trunc; + } else if (dz == sz) { + // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment + // NOTE(bill): Copy the value just for type correctness + kind = irConv_bitcast; + } else if (dz > sz) { + if (is_type_unsigned(src)) { + kind = irConv_zext; // zero extent + } else { + kind = irConv_sext; // sign extent + } + } + + if (dz > 1 && is_type_different_to_arch_endianness(dst)) { + Type *platform_dst_type = integer_endian_type_to_platform_type(dst); + lbValue res = ir_emit(p, ir_instr_conv(p, kind, value, src_type, platform_dst_type)); + return ir_emit_byte_swap(p, res, t); + } else { + return ir_emit(p, ir_instr_conv(p, kind, value, src_type, t)); + } + } + + // boolean -> boolean/integer + if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) { + lbValue b = ir_emit(p, ir_instr_binary_op(p, Token_NotEq, value, v_zero, t_llvm_bool)); + return ir_emit(p, ir_instr_conv(p, irConv_zext, b, t_llvm_bool, t)); + } + + if (is_type_cstring(src) && is_type_u8_ptr(dst)) { + return ir_emit_bitcast(p, value, dst); + } + if (is_type_u8_ptr(src) && is_type_cstring(dst)) { + return ir_emit_bitcast(p, value, dst); + } + if (is_type_cstring(src) && is_type_rawptr(dst)) { + return ir_emit_bitcast(p, value, dst); + } + if (is_type_rawptr(src) && is_type_cstring(dst)) { + return ir_emit_bitcast(p, value, dst); + } + + if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) { + lbValue c = ir_emit_conv(p, value, t_cstring); + auto args = array_make(ir_allocator(), 1); + args[0] = c; + lbValue s = ir_emit_runtime_call(p, "cstring_to_string", args); + return ir_emit_conv(p, s, dst); + } + + + // integer -> boolean + if (is_type_integer(src) && is_type_boolean(dst)) { + return ir_emit_comp(p, Token_NotEq, value, v_zero); + } + + // float -> float + if (is_type_float(src) && is_type_float(dst)) { + gbAllocator a = ir_allocator(); + i64 sz = type_size_of(src); + i64 dz = type_size_of(dst); + irConvKind kind = irConv_fptrunc; + if (dz >= sz) { + kind = irConv_fpext; + } + return ir_emit(p, ir_instr_conv(p, kind, value, src_type, t)); + } + + if (is_type_complex(src) && is_type_complex(dst)) { + Type *ft = base_complex_elem_type(dst); + lbValue gen = ir_add_local_generated(p, dst, false); + lbValue real = ir_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); + lbValue imag = ir_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); + ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), real); + ir_emit_store(p, ir_emit_struct_ep(p, gen, 1), imag); + return ir_emit_load(p, gen); + } + + if (is_type_quaternion(src) && is_type_quaternion(dst)) { + // @QuaternionLayout + Type *ft = base_complex_elem_type(dst); + lbValue gen = ir_add_local_generated(p, dst, false); + lbValue q0 = ir_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); + lbValue q1 = ir_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); + lbValue q2 = ir_emit_conv(p, ir_emit_struct_ev(p, value, 2), ft); + lbValue q3 = ir_emit_conv(p, ir_emit_struct_ev(p, value, 3), ft); + ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), q0); + ir_emit_store(p, ir_emit_struct_ep(p, gen, 1), q1); + ir_emit_store(p, ir_emit_struct_ep(p, gen, 2), q2); + ir_emit_store(p, ir_emit_struct_ep(p, gen, 3), q3); + return ir_emit_load(p, gen); + } + + if (is_type_float(src) && is_type_complex(dst)) { + Type *ft = base_complex_elem_type(dst); + lbValue gen = ir_add_local_generated(p, dst, true); + lbValue real = ir_emit_conv(p, value, ft); + ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), real); + return ir_emit_load(p, gen); + } + if (is_type_float(src) && is_type_quaternion(dst)) { + Type *ft = base_complex_elem_type(dst); + lbValue gen = ir_add_local_generated(p, dst, true); + lbValue real = ir_emit_conv(p, value, ft); + // @QuaternionLayout + ir_emit_store(p, ir_emit_struct_ep(p, gen, 3), real); + return ir_emit_load(p, gen); + } + if (is_type_complex(src) && is_type_quaternion(dst)) { + Type *ft = base_complex_elem_type(dst); + lbValue gen = ir_add_local_generated(p, dst, true); + lbValue real = ir_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); + lbValue imag = ir_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); + // @QuaternionLayout + ir_emit_store(p, ir_emit_struct_ep(p, gen, 3), real); + ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), imag); + return ir_emit_load(p, gen); + } + + + + // float <-> integer + if (is_type_float(src) && is_type_integer(dst)) { + irConvKind kind = irConv_fptosi; + if (is_type_unsigned(dst)) { + kind = irConv_fptoui; + } + return ir_emit(p, ir_instr_conv(p, kind, value, src_type, t)); + } + if (is_type_integer(src) && is_type_float(dst)) { + irConvKind kind = irConv_sitofp; + if (is_type_unsigned(src)) { + kind = irConv_uitofp; + } + return ir_emit(p, ir_instr_conv(p, kind, value, src_type, t)); + } + + // Pointer <-> uintptr + if (is_type_pointer(src) && is_type_uintptr(dst)) { + return ir_emit_ptr_to_uintptr(p, value, t); + } + if (is_type_uintptr(src) && is_type_pointer(dst)) { + return ir_emit_uintptr_to_ptr(p, value, t); + } + + if (is_type_union(dst)) { + for_array(i, dst->Union.variants) { + Type *vt = dst->Union.variants[i]; + if (are_types_identical(vt, src_type)) { + ir_emit_comment(p, str_lit("union - child to parent")); + gbAllocator a = ir_allocator(); + lbValue parent = ir_add_local_generated(p, t, true); + ir_emit_store_union_variant(p, parent, value, vt); + return ir_emit_load(p, parent); + } + } + } + + // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's + // subtype polymorphism casting + if (check_is_assignable_to_using_subtype(src_type, t)) { + Type *st = type_deref(src_type); + Type *pst = st; + st = type_deref(st); + + bool st_is_ptr = is_type_pointer(src_type); + st = base_type(st); + + Type *dt = t; + bool dt_is_ptr = type_deref(dt) != dt; + + GB_ASSERT(is_type_struct(st) || is_type_raw_union(st)); + String field_name = ir_lookup_subtype_polymorphic_field(p->module->info, t, src_type); + if (field_name.len > 0) { + // NOTE(bill): It can be casted + Selection sel = lookup_field(st, field_name, false, true); + if (sel.entity != nullptr) { + ir_emit_comment(p, str_lit("cast - polymorphism")); + if (st_is_ptr) { + lbValue res = ir_emit_deep_field_gep(p, value, sel); + Type *rt = ir_type(res); + if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) { + res = ir_emit_load(p, res); + } + return res; + } else { + if (is_type_pointer(ir_type(value))) { + Type *rt = ir_type(value); + if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) { + value = ir_emit_load(p, value); + } else { + value = ir_emit_deep_field_gep(p, value, sel); + return ir_emit_load(p, value); + } + } + + return ir_emit_deep_field_ev(p, value, sel); + + } + } else { + GB_PANIC("invalid subtype cast %s.%.*s", type_to_string(src_type), LIT(field_name)); + } + } + } + + + + // Pointer <-> Pointer + if (is_type_pointer(src) && is_type_pointer(dst)) { + return ir_emit_bitcast(p, value, t); + } + + + + // proc <-> proc + if (is_type_p(src) && is_type_p(dst)) { + return ir_emit_bitcast(p, value, t); + } + + // pointer -> proc + if (is_type_pointer(src) && is_type_p(dst)) { + return ir_emit_bitcast(p, value, t); + } + // proc -> pointer + if (is_type_p(src) && is_type_pointer(dst)) { + return ir_emit_bitcast(p, value, t); + } + + + + // []byte/[]u8 <-> string + if (is_type_u8_slice(src) && is_type_string(dst)) { + lbValue elem = ir_slice_elem(p, value); + lbValue len = ir_slice_len(p, value); + return ir_emit_string(p, elem, len); + } + if (is_type_string(src) && is_type_u8_slice(dst)) { + lbValue elem = ir_string_elem(p, value); + lbValue elem_ptr = ir_add_local_generated(p, ir_type(elem), false); + ir_emit_store(p, elem_ptr, elem); + + lbValue len = ir_string_len(p, value); + lbValue slice = ir_add_local_slice(p, t, elem_ptr, v_zero, len); + return ir_emit_load(p, slice); + } + + if (is_type_array(dst)) { + Type *elem = dst->Array.elem; + lbValue e = ir_emit_conv(p, value, elem); + // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops + lbValue v = ir_add_local_generated(p, t, false); + isize index_count = cast(isize)dst->Array.count; + + for (i32 i = 0; i < index_count; i++) { + lbValue elem = ir_emit_array_epi(p, v, i); + ir_emit_store(p, elem, e); + } + return ir_emit_load(p, v); + } + + if (is_type_any(dst)) { + lbValue result = ir_add_local_generated(p, t_any, true); + + if (is_type_untyped_nil(src)) { + return ir_emit_load(p, result); + } + + Type *st = default_type(src_type); + + lbValue data = ir_address_from_load_or_generate_local(p, value); + GB_ASSERT_MSG(is_type_pointer(ir_type(data)), type_to_string(ir_type(data))); + GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st)); + data = ir_emit_conv(p, data, t_rawptr); + + + lbValue id = ir_typeid(p->module, st); + + ir_emit_store(p, ir_emit_struct_ep(p, result, 0), data); + ir_emit_store(p, ir_emit_struct_ep(p, result, 1), id); + + return ir_emit_load(p, result); + } + + if (is_type_untyped(src)) { + if (is_type_string(src) && is_type_string(dst)) { + lbValue result = ir_add_local_generated(p, t, false); + ir_emit_store(p, result, value); + return ir_emit_load(p, result); + } + } +#endif + + gb_printf_err("ir_emit_conv: src -> dst\n"); + gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t)); + gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst)); + + + GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'", + type_to_string(src_type), type_to_string(t), + LIT(p->name)); + + return {}; } lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) { @@ -3627,7 +4247,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } gbAllocator a = ir_allocator(); { - auto args = array_make(a, 3); + auto args = array_make(a, 3); args[0] = ir_gen_map_header(proc, v, type); args[1] = ir_const_int(2*cl->elems.count); args[2] = ir_emit_source_code_location(proc, proc_name, pos); diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 3046ebfea..0dfd14163 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -85,71 +85,37 @@ struct lbBranchBlocks { lbBlock *continue_; }; -enum lbCallingConventionKind { - lbCallingConvention_C = 0, - lbCallingConvention_Fast = 8, - lbCallingConvention_Cold = 9, - lbCallingConvention_GHC = 10, - lbCallingConvention_HiPE = 11, - lbCallingConvention_WebKit_JS = 12, - lbCallingConvention_AnyReg = 13, - lbCallingConvention_PreserveMost = 14, - lbCallingConvention_PreserveAll = 15, - lbCallingConvention_Swift = 16, - lbCallingConvention_CXX_FAST_TLS = 17, - lbCallingConvention_FirstTargetCC = 64, - lbCallingConvention_X86_StdCall = 64, - lbCallingConvention_X86_FastCall = 65, - lbCallingConvention_ARM_APCS = 66, - lbCallingConvention_ARM_AAPCS = 67, - lbCallingConvention_ARM_AAPCS_VFP = 68, - lbCallingConvention_MSP430_INTR = 69, - lbCallingConvention_X86_ThisCall = 70, - lbCallingConvention_PTX_Kernel = 71, - lbCallingConvention_PTX_Device = 72, - lbCallingConvention_SPIR_FUNC = 75, - lbCallingConvention_SPIR_KERNEL = 76, - lbCallingConvention_Intel_OCL_BI = 77, - lbCallingConvention_X86_64_SysV = 78, - lbCallingConvention_Win64 = 79, - lbCallingConvention_X86_VectorCall = 80, - lbCallingConvention_HHVM = 81, - lbCallingConvention_HHVM_C = 82, - lbCallingConvention_X86_INTR = 83, - lbCallingConvention_AVR_INTR = 84, - lbCallingConvention_AVR_SIGNAL = 85, - lbCallingConvention_AVR_BUILTIN = 86, - lbCallingConvention_AMDGPU_VS = 87, - lbCallingConvention_AMDGPU_GS = 88, - lbCallingConvention_AMDGPU_PS = 89, - lbCallingConvention_AMDGPU_CS = 90, - lbCallingConvention_AMDGPU_KERNEL = 91, - lbCallingConvention_X86_RegCall = 92, - lbCallingConvention_AMDGPU_HS = 93, - lbCallingConvention_MSP430_BUILTIN = 94, - lbCallingConvention_AMDGPU_LS = 95, - lbCallingConvention_AMDGPU_ES = 96, - lbCallingConvention_AArch64_VectorCall = 97, - lbCallingConvention_MaxID = 1023, + +struct lbContextData { + lbAddr ctx; + isize scope_index; }; -lbCallingConventionKind const lb_calling_convention_map[ProcCC_MAX] = { - lbCallingConvention_C, // ProcCC_Invalid, - lbCallingConvention_C, // ProcCC_Odin, - lbCallingConvention_C, // ProcCC_Contextless, - lbCallingConvention_C, // ProcCC_CDecl, - lbCallingConvention_X86_StdCall, // ProcCC_StdCall, - lbCallingConvention_X86_FastCall, // ProcCC_FastCall, +enum lbParamPasskind { + lbParamPass_Value, // Pass by value + lbParamPass_Pointer, // Pass as a pointer rather than by value + lbParamPass_Integer, // Pass as an integer of the same size + lbParamPass_ConstRef, // Pass as a pointer but the value is immutable + lbParamPass_BitCast, // Pass by value and bit cast to the correct type + lbParamPass_Tuple, // Pass across multiple parameters (System V AMD64, up to 2) +}; - lbCallingConvention_C, // ProcCC_None, +enum lbDeferExitKind { + lbDeferExit_Default, + lbDeferExit_Return, + lbDeferExit_Branch, }; -struct lbContextData { - lbAddr ctx; - isize scope_index; +struct lbTargetList { + lbTargetList *prev; + bool is_block; + lbBlock * break_; + lbBlock * continue_; + lbBlock * fallthrough_; }; + struct lbProcedure { lbProcedure *parent; Array children; @@ -179,6 +145,7 @@ struct lbProcedure { lbBlock * decl_block; lbBlock * entry_block; lbBlock * curr_block; + lbTargetList * target_list; Array context_stack; @@ -187,14 +154,7 @@ struct lbProcedure { bool return_ptr_hint_used; }; -enum lbParamPasskind { - lbParamPass_Value, // Pass by value - lbParamPass_Pointer, // Pass as a pointer rather than by value - lbParamPass_Integer, // Pass as an integer of the same size - lbParamPass_ConstRef, // Pass as a pointer but the value is immutable - lbParamPass_BitCast, // Pass by value and bit cast to the correct type - lbParamPass_Tuple, // Pass across multiple parameters (System V AMD64, up to 2) -}; + @@ -251,3 +211,63 @@ lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value={}); lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr, bool zero_init=true, i32 param_index=0); lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t); + + +enum lbCallingConventionKind { + lbCallingConvention_C = 0, + lbCallingConvention_Fast = 8, + lbCallingConvention_Cold = 9, + lbCallingConvention_GHC = 10, + lbCallingConvention_HiPE = 11, + lbCallingConvention_WebKit_JS = 12, + lbCallingConvention_AnyReg = 13, + lbCallingConvention_PreserveMost = 14, + lbCallingConvention_PreserveAll = 15, + lbCallingConvention_Swift = 16, + lbCallingConvention_CXX_FAST_TLS = 17, + lbCallingConvention_FirstTargetCC = 64, + lbCallingConvention_X86_StdCall = 64, + lbCallingConvention_X86_FastCall = 65, + lbCallingConvention_ARM_APCS = 66, + lbCallingConvention_ARM_AAPCS = 67, + lbCallingConvention_ARM_AAPCS_VFP = 68, + lbCallingConvention_MSP430_INTR = 69, + lbCallingConvention_X86_ThisCall = 70, + lbCallingConvention_PTX_Kernel = 71, + lbCallingConvention_PTX_Device = 72, + lbCallingConvention_SPIR_FUNC = 75, + lbCallingConvention_SPIR_KERNEL = 76, + lbCallingConvention_Intel_OCL_BI = 77, + lbCallingConvention_X86_64_SysV = 78, + lbCallingConvention_Win64 = 79, + lbCallingConvention_X86_VectorCall = 80, + lbCallingConvention_HHVM = 81, + lbCallingConvention_HHVM_C = 82, + lbCallingConvention_X86_INTR = 83, + lbCallingConvention_AVR_INTR = 84, + lbCallingConvention_AVR_SIGNAL = 85, + lbCallingConvention_AVR_BUILTIN = 86, + lbCallingConvention_AMDGPU_VS = 87, + lbCallingConvention_AMDGPU_GS = 88, + lbCallingConvention_AMDGPU_PS = 89, + lbCallingConvention_AMDGPU_CS = 90, + lbCallingConvention_AMDGPU_KERNEL = 91, + lbCallingConvention_X86_RegCall = 92, + lbCallingConvention_AMDGPU_HS = 93, + lbCallingConvention_MSP430_BUILTIN = 94, + lbCallingConvention_AMDGPU_LS = 95, + lbCallingConvention_AMDGPU_ES = 96, + lbCallingConvention_AArch64_VectorCall = 97, + lbCallingConvention_MaxID = 1023, +}; + +lbCallingConventionKind const lb_calling_convention_map[ProcCC_MAX] = { + lbCallingConvention_C, // ProcCC_Invalid, + lbCallingConvention_C, // ProcCC_Odin, + lbCallingConvention_C, // ProcCC_Contextless, + lbCallingConvention_C, // ProcCC_CDecl, + lbCallingConvention_X86_StdCall, // ProcCC_StdCall, + lbCallingConvention_X86_FastCall, // ProcCC_FastCall, + + lbCallingConvention_C, // ProcCC_None, +}; -- cgit v1.2.3 From 7d9600b740aa815c0eaa8a5424e7949a2ac2963e Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 6 Feb 2020 23:33:41 +0000 Subject: Ternary Expr; lbAddr extra; Phi node support --- src/llvm_backend.cpp | 1138 +++++++++++++++++++++++++++++++++++++++++++------- src/llvm_backend.hpp | 39 +- src/main.cpp | 2 +- src/tokenizer.cpp | 2 +- src/types.cpp | 6 + 5 files changed, 1037 insertions(+), 150 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 41de200e2..886c87e7d 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -15,12 +15,49 @@ lbAddr lb_addr(lbValue addr) { } Type *lb_addr_type(lbAddr const &addr) { + if (addr.addr.value == nullptr) { + return nullptr; + } + if (addr.kind == lbAddr_Map) { + Type *t = base_type(addr.map.type); + GB_ASSERT(is_type_map(t)); + return t->Map.value; + } return type_deref(addr.addr.type); } LLVMTypeRef lb_addr_lb_type(lbAddr const &addr) { return LLVMGetElementType(LLVMTypeOf(addr.addr.value)); } +lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) { + if (addr.addr.value == nullptr) { + GB_PANIC("Illegal addr -> nullptr"); + return {}; + } + + switch (addr.kind) { + case lbAddr_Map: + case lbAddr_BitField: { + lbValue v = lb_addr_load(p, addr); + return lb_address_from_load_or_generate_local(p, v); + } + + case lbAddr_Context: + GB_PANIC("lbAddr_Context should be handled elsewhere"); + } + + return addr.addr; +} + +lbAddr lb_addr_bit_field(lbValue value, i32 index) { + lbAddr addr = {}; + addr.kind = lbAddr_BitField; + addr.addr = value; + addr.bit_field.value_index = index; + return addr; +} + + void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue const &value) { if (addr.addr.value == nullptr) { return; @@ -619,11 +656,13 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { p->is_export = false; p->is_entry_point = false; - p->children.allocator = heap_allocator(); - p->params.allocator = heap_allocator(); - p->blocks.allocator = heap_allocator(); - p->branch_blocks.allocator = heap_allocator(); - p->context_stack.allocator = heap_allocator(); + gbAllocator a = heap_allocator(); + p->children.allocator = a; + p->params.allocator = a; + p->defer_stmts.allocator = a; + p->blocks.allocator = a; + p->branch_blocks.allocator = a; + p->context_stack.allocator = a; char *name = alloc_cstring(heap_allocator(), p->name); @@ -953,13 +992,26 @@ void lb_end_procedure(lbProcedure *p) { LLVMDisposeBuilder(p->builder); } +void lb_add_edge(lbBlock *from, lbBlock *to) { + LLVMValueRef instr = LLVMGetLastInstruction(from->block); + if (instr == nullptr || !LLVMIsATerminatorInst(instr)) { + array_add(&from->succs, to); + array_add(&to->preds, from); + } +} + lbBlock *lb_create_block(lbProcedure *p, char const *name) { lbBlock *b = gb_alloc_item(heap_allocator(), lbBlock); b->block = LLVMAppendBasicBlockInContext(p->module->ctx, p->value, name); b->scope = p->curr_scope; b->scope_index = p->scope_index; + + b->preds.allocator = heap_allocator(); + b->succs.allocator = heap_allocator(); + array_add(&p->blocks, b); + return b; } @@ -972,10 +1024,21 @@ void lb_emit_jump(lbProcedure *p, lbBlock *target_block) { if (p->curr_block == nullptr) { return; } + lb_add_edge(p->curr_block, target_block); LLVMBuildBr(p->builder, target_block->block); p->curr_block = nullptr; } +void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block) { + lbBlock *b = p->curr_block; + if (b == nullptr) { + return; + } + lb_add_edge(b, true_block); + lb_add_edge(b, false_block); + LLVMBuildCondBr(p->builder, cond.value, true_block->block, false_block->block); +} + lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) { switch (cond->kind) { case_ast_node(pe, ParenExpr, cond); @@ -1039,9 +1102,7 @@ lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 p } lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) { - lbAddr addr = lb_add_local(p, type, nullptr); - lb_addr_store(p, addr, lb_const_nil(p->module, type)); - return addr; + return lb_add_local(p, type, nullptr, zero_init); } @@ -1129,6 +1190,7 @@ void lb_open_scope(lbProcedure *p) { } void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool pop_stack=true) { + lb_emit_defer_stmts(p, kind, block); GB_ASSERT(p->scope_index > 0); // NOTE(bill): Remove `context`s made in that scope @@ -1527,6 +1589,52 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(fs, ForStmt, node); + lb_open_scope(p); // Open Scope here + + if (fs->init != nullptr) { + #if 1 + lbBlock *init = lb_create_block(p, "for.init"); + lb_emit_jump(p, init); + lb_start_block(p, init); + #endif + lb_build_stmt(p, fs->init); + } + lbBlock *body = lb_create_block(p, "for.body"); + lbBlock *done = lb_create_block(p, "for.done"); // NOTE(bill): Append later + lbBlock *loop = body; + if (fs->cond != nullptr) { + loop = lb_create_block(p, "for.loop"); + } + lbBlock *post = loop; + if (fs->post != nullptr) { + post = lb_create_block(p, "for.post"); + } + + + lb_emit_jump(p, loop); + lb_start_block(p, loop); + + if (loop != body) { + lb_build_cond(p, fs->cond, body, done); + lb_start_block(p, body); + } + + lb_push_target_list(p, fs->label, done, post, nullptr); + + lb_build_stmt(p, fs->body); + lb_close_scope(p, lbDeferExit_Default, nullptr); + + lb_pop_target_list(p); + + lb_emit_jump(p, post); + + if (fs->post != nullptr) { + lb_start_block(p, post); + lb_build_stmt(p, fs->post); + lb_emit_jump(p, loop); + } + + lb_start_block(p, done); case_end; case_ast_node(rs, RangeStmt, node); @@ -1536,6 +1644,112 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(ss, SwitchStmt, node); + if (ss->init != nullptr) { + lb_build_stmt(p, ss->init); + } + lbValue tag = lb_const_bool(p->module, t_llvm_bool, true); + if (ss->tag != nullptr) { + tag = lb_build_expr(p, ss->tag); + } + lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later + + ast_node(body, BlockStmt, ss->body); + + Array default_stmts = {}; + lbBlock *default_fall = nullptr; + lbBlock *default_block = nullptr; + + lbBlock *fall = nullptr; + bool append_fall = false; + + isize case_count = body->stmts.count; + for_array(i, body->stmts) { + Ast *clause = body->stmts[i]; + lbBlock *body = fall; + + ast_node(cc, CaseClause, clause); + + if (body == nullptr) { + if (cc->list.count == 0) { + body = lb_create_block(p, "switch.dflt.body"); + } else { + body = lb_create_block(p, "switch.case.body"); + } + } + if (append_fall && body == fall) { + append_fall = false; + } + + fall = done; + if (i+1 < case_count) { + append_fall = true; + fall = lb_create_block(p, "switch.fall.body"); + } + + if (cc->list.count == 0) { + // default case + default_stmts = cc->stmts; + default_fall = fall; + default_block = body; + continue; + } + + lbBlock *next_cond = nullptr; + for_array(j, cc->list) { + Ast *expr = unparen_expr(cc->list[j]); + next_cond = lb_create_block(p, "switch.case.next"); + lbValue cond = lb_const_bool(p->module, t_llvm_bool, false); + 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_RangeHalf: op = Token_Lt; break; + default: GB_PANIC("Invalid interval operator"); break; + } + lbValue lhs = lb_build_expr(p, ie->left); + lbValue rhs = lb_build_expr(p, ie->right); + // TODO(bill): do short circuit here + lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag); + lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs); + cond = lb_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)); + lbValue e = lb_typeid(p->module, expr->tav.type); + e = lb_emit_conv(p, e, tag.type); + cond = lb_emit_comp(p, Token_CmpEq, tag, e); + } else { + cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr)); + } + } + lb_emit_if(p, cond, body, next_cond); + lb_start_block(p, next_cond); + } + lb_start_block(p, body); + + lb_push_target_list(p, ss->label, done, nullptr, fall); + lb_open_scope(p); + lb_build_stmt_list(p, cc->stmts); + lb_close_scope(p, lbDeferExit_Default, body); + lb_pop_target_list(p); + + lb_emit_jump(p, done); + p->curr_block = next_cond; + } + + if (default_block != nullptr) { + lb_emit_jump(p, default_block); + lb_start_block(p, default_block); + + lb_push_target_list(p, ss->label, done, nullptr, default_fall); + lb_open_scope(p); + lb_build_stmt_list(p, default_stmts); + lb_close_scope(p, lbDeferExit_Default, default_block); + lb_pop_target_list(p); + } + lb_emit_jump(p, done); + lb_start_block(p, done); case_end; case_ast_node(ss, TypeSwitchStmt, node); @@ -1567,7 +1781,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { } } if (block != nullptr) { - // ir_emit_defer_stmts(p, irDeferExit_Branch, block); + lb_emit_defer_stmts(p, lbDeferExit_Branch, block); } lb_emit_jump(p, block); case_end; @@ -1592,6 +1806,13 @@ lbValue lb_const_int(lbModule *m, Type *type, u64 value) { return res; } +lbValue lb_const_bool(lbModule *m, Type *type, bool value) { + lbValue res = {}; + res.value = LLVMConstInt(lb_type(m, type), value, false); + res.type = type; + return res; +} + LLVMValueRef llvm_const_f32(lbModule *m, f32 f, Type *type=t_f32) { u32 u = bit_cast(f); LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false); @@ -1640,7 +1861,7 @@ isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=tr return -1; } -lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type=t_typeid) { +lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type) { type = default_type(type); u64 id = cast(u64)lb_type_info_index(m->info, type); @@ -1814,7 +2035,15 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { cast(char const *)value.value_string.text, cast(unsigned)value.value_string.len, false); - LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), "test_string_data"); + + + isize max_len = 7+8+1; + char *str = gb_alloc_array(heap_allocator(), char, max_len); + isize len = gb_snprintf(str, max_len, "csbs$%x", m->global_array_index); + len -= 1; + m->global_array_index++; + + LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), str); LLVMSetInitializer(global_data, data); LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); @@ -1824,8 +2053,8 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { return res; } - LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true); - LLVMValueRef values[2] = {ptr, len}; + LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), len, true); + LLVMValueRef values[2] = {ptr, str_len}; res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); @@ -2503,11 +2732,11 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { } if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) { - lbValue c = ir_emit_conv(p, value, t_cstring); - auto args = array_make(ir_allocator(), 1); + lbValue c = lb_emit_conv(p, value, t_cstring); + auto args = array_make(heap_allocator(), 1); args[0] = c; - lbValue s = ir_emit_runtime_call(p, "cstring_to_string", args); - return ir_emit_conv(p, s, dst); + lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args); + return lb_emit_conv(p, s, dst); } @@ -2518,7 +2747,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { // float -> float if (is_type_float(src) && is_type_float(dst)) { - gbAllocator a = ir_allocator(); + gbAllocator a = heap_allocator(); i64 sz = type_size_of(src); i64 dz = type_size_of(dst); irConvKind kind = irConv_fptrunc; @@ -2530,9 +2759,9 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (is_type_complex(src) && is_type_complex(dst)) { Type *ft = base_complex_elem_type(dst); - lbValue gen = ir_add_local_generated(p, dst, false); - lbValue real = ir_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); - lbValue imag = ir_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); + lbValue gen = lb_add_local_generated(p, dst, false); + lbValue real = lb_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); + lbValue imag = lb_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), real); ir_emit_store(p, ir_emit_struct_ep(p, gen, 1), imag); return ir_emit_load(p, gen); @@ -2541,11 +2770,11 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (is_type_quaternion(src) && is_type_quaternion(dst)) { // @QuaternionLayout Type *ft = base_complex_elem_type(dst); - lbValue gen = ir_add_local_generated(p, dst, false); - lbValue q0 = ir_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); - lbValue q1 = ir_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); - lbValue q2 = ir_emit_conv(p, ir_emit_struct_ev(p, value, 2), ft); - lbValue q3 = ir_emit_conv(p, ir_emit_struct_ev(p, value, 3), ft); + lbValue gen = lb_add_local_generated(p, dst, false); + lbValue q0 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); + lbValue q1 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); + lbValue q2 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 2), ft); + lbValue q3 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 3), ft); ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), q0); ir_emit_store(p, ir_emit_struct_ep(p, gen, 1), q1); ir_emit_store(p, ir_emit_struct_ep(p, gen, 2), q2); @@ -2555,24 +2784,24 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (is_type_float(src) && is_type_complex(dst)) { Type *ft = base_complex_elem_type(dst); - lbValue gen = ir_add_local_generated(p, dst, true); - lbValue real = ir_emit_conv(p, value, ft); + lbValue gen = lb_add_local_generated(p, dst, true); + lbValue real = lb_emit_conv(p, value, ft); ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), real); return ir_emit_load(p, gen); } if (is_type_float(src) && is_type_quaternion(dst)) { Type *ft = base_complex_elem_type(dst); - lbValue gen = ir_add_local_generated(p, dst, true); - lbValue real = ir_emit_conv(p, value, ft); + lbValue gen = lb_add_local_generated(p, dst, true); + lbValue real = lb_emit_conv(p, value, ft); // @QuaternionLayout ir_emit_store(p, ir_emit_struct_ep(p, gen, 3), real); return ir_emit_load(p, gen); } if (is_type_complex(src) && is_type_quaternion(dst)) { Type *ft = base_complex_elem_type(dst); - lbValue gen = ir_add_local_generated(p, dst, true); - lbValue real = ir_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); - lbValue imag = ir_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); + lbValue gen = lb_add_local_generated(p, dst, true); + lbValue real = lb_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); + lbValue imag = lb_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); // @QuaternionLayout ir_emit_store(p, ir_emit_struct_ep(p, gen, 3), real); ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), imag); @@ -2610,8 +2839,8 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { Type *vt = dst->Union.variants[i]; if (are_types_identical(vt, src_type)) { ir_emit_comment(p, str_lit("union - child to parent")); - gbAllocator a = ir_allocator(); - lbValue parent = ir_add_local_generated(p, t, true); + gbAllocator a = heap_allocator(); + lbValue parent = lb_add_local_generated(p, t, true); ir_emit_store_union_variant(p, parent, value, vt); return ir_emit_load(p, parent); } @@ -2639,7 +2868,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (sel.entity != nullptr) { ir_emit_comment(p, str_lit("cast - polymorphism")); if (st_is_ptr) { - lbValue res = ir_emit_deep_field_gep(p, value, sel); + lbValue res = lb_emit_deep_field_gep(p, value, sel); Type *rt = ir_type(res); if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) { res = ir_emit_load(p, res); @@ -2651,7 +2880,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) { value = ir_emit_load(p, value); } else { - value = ir_emit_deep_field_gep(p, value, sel); + value = lb_emit_deep_field_gep(p, value, sel); return ir_emit_load(p, value); } } @@ -2698,7 +2927,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { } if (is_type_string(src) && is_type_u8_slice(dst)) { lbValue elem = ir_string_elem(p, value); - lbValue elem_ptr = ir_add_local_generated(p, ir_type(elem), false); + lbValue elem_ptr = lb_add_local_generated(p, ir_type(elem), false); ir_emit_store(p, elem_ptr, elem); lbValue len = ir_string_len(p, value); @@ -2708,9 +2937,9 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (is_type_array(dst)) { Type *elem = dst->Array.elem; - lbValue e = ir_emit_conv(p, value, elem); + lbValue e = lb_emit_conv(p, value, elem); // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops - lbValue v = ir_add_local_generated(p, t, false); + lbValue v = lb_add_local_generated(p, t, false); isize index_count = cast(isize)dst->Array.count; for (i32 i = 0; i < index_count; i++) { @@ -2721,7 +2950,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { } if (is_type_any(dst)) { - lbValue result = ir_add_local_generated(p, t_any, true); + lbValue result = lb_add_local_generated(p, t_any, true); if (is_type_untyped_nil(src)) { return ir_emit_load(p, result); @@ -2732,7 +2961,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { lbValue data = ir_address_from_load_or_generate_local(p, value); GB_ASSERT_MSG(is_type_pointer(ir_type(data)), type_to_string(ir_type(data))); GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st)); - data = ir_emit_conv(p, data, t_rawptr); + data = lb_emit_conv(p, data, t_rawptr); lbValue id = ir_typeid(p->module, st); @@ -2745,14 +2974,14 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (is_type_untyped(src)) { if (is_type_string(src) && is_type_string(dst)) { - lbValue result = ir_add_local_generated(p, t, false); + lbValue result = lb_add_local_generated(p, t, false); ir_emit_store(p, result, value); return ir_emit_load(p, result); } } #endif - gb_printf_err("ir_emit_conv: src -> dst\n"); + gb_printf_err("lb_emit_conv: src -> dst\n"); gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t)); gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst)); @@ -2775,7 +3004,7 @@ void lb_emit_init_context(lbProcedure *p, lbValue c) { gbAllocator a = heap_allocator(); auto args = array_make(a, 1); args[0] = c.value != nullptr ? c : m->global_default_context.addr; - // ir_emit_runtime_call(p, "__init_context", args); + // lb_emit_runtime_call(p, "__init_context", args); } void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) { @@ -2794,7 +3023,7 @@ lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) { defer (p->curr_block = tmp_block); - lbAddr c = lb_add_local_generated(p, t_context, true); + lbAddr c = lb_add_local_generated(p, t_context, false); lb_push_context_onto_stack(p, c); lb_addr_store(p, c, lb_addr_load(p, p->module->global_default_context)); lb_emit_init_context(p, c.addr); @@ -3014,6 +3243,124 @@ lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) { return res; } +lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) { + GB_ASSERT(sel.index.count > 0); + Type *type = type_deref(e.type); + gbAllocator a = heap_allocator(); + + for_array(i, sel.index) { + i32 index = cast(i32)sel.index[i]; + if (is_type_pointer(type)) { + type = type_deref(type); + e = lb_emit_load(p, e); + } + type = core_type(type); + if (type->kind == Type_Opaque) { + type = type->Opaque.elem; + } + + if (is_type_quaternion(type)) { + e = lb_emit_struct_ep(p, e, index); + } else if (is_type_raw_union(type)) { + type = type->Struct.fields[index]->type; + GB_ASSERT(is_type_pointer(e.type)); + e = lb_emit_transmute(p, e, alloc_type_pointer(type)); + } else if (is_type_struct(type)) { + type = type->Struct.fields[index]->type; + e = lb_emit_struct_ep(p, e, index); + } else if (type->kind == Type_Union) { + GB_ASSERT(index == -1); + type = t_type_info_ptr; + e = lb_emit_struct_ep(p, e, index); + } else if (type->kind == Type_Tuple) { + type = type->Tuple.variables[index]->type; + e = lb_emit_struct_ep(p, e, index); + } else if (type->kind == Type_Basic) { + switch (type->Basic.kind) { + case Basic_any: { + if (index == 0) { + type = t_rawptr; + } else if (index == 1) { + type = t_type_info_ptr; + } + e = lb_emit_struct_ep(p, e, index); + break; + } + + case Basic_string: + e = lb_emit_struct_ep(p, e, index); + break; + + default: + GB_PANIC("un-gep-able type"); + break; + } + } else if (type->kind == Type_Slice) { + e = lb_emit_struct_ep(p, e, index); + } else if (type->kind == Type_DynamicArray) { + e = lb_emit_struct_ep(p, e, index); + } else if (type->kind == Type_Array) { + e = lb_emit_array_epi(p, e, index); + } else if (type->kind == Type_Map) { + e = lb_emit_struct_ep(p, e, index); + } else { + GB_PANIC("un-gep-able type %s", type_to_string(type)); + } + } + + return e; +} + + +void lb_build_defer_stmt(lbProcedure *p, lbDefer d) { + lbBlock *b = lb_create_block(p, "defer"); + // NOTE(bill): The prev block may defer injection before it's terminator + LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block); + if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) { + lb_emit_jump(p, b); + } + lb_start_block(p, b); + if (d.kind == lbDefer_Node) { + lb_build_stmt(p, d.stmt); + } else if (d.kind == lbDefer_Instr) { + // NOTE(bill): Need to make a new copy + LLVMValueRef instr = LLVMInstructionClone(d.instr.value); + LLVMInsertIntoBuilder(p->builder, instr); + } else if (d.kind == lbDefer_Proc) { + lb_emit_call(p, d.proc.deferred, d.proc.result_as_args); + } +} + +void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) { + isize count = p->defer_stmts.count; + isize i = count; + while (i --> 0) { + lbDefer d = p->defer_stmts[i]; + if (p->context_stack.count >= d.context_stack_count) { + p->context_stack.count = d.context_stack_count; + } + + if (kind == lbDeferExit_Default) { + if (p->scope_index == d.scope_index && + d.scope_index > 0) { // TODO(bill): Which is correct: > 0 or > 1? + lb_build_defer_stmt(p, d); + array_pop(&p->defer_stmts); + continue; + } else { + break; + } + } else if (kind == lbDeferExit_Return) { + lb_build_defer_stmt(p, d); + } else if (kind == lbDeferExit_Branch) { + GB_ASSERT(block != nullptr); + isize lower_limit = block->scope_index; + if (lower_limit < d.scope_index) { + lb_build_defer_stmt(p, d); + } + } + } +} + lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) { unsigned arg_count = cast(unsigned)processed_args.count; @@ -3044,7 +3391,27 @@ lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, return res; } -lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false) { +lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array const &args) { + String name = make_string_c(c_name); + + + AstPackage *pkg = p->module->info->runtime_package; + Entity *e = scope_lookup_current(pkg->scope, name); + + lbValue *found = nullptr; + if (p->module != e->code_gen_module) { + gb_mutex_lock(&p->module->mutex); + } + found = map_get(&e->code_gen_module->values, hash_entity(e)); + if (p->module != e->code_gen_module) { + gb_mutex_unlock(&p->module->mutex); + } + + GB_ASSERT_MSG(found != nullptr, "%s", c_name); + return lb_emit_call(p, *found, args); +} + +lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, ProcInlining inlining, bool use_return_ptr_hint) { lbModule *m = p->module; Type *pt = base_type(value.type); @@ -3178,6 +3545,23 @@ lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, return result; } +lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) { + Type *t = s.type; + GB_ASSERT(is_type_pointer(t)); + Type *st = base_type(type_deref(t)); + GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st)); + + LLVMValueRef indices[2] = {}; + indices[0] = lb_zero32(p->module); + indices[1] = lb_emit_conv(p, index, t_i32).value; + + Type *ptr = base_array_type(st); + lbValue res = {}; + res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, ptr), s.value, indices, 2, ""); + res.type = alloc_type_pointer(ptr); + return res; +} + lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, i32 index) { Type *t = s.type; GB_ASSERT(is_type_pointer(t)); @@ -3192,6 +3576,15 @@ lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, i32 index) { return res; } +lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) { + LLVMValueRef indices[1] = {index.value}; + lbValue res = {}; + res.type = ptr.type; + res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, ptr.type), ptr.value, indices, 1, ""); + return res; +} + + void lb_fill_slice(lbProcedure *p, lbAddr slice, lbValue base_elem, lbValue len) { } @@ -3509,6 +3902,375 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr); } +bool lb_is_const(lbValue value) { + LLVMValueRef v = value.value; + if (LLVMIsConstant(v)) { + return true; + } + return false; +} +bool lb_is_const_nil(lbValue value) { + LLVMValueRef v = value.value; + if (LLVMIsConstant(v)) { + if (LLVMIsAConstantAggregateZero(v)) { + return true; + } else if (LLVMIsAConstantPointerNull(v)) { + return true; + } + } + return false; +} + +void lb_emit_increment(lbProcedure *p, lbValue addr) { + GB_ASSERT(is_type_pointer(addr.type)); + Type *type = type_deref(addr.type); + lbValue v_one = lb_const_value(p->module, type, exact_value_i64(1)); + lb_emit_store(p, addr, lb_emit_arith(p, Token_Add, lb_emit_load(p, addr), v_one, type)); + +} + +lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) { + Type *vt = core_type(value.type); + GB_ASSERT(type_size_of(vt) == type_size_of(platform_type)); + // TODO(bill): lb_emit_byte_swap + return value; +} + + + +struct lbLoopData { + lbAddr idx_addr; + lbValue idx; + lbBlock *body; + lbBlock *done; + lbBlock *loop; +}; + +lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_int) { + lbLoopData data = {}; + + lbValue max = lb_const_int(p->module, t_int, count); + + data.idx_addr = lb_add_local_generated(p, index_type, true); + + data.body = lb_create_block(p, "loop.body"); + data.done = lb_create_block(p, "loop.done"); + data.loop = lb_create_block(p, "loop.loop"); + + lb_emit_jump(p, data.loop); + lb_start_block(p, data.loop); + + data.idx = lb_addr_load(p, data.idx_addr); + + lbValue cond = lb_emit_comp(p, Token_Lt, data.idx, max); + lb_emit_if(p, cond, data.body, data.done); + lb_start_block(p, data.body); + + return data; +} + +void lb_loop_end(lbProcedure *p, lbLoopData const &data) { + if (data.idx_addr.addr.value != nullptr) { + lb_emit_increment(p, data.idx_addr.addr); + lb_emit_jump(p, data.loop); + lb_start_block(p, data.done); + } +} + + +lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) { + Type *a = base_type(left.type); + Type *b = base_type(right.type); + + GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1)); + + // lbValue nil_check = {}; + // if (left->kind == irValue_Nil) { + // nil_check = lb_emit_comp_against_nil(p, op_kind, right); + // } else if (right->kind == irValue_Nil) { + // nil_check = lb_emit_comp_against_nil(p, op_kind, left); + // } + // if (nil_check.value != nullptr) { + // return nil_check; + // } + + if (are_types_identical(a, b)) { + // NOTE(bill): No need for a conversion + } else if (lb_is_const(left) || lb_is_const_nil(left)) { + left = lb_emit_conv(p, left, right.type); + } else if (lb_is_const(right) || lb_is_const_nil(right)) { + right = lb_emit_conv(p, right, left.type); + } else { + gbAllocator a = heap_allocator(); + + Type *lt = left.type; + Type *rt = right.type; + + if (is_type_bit_set(lt) && is_type_bit_set(rt)) { + Type *blt = base_type(lt); + Type *brt = base_type(rt); + GB_ASSERT(is_type_bit_field_value(blt)); + GB_ASSERT(is_type_bit_field_value(brt)); + i64 bits = gb_max(blt->BitFieldValue.bits, brt->BitFieldValue.bits); + i64 bytes = bits / 8; + switch (bytes) { + case 1: + left = lb_emit_conv(p, left, t_u8); + right = lb_emit_conv(p, right, t_u8); + break; + case 2: + left = lb_emit_conv(p, left, t_u16); + right = lb_emit_conv(p, right, t_u16); + break; + case 4: + left = lb_emit_conv(p, left, t_u32); + right = lb_emit_conv(p, right, t_u32); + break; + case 8: + left = lb_emit_conv(p, left, t_u64); + right = lb_emit_conv(p, right, t_u64); + break; + default: GB_PANIC("Unknown integer size"); break; + } + } + + lt = left.type; + rt = right.type; + i64 ls = type_size_of(lt); + i64 rs = type_size_of(rt); + if (ls < rs) { + left = lb_emit_conv(p, left, rt); + } else if (ls > rs) { + right = lb_emit_conv(p, right, lt); + } else { + right = lb_emit_conv(p, right, lt); + } + } + + if (is_type_array(a)) { + Type *tl = base_type(a); + lbValue lhs = lb_address_from_load_or_generate_local(p, left); + lbValue rhs = lb_address_from_load_or_generate_local(p, right); + + + TokenKind cmp_op = Token_And; + lbValue res = lb_const_bool(p->module, t_llvm_bool, true); + if (op_kind == Token_NotEq) { + res = lb_const_bool(p->module, t_llvm_bool, false); + cmp_op = Token_Or; + } else if (op_kind == Token_CmpEq) { + res = lb_const_bool(p->module, t_llvm_bool, true); + cmp_op = Token_And; + } + + bool inline_array_arith = type_size_of(tl) <= build_context.max_align; + i32 count = cast(i32)tl->Array.count; + + if (inline_array_arith) { + // inline + lbAddr val = lb_add_local_generated(p, t_bool, false); + lb_addr_store(p, val, res); + for (i32 i = 0; i < count; i++) { + lbValue x = lb_emit_load(p, lb_emit_array_epi(p, lhs, i)); + lbValue y = lb_emit_load(p, lb_emit_array_epi(p, rhs, i)); + lbValue cmp = lb_emit_comp(p, op_kind, x, y); + lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool); + lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool)); + } + + return lb_addr_load(p, val); + } else { + if (is_type_simple_compare(tl) && (op_kind == Token_CmpEq || op_kind == Token_NotEq)) { + // TODO(bill): Test to see if this is actually faster!!!! + auto args = array_make(heap_allocator(), 3); + args[0] = lb_emit_conv(p, lhs, t_rawptr); + args[1] = lb_emit_conv(p, rhs, t_rawptr); + args[2] = lb_const_int(p->module, t_int, type_size_of(tl)); + lbValue val = lb_emit_runtime_call(p, "memory_compare", args); + lbValue res = lb_emit_comp(p, op_kind, val, lb_const_nil(p->module, val.type)); + return lb_emit_conv(p, res, t_bool); + } else { + lbAddr val = lb_add_local_generated(p, t_bool, false); + lb_addr_store(p, val, res); + auto loop_data = lb_loop_start(p, count, t_i32); + { + lbValue i = loop_data.idx; + lbValue x = lb_emit_load(p, lb_emit_array_ep(p, lhs, i)); + lbValue y = lb_emit_load(p, lb_emit_array_ep(p, rhs, i)); + lbValue cmp = lb_emit_comp(p, op_kind, x, y); + lbValue new_res = lb_emit_arith(p, cmp_op, lb_addr_load(p, val), cmp, t_bool); + lb_addr_store(p, val, lb_emit_conv(p, new_res, t_bool)); + } + lb_loop_end(p, loop_data); + + return lb_addr_load(p, val); + } + } + } + + if (is_type_string(a)) { + if (is_type_cstring(a)) { + left = lb_emit_conv(p, left, t_string); + right = lb_emit_conv(p, right, t_string); + } + + char const *runtime_proc = nullptr; + switch (op_kind) { + case Token_CmpEq: runtime_proc = "string_eq"; break; + case Token_NotEq: runtime_proc = "string_ne"; break; + case Token_Lt: runtime_proc = "string_lt"; break; + case Token_Gt: runtime_proc = "string_gt"; break; + case Token_LtEq: runtime_proc = "string_le"; break; + case Token_GtEq: runtime_proc = "string_gt"; break; + } + GB_ASSERT(runtime_proc != nullptr); + + auto args = array_make(heap_allocator(), 2); + args[0] = left; + args[1] = right; + return lb_emit_runtime_call(p, runtime_proc, args); + } + + if (is_type_complex(a)) { + char const *runtime_proc = ""; + i64 sz = 8*type_size_of(a); + switch (sz) { + case 64: + switch (op_kind) { + case Token_CmpEq: runtime_proc = "complex64_eq"; break; + case Token_NotEq: runtime_proc = "complex64_ne"; break; + } + break; + case 128: + switch (op_kind) { + case Token_CmpEq: runtime_proc = "complex128_eq"; break; + case Token_NotEq: runtime_proc = "complex128_ne"; break; + } + break; + } + GB_ASSERT(runtime_proc != nullptr); + + auto args = array_make(heap_allocator(), 2); + args[0] = left; + args[1] = right; + return lb_emit_runtime_call(p, runtime_proc, args); + } + + if (is_type_quaternion(a)) { + char const *runtime_proc = ""; + i64 sz = 8*type_size_of(a); + switch (sz) { + case 128: + switch (op_kind) { + case Token_CmpEq: runtime_proc = "quaternion128_eq"; break; + case Token_NotEq: runtime_proc = "quaternion128_ne"; break; + } + break; + case 256: + switch (op_kind) { + case Token_CmpEq: runtime_proc = "quaternion256_eq"; break; + case Token_NotEq: runtime_proc = "quaternion256_ne"; break; + } + break; + } + GB_ASSERT(runtime_proc != nullptr); + + auto args = array_make(heap_allocator(), 2); + args[0] = left; + args[1] = right; + return lb_emit_runtime_call(p, runtime_proc, args); + } + + if (is_type_bit_set(a)) { + switch (op_kind) { + case Token_Lt: + case Token_LtEq: + case Token_Gt: + case Token_GtEq: + { + Type *it = bit_set_to_int(a); + lbValue lhs = lb_emit_transmute(p, left, it); + lbValue rhs = lb_emit_transmute(p, right, it); + lbValue res = lb_emit_arith(p, Token_And, lhs, rhs, it); + + if (op_kind == Token_Lt || op_kind == Token_LtEq) { + // (lhs & rhs) == lhs + res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, lhs.value, ""); + res.type = t_llvm_bool; + } else if (op_kind == Token_Gt || op_kind == Token_GtEq) { + // (lhs & rhs) == rhs + res.value = LLVMBuildICmp(p->builder, LLVMIntEQ, res.value, rhs.value, ""); + res.type = t_llvm_bool; + } + + // NOTE(bill): Strict subsets + if (op_kind == Token_Lt || op_kind == Token_Gt) { + // res &~ (lhs == rhs) + lbValue eq = {}; + eq.value = LLVMBuildICmp(p->builder, LLVMIntEQ, lhs.value, rhs.value, ""); + eq.type = t_llvm_bool; + res = lb_emit_arith(p, Token_AndNot, res, eq, t_llvm_bool); + } + + return res; + } + } + } + + if (op_kind != Token_CmpEq && op_kind != Token_NotEq) { + Type *t = left.type; + if (is_type_integer(t) && is_type_different_to_arch_endianness(t)) { + Type *platform_type = integer_endian_type_to_platform_type(t); + lbValue x = lb_emit_byte_swap(p, left, platform_type); + lbValue y = lb_emit_byte_swap(p, right, platform_type); + left = x; + right = y; + } + } + + + lbValue res = {}; + res.type = t_llvm_bool; + if (is_type_integer(left.type) || is_type_boolean(left.type) || is_type_integer(left.type)) { + LLVMIntPredicate pred = {}; + if (is_type_unsigned(left.type)) { + switch (op_kind) { + case Token_Gt: pred = LLVMIntUGT; break; + case Token_GtEq: pred = LLVMIntUGE; break; + case Token_Lt: pred = LLVMIntULT; break; + case Token_LtEq: pred = LLVMIntULE; break; + } + } else { + switch (op_kind) { + case Token_Gt: pred = LLVMIntSGT; break; + case Token_GtEq: pred = LLVMIntSGE; break; + case Token_Lt: pred = LLVMIntSLT; break; + case Token_LtEq: pred = LLVMIntSLE; break; + } + } + switch (op_kind) { + case Token_CmpEq: pred = LLVMIntEQ; break; + case Token_NotEq: pred = LLVMIntNE; break; + } + res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, ""); + } else if (is_type_float(left.type)) { + LLVMRealPredicate pred = {}; + switch (op_kind) { + case Token_CmpEq: pred = LLVMRealOEQ; break; + case Token_Gt: pred = LLVMRealOGT; break; + case Token_GtEq: pred = LLVMRealOGE; break; + case Token_Lt: pred = LLVMRealOLT; break; + case Token_LtEq: pred = LLVMRealOLE; break; + case Token_NotEq: pred = LLVMRealONE; break; + } + res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, ""); + } else { + GB_PANIC("Unhandled comparison kind"); + } + + return res; +} + lbValue lb_build_expr(lbProcedure *p, Ast *expr) { lbModule *m = p->module; @@ -3555,6 +4317,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { LIT(token.pos.file), token.pos.line, token.pos.column); return {}; } else if (e->kind == Entity_Nil) { + GB_PANIC("Entity_Nil"); return lb_const_nil(m, tv.type); } @@ -3566,23 +4329,82 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { return v; } return lb_emit_load(p, v); - // } else if (e != nullptr && e->kind == Entity_Variable) { - // return ir_addr_load(p, lb_build_addr(p, expr)); + } else if (e != nullptr && e->kind == Entity_Variable) { + return lb_addr_load(p, lb_build_addr(p, expr)); } - GB_PANIC("nullptr value for expression from identifier: %.*s : %s @ %p", LIT(i->token.string), type_to_string(e->type), expr); + GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s : %s @ %p", LIT(e->pkg->name), LIT(i->token.string), type_to_string(e->type), expr); return {}; case_end; + case_ast_node(de, DerefExpr, expr); + return lb_addr_load(p, lb_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 lb_addr_load(p, lb_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 lb_const_value(p->module, tv.type, tv.value); + case_end; + + case_ast_node(te, TernaryExpr, expr); + LLVMValueRef incoming_values[2] = {}; + LLVMBasicBlockRef incoming_blocks[2] = {}; + + GB_ASSERT(te->y != nullptr); + lbBlock *then = lb_create_block(p, "if.then"); + lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later + lbBlock *else_ = lb_create_block(p, "if.else"); + + lbValue cond = lb_build_cond(p, te->cond, then, else_); + lb_start_block(p, then); + + Type *type = type_of_expr(expr); + + lb_open_scope(p); + incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value; + lb_close_scope(p, lbDeferExit_Default, nullptr); + + lb_emit_jump(p, done); + lb_start_block(p, else_); + + lb_open_scope(p); + incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value; + lb_close_scope(p, lbDeferExit_Default, nullptr); + + lb_emit_jump(p, done); + lb_start_block(p, done); + + lbValue res = {}; + res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), ""); + res.type = type; + + GB_ASSERT(p->curr_block->preds.count >= 2); + incoming_blocks[0] = p->curr_block->preds[0]->block; + incoming_blocks[1] = p->curr_block->preds[1]->block; + + LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2); + + return res; + case_end; + case_ast_node(be, BinaryExpr, expr); return lb_build_binary_expr(p, expr); case_end; - case_ast_node(ce, CallExpr, expr); return lb_build_call_expr(p, expr); case_end; } + GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind])); + return {}; } @@ -3644,9 +4466,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { return lb_build_addr_from_entity(p, e, expr); case_end; -#if 0 case_ast_node(se, SelectorExpr, expr); - ir_emit_comment(proc, str_lit("SelectorExpr")); Ast *sel = unparen_expr(se->selector); if (sel->kind == Ast_Ident) { String selector = sel->Ident.token.string; @@ -3658,7 +4478,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (imp != nullptr) { GB_ASSERT(imp->kind == Entity_ImportName); } - return ir_build_addr(proc, unparen_expr(se->selector)); + return lb_build_addr(p, unparen_expr(se->selector)); } @@ -3669,21 +4489,21 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT(e->kind == Entity_Variable); GB_ASSERT(e->flags & EntityFlag_TypeField); String name = e->token.string; - if (name == "names") { + /*if (name == "names") { lbValue ti_ptr = ir_type_info(proc, type); lbValue variant = ir_emit_struct_ep(proc, ti_ptr, 2); lbValue names_ptr = nullptr; if (is_type_enum(type)) { - lbValue enum_info = ir_emit_conv(proc, variant, t_type_info_enum_ptr); + lbValue enum_info = lb_emit_conv(proc, variant, t_type_info_enum_ptr); names_ptr = ir_emit_struct_ep(proc, enum_info, 1); } else if (type->kind == Type_Struct) { - lbValue struct_info = ir_emit_conv(proc, variant, t_type_info_struct_ptr); + lbValue struct_info = lb_emit_conv(proc, variant, t_type_info_struct_ptr); names_ptr = ir_emit_struct_ep(proc, struct_info, 1); } return ir_addr(names_ptr); - } else { + } else */{ GB_PANIC("Unhandled TypeField %.*s", LIT(name)); } GB_PANIC("Unreachable"); @@ -3694,23 +4514,23 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (sel.entity->type->kind == Type_BitFieldValue) { - irAddr addr = ir_build_addr(proc, se->expr); - Type *bft = type_deref(ir_addr_type(addr)); + lbAddr addr = lb_build_addr(p, se->expr); + Type *bft = type_deref(lb_addr_type(addr)); if (sel.index.count == 1) { GB_ASSERT(is_type_bit_field(bft)); i32 index = sel.index[0]; - return ir_addr_bit_field(ir_addr_get_ptr(proc, addr), index); + return lb_addr_bit_field(lb_addr_get_ptr(p, addr), index); } else { Selection s = sel; s.index.count--; i32 index = s.index[s.index.count-1]; - lbValue a = ir_addr_get_ptr(proc, addr); - a = ir_emit_deep_field_gep(proc, a, s); - return ir_addr_bit_field(a, index); + lbValue a = lb_addr_get_ptr(p, addr); + a = lb_emit_deep_field_gep(p, a, s); + return lb_addr_bit_field(a, index); } } else { - irAddr addr = ir_build_addr(proc, se->expr); - if (addr.kind == irAddr_Context) { + lbAddr addr = lb_build_addr(p, se->expr); + if (addr.kind == lbAddr_Context) { GB_ASSERT(sel.index.count > 0); if (addr.ctx.sel.index.count >= 0) { sel = selection_combine(addr.ctx.sel, sel); @@ -3718,52 +4538,54 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { addr.ctx.sel = sel; return addr; - } else if (addr.kind == irAddr_SoaVariable) { + } else if (addr.kind == lbAddr_SoaVariable) { lbValue index = addr.soa.index; i32 first_index = sel.index[0]; Selection sub_sel = sel; sub_sel.index.data += 1; sub_sel.index.count -= 1; - lbValue arr = ir_emit_struct_ep(proc, addr.addr, first_index); + lbValue arr = lb_emit_struct_ep(p, addr.addr, first_index); - Type *t = base_type(type_deref(ir_type(addr.addr))); + Type *t = base_type(type_deref(addr.addr.type)); GB_ASSERT(is_type_soa_struct(t)); - if (addr.soa.index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) { - lbValue len = ir_soa_struct_len(proc, addr.addr); - ir_emit_bounds_check(proc, ast_token(addr.soa.index_expr), addr.soa.index, len); - } + // TODO(bill): Bounds check + // if (addr.soa.index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) { + // lbValue len = ir_soa_struct_len(p, addr.addr); + // ir_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len); + // } - lbValue item = nullptr; + lbValue item = {}; if (t->Struct.soa_kind == StructSoa_Fixed) { - item = ir_emit_array_ep(proc, arr, index); + item = lb_emit_array_ep(p, arr, index); } else { - item = ir_emit_load(proc, ir_emit_ptr_offset(proc, arr, index)); + item = lb_emit_load(p, lb_emit_ptr_offset(p, arr, index)); } if (sub_sel.index.count > 0) { - item = ir_emit_deep_field_gep(proc, item, sub_sel); + item = lb_emit_deep_field_gep(p, item, sub_sel); } - return ir_addr(item); + return lb_addr(item); } - lbValue a = ir_addr_get_ptr(proc, addr); - a = ir_emit_deep_field_gep(proc, a, sel); - return ir_addr(a); + lbValue a = lb_addr_get_ptr(p, addr); + a = lb_emit_deep_field_gep(p, a, sel); + return lb_addr(a); } } else { GB_PANIC("Unsupported selector expression"); } case_end; +#if 0 case_ast_node(ta, TypeAssertion, expr); - gbAllocator a = ir_allocator(); + gbAllocator a = heap_allocator(); TokenPos pos = ast_token(expr).pos; lbValue e = ir_build_expr(proc, ta->expr); Type *t = type_deref(ir_type(e)); if (is_type_union(t)) { Type *type = type_of_expr(expr); - lbValue v = ir_add_local_generated(proc, type, false); + lbValue v = lb_add_local_generated(proc, type, false); ir_emit_comment(proc, str_lit("cast - union_cast")); ir_emit_store(proc, v, ir_emit_union_cast(proc, ir_build_expr(proc, ta->expr), type, pos)); return ir_addr(v); @@ -3798,7 +4620,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { case_ast_node(ie, IndexExpr, expr); ir_emit_comment(proc, str_lit("IndexExpr")); Type *t = base_type(type_of_expr(ie->expr)); - gbAllocator a = ir_allocator(); + gbAllocator a = heap_allocator(); bool deref = is_type_pointer(t); t = base_type(type_deref(t)); @@ -3852,7 +4674,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } lbValue key = ir_build_expr(proc, ie->index); - key = ir_emit_conv(proc, key, t->Map.key); + key = lb_emit_conv(proc, key, t->Map.key); Type *result_type = type_of_expr(expr); return ir_addr_map(map_val, key, t, result_type); @@ -3871,7 +4693,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { array = ir_emit_load(proc, array); } } - lbValue index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + lbValue index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); lbValue elem = ir_emit_array_ep(proc, array, index); auto index_tv = type_and_value_of_expr(ie->index); @@ -3903,11 +4725,11 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value); index = ir_value_constant(index_type, idx); } else { - index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); index = ir_emit_arith(proc, Token_Sub, index, ir_value_constant(index_type, t->EnumeratedArray.min_value), index_type); } } else { - index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); } lbValue elem = ir_emit_array_ep(proc, array, index); @@ -3930,7 +4752,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } } lbValue elem = ir_slice_elem(proc, slice); - lbValue index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + lbValue index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); lbValue len = ir_slice_len(proc, slice); ir_emit_bounds_check(proc, ast_token(ie->index), index, len); lbValue v = ir_emit_ptr_offset(proc, elem, index); @@ -3949,7 +4771,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } lbValue elem = ir_dynamic_array_elem(proc, dynamic_array); lbValue len = ir_dynamic_array_len(proc, dynamic_array); - lbValue index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + lbValue index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); ir_emit_bounds_check(proc, ast_token(ie->index), index, len); lbValue v = ir_emit_ptr_offset(proc, elem, index); return ir_addr(v); @@ -3973,7 +4795,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { elem = ir_string_elem(proc, str); len = ir_string_len(proc, str); - index = ir_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); ir_emit_bounds_check(proc, ast_token(ie->index), index, len); return ir_addr(ir_emit_ptr_offset(proc, elem, index)); @@ -3983,7 +4805,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { case_ast_node(se, SliceExpr, expr); ir_emit_comment(proc, str_lit("SliceExpr")); - gbAllocator a = ir_allocator(); + gbAllocator a = heap_allocator(); lbValue low = v_zero; lbValue high = nullptr; @@ -4016,7 +4838,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue elem = ir_emit_ptr_offset(proc, ir_slice_elem(proc, base), low); lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); - lbValue slice = ir_add_local_generated(proc, slice_type, false); + lbValue slice = lb_add_local_generated(proc, slice_type, false); ir_fill_slice(proc, slice, elem, new_len); return ir_addr(slice); } @@ -4035,7 +4857,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue elem = ir_emit_ptr_offset(proc, ir_dynamic_array_elem(proc, base), low); lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); - lbValue slice = ir_add_local_generated(proc, slice_type, false); + lbValue slice = lb_add_local_generated(proc, slice_type, false); ir_fill_slice(proc, slice, elem, new_len); return ir_addr(slice); } @@ -4058,7 +4880,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue elem = ir_emit_ptr_offset(proc, ir_array_elem(proc, addr), low); lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); - lbValue slice = ir_add_local_generated(proc, slice_type, false); + lbValue slice = lb_add_local_generated(proc, slice_type, false); ir_fill_slice(proc, slice, elem, new_len); return ir_addr(slice); } @@ -4075,7 +4897,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, base), low); lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); - lbValue str = ir_add_local_generated(proc, t_string, false); + lbValue str = lb_add_local_generated(proc, t_string, false); ir_fill_string(proc, str, elem, new_len); return ir_addr(str); } @@ -4090,7 +4912,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); } - lbValue dst = ir_add_local_generated(proc, type_of_expr(expr), true); + lbValue dst = lb_add_local_generated(proc, 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++) { @@ -4154,7 +4976,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { case_ast_node(ce, CallExpr, expr); // NOTE(bill): This is make sure you never need to have an 'array_ev' lbValue e = ir_build_expr(proc, expr); - lbValue v = ir_add_local_generated(proc, ir_type(e), false); + lbValue v = lb_add_local_generated(proc, ir_type(e), false); ir_emit_store(proc, v, e); return ir_addr(v); case_end; @@ -4164,7 +4986,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { Type *type = type_of_expr(expr); Type *bt = base_type(type); - lbValue v = ir_add_local_generated(proc, type, true); + lbValue v = lb_add_local_generated(proc, type, true); Type *et = nullptr; switch (bt->kind) { @@ -4232,7 +5054,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue gep = ir_emit_struct_ep(proc, v, cast(i32)index); ir_emit_store_union_variant(proc, gep, field_expr, fet); } else { - lbValue fv = ir_emit_conv(proc, field_expr, ft); + lbValue fv = lb_emit_conv(proc, field_expr, ft); lbValue gep = ir_emit_struct_ep(proc, v, cast(i32)index); ir_emit_store(proc, gep, fv); } @@ -4245,13 +5067,13 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (cl->elems.count == 0) { break; } - gbAllocator a = ir_allocator(); + gbAllocator a = heap_allocator(); { auto args = array_make(a, 3); args[0] = ir_gen_map_header(proc, v, type); args[1] = ir_const_int(2*cl->elems.count); args[2] = ir_emit_source_code_location(proc, proc_name, pos); - ir_emit_runtime_call(proc, "__dynamic_map_reserve", args); + lb_emit_runtime_call(proc, "__dynamic_map_reserve", args); } for_array(field_index, cl->elems) { Ast *elem = cl->elems[field_index]; @@ -4308,7 +5130,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { i64 index = exact_value_to_i64(tav.value); irCompoundLitElemTempData data = {}; - data.value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et); + data.value = lb_emit_conv(proc, ir_build_expr(proc, fv->value), et); data.expr = fv->value; data.elem_index = cast(i32)index; array_add(&temp_data, data); @@ -4348,7 +5170,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } Type *t = ir_type(field_expr); GB_ASSERT(t->kind != Type_Tuple); - lbValue ev = ir_emit_conv(proc, field_expr, et); + lbValue ev = lb_emit_conv(proc, field_expr, et); if (!proc->return_ptr_hint_used) { temp_data[i].value = ev; @@ -4407,7 +5229,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { i64 index = exact_value_to_i64(tav.value); irCompoundLitElemTempData data = {}; - data.value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et); + data.value = lb_emit_conv(proc, ir_build_expr(proc, fv->value), et); data.expr = fv->value; data.elem_index = cast(i32)index; array_add(&temp_data, data); @@ -4451,7 +5273,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } Type *t = ir_type(field_expr); GB_ASSERT(t->kind != Type_Tuple); - lbValue ev = ir_emit_conv(proc, field_expr, et); + lbValue ev = lb_emit_conv(proc, field_expr, et); if (!proc->return_ptr_hint_used) { temp_data[i].value = ev; @@ -4502,7 +5324,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { hi += 1; } - lbValue value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et); + lbValue value = lb_emit_conv(proc, ir_build_expr(proc, fv->value), et); for (i64 k = lo; k < hi; k++) { irCompoundLitElemTempData data = {}; @@ -4518,7 +5340,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue field_expr = ir_build_expr(proc, fv->value); GB_ASSERT(!is_type_tuple(ir_type(field_expr))); - lbValue ev = ir_emit_conv(proc, field_expr, et); + lbValue ev = lb_emit_conv(proc, field_expr, et); irCompoundLitElemTempData data = {}; data.value = ev; @@ -4532,7 +5354,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue field_expr = ir_build_expr(proc, elem); GB_ASSERT(!is_type_tuple(ir_type(field_expr))); - lbValue ev = ir_emit_conv(proc, field_expr, et); + lbValue ev = lb_emit_conv(proc, field_expr, et); irCompoundLitElemTempData data = {}; data.value = ev; @@ -4560,20 +5382,20 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { break; } Type *et = bt->DynamicArray.elem; - gbAllocator a = ir_allocator(); + gbAllocator a = heap_allocator(); lbValue size = ir_const_int(type_size_of(et)); lbValue align = ir_const_int(type_align_of(et)); i64 item_count = gb_max(cl->max_count, cl->elems.count); { - auto args = array_make(a, 5); - args[0] = ir_emit_conv(proc, v, t_rawptr); + auto args = array_make(a, 5); + args[0] = lb_emit_conv(proc, v, t_rawptr); args[1] = size; args[2] = align; args[3] = ir_const_int(2*item_count); // TODO(bill): Is this too much waste? args[4] = ir_emit_source_code_location(proc, proc_name, pos); - ir_emit_runtime_call(proc, "__dynamic_array_reserve", args); + lb_emit_runtime_call(proc, "__dynamic_array_reserve", args); } lbValue items = ir_generate_array(proc->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr); @@ -4596,7 +5418,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { hi += 1; } - lbValue value = ir_emit_conv(proc, ir_build_expr(proc, fv->value), et); + lbValue value = lb_emit_conv(proc, ir_build_expr(proc, fv->value), et); for (i64 k = lo; k < hi; k++) { lbValue ep = ir_emit_array_epi(proc, items, cast(i32)k); @@ -4608,26 +5430,26 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { i64 field_index = exact_value_to_i64(fv->field->tav.value); lbValue ev = ir_build_expr(proc, fv->value); - lbValue value = ir_emit_conv(proc, ev, et); + lbValue value = lb_emit_conv(proc, ev, et); lbValue ep = ir_emit_array_epi(proc, items, cast(i32)field_index); ir_emit_store(proc, ep, value); } } else { - lbValue value = ir_emit_conv(proc, ir_build_expr(proc, elem), et); + lbValue value = lb_emit_conv(proc, ir_build_expr(proc, elem), et); lbValue ep = ir_emit_array_epi(proc, items, cast(i32)i); ir_emit_store(proc, ep, value); } } { - auto args = array_make(a, 6); - args[0] = ir_emit_conv(proc, v, t_rawptr); + auto args = array_make(a, 6); + args[0] = lb_emit_conv(proc, v, t_rawptr); args[1] = size; args[2] = align; - args[3] = ir_emit_conv(proc, items, t_rawptr); + args[3] = lb_emit_conv(proc, items, t_rawptr); args[4] = ir_const_int(item_count); args[5] = ir_emit_source_code_location(proc, proc_name, pos); - ir_emit_runtime_call(proc, "__dynamic_array_append", args); + lb_emit_runtime_call(proc, "__dynamic_array_append", args); } break; } @@ -4667,7 +5489,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple); Type *ft = field_types[index]; - lbValue fv = ir_emit_conv(proc, field_expr, ft); + lbValue fv = lb_emit_conv(proc, field_expr, ft); lbValue gep = ir_emit_struct_ep(proc, v, cast(i32)index); ir_emit_store(proc, gep, fv); } @@ -4694,7 +5516,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT(ir_type(expr)->kind != Type_Tuple); Type *it = bit_set_to_int(bt); - lbValue e = ir_emit_conv(proc, expr, it); + lbValue e = lb_emit_conv(proc, expr, it); e = ir_emit_arith(proc, Token_Sub, e, lower, it); e = ir_emit_arith(proc, Token_Shl, v_one, e, it); @@ -4718,7 +5540,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue e = nullptr; switch (tc->token.kind) { case Token_cast: - e = ir_emit_conv(proc, x, type); + e = lb_emit_conv(proc, x, type); break; case Token_transmute: e = lb_emit_transmute(proc, x, type); @@ -4726,7 +5548,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { default: GB_PANIC("Invalid AST TypeCast"); } - lbValue v = ir_add_local_generated(proc, type, false); + lbValue v = lb_add_local_generated(proc, type, false); ir_emit_store(proc, v, e); return ir_addr(v); case_end; @@ -4796,6 +5618,7 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { // gen->ctx = LLVMContextCreate(); gen->module.ctx = LLVMGetGlobalContext(); gen->module.mod = LLVMModuleCreateWithNameInContext("odin_module", gen->module.ctx); + gb_mutex_init(&gen->module.mutex); map_init(&gen->module.types, heap_allocator()); map_init(&gen->module.values, heap_allocator()); map_init(&gen->module.members, heap_allocator()); @@ -4831,7 +5654,7 @@ lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) { } -void lb_generate_module(lbGenerator *gen) { +void lb_generate_code(lbGenerator *gen) { lbModule *m = &gen->module; LLVMModuleRef mod = gen->module.mod; CheckerInfo *info = gen->info; @@ -4906,18 +5729,34 @@ void lb_generate_module(lbGenerator *gen) { String name = lb_get_entity_name(m, e); - if (true) { - continue; - } lbValue g = {}; g.value = LLVMAddGlobal(m->mod, lb_type(m, e->type), alloc_cstring(heap_allocator(), name)); g.type = alloc_type_pointer(e->type); - // lbValue g = ir_value_global(e, nullptr); - // g->Global.name = name; - // g->Global.thread_local_model = e->Variable.thread_local_model; - // g->Global.is_foreign = is_foreign; - // g->Global.is_export = is_export; + if (e->Variable.thread_local_model != "") { + LLVMSetThreadLocal(g.value, true); + + String m = e->Variable.thread_local_model; + LLVMThreadLocalMode mode = LLVMGeneralDynamicTLSModel; + if (m == "default") { + mode = LLVMGeneralDynamicTLSModel; + } else if (m == "localdynamic") { + mode = LLVMLocalDynamicTLSModel; + } else if (m == "initialexec") { + mode = LLVMInitialExecTLSModel; + } else if (m == "localexec") { + mode = LLVMLocalExecTLSModel; + } else { + GB_PANIC("Unhandled thread local mode %.*s", LIT(m)); + } + LLVMSetThreadLocalMode(g.value, mode); + } + if (is_foreign) { + LLVMSetExternallyInitialized(g.value, true); + } + if (is_export) { + LLVMSetLinkage(g.value, LLVMDLLExportLinkage); + } GlobalVariable var = {}; var.var = g; @@ -4940,6 +5779,9 @@ void lb_generate_module(lbGenerator *gen) { lb_add_member(m, name, g); } + Array procedures = {}; + procedures.allocator = heap_allocator(); + for_array(i, info->entities) { // arena_free_all(&temp_arena); @@ -4995,37 +5837,39 @@ void lb_generate_module(lbGenerator *gen) { case Entity_Procedure: { - if (e->pkg->name != "demo") { + if (e->pkg->name == "demo") { + // } else if (e->pkg->name == "os") { + } else { continue; } lbProcedure *p = lb_create_procedure(m, e); - - if (p->body != nullptr) { // Build Procedure - lb_begin_procedure_body(p); - lb_build_stmt(p, p->body); - lb_end_procedure_body(p); - } - - lb_end_procedure(p); + array_add(&procedures, p); } break; } } + for_array(i, procedures) { + lbProcedure *p = procedures[i]; + if (p->body != nullptr) { // Build Procedure + lb_begin_procedure_body(p); + lb_build_stmt(p, p->body); + lb_end_procedure_body(p); + } + + lb_end_procedure(p); + } + char *llvm_error = nullptr; defer (LLVMDisposeMessage(llvm_error)); LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); + LLVMDumpModule(mod); - // LLVMInitializeAllTargetInfos(); - // LLVMInitializeAllTargets(); - // LLVMInitializeAllTargetMCs(); - // LLVMInitializeAllAsmParsers(); - // LLVMInitializeAllAsmPrinters(); // char const *target_triple = "x86_64-pc-windows-msvc"; // char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 0dfd14163..eec14b4d5 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -49,6 +49,8 @@ struct lbModule { LLVMContextRef ctx; CheckerInfo *info; + gbMutex mutex; + Map types; // Key: Type * Map values; // Key: Entity * @@ -77,6 +79,9 @@ struct lbBlock { LLVMBasicBlockRef block; Scope *scope; isize scope_index; + + Array preds; + Array succs; }; struct lbBranchBlocks { @@ -106,6 +111,28 @@ enum lbDeferExitKind { lbDeferExit_Branch, }; +enum lbDeferKind { + lbDefer_Node, + lbDefer_Instr, + lbDefer_Proc, +}; + +struct lbDefer { + lbDeferKind kind; + isize scope_index; + isize context_stack_count; + lbBlock * block; + union { + Ast *stmt; + // NOTE(bill): 'instr' will be copied every time to create a new one + lbValue instr; + struct { + lbValue deferred; + Array result_as_args; + } proc; + }; +}; + struct lbTargetList { lbTargetList *prev; bool is_block; @@ -138,6 +165,7 @@ struct lbProcedure { lbAddr return_ptr; Array params; + Array defer_stmts; Array blocks; Array branch_blocks; Scope * curr_scope; @@ -176,7 +204,10 @@ LLVMTypeRef lb_type(lbModule *m, Type *type); lbBlock *lb_create_block(lbProcedure *p, char const *name); lbValue lb_const_nil(lbModule *m, Type *type); +lbValue lb_const_undef(lbModule *m, Type *type); lbValue lb_const_value(lbModule *m, Type *type, ExactValue value); +lbValue lb_const_bool(lbModule *m, Type *type, bool value); +lbValue lb_const_int(lbModule *m, Type *type, u64 value); lbAddr lb_addr(lbValue addr); @@ -200,7 +231,7 @@ lbValue lb_emit_array_epi(lbProcedure *p, lbValue value, i32 index); lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type); - +void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block); lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t); lbValue lb_build_call_expr(lbProcedure *p, Ast *expr); @@ -212,6 +243,12 @@ lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr, bool zero_ini lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t); +lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right); +lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false); + +lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type=t_typeid); + +lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value); enum lbCallingConventionKind { lbCallingConvention_C = 0, diff --git a/src/main.cpp b/src/main.cpp index bed1935ec..119e6fc62 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1280,7 +1280,7 @@ int main(int arg_count, char const **arg_ptr) { if (!lb_init_generator(&gen, &checker)) { return 1; } - lb_generate_module(&gen); + lb_generate_code(&gen); if (build_context.show_timings) { show_timings(&checker, timings); diff --git a/src/tokenizer.cpp b/src/tokenizer.cpp index 19cb9b9aa..1854020f9 100644 --- a/src/tokenizer.cpp +++ b/src/tokenizer.cpp @@ -904,7 +904,7 @@ Token tokenizer_get_token(Tokenizer *t) { } if (token.kind == Token_Ident && token.string == "notin") { - token.kind = Token_not_in; + token.kind = Token_not_in; } } diff --git a/src/types.cpp b/src/types.cpp index 2afba733c..73023001a 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -3421,7 +3421,13 @@ gbString write_type_to_string(gbString str, Type *type) { str = gb_string_appendc(str, ")"); if (type->Proc.results) { str = gb_string_appendc(str, " -> "); + if (type->Proc.results->Tuple.variables.count > 1) { + str = gb_string_appendc(str, "("); + } str = write_type_to_string(str, type->Proc.results); + if (type->Proc.results->Tuple.variables.count > 1) { + str = gb_string_appendc(str, ")"); + } } break; -- cgit v1.2.3 From 66da96284a4674e87cdf17b546620d84a817971d Mon Sep 17 00:00:00 2001 From: gingerBill Date: Fri, 7 Feb 2020 00:01:44 +0000 Subject: Add `defer` statement for LB --- src/llvm_backend.cpp | 185 ++++++++++++++++++++++++++++++++++++++++++++++++--- src/llvm_backend.hpp | 3 + 2 files changed, 178 insertions(+), 10 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 886c87e7d..c0b015540 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -49,6 +49,12 @@ lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) { return addr.addr; } + +lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) { + lbAddr addr = lb_build_addr(p, expr); + return lb_addr_get_ptr(p, addr); +} + lbAddr lb_addr_bit_field(lbValue value, i32 index) { lbAddr addr = {}; addr.kind = lbAddr_BitField; @@ -1464,6 +1470,8 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(ds, DeferStmt, node); + isize scope_index = p->scope_index; + lb_add_defer_node(p, scope_index, ds->stmt); case_end; case_ast_node(rs, ReturnStmt, node); @@ -1638,9 +1646,11 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(rs, RangeStmt, node); + // TODO(bill): RangeStmt case_end; case_ast_node(rs, InlineRangeStmt, node); + // TODO(bill): InlineRangeStmt case_end; case_ast_node(ss, SwitchStmt, node); @@ -1753,6 +1763,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(ss, TypeSwitchStmt, node); + // TODO(bill): TypeSwitchStmt case_end; case_ast_node(bs, BranchStmt, node); @@ -1813,7 +1824,7 @@ lbValue lb_const_bool(lbModule *m, Type *type, bool value) { return res; } -LLVMValueRef llvm_const_f32(lbModule *m, f32 f, Type *type=t_f32) { +LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) { u32 u = bit_cast(f); LLVMValueRef i = LLVMConstInt(LLVMInt32TypeInContext(m->ctx), u, false); return LLVMConstBitCast(i, lb_type(m, type)); @@ -2074,7 +2085,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { case ExactValue_Float: if (type_size_of(type) == 4) { f32 f = cast(f32)value.value_float; - res.value = llvm_const_f32(m, f, type); + res.value = lb_const_f32(m, f, type); return res; } res.value = LLVMConstReal(lb_type(m, original_type), value.value_float); @@ -2084,8 +2095,8 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { LLVMValueRef values[2] = {}; switch (8*type_size_of(type)) { case 64: - values[0] = llvm_const_f32(m, cast(f32)value.value_complex.real); - values[1] = llvm_const_f32(m, cast(f32)value.value_complex.imag); + values[0] = lb_const_f32(m, cast(f32)value.value_complex.real); + values[1] = lb_const_f32(m, cast(f32)value.value_complex.imag); break; case 128: values[0] = LLVMConstReal(lb_type(m, t_f64), value.value_complex.real); @@ -2103,10 +2114,10 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { switch (8*type_size_of(type)) { case 128: // @QuaternionLayout - values[3] = llvm_const_f32(m, cast(f32)value.value_quaternion.real); - values[0] = llvm_const_f32(m, cast(f32)value.value_quaternion.imag); - values[1] = llvm_const_f32(m, cast(f32)value.value_quaternion.jmag); - values[2] = llvm_const_f32(m, cast(f32)value.value_quaternion.kmag); + values[3] = lb_const_f32(m, cast(f32)value.value_quaternion.real); + values[0] = lb_const_f32(m, cast(f32)value.value_quaternion.imag); + values[1] = lb_const_f32(m, cast(f32)value.value_quaternion.jmag); + values[2] = lb_const_f32(m, cast(f32)value.value_quaternion.kmag); break; case 256: // @QuaternionLayout @@ -3361,6 +3372,16 @@ void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) { } } +lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) { + lbDefer d = {lbDefer_Node}; + d.scope_index = scope_index; + d.context_stack_count = p->context_stack.count; + d.block = p->curr_block; + d.stmt = stmt; + array_add(&p->defer_stmts, d); + return d; +} + lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) { unsigned arg_count = cast(unsigned)processed_args.count; @@ -4394,13 +4415,139 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { return res; case_end; + case_ast_node(ta, TypeAssertion, expr); + TokenPos pos = ast_token(expr).pos; + Type *type = tv.type; + lbValue e = lb_build_expr(p, ta->expr); + Type *t = type_deref(e.type); + if (is_type_union(t)) { + GB_PANIC("cast - union_cast"); + // return lb_emit_union_cast(p, e, type, pos); + } else if (is_type_any(t)) { + GB_PANIC("cast - any_cast"); + // return lb_emit_any_cast(p, e, type, pos); + } else { + GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type)); + } + case_end; + + case_ast_node(tc, TypeCast, expr); + lbValue e = lb_build_expr(p, tc->expr); + switch (tc->token.kind) { + case Token_cast: + return lb_emit_conv(p, e, tv.type); + case Token_transmute: + return lb_emit_transmute(p, e, tv.type); + } + GB_PANIC("Invalid AST TypeCast"); + case_end; + + case_ast_node(ac, AutoCast, expr); + return lb_build_expr(p, ac->expr); + case_end; + + case_ast_node(ue, UnaryExpr, expr); + #if 0 + switch (ue->op.kind) { + case Token_And: { + Ast *ue_expr = unparen_expr(ue->expr); + if (ue_expr->kind == Ast_TypeAssertion) { + gbAllocator a = heap_allocator(); + GB_ASSERT(is_type_pointer(tv.type)); + + ast_node(ta, TypeAssertion, ue_expr); + TokenPos pos = ast_token(expr).pos; + Type *type = type_of_expr(ue_expr); + GB_ASSERT(!is_type_tuple(type)); + + lbValue e = lb_build_expr(p, ta->expr); + Type *t = type_deref(e.type); + if (is_type_union(t)) { + lbValue v = e; + if (!is_type_pointer(v.type)) { + v = lb_address_from_load_or_generate_local(p, v); + } + Type *src_type = type_deref(v.type); + Type *dst_type = type; + + lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v)); + lbValue dst_tag = lb_const_union_tag(src_type, dst_type); + + lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag); + auto args = array_make(heap_allocator(), 6); + args[0] = ok; + + args[1] = lb_find_or_add_entity_string(p->module, pos.file); + args[2] = lb_const_int(pos.line); + args[3] = lb_const_int(pos.column); + + args[4] = lb_typeid(p->module, src_type); + args[5] = lb_typeid(p->module, dst_type); + lb_emit_runtime_call(p, "type_assertion_check", args); + + lbValue data_ptr = v; + return ir_emit_conv(p, data_ptr, tv.type); + } else if (is_type_any(t)) { + lbValue v = e; + if (is_type_pointer(ir_type(v))) { + v = ir_emit_load(p, v); + } + + lbValue data_ptr = ir_emit_struct_ev(p, v, 0); + lbValue any_id = ir_emit_struct_ev(p, v, 1); + lbValue id = lb_typeid(p->module, type); + + + lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id); + auto args = array_make(ir_allocator(), 6); + args[0] = ok; + + args[1] = lb_find_or_add_entity_string(p->module, pos.file); + args[2] = lb_const_int(pos.line); + args[3] = ir_const_int(pos.column); + + args[4] = any_id; + args[5] = id; + lb_emit_runtime_call(p, "type_assertion_check", args); + + return ir_emit_conv(p, data_ptr, tv.type); + } else { + GB_PANIC("TODO(bill): type assertion %s", type_to_string(type)); + } + } else if (ue_expr->kind == Ast_IndexExpr) { + } + + return lb_build_addr_ptr(p, ue->expr); + } + default: + return lb_emit_unary_arith(p, ue->op.kind, lb_build_expr(p, ue->expr), tv.type); + } + #endif + case_end; + case_ast_node(be, BinaryExpr, expr); return lb_build_binary_expr(p, expr); case_end; + case_ast_node(pl, ProcLit, expr); + // return lb_gen_anonymous_proc_lit(p->module, p->name, expr, p); + case_end; + + case_ast_node(cl, CompoundLit, expr); + return lb_addr_load(p, lb_build_addr(p, expr)); + case_end; + case_ast_node(ce, CallExpr, expr); return lb_build_call_expr(p, expr); case_end; + + case_ast_node(se, SliceExpr, expr); + return lb_addr_load(p, lb_build_addr(p, expr)); + case_end; + + case_ast_node(ie, IndexExpr, expr); + return lb_addr_load(p, lb_build_addr(p, expr)); + case_end; } GB_PANIC("lb_build_expr: %.*s", LIT(ast_strings[expr->kind])); @@ -4408,6 +4555,25 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { return {}; } +lbValue lb_get_using_variable(lbProcedure *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); + lbValue *pv = map_get(&p->module->values, hash_entity(parent)); + lbValue v = {}; + if (pv != nullptr) { + v = *pv; + } else { + GB_ASSERT_MSG(e->using_expr != nullptr, "%.*s", LIT(name)); + v = lb_build_addr_ptr(p, e->using_expr); + } + GB_ASSERT(v.value != nullptr); + GB_ASSERT(parent->type == type_deref(v.type)); + return lb_emit_deep_field_gep(p, v, sel); +} + lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) { GB_ASSERT(e != nullptr); @@ -4425,8 +4591,7 @@ lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) { v = *found; } else if (e->kind == Entity_Variable && e->flags & EntityFlag_Using) { // NOTE(bill): Calculate the using variable every time - GB_PANIC("HERE: using variable"); - // v = lb_get_using_variable(p, e); + v = lb_get_using_variable(p, e); } if (v.value == nullptr) { diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index eec14b4d5..2e976cf11 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -250,6 +250,9 @@ lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type=t_typeid); lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value); +lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt); + + enum lbCallingConventionKind { lbCallingConvention_C = 0, lbCallingConvention_Fast = 8, -- cgit v1.2.3 From 35711a400c4245a75b0548577fd432c5bf674c37 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 8 Feb 2020 12:49:38 +0000 Subject: Anonymous procedure literal support --- examples/llvm-demo/demo.odin | 25 +++- src/check_expr.cpp | 1 + src/llvm_backend.cpp | 267 ++++++++++++++++++++++++++++++++++++++----- src/llvm_backend.hpp | 10 +- src/parser.hpp | 1 + 5 files changed, 268 insertions(+), 36 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/examples/llvm-demo/demo.odin b/examples/llvm-demo/demo.odin index 58bb10682..578f98e0a 100644 --- a/examples/llvm-demo/demo.odin +++ b/examples/llvm-demo/demo.odin @@ -1,9 +1,12 @@ package demo +import "core:os" + BarBar :: struct { x, y: int, }; foo :: proc(x: int) -> (b: BarBar) { + b = {1, 2}; return; } @@ -15,12 +18,19 @@ main :: proc() { array := [4]int{3 = 1, 0 .. 1 = 3, 2 = 9}; slice := []int{1, 2, 3, 4}; + x: ^int = nil; + y := slice != nil; + @thread_local a: int; - x := i32(1); - y := i32(2); - z := x + y; - w := z - 2; + if true { + foo(1); + } + + x1 := i32(1); + y1 := i32(2); + z1 := x1 + y1; + w1 := z1 - 2; f := foo; @@ -29,6 +39,13 @@ main :: proc() { s := "Hellope"; + b := true; + aaa := b ? int(123) : int(34); + defer aaa = 333; + + p := proc(x: int) {}; + + bb := BarBar{1, 2}; pc: proc "contextless" (x: i32) -> BarBar; po: proc "odin" (x: i32) -> BarBar; diff --git a/src/check_expr.cpp b/src/check_expr.cpp index 52c1f38b7..6d049747f 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -7643,6 +7643,7 @@ ExprKind check_expr_base_internal(CheckerContext *c, Operand *o, Ast *node, Type return kind; } + pl->decl = decl; check_procedure_later(ctx.checker, ctx.file, empty_token, decl, type, pl->body, pl->tags); } check_close_scope(&ctx); diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index c0b015540..fe42dae9d 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -64,10 +64,21 @@ lbAddr lb_addr_bit_field(lbValue value, i32 index) { } -void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue const &value) { +void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value) { if (addr.addr.value == nullptr) { return; } + GB_ASSERT(value.type != nullptr); + if (is_type_untyped_nil(value.type)) { + Type *t = lb_addr_type(addr); + value.type = t; + value.value = LLVMConstNull(lb_type(p->module, t)); + } else if (is_type_untyped_undef(value.type)) { + Type *t = lb_addr_type(addr); + value.type = t; + value.value = LLVMGetUndef(lb_type(p->module, t)); + } + GB_ASSERT(value.value != nullptr); LLVMBuildStore(p->builder, value.value, addr.addr.value); } @@ -156,6 +167,10 @@ String lb_get_entity_name(lbModule *m, Entity *e, String default_name) { return e->TypeName.ir_mangled_name; } + if (e->pkg == nullptr) { + return e->token.string; + } + String name = {}; bool no_name_mangle = false; @@ -640,8 +655,8 @@ void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *nam lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure); - entity->code_gen_module = m; p->module = m; + entity->code_gen_module = m; p->entity = entity; p->name = lb_get_entity_name(m, entity); @@ -2603,6 +2618,29 @@ lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { lbValue right = lb_build_expr(p, be->right); return lb_emit_arith(p, be->op.kind, left, right, type); } + + case Token_CmpEq: + case Token_NotEq: + case Token_Lt: + case Token_LtEq: + case Token_Gt: + case Token_GtEq: + { + lbValue left = lb_build_expr(p, be->left); + Type *type = default_type(tv.type); + lbValue right = lb_build_expr(p, be->right); + lbValue cmp = lb_emit_comp(p, be->op.kind, left, right); + return lb_emit_conv(p, cmp, type); + } + + case Token_CmpAnd: + case Token_CmpOr: + GB_PANIC("TODO(bill): && ||"); + break; + case Token_in: + case Token_not_in: + GB_PANIC("TODO(bill): in/not_in"); + break; default: GB_PANIC("Invalid binary expression"); break; @@ -3143,7 +3181,7 @@ lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index); lbValue res = {}; - res.value = LLVMBuildStructGEP2(p->builder, lb_type(p->module, result_type), s.value, cast(unsigned)index, ""); + res.value = LLVMBuildStructGEP2(p->builder, lb_type(p->module, type_deref(s.type)), s.value, cast(unsigned)index, ""); res.type = result_type; return res; } @@ -3592,7 +3630,7 @@ lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, i32 index) { GB_ASSERT(0 <= index); Type *ptr = base_array_type(st); lbValue res = {}; - res.value = LLVMBuildStructGEP2(p->builder, lb_type(p->module, ptr), s.value, index, ""); + res.value = LLVMBuildStructGEP2(p->builder, lb_type(p->module, st), s.value, index, ""); res.type = alloc_type_pointer(ptr); return res; } @@ -3998,6 +4036,135 @@ void lb_loop_end(lbProcedure *p, lbLoopData const &data) { } } +lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) { + lbValue res = {}; + res.type = t_llvm_bool; + Type *t = x.type; + if (is_type_pointer(t)) { + if (op_kind == Token_CmpEq) { + res.value = LLVMBuildIsNull(p->builder, x.value, ""); + } else if (op_kind == Token_NotEq) { + res.value = LLVMBuildIsNotNull(p->builder, x.value, ""); + } + return res; + } else if (is_type_cstring(t)) { + lbValue ptr = lb_emit_conv(p, x, t_u8_ptr); + if (op_kind == Token_CmpEq) { + res.value = LLVMBuildIsNull(p->builder, ptr.value, ""); + } else if (op_kind == Token_NotEq) { + res.value = LLVMBuildIsNotNull(p->builder, ptr.value, ""); + } + return res; + } else if (is_type_any(t)) { + lbValue data = lb_emit_struct_ev(p, x, 0); + lbValue ti = lb_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; + } + } else if (is_type_slice(t)) { + gb_printf_err("HERE\n"); + lbValue data = lb_emit_struct_ev(p, x, 0); + lbValue cap = lb_emit_struct_ev(p, x, 1); + if (op_kind == Token_CmpEq) { + LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, ""); + LLVMValueRef b = LLVMBuildIsNull(p->builder, cap.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, cap.value, ""); + res.value = LLVMBuildAnd(p->builder, a, b, ""); + return res; + } + } else if (is_type_dynamic_array(t)) { + lbValue data = lb_emit_struct_ev(p, x, 0); + lbValue cap = lb_emit_struct_ev(p, x, 2); + if (op_kind == Token_CmpEq) { + LLVMValueRef a = LLVMBuildIsNull(p->builder, data.value, ""); + LLVMValueRef b = LLVMBuildIsNull(p->builder, cap.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, cap.value, ""); + res.value = LLVMBuildAnd(p->builder, a, b, ""); + return res; + } + } else if (is_type_map(t)) { + GB_PANIC("map nil comparison"); + // lbValue len = lb_map_len(p, x); + // return lb_emit_comp(p, op_kind, len, v_zero); + } else if (is_type_union(t)) { + if (type_size_of(t) == 0) { + if (op_kind == Token_CmpEq) { + return lb_const_bool(p->module, t_llvm_bool, true); + } else if (op_kind == Token_NotEq) { + return lb_const_bool(p->module, t_llvm_bool, false); + } + } else { + GB_PANIC("lb_emit_union_tag_value"); + // lbValue tag = lb_emit_union_tag_value(p, x); + // return lb_emit_comp(p, op_kind, tag, v_zero); + } + } else if (is_type_typeid(t)) { + lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0)); + return lb_emit_comp(p, op_kind, x, invalid_typeid); + } else if (is_type_bit_field(t)) { + auto args = array_make(heap_allocator(), 2); + lbValue lhs = lb_address_from_load_or_generate_local(p, x); + args[0] = lb_emit_conv(p, lhs, t_rawptr); + args[1] = lb_const_int(p->module, t_int, type_size_of(t)); + lbValue val = lb_emit_runtime_call(p, "memory_compare_zero", args); + lbValue res = lb_emit_comp(p, op_kind, val, lb_const_int(p->module, t_int, 0)); + return res; + } else if (is_type_soa_struct(t)) { + GB_PANIC("#soa struct nil comparison"); + // Type *bt = base_type(t); + // if (bt->Struct.soa_kind == StructSoa_Slice) { + // lbValue len = lb_soa_struct_len(p, x); + // if (bt->Struct.fields.count > 1) { + // lbValue data = lb_emit_struct_ev(p, x, 0); + // if (op_kind == Token_CmpEq) { + // lbValue a = lb_emit_comp(p, Token_CmpEq, data, v_raw_nil); + // lbValue b = lb_emit_comp(p, Token_CmpEq, len, v_zero); + // return lb_emit_arith(p, Token_Or, a, b, t_bool); + // } else if (op_kind == Token_NotEq) { + // lbValue a = lb_emit_comp(p, Token_NotEq, data, v_raw_nil); + // lbValue b = lb_emit_comp(p, Token_NotEq, len, v_zero); + // return lb_emit_arith(p, Token_And, a, b, t_bool); + // } + // } else { + // return lb_emit_comp(p, op_kind, len, v_zero); + // } + // } else if (bt->Struct.soa_kind == StructSoa_Dynamic) { + // lbValue cap = lb_soa_struct_len(p, x); + // if (bt->Struct.fields.count > 1) { + // lbValue data = lb_emit_struct_ev(p, x, 0); + // if (op_kind == Token_CmpEq) { + // lbValue a = lb_emit_comp(p, Token_CmpEq, data, v_raw_nil); + // lbValue b = lb_emit_comp(p, Token_CmpEq, cap, v_zero); + // return lb_emit_arith(p, Token_Or, a, b, t_bool); + // } else if (op_kind == Token_NotEq) { + // lbValue a = lb_emit_comp(p, Token_NotEq, data, v_raw_nil); + // lbValue b = lb_emit_comp(p, Token_NotEq, cap, v_zero); + // return lb_emit_arith(p, Token_And, a, b, t_bool); + // } + // } else { + // return lb_emit_comp(p, op_kind, cap, v_zero); + // } + // } + } + return {}; +} + lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right) { Type *a = base_type(left.type); @@ -4005,15 +4172,15 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri GB_ASSERT(gb_is_between(op_kind, Token__ComparisonBegin+1, Token__ComparisonEnd-1)); - // lbValue nil_check = {}; - // if (left->kind == irValue_Nil) { - // nil_check = lb_emit_comp_against_nil(p, op_kind, right); - // } else if (right->kind == irValue_Nil) { - // nil_check = lb_emit_comp_against_nil(p, op_kind, left); - // } - // if (nil_check.value != nullptr) { - // return nil_check; - // } + lbValue nil_check = {}; + if (is_type_untyped_nil(left.type)) { + nil_check = lb_emit_comp_against_nil(p, op_kind, right); + } else if (is_type_untyped_nil(right.type)) { + nil_check = lb_emit_comp_against_nil(p, op_kind, left); + } + if (nil_check.value != nullptr) { + return nil_check; + } if (are_types_identical(a, b)) { // NOTE(bill): No need for a conversion @@ -4293,6 +4460,46 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri } +lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent = nullptr) { + ast_node(pl, ProcLit, expr); + + // NOTE(bill): Generate a new name + // parent$count + isize name_len = prefix_name.len + 1 + 8 + 1; + char *name_text = gb_alloc_array(heap_allocator(), char, name_len); + i32 name_id = cast(i32)m->anonymous_proc_lits.entries.count; + + name_len = gb_snprintf(name_text, name_len, "%.*s$anon-%d", LIT(prefix_name), name_id); + String name = make_string((u8 *)name_text, name_len-1); + + Type *type = type_of_expr(expr); + set_procedure_abi_types(heap_allocator(), type); + + + 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->decl_info = pl->decl; + lbProcedure *p = lb_create_procedure(m, e); + + lbValue value = {}; + value.value = p->value; + value.type = p->type; + + array_add(&m->procedures_to_generate, p); + if (parent != nullptr) { + array_add(&parent->children, p); + } else { + map_set(&m->members, hash_string(name), value); + } + + map_set(&m->anonymous_proc_lits, hash_pointer(expr), p); + + return value; +} + lbValue lb_build_expr(lbProcedure *p, Ast *expr) { lbModule *m = p->module; @@ -4320,8 +4527,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { case_end; case_ast_node(i, Implicit, expr); - // return ir_addr_load(p, lb_build_addr(p, expr)); - GB_PANIC("TODO(bill): Implicit"); + return lb_addr_load(p, lb_build_addr(p, expr)); case_end; case_ast_node(u, Undef, expr); @@ -4338,8 +4544,10 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { LIT(token.pos.file), token.pos.line, token.pos.column); return {}; } else if (e->kind == Entity_Nil) { - GB_PANIC("Entity_Nil"); - return lb_const_nil(m, tv.type); + lbValue res = {}; + res.value = nullptr; + res.type = e->type; + return res; } auto *found = map_get(&p->module->values, hash_entity(e)); @@ -4530,7 +4738,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { case_end; case_ast_node(pl, ProcLit, expr); - // return lb_gen_anonymous_proc_lit(p->module, p->name, expr, p); + return lb_generate_anonymous_proc_lit(p->module, p->name, expr, p); case_end; case_ast_node(cl, CompoundLit, expr); @@ -5784,11 +5992,14 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { gen->module.ctx = LLVMGetGlobalContext(); gen->module.mod = LLVMModuleCreateWithNameInContext("odin_module", gen->module.ctx); gb_mutex_init(&gen->module.mutex); - map_init(&gen->module.types, heap_allocator()); - map_init(&gen->module.values, heap_allocator()); - map_init(&gen->module.members, heap_allocator()); - map_init(&gen->module.const_strings, heap_allocator()); - map_init(&gen->module.const_string_byte_slices, heap_allocator()); + gbAllocator a = heap_allocator(); + map_init(&gen->module.types, a); + map_init(&gen->module.values, a); + map_init(&gen->module.members, a); + map_init(&gen->module.const_strings, a); + map_init(&gen->module.const_string_byte_slices, a); + map_init(&gen->module.anonymous_proc_lits, a); + array_init(&gen->module.procedures_to_generate, a); return true; } @@ -5944,9 +6155,6 @@ void lb_generate_code(lbGenerator *gen) { lb_add_member(m, name, g); } - Array procedures = {}; - procedures.allocator = heap_allocator(); - for_array(i, info->entities) { // arena_free_all(&temp_arena); @@ -6009,20 +6217,19 @@ void lb_generate_code(lbGenerator *gen) { } lbProcedure *p = lb_create_procedure(m, e); - array_add(&procedures, p); + array_add(&m->procedures_to_generate, p); } break; } } - for_array(i, procedures) { - lbProcedure *p = procedures[i]; + for_array(i, m->procedures_to_generate) { + lbProcedure *p = m->procedures_to_generate[i]; if (p->body != nullptr) { // Build Procedure lb_begin_procedure_body(p); lb_build_stmt(p, p->body); lb_end_procedure_body(p); } - lb_end_procedure(p); } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 2e976cf11..2ee269bb6 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -8,6 +8,8 @@ #include "llvm-c/Transforms/InstCombine.h" #include "llvm-c/Transforms/IPO.h" +struct lbProcedure; + struct lbValue { LLVMValueRef value; Type *type; @@ -59,10 +61,14 @@ struct lbModule { Map const_strings; // Key: String Map const_string_byte_slices; // Key: String + Map anonymous_proc_lits; // Key: Ast * + lbAddr global_default_context; u32 global_array_index; u32 global_generated_index; + + Array procedures_to_generate; }; struct lbGenerator { @@ -145,7 +151,7 @@ struct lbTargetList { struct lbProcedure { lbProcedure *parent; - Array children; + Array children; Entity * entity; lbModule * module; @@ -213,7 +219,7 @@ lbValue lb_const_int(lbModule *m, Type *type, u64 value); lbAddr lb_addr(lbValue addr); Type *lb_addr_type(lbAddr const &addr); LLVMTypeRef lb_addr_lb_type(lbAddr const &addr); -void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue const &value); +void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value); lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr); lbValue lb_emit_load(lbProcedure *p, lbValue v); diff --git a/src/parser.hpp b/src/parser.hpp index 28c5d880a..00366d79a 100644 --- a/src/parser.hpp +++ b/src/parser.hpp @@ -248,6 +248,7 @@ enum StmtAllowFlag { ProcInlining inlining; \ Token where_token; \ Array where_clauses; \ + DeclInfo *decl; \ }) \ AST_KIND(CompoundLit, "compound literal", struct { \ Ast *type; \ -- cgit v1.2.3 From bfda1016860942564abdbfe86cbb3487469c8ea5 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 10 Feb 2020 00:14:43 +0000 Subject: Get basic IR code generation working properly --- src/checker.cpp | 5 +- src/llvm_backend.cpp | 2629 +++++++++++++++++++++++++++++++++++++------------- src/llvm_backend.hpp | 30 +- 3 files changed, 2003 insertions(+), 661 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/checker.cpp b/src/checker.cpp index 3f9d3ba71..bfd2d3149 100644 --- a/src/checker.cpp +++ b/src/checker.cpp @@ -1625,6 +1625,7 @@ void add_dependency_to_set(Checker *c, Entity *entity) { if (decl == nullptr) { return; } + for_array(i, decl->type_info_deps.entries) { Type *type = decl->type_info_deps.entries[i].ptr; add_min_dep_type_info(c, type); @@ -1670,8 +1671,8 @@ void generate_minimum_dependency_set(Checker *c, Entity *start) { str_lit("type_table"), str_lit("__type_info_of"), str_lit("default_temp_allocator"), - str_lit("default_temp_allocator_init"), - str_lit("default_temp_allocator_destroy"), + // str_lit("default_temp_allocator_init"), + // str_lit("default_temp_allocator_destroy"), str_lit("default_temp_allocator_proc"), str_lit("Type_Info"), diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index fe42dae9d..8d4b47e78 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -1,10 +1,27 @@ #include "llvm_backend.hpp" +struct lbLoopData { + lbAddr idx_addr; + lbValue idx; + lbBlock *body; + lbBlock *done; + lbBlock *loop; +}; + +struct lbCompoundLitElemTempData { + Ast * expr; + lbValue value; + i32 elem_index; + lbValue gep; +}; -LLVMValueRef lb_zero32(lbModule *m) { +lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_i32); +void lb_loop_end(lbProcedure *p, lbLoopData const &data); + +LLVMValueRef llvm_zero32(lbModule *m) { return LLVMConstInt(lb_type(m, t_i32), 0, false); } -LLVMValueRef lb_one32(lbModule *m) { +LLVMValueRef llvm_one32(lbModule *m) { return LLVMConstInt(lb_type(m, t_i32), 1, false); } @@ -69,23 +86,60 @@ void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value) { return; } GB_ASSERT(value.type != nullptr); - if (is_type_untyped_nil(value.type)) { + if (is_type_untyped_undef(value.type)) { Type *t = lb_addr_type(addr); value.type = t; - value.value = LLVMConstNull(lb_type(p->module, t)); - } else if (is_type_untyped_undef(value.type)) { + value.value = LLVMGetUndef(lb_type(p->module, t)); + } else if (is_type_untyped_nil(value.type)) { Type *t = lb_addr_type(addr); value.type = t; - value.value = LLVMGetUndef(lb_type(p->module, t)); + value.value = LLVMConstNull(lb_type(p->module, t)); + } + + + if (addr.kind == lbAddr_Map) { + GB_PANIC("lbAddr_Map"); + } else if (addr.kind == lbAddr_BitField) { + GB_PANIC("lbAddr_BitField"); + } else if (addr.kind == lbAddr_Context) { + lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p)); + lbAddr next_addr = lb_add_local_generated(p, t_context, true); + lb_addr_store(p, next_addr, old); + lb_push_context_onto_stack(p, next_addr); + lbValue next = lb_addr_get_ptr(p, next_addr); + + if (addr.ctx.sel.index.count > 0) { + lbValue lhs = lb_emit_deep_field_gep(p, next, addr.ctx.sel); + lbValue rhs = lb_emit_conv(p, value, type_deref(lhs.type)); + lb_emit_store(p, lhs, rhs); + } else { + lbValue lhs = next; + lbValue rhs = lb_emit_conv(p, value, lb_addr_type(addr)); + lb_emit_store(p, lhs, rhs); + } + + return; + } else if (addr.kind == lbAddr_SoaVariable) { + GB_PANIC("lbAddr_SoaVariable"); } GB_ASSERT(value.value != nullptr); + value = lb_emit_conv(p, value, lb_addr_type(addr)); + LLVMBuildStore(p->builder, value.value, addr.addr.value); } void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) { GB_ASSERT(value.value != nullptr); + Type *a = type_deref(ptr.type); + if (is_type_boolean(a)) { + // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily) + value = lb_emit_conv(p, value, a); + } + + GB_ASSERT(are_types_identical(a, value.type)); + LLVMValueRef v = LLVMBuildStore(p->builder, value.value, ptr.value); } @@ -99,6 +153,52 @@ lbValue lb_emit_load(lbProcedure *p, lbValue value) { lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) { GB_ASSERT(addr.addr.value != nullptr); + + if (addr.kind == lbAddr_Map) { + GB_PANIC("lbAddr_Map"); + } else if (addr.kind == lbAddr_BitField) { + Type *bft = base_type(type_deref(addr.addr.type)); + GB_ASSERT(is_type_bit_field(bft)); + + unsigned value_index = cast(unsigned)addr.bit_field.value_index; + i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits; + + i32 size_in_bytes = next_pow2((size_in_bits+7)/8); + if (size_in_bytes == 0) { + GB_ASSERT(size_in_bits == 0); + lbValue res = {}; + res.type = t_i32; + res.value = LLVMConstInt(lb_type(p->module, res.type), 0, false); + return res; + } + + Type *int_type = nullptr; + switch (size_in_bytes) { + case 1: int_type = t_u8; break; + case 2: int_type = t_u16; break; + case 4: int_type = t_u32; break; + case 8: int_type = t_u64; break; + case 16: int_type = t_u128; break; + } + GB_ASSERT(int_type != nullptr); + + LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""); + LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, ""); + LLVMValueRef field = LLVMBuildLoad(p->builder, field_ptr, ""); + + lbValue res = {}; + res.type = int_type; + res.value = LLVMBuildZExtOrBitCast(p->builder, field, lb_type(p->module, int_type), ""); + return res; + } else if (addr.kind == lbAddr_Context) { + if (addr.ctx.sel.index.count > 0) { + lbValue a = addr.addr; + lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel); + return lb_emit_load(p, b); + } + } else if (addr.kind == lbAddr_SoaVariable) { + GB_PANIC("lbAddr_SoaVariable"); + } return lb_emit_load(p, addr.addr); } @@ -130,6 +230,18 @@ LLVMTypeRef lb_alignment_prefix_type_hack(lbModule *m, i64 alignment) { return nullptr; } +bool lb_is_elem_const(Ast *elem, Type *elem_type) { + if (!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; +} + String lb_mangle_name(lbModule *m, Entity *e) { gbAllocator a = heap_allocator(); @@ -147,19 +259,19 @@ String lb_mangle_name(lbModule *m, Entity *e) { max_len += 21; } - u8 *new_name = gb_alloc_array(a, u8, max_len); + char *new_name = gb_alloc_array(a, char, max_len); isize new_name_len = gb_snprintf( - cast(char *)new_name, max_len, + new_name, max_len, "%.*s.%.*s", LIT(pkgn), LIT(name) ); if (require_suffix_id) { - char *str = cast(char *)new_name + new_name_len-1; + char *str = new_name + new_name_len-1; isize len = max_len-new_name_len; isize extra = gb_snprintf(str, len, "-%llu", cast(unsigned long long)e->id); new_name_len += extra-1; } - return make_string(new_name, new_name_len-1); + return make_string((u8 *)new_name, new_name_len-1); } String lb_get_entity_name(lbModule *m, Entity *e, String default_name) { @@ -179,9 +291,12 @@ String lb_get_entity_name(lbModule *m, Entity *e, String default_name) { bool is_foreign = e->Variable.is_foreign; bool is_export = e->Variable.is_export; no_name_mangle = e->Variable.link_name.len > 0 || is_foreign || is_export; - } else if (e->kind == Entity_Procedure && e->Procedure.is_export) { - no_name_mangle = true; + if (e->Variable.link_name.len > 0) { + return e->Variable.link_name; + } } else if (e->kind == Entity_Procedure && e->Procedure.link_name.len > 0) { + return e->Procedure.link_name; + } else if (e->kind == Entity_Procedure && e->Procedure.is_export) { no_name_mangle = true; } @@ -542,22 +657,26 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { extra_param_count += 1; } - unsigned param_count = cast(unsigned)(type->Proc.abi_compat_params.count + extra_param_count); + isize param_count = type->Proc.abi_compat_params.count + extra_param_count; LLVMTypeRef *param_types = gb_alloc_array(heap_allocator(), LLVMTypeRef, param_count); defer (gb_free(heap_allocator(), param_types)); + isize param_index = offset; for_array(i, type->Proc.abi_compat_params) { Type *param = type->Proc.abi_compat_params[i]; - param_types[i+offset] = lb_type(m, param); + if (param == nullptr) { + continue; + } + param_types[param_index++] = lb_type(m, param); } if (type->Proc.return_by_pointer) { param_types[0] = LLVMPointerType(lb_type(m, type->Proc.abi_compat_result_type), 0); } if (type->Proc.calling_convention == ProcCC_Odin) { - param_types[param_count-1] = lb_type(m, t_context_ptr); + param_types[param_index++] = lb_type(m, t_context_ptr); } - LLVMTypeRef t = LLVMFunctionType(return_type, param_types, param_count, type->Proc.c_vararg); + LLVMTypeRef t = LLVMFunctionType(return_type, param_types, cast(unsigned)param_index, type->Proc.c_vararg); return LLVMPointerType(t, 0); } break; @@ -634,6 +753,12 @@ void lb_add_member(lbModule *m, String const &name, lbValue val) { void lb_add_member(lbModule *m, HashKey const &key, lbValue val) { map_set(&m->members, key, val); } +void lb_add_procedure_value(lbModule *m, lbProcedure *p) { + if (p->entity != nullptr) { + map_set(&m->procedure_values, hash_pointer(p->value), p->entity); + } +} + LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) { @@ -653,6 +778,8 @@ void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *nam lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { + GB_ASSERT(entity != nullptr); + lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure); p->module = m; @@ -691,6 +818,14 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type); p->value = LLVMAddFunction(m->mod, name, func_type); + + lbValue value = {}; + value.type = p->type; + value.value = p->value; + lb_add_entity(m, entity, value); + lb_add_procedure_value(m, p); + + LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]); lbValue proc_value = {p->value, p->type}; lb_add_entity(m, entity, proc_value); @@ -709,7 +844,7 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { isize parameter_index = 0; if (pt->Proc.param_count) { TypeTuple *params = &pt->Proc.params->Tuple; - for (isize i = 0; i < pt->Proc.param_count; i++, parameter_index++) { + for (isize i = 0; i < pt->Proc.param_count; i++) { Entity *e = params->variables[i]; Type *original_type = e->type; Type *abi_type = pt->Proc.abi_compat_params[i]; @@ -725,11 +860,12 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias"); } } - parameter_index += abi_type->Tuple.variables.count-1; + parameter_index += abi_type->Tuple.variables.count; } else { if (e->flags&EntityFlag_NoAlias) { lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias"); } + parameter_index += 1; } } } @@ -740,7 +876,6 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture"); } - return p; } @@ -841,6 +976,12 @@ lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 i } +void lb_start_block(lbProcedure *p, lbBlock *b) { + GB_ASSERT(b != nullptr); + p->curr_block = b; + LLVMPositionBuilderAtEnd(p->builder, b->block); +} + void lb_begin_procedure_body(lbProcedure *p) { DeclInfo *decl = decl_info_of_entity(p->entity); if (decl != nullptr) { @@ -855,9 +996,7 @@ void lb_begin_procedure_body(lbProcedure *p) { p->decl_block = lb_create_block(p, "decls"); p->entry_block = lb_create_block(p, "entry"); - p->curr_block = p->entry_block; - - LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); + lb_start_block(p, p->entry_block); GB_ASSERT(p->type != nullptr); @@ -899,7 +1038,6 @@ void lb_begin_procedure_body(lbProcedure *p) { Entity *e = params->variables[i]; if (e->kind != Entity_Variable) { - parameter_index += 1; continue; } @@ -920,7 +1058,6 @@ void lb_begin_procedure_body(lbProcedure *p) { for_array(i, params->variables) { Entity *e = params->variables[i]; if (e->kind != Entity_Variable) { - parameter_index += 1; continue; } Type *abi_type = e->type; @@ -992,6 +1129,8 @@ void lb_begin_procedure_body(lbProcedure *p) { lbContextData ctx = {ctx_addr, p->scope_index}; array_add(&p->context_stack, ctx); } + + lb_start_block(p, p->entry_block); } void lb_end_procedure_body(lbProcedure *p) { @@ -1036,15 +1175,15 @@ lbBlock *lb_create_block(lbProcedure *p, char const *name) { return b; } -void lb_start_block(lbProcedure *p, lbBlock *b) { - p->curr_block = b; - LLVMPositionBuilderAtEnd(p->builder, b->block); -} - void lb_emit_jump(lbProcedure *p, lbBlock *target_block) { if (p->curr_block == nullptr) { return; } + LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block); + if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) { + return; + } + lb_add_edge(p->curr_block, target_block); LLVMBuildBr(p->builder, target_block->block); p->curr_block = nullptr; @@ -1055,6 +1194,11 @@ void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *fals if (b == nullptr) { return; } + LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block); + if (last_instr != nullptr && LLVMIsATerminatorInst(last_instr)) { + return; + } + lb_add_edge(b, true_block); lb_add_edge(b, false_block); LLVMBuildCondBr(p->builder, cond.value, true_block->block, false_block->block); @@ -1099,18 +1243,23 @@ lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *f lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 param_index) { + GB_ASSERT(p->decl_block != p->curr_block); LLVMPositionBuilderAtEnd(p->builder, p->decl_block->block); + char const *name = ""; + if (e != nullptr) { + name = alloc_cstring(heap_allocator(), e->token.string); + } + LLVMTypeRef llvm_type = lb_type(p->module, type); - LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, ""); - LLVMSetAlignment(ptr, 16); + LLVMValueRef ptr = LLVMBuildAlloca(p->builder, llvm_type, name); + LLVMSetAlignment(ptr, 16); // TODO(bill): Make this configurable + LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); if (zero_init) { LLVMBuildStore(p->builder, LLVMConstNull(lb_type(p->module, type)), ptr); } - LLVMPositionBuilderAtEnd(p->builder, p->curr_block->block); - lbValue val = {}; val.value = ptr; val.type = alloc_type_pointer(type); @@ -1127,12 +1276,164 @@ lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init) { } +void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) { + GB_ASSERT(pd->body != nullptr); + lbModule *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; + } + + // 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(heap_allocator(), char, name_len); + + i32 guid = cast(i32)p->children.count; + name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(pd_name), guid); + String name = make_string(cast(u8 *)name_text, name_len-1); + + set_procedure_abi_types(heap_allocator(), e->type); + + + e->Procedure.link_name = name; + + lbProcedure *nested_proc = lb_create_procedure(p->module, e); + + lbValue value = {}; + value.value = nested_proc->value; + value.type = nested_proc->type; + + lb_add_entity(m, e, value); + array_add(&p->children, nested_proc); + array_add(&m->procedures_to_generate, nested_proc); +} + +void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) { + if (vd == nullptr || vd->is_mutable) { + return; + } + + auto *min_dep_set = &p->module->info->minimum_dependency_set; + + + for_array(i, vd->names) { + Ast *ident = vd->names[i]; + GB_ASSERT(ident->kind == Ast_Ident); + Entity *e = entity_of_ident(ident); + GB_ASSERT(e != nullptr); + switch (e->kind) { + case Entity_TypeName: + case Entity_Procedure: + break; + default: + continue; + } + + if (e->kind == Entity_TypeName) { + 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; + } + + // NOTE(bill): Generate a new name + // parent_proc.name-guid + String ts_name = e->token.string; + + lbModule *m = p->module; + isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1; + char *name_text = gb_alloc_array(heap_allocator(), char, name_len); + i32 guid = cast(i32)m->members.entries.count; + name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(ts_name), guid); + + String name = make_string(cast(u8 *)name_text, name_len-1); + e->TypeName.ir_mangled_name = name; + + // irValue *value = ir_value_type_name(name, e->type); + // ir_add_entity_name(m, e, name); + // ir_gen_global_type_name(m, e, name); + } else if (e->kind == Entity_Procedure) { + CheckerInfo *info = p->module->info; + DeclInfo *decl = decl_info_of_entity(e); + ast_node(pl, ProcLit, decl->proc_lit); + if (pl->body != nullptr) { + auto *found = map_get(&info->gen_procs, hash_pointer(ident)); + if (found) { + auto procs = *found; + for_array(i, procs) { + Entity *e = procs[i]; + if (!ptr_set_exists(min_dep_set, e)) { + continue; + } + DeclInfo *d = decl_info_of_entity(e); + lb_build_nested_proc(p, &d->proc_lit->ProcLit, e); + } + } else { + lb_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) { + // lb_add_foreign_library_path(proc->module, e->Procedure.foreign_library); + } + + if (e->Procedure.link_name.len > 0) { + name = e->Procedure.link_name; + } + + HashKey key = hash_string(name); + lbValue *prev_value = map_get(&p->module->members, key); + if (prev_value != nullptr) { + // NOTE(bill): Don't do mutliple declarations in the IR + return; + } + + set_procedure_abi_types(heap_allocator(), e->type); + e->Procedure.link_name = name; + + lbProcedure *nested_proc = lb_create_procedure(p->module, e); + + lbValue value = {}; + value.value = nested_proc->value; + value.type = nested_proc->type; + + array_add(&p->module->procedures_to_generate, nested_proc); + if (p != nullptr) { + array_add(&p->children, nested_proc); + } else { + map_set(&p->module->members, hash_string(name), value); + } + } + } + } +} + + void lb_build_stmt_list(lbProcedure *p, Array const &stmts) { for_array(i, stmts) { Ast *stmt = stmts[i]; switch (stmt->kind) { case_ast_node(vd, ValueDecl, stmt); - // lb_build_constant_value_decl(b, vd); + lb_build_constant_value_decl(p, vd); case_end; case_ast_node(fb, ForeignBlockDecl, stmt); ast_node(block, BlockStmt, fb->body); @@ -1145,15 +1446,6 @@ void lb_build_stmt_list(lbProcedure *p, Array const &stmts) { } } -lbValue lb_build_gep(lbProcedure *p, lbValue const &value, i32 index) { - Type *elem_type = nullptr; - - - GB_ASSERT(elem_type != nullptr); - return lbValue{LLVMBuildStructGEP2(p->builder, lb_type(p->module, elem_type), value.value, index, ""), elem_type}; -} - - lbBranchBlocks lb_lookup_branch_blocks(lbProcedure *p, Ast *ident) { GB_ASSERT(ident->kind == Ast_Ident); Entity *e = entity_of_ident(ident); @@ -1342,6 +1634,8 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { LLVMValueRef global = LLVMAddGlobal(p->module->mod, lb_type(p->module, e->type), c_name); if (value.value != nullptr) { LLVMSetInitializer(global, value.value); + } else { + LLVMSetInitializer(global, LLVMConstNull(lb_type(p->module, e->type))); } if (e->Variable.thread_local_model != "") { LLVMSetThreadLocal(global, true); @@ -1373,37 +1667,48 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { } + if (vd->values.count == 0) { // declared and zero-initialized + for_array(i, vd->names) { + Ast *name = vd->names[i]; + if (!is_blank_ident(name)) { + Entity *e = entity_of_ident(name); + lb_add_local(p, e->type, e, true); + } + } + } else { // Tuple(s) + auto lvals = array_make(heap_allocator(), 0, vd->names.count); + auto inits = array_make(heap_allocator(), 0, vd->names.count); + for_array(i, vd->names) { + Ast *name = vd->names[i]; + lbAddr lval = {}; + if (!is_blank_ident(name)) { + Entity *e = entity_of_ident(name); + lval = lb_add_local(p, e->type, e, false); + } + array_add(&lvals, lval); + } - auto addrs = array_make(heap_allocator(), vd->names.count); - auto values = array_make(heap_allocator(), 0, vd->names.count); - defer (array_free(&addrs)); - defer (array_free(&values)); - - for_array(i, vd->names) { - Ast *name = vd->names[i]; - if (!is_blank_ident(name)) { - Entity *e = entity_of_ident(name); - lbAddr local = lb_add_local(p, e->type, e); - addrs[i] = local; - if (vd->values.count == 0) { - lb_addr_store(p, addrs[i], lb_const_nil(p->module, lb_addr_type(addrs[i]))); + for_array(i, vd->values) { + lbValue init = lb_build_expr(p, vd->values[i]); + Type *t = init.type; + if (t->kind == Type_Tuple) { + for_array(i, t->Tuple.variables) { + Entity *e = t->Tuple.variables[i]; + lbValue v = lb_emit_struct_ev(p, init, cast(i32)i); + array_add(&inits, v); + } + } else { + array_add(&inits, init); } } - } - for_array(i, vd->values) { - Ast *expr = vd->values[i]; - lbValue value = lb_build_expr(p, expr); - GB_ASSERT_MSG(value.type != nullptr, "%s", expr_to_string(expr)); - if (is_type_tuple(value.type)) { + for_array(i, inits) { + lbAddr lval = lvals[i]; + lbValue init = inits[i]; + lb_addr_store(p, lval, init); } - array_add(&values, value); - } - - for_array(i, values) { - lb_addr_store(p, addrs[i], values[i]); } case_end; @@ -1422,6 +1727,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { if (as->lhs.count == as->rhs.count) { if (as->lhs.count == 1) { + lbAddr lval = lvals[0]; Ast *rhs = as->rhs[0]; lbValue init = lb_build_expr(p, rhs); lb_addr_store(p, lvals[0], init); @@ -1434,8 +1740,9 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { } for_array(i, inits) { - auto lval = lvals[i]; - lb_addr_store(p, lval, inits[i]); + lbAddr lval = lvals[i]; + lbValue init = inits[i]; + lb_addr_store(p, lval, init); } } } else { @@ -1457,25 +1764,29 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { } for_array(i, inits) { - lb_addr_store(p, lvals[i], inits[i]); + lbAddr lval = lvals[i]; + lbValue init = inits[i]; + lb_addr_store(p, lval, init); } } } else { - // // NOTE(bill): Only 1 += 1 is allowed, no tuples - // // +=, -=, etc - // i32 op = cast(i32)as->op.kind; - // op += Token_Add - Token_AddEq; // Convert += to + - // if (op == Token_CmpAnd || op == Token_CmpOr) { - // Type *type = as->lhs[0]->tav.type; - // lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type); - - // lbAddr lhs = lb_build_addr(p, as->lhs[0]); - // lb_addr_store(p, lhs, new_value); - // } else { - // lbAddr lhs = lb_build_addr(p, as->lhs[0]); - // lbValue value = lb_build_expr(p, as->rhs[0]); - // ir_build_assign_op(p, lhs, value, cast(TokenKind)op); - // } + // NOTE(bill): Only 1 += 1 is allowed, no tuples + // +=, -=, etc + i32 op = cast(i32)as->op.kind; + op += Token_Add - Token_AddEq; // Convert += to + + if (op == Token_CmpAnd || op == Token_CmpOr) { + // TODO(bill): assign op + // Type *type = as->lhs[0]->tav.type; + // lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type); + + // lbAddr lhs = lb_build_addr(p, as->lhs[0]); + // lb_addr_store(p, lhs, new_value); + } else { + // TODO(bill): Assign op + // lbAddr lhs = lb_build_addr(p, as->lhs[0]); + // lbValue value = lb_build_expr(p, as->rhs[0]); + // lb_build_assign_op(p, lhs, value, cast(TokenKind)op); + } return; } case_end; @@ -1544,9 +1855,9 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { res = lb_add_local_generated(p, ret_type, false).addr; for_array(i, results) { Entity *e = tuple->variables[i]; - lbValue res = lb_emit_conv(p, results[i], e->type); lbValue field = lb_emit_struct_ep(p, res, cast(i32)i); - lb_emit_store(p, field, res); + lbValue val = lb_emit_conv(p, results[i], e->type); + lb_emit_store(p, field, val); } res = lb_emit_load(p, res); @@ -1561,6 +1872,10 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { LLVMBuildRetVoid(p->builder); } else { GB_ASSERT_MSG(res.value != nullptr, "%.*s", LIT(p->name)); + Type *abi_rt = p->type->Proc.abi_compat_result_type; + if (!are_types_identical(res.type, abi_rt)) { + res = lb_emit_transmute(p, res, abi_rt); + } LLVMBuildRet(p->builder, res.value); } case_end; @@ -1669,6 +1984,9 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(ss, SwitchStmt, node); + if (true) { + return; + } if (ss->init != nullptr) { lb_build_stmt(p, ss->init); } @@ -1751,6 +2069,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { lb_emit_if(p, cond, body, next_cond); lb_start_block(p, next_cond); } + lb_emit_jump(p, body); lb_start_block(p, body); lb_push_target_list(p, ss->label, done, nullptr, fall); @@ -1814,6 +2133,14 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { } } +lbValue lb_emit_select(lbProcedure *p, lbValue cond, lbValue x, lbValue y) { + cond = lb_emit_conv(p, cond, t_llvm_bool); + lbValue res = {}; + res.value = LLVMBuildSelect(p->builder, cond.value, x.value, y.value, ""); + res.type = x.type; + return res; +} + lbValue lb_const_nil(lbModule *m, Type *type) { LLVMValueRef v = LLVMConstNull(lb_type(m, type)); return lbValue{v, type}; @@ -1845,6 +2172,51 @@ LLVMValueRef lb_const_f32(lbModule *m, f32 f, Type *type=t_f32) { return LLVMConstBitCast(i, lb_type(m, type)); } +lbValue lb_emit_min(lbProcedure *p, Type *t, lbValue x, lbValue y) { + x = lb_emit_conv(p, x, t); + y = lb_emit_conv(p, y, t); + + if (is_type_float(t)) { + gbAllocator a = heap_allocator(); + i64 sz = 8*type_size_of(t); + auto args = array_make(heap_allocator(), 2); + args[0] = x; + args[1] = y; + switch (sz) { + case 32: return lb_emit_runtime_call(p, "min_f32", args); + case 64: return lb_emit_runtime_call(p, "min_f64", args); + } + GB_PANIC("Unknown float type"); + } + return lb_emit_select(p, lb_emit_comp(p, Token_Lt, x, y), x, y); +} +lbValue lb_emit_max(lbProcedure *p, Type *t, lbValue x, lbValue y) { + x = lb_emit_conv(p, x, t); + y = lb_emit_conv(p, y, t); + + if (is_type_float(t)) { + gbAllocator a = heap_allocator(); + i64 sz = 8*type_size_of(t); + auto args = array_make(heap_allocator(), 2); + args[0] = x; + args[1] = y; + switch (sz) { + case 32: return lb_emit_runtime_call(p, "max_f32", args); + case 64: return lb_emit_runtime_call(p, "max_f64", args); + } + GB_PANIC("Unknown float type"); + } + return lb_emit_select(p, lb_emit_comp(p, Token_Gt, x, y), x, y); +} + + +lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue max) { + lbValue z = {}; + z = lb_emit_max(p, t, x, min); + z = lb_emit_min(p, t, z, max); + return z; +} + @@ -1882,7 +2254,7 @@ isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=tr } } if (err_on_not_found) { - GB_PANIC("NOT FOUND ir_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; } @@ -1956,16 +2328,29 @@ lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type) { return res; } +lbValue lb_type_info(lbModule *m, Type *type) { + GB_PANIC("TODO(bill): lb_type_info"); + return {}; +} + + lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { LLVMContextRef ctx = m->ctx; + type = default_type(type); Type *original_type = type; lbValue res = {}; - res.type = type; + res.type = original_type; type = core_type(type); value = convert_exact_value_for_type(value, type); + if (value.kind == ExactValue_Typeid) { + return lb_typeid(m, value.value_typeid, original_type); + } + + // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type)); + if (is_type_slice(type)) { if (value.kind == ExactValue_String) { GB_ASSERT(is_type_u8_slice(type)); @@ -1985,14 +2370,14 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { isize max_len = 7+8+1; - u8 *str = cast(u8 *)gb_alloc_array(heap_allocator(), u8, max_len); - isize len = gb_snprintf(cast(char *)str, max_len, "csba$%x", m->global_array_index); + char *str = gb_alloc_array(heap_allocator(), char, max_len); + isize len = gb_snprintf(str, max_len, "csba$%x", m->global_array_index); m->global_array_index++; - String name = make_string(str, len-1); + String name = make_string(cast(u8 *)str, len-1); Entity *e = alloc_entity_constant(nullptr, make_token_ident(name), t, value); - LLVMValueRef global_data = LLVMAddGlobal(m->mod, lb_type(m, t), cast(char const *)str); + LLVMValueRef global_data = LLVMAddGlobal(m->mod, lb_type(m, t), str); LLVMSetInitializer(global_data, backing_array.value); lbValue g = {}; @@ -2003,7 +2388,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { lb_add_member(m, name, g); { - LLVMValueRef indices[2] = {lb_zero32(m), lb_zero32(m)}; + LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)}; LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), count, true); LLVMValueRef values[2] = {ptr, len}; @@ -2053,10 +2438,11 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { lbValue *found = map_get(&m->const_strings, key); if (found != nullptr) { res.value = found->value; + res.type = default_type(original_type); return res; } - LLVMValueRef indices[2] = {lb_zero32(m), lb_zero32(m)}; + LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)}; LLVMValueRef data = LLVMConstStringInContext(ctx, cast(char const *)value.value_string.text, cast(unsigned)value.value_string.len, @@ -2083,6 +2469,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { LLVMValueRef values[2] = {ptr, str_len}; res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); + res.type = default_type(original_type); map_set(&m->const_strings, key, res); @@ -2500,10 +2887,109 @@ lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, To return res; } +lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) { + switch (op) { + case Token_Add: + return x; + case Token_Not: // Boolean not + case Token_Xor: // Bitwise not + case Token_Sub: // Number negation + break; + case Token_Pointer: + GB_PANIC("This should be handled elsewhere"); + break; + } + + if (is_type_array(x.type)) { + // IMPORTANT TODO(bill): This is very wasteful with regards to stack memory + Type *tl = base_type(x.type); + lbValue val = lb_address_from_load_or_generate_local(p, x); + GB_ASSERT(is_type_array(type)); + Type *elem_type = base_array_type(type); + + // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops + lbAddr res_addr = lb_add_local_generated(p, type, false); + lbValue res = lb_addr_get_ptr(p, res_addr); + + bool inline_array_arith = type_size_of(type) <= build_context.max_align; + + i32 count = cast(i32)tl->Array.count; + + if (inline_array_arith) { + // inline + for (i32 i = 0; i < count; i++) { + lbValue e = lb_emit_load(p, lb_emit_array_epi(p, val, i)); + lbValue z = lb_emit_unary_arith(p, op, e, elem_type); + lb_emit_store(p, lb_emit_array_epi(p, res, i), z); + } + } else { + auto loop_data = lb_loop_start(p, count, t_i32); + + lbValue e = lb_emit_load(p, lb_emit_array_ep(p, val, loop_data.idx)); + lbValue z = lb_emit_unary_arith(p, op, e, elem_type); + lb_emit_store(p, lb_emit_array_ep(p, res, loop_data.idx), z); + + lb_loop_end(p, loop_data); + } + return lb_emit_load(p, res); + + } + + if (op == Token_Not) { + lbValue cmp = {}; + cmp.value = LLVMBuildNot(p->builder, x.value, ""); + cmp.type = x.type; + return lb_emit_conv(p, cmp, type); + } + + if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) { + Type *platform_type = integer_endian_type_to_platform_type(type); + lbValue v = lb_emit_byte_swap(p, x, platform_type); + + lbValue res = {}; + res.value = LLVMBuildNeg(p->builder, v.value, ""); + res.type = platform_type; + + return lb_emit_byte_swap(p, res, type); + } + + + lbValue res = {}; + + switch (op) { + case Token_Not: // Boolean not + res.value = LLVMBuildNot(p->builder, x.value, ""); + res.type = x.type; + return res; + case Token_Xor: // Bitwise not + res.value = LLVMBuildXor(p->builder, x.value, LLVMConstAllOnes(lb_type(p->module, x.type)), ""); + res.type = x.type; + return res; + case Token_Sub: // Number negation + if (is_type_integer(x.type)) { + res.value = LLVMBuildNeg(p->builder, x.value, ""); + } else if (is_type_float(x.type)) { + res.value = LLVMBuildFNeg(p->builder, x.value, ""); + } else { + GB_PANIC("Unhandled type %s", type_to_string(x.type)); + } + res.type = x.type; + return res; + } + + return res; +} + + lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) { lbModule *m = p->module; + + lhs = lb_emit_conv(p, lhs, type); + rhs = lb_emit_conv(p, rhs, type); + + lbValue res = {}; res.type = type; @@ -2571,6 +3057,7 @@ lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Ty res.value = LLVMBuildXor(p->builder, lhs.value, rhs.value, ""); return res; case Token_Shl: + rhs = lb_emit_conv(p, rhs, lhs.type); res.value = LLVMBuildShl(p->builder, lhs.value, rhs.value, ""); return res; case Token_Shr: @@ -2578,6 +3065,7 @@ lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Ty res.value = LLVMBuildLShr(p->builder, lhs.value, rhs.value, ""); return res; } + rhs = lb_emit_conv(p, rhs, lhs.type); res.value = LLVMBuildAShr(p->builder, lhs.value, rhs.value, ""); return res; case Token_AndNot: @@ -2650,6 +3138,7 @@ lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { lbModule *m = p->module; + t = reduce_tuple_to_single_type(t); Type *src_type = value.type; if (are_types_identical(t, src_type)) { @@ -2674,11 +3163,11 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { lb_addr_store(p, default_value, value); return lb_emit_conv(p, lb_addr_load(p, default_value), t_any); } else if (dst->kind == Type_Basic) { - if (is_type_float(dst)) { - return value; - } else if (is_type_integer(dst)) { - return value; - } + // if (is_type_float(dst)) { + // return value; + // } else if (is_type_integer(dst)) { + // return value; + // } // ExactValue ev = value->Constant.value; // if (is_type_float(dst)) { // ev = exact_value_to_float(ev); @@ -2723,7 +3212,6 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { return res; } -#if 0 // integer -> integer if (is_type_integer(src) && is_type_integer(dst)) { @@ -2734,55 +3222,64 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (sz > 1 && is_type_different_to_arch_endianness(src)) { Type *platform_src_type = integer_endian_type_to_platform_type(src); - value = ir_emit_byte_swap(p, value, platform_src_type); + value = lb_emit_byte_swap(p, value, platform_src_type); } - irConvKind kind = irConv_trunc; + LLVMOpcode op = LLVMTrunc; if (dz < sz) { - kind = irConv_trunc; + op = LLVMTrunc; } else if (dz == sz) { // NOTE(bill): In LLVM, all integers are signed and rely upon 2's compliment // NOTE(bill): Copy the value just for type correctness - kind = irConv_bitcast; + op = LLVMBitCast; } else if (dz > sz) { if (is_type_unsigned(src)) { - kind = irConv_zext; // zero extent + op = LLVMZExt; // zero extent } else { - kind = irConv_sext; // sign extent + op = LLVMSExt; // sign extent } } if (dz > 1 && is_type_different_to_arch_endianness(dst)) { Type *platform_dst_type = integer_endian_type_to_platform_type(dst); - lbValue res = ir_emit(p, ir_instr_conv(p, kind, value, src_type, platform_dst_type)); - return ir_emit_byte_swap(p, res, t); + lbValue res = {}; + res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, platform_dst_type), ""); + res.type = t; + return lb_emit_byte_swap(p, res, t); } else { - return ir_emit(p, ir_instr_conv(p, kind, value, src_type, t)); + lbValue res = {}; + res.value = LLVMBuildCast(p->builder, op, value.value, lb_type(m, t), ""); + res.type = t; + return res; } } + // boolean -> boolean/integer if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) { - lbValue b = ir_emit(p, ir_instr_binary_op(p, Token_NotEq, value, v_zero, t_llvm_bool)); - return ir_emit(p, ir_instr_conv(p, irConv_zext, b, t_llvm_bool, t)); + LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), ""); + lbValue res = {}; + res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, t), ""); + res.type = t; + return res; } if (is_type_cstring(src) && is_type_u8_ptr(dst)) { - return ir_emit_bitcast(p, value, dst); + return lb_emit_transmute(p, value, dst); } if (is_type_u8_ptr(src) && is_type_cstring(dst)) { - return ir_emit_bitcast(p, value, dst); + return lb_emit_transmute(p, value, dst); } if (is_type_cstring(src) && is_type_rawptr(dst)) { - return ir_emit_bitcast(p, value, dst); + return lb_emit_transmute(p, value, dst); } if (is_type_rawptr(src) && is_type_cstring(dst)) { - return ir_emit_bitcast(p, value, dst); + return lb_emit_transmute(p, value, dst); } if (are_types_identical(src, t_cstring) && are_types_identical(dst, t_string)) { lbValue c = lb_emit_conv(p, value, t_cstring); - auto args = array_make(heap_allocator(), 1); + auto args = array_make(heap_allocator(), 1); args[0] = c; lbValue s = lb_emit_runtime_call(p, "cstring_to_string", args); return lb_emit_conv(p, s, dst); @@ -2791,7 +3288,10 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { // integer -> boolean if (is_type_integer(src) && is_type_boolean(dst)) { - return ir_emit_comp(p, Token_NotEq, value, v_zero); + lbValue res = {}; + res.value = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), ""); + res.type = t_llvm_bool; + return lb_emit_conv(p, res, t); } // float -> float @@ -2799,21 +3299,27 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { gbAllocator a = heap_allocator(); i64 sz = type_size_of(src); i64 dz = type_size_of(dst); - irConvKind kind = irConv_fptrunc; + + lbValue res = {}; + res.type = t; + if (dz >= sz) { - kind = irConv_fpext; + res.value = LLVMBuildFPExt(p->builder, value.value, lb_type(m, t), ""); + } else { + res.value = LLVMBuildFPTrunc(p->builder, value.value, lb_type(m, t), ""); } - return ir_emit(p, ir_instr_conv(p, kind, value, src_type, t)); + return res; } +#if 0 if (is_type_complex(src) && is_type_complex(dst)) { Type *ft = base_complex_elem_type(dst); lbValue gen = lb_add_local_generated(p, dst, false); lbValue real = lb_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); lbValue imag = lb_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); - ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), real); - ir_emit_store(p, ir_emit_struct_ep(p, gen, 1), imag); - return ir_emit_load(p, gen); + lb_emit_store(p, ir_emit_struct_ep(p, gen, 0), real); + lb_emit_store(p, ir_emit_struct_ep(p, gen, 1), imag); + return lb_emit_load(p, gen); } if (is_type_quaternion(src) && is_type_quaternion(dst)) { @@ -2824,27 +3330,27 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { lbValue q1 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); lbValue q2 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 2), ft); lbValue q3 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 3), ft); - ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), q0); - ir_emit_store(p, ir_emit_struct_ep(p, gen, 1), q1); - ir_emit_store(p, ir_emit_struct_ep(p, gen, 2), q2); - ir_emit_store(p, ir_emit_struct_ep(p, gen, 3), q3); - return ir_emit_load(p, gen); + lb_emit_store(p, ir_emit_struct_ep(p, gen, 0), q0); + lb_emit_store(p, ir_emit_struct_ep(p, gen, 1), q1); + lb_emit_store(p, ir_emit_struct_ep(p, gen, 2), q2); + lb_emit_store(p, ir_emit_struct_ep(p, gen, 3), q3); + return lb_emit_load(p, gen); } if (is_type_float(src) && is_type_complex(dst)) { Type *ft = base_complex_elem_type(dst); lbValue gen = lb_add_local_generated(p, dst, true); lbValue real = lb_emit_conv(p, value, ft); - ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), real); - return ir_emit_load(p, gen); + lb_emit_store(p, ir_emit_struct_ep(p, gen, 0), real); + return lb_emit_load(p, gen); } if (is_type_float(src) && is_type_quaternion(dst)) { Type *ft = base_complex_elem_type(dst); lbValue gen = lb_add_local_generated(p, dst, true); lbValue real = lb_emit_conv(p, value, ft); // @QuaternionLayout - ir_emit_store(p, ir_emit_struct_ep(p, gen, 3), real); - return ir_emit_load(p, gen); + lb_emit_store(p, ir_emit_struct_ep(p, gen, 3), real); + return lb_emit_load(p, gen); } if (is_type_complex(src) && is_type_quaternion(dst)) { Type *ft = base_complex_elem_type(dst); @@ -2852,46 +3358,57 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { lbValue real = lb_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); lbValue imag = lb_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); // @QuaternionLayout - ir_emit_store(p, ir_emit_struct_ep(p, gen, 3), real); - ir_emit_store(p, ir_emit_struct_ep(p, gen, 0), imag); - return ir_emit_load(p, gen); + lb_emit_store(p, ir_emit_struct_ep(p, gen, 3), real); + lb_emit_store(p, ir_emit_struct_ep(p, gen, 0), imag); + return lb_emit_load(p, gen); } - - +#endif // float <-> integer if (is_type_float(src) && is_type_integer(dst)) { - irConvKind kind = irConv_fptosi; + lbValue res = {}; + res.type = t; if (is_type_unsigned(dst)) { - kind = irConv_fptoui; + res.value = LLVMBuildFPToUI(p->builder, value.value, lb_type(m, t), ""); + } else { + res.value = LLVMBuildFPToSI(p->builder, value.value, lb_type(m, t), ""); } - return ir_emit(p, ir_instr_conv(p, kind, value, src_type, t)); + return res; } if (is_type_integer(src) && is_type_float(dst)) { - irConvKind kind = irConv_sitofp; + lbValue res = {}; + res.type = t; if (is_type_unsigned(src)) { - kind = irConv_uitofp; + res.value = LLVMBuildUIToFP(p->builder, value.value, lb_type(m, t), ""); + } else { + res.value = LLVMBuildSIToFP(p->builder, value.value, lb_type(m, t), ""); } - return ir_emit(p, ir_instr_conv(p, kind, value, src_type, t)); + return res; } // Pointer <-> uintptr if (is_type_pointer(src) && is_type_uintptr(dst)) { - return ir_emit_ptr_to_uintptr(p, value, t); + lbValue res = {}; + res.type = t; + res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), ""); + return res; } if (is_type_uintptr(src) && is_type_pointer(dst)) { - return ir_emit_uintptr_to_ptr(p, value, t); + lbValue res = {}; + res.type = t; + res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), ""); + return res; } +#if 0 if (is_type_union(dst)) { for_array(i, dst->Union.variants) { Type *vt = dst->Union.variants[i]; if (are_types_identical(vt, src_type)) { - ir_emit_comment(p, str_lit("union - child to parent")); gbAllocator a = heap_allocator(); lbValue parent = lb_add_local_generated(p, t, true); - ir_emit_store_union_variant(p, parent, value, vt); - return ir_emit_load(p, parent); + lb_emit_store_union_variant(p, parent, value, vt); + return lb_emit_load(p, parent); } } } @@ -2920,17 +3437,17 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { lbValue res = lb_emit_deep_field_gep(p, value, sel); Type *rt = ir_type(res); if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) { - res = ir_emit_load(p, res); + res = lb_emit_load(p, res); } return res; } else { if (is_type_pointer(ir_type(value))) { Type *rt = ir_type(value); if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) { - value = ir_emit_load(p, value); + value = lb_emit_load(p, value); } else { value = lb_emit_deep_field_gep(p, value, sel); - return ir_emit_load(p, value); + return lb_emit_load(p, value); } } @@ -2942,31 +3459,45 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { } } } +#endif // Pointer <-> Pointer if (is_type_pointer(src) && is_type_pointer(dst)) { - return ir_emit_bitcast(p, value, t); + lbValue res = {}; + res.type = t; + res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(m, t), ""); + return res; } // proc <-> proc - if (is_type_p(src) && is_type_p(dst)) { - return ir_emit_bitcast(p, value, t); + if (is_type_proc(src) && is_type_proc(dst)) { + lbValue res = {}; + res.type = t; + res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(m, t), ""); + return res; } // pointer -> proc - if (is_type_pointer(src) && is_type_p(dst)) { - return ir_emit_bitcast(p, value, t); + if (is_type_pointer(src) && is_type_proc(dst)) { + lbValue res = {}; + res.type = t; + res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(m, t), ""); + return res; } // proc -> pointer - if (is_type_p(src) && is_type_pointer(dst)) { - return ir_emit_bitcast(p, value, t); + if (is_type_proc(src) && is_type_pointer(dst)) { + lbValue res = {}; + res.type = t; + res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(m, t), ""); + return res; } +#if 0 // []byte/[]u8 <-> string if (is_type_u8_slice(src) && is_type_string(dst)) { @@ -2977,11 +3508,11 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (is_type_string(src) && is_type_u8_slice(dst)) { lbValue elem = ir_string_elem(p, value); lbValue elem_ptr = lb_add_local_generated(p, ir_type(elem), false); - ir_emit_store(p, elem_ptr, elem); + lb_emit_store(p, elem_ptr, elem); lbValue len = ir_string_len(p, value); lbValue slice = ir_add_local_slice(p, t, elem_ptr, v_zero, len); - return ir_emit_load(p, slice); + return lb_emit_load(p, slice); } if (is_type_array(dst)) { @@ -2993,16 +3524,16 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { for (i32 i = 0; i < index_count; i++) { lbValue elem = ir_emit_array_epi(p, v, i); - ir_emit_store(p, elem, e); + lb_emit_store(p, elem, e); } - return ir_emit_load(p, v); + return lb_emit_load(p, v); } if (is_type_any(dst)) { lbValue result = lb_add_local_generated(p, t_any, true); if (is_type_untyped_nil(src)) { - return ir_emit_load(p, result); + return lb_emit_load(p, result); } Type *st = default_type(src_type); @@ -3013,38 +3544,133 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { data = lb_emit_conv(p, data, t_rawptr); - lbValue id = ir_typeid(p->module, st); + lbValue id = lb_typeid(p->module, st); - ir_emit_store(p, ir_emit_struct_ep(p, result, 0), data); - ir_emit_store(p, ir_emit_struct_ep(p, result, 1), id); + lb_emit_store(p, ir_emit_struct_ep(p, result, 0), data); + lb_emit_store(p, ir_emit_struct_ep(p, result, 1), id); - return ir_emit_load(p, result); + return lb_emit_load(p, result); } +#endif if (is_type_untyped(src)) { if (is_type_string(src) && is_type_string(dst)) { - lbValue result = lb_add_local_generated(p, t, false); - ir_emit_store(p, result, value); - return ir_emit_load(p, result); + lbAddr result = lb_add_local_generated(p, t, false); + lb_addr_store(p, result, value); + return lb_addr_load(p, result); } } -#endif + gb_printf_err("%.*s\n", LIT(p->name)); gb_printf_err("lb_emit_conv: src -> dst\n"); gb_printf_err("Not Identical %s != %s\n", type_to_string(src_type), type_to_string(t)); gb_printf_err("Not Identical %s != %s\n", type_to_string(src), type_to_string(dst)); + gb_printf_err("Not Identical %p != %p\n", src_type, t); + gb_printf_err("Not Identical %p != %p\n", src, dst); + + + GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'", + type_to_string(src_type), type_to_string(t), + LIT(p->name)); + + return {}; +} + +bool lb_is_type_aggregate(Type *t) { + t = base_type(t); + switch (t->kind) { + case Type_Basic: + switch (t->Basic.kind) { + case Basic_string: + case Basic_any: + return true; + + // case Basic_complex32: + case Basic_complex64: + case Basic_complex128: + case Basic_quaternion128: + case Basic_quaternion256: + return true; + } + break; + + case Type_Pointer: + return false; + + case Type_Array: + case Type_Slice: + case Type_Struct: + case Type_Union: + case Type_Tuple: + case Type_DynamicArray: + case Type_Map: + case Type_BitField: + case Type_SimdVector: + return true; + + case Type_Named: + return lb_is_type_aggregate(t->Named.base); + } + + return false; +} + +lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) { + Type *src_type = value.type; + if (are_types_identical(t, src_type)) { + return value; + } + + lbValue res = {}; + res.type = t; + + + Type *src = base_type(src_type); + Type *dst = base_type(t); + + lbModule *m = p->module; + + i64 sz = type_size_of(src); + i64 dz = type_size_of(dst); + + GB_ASSERT_MSG(sz == dz, "Invalid transmute conversion: '%s' to '%s'", type_to_string(src_type), type_to_string(t)); + + // NOTE(bill): Casting between an integer and a pointer cannot be done through a bitcast + if (is_type_uintptr(src) && is_type_pointer(dst)) { + res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), ""); + return res; + } + if (is_type_pointer(src) && is_type_uintptr(dst)) { + res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), ""); + return res; + } + if (is_type_uintptr(src) && is_type_proc(dst)) { + res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), ""); + return res; + } + if (is_type_proc(src) && is_type_uintptr(dst)) { + res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), ""); + return res; + } + if (is_type_integer(src) && (is_type_pointer(dst) || is_type_cstring(dst))) { + res.value = LLVMBuildIntToPtr(p->builder, value.value, lb_type(m, t), ""); + return res; + } else if ((is_type_pointer(src) || is_type_cstring(src)) && is_type_integer(dst)) { + res.value = LLVMBuildPtrToInt(p->builder, value.value, lb_type(m, t), ""); + return res; + } - GB_PANIC("Invalid type conversion: '%s' to '%s' for procedure '%.*s'", - type_to_string(src_type), type_to_string(t), - LIT(p->name)); + if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) { + lbValue s = lb_address_from_load_or_generate_local(p, value); + lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t)); + return lb_emit_load(p, d); + } - return {}; -} -lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) { - // TODO(bill): lb_emit_transmute - return value; + res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(p->module, t), ""); + // GB_PANIC("lb_emit_transmute"); + return res; } @@ -3067,12 +3693,12 @@ lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) { return p->context_stack[p->context_stack.count-1].ctx; } - lbBlock *tmp_block = p->curr_block; - p->curr_block = p->blocks[0]; - - defer (p->curr_block = tmp_block); + // lbBlock *tmp_block = p->curr_block; + // p->curr_block = p->blocks[0]; + // defer (p->curr_block = tmp_block); lbAddr c = lb_add_local_generated(p, t_context, false); + c.kind = lbAddr_Context; lb_push_context_onto_stack(p, c); lb_addr_store(p, c, lb_addr_load(p, p->module->global_default_context)); lb_emit_init_context(p, c.addr); @@ -3247,6 +3873,9 @@ lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) { case Type_Tuple: GB_ASSERT(t->Tuple.variables.count > 0); result_type = t->Tuple.variables[index]->type; + if (t->Tuple.variables.count == 1) { + return s; + } break; case Type_Slice: switch (index) { @@ -3420,6 +4049,41 @@ lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) { return d; } +lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array const &result_as_args) { + lbDefer d = {lbDefer_Proc}; + d.scope_index = p->scope_index; + d.block = p->curr_block; + d.proc.deferred = deferred; + d.proc.result_as_args = result_as_args; + array_add(&p->defer_stmts, d); + return d; +} + + + +Array lb_value_to_array(lbProcedure *p, lbValue value) { + Array array = {}; + Type *t = base_type(value.type); + if (t == nullptr) { + // Do nothing + } else if (is_type_tuple(t)) { + GB_ASSERT(t->kind == Type_Tuple); + auto *rt = &t->Tuple; + if (rt->variables.count > 0) { + array = array_make(heap_allocator(), rt->variables.count); + for_array(i, rt->variables) { + lbValue elem = lb_emit_struct_ev(p, value, cast(i32)i); + array[i] = elem; + } + } + } else { + array = array_make(heap_allocator(), 1); + array[0] = value; + } + return array; +} + + lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, Array const &processed_args, Type *abi_rt, lbAddr context_ptr, ProcInlining inlining) { unsigned arg_count = cast(unsigned)processed_args.count; @@ -3443,9 +4107,12 @@ lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, args[arg_index++] = context_ptr.addr.value; } + LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder); + GB_ASSERT(curr_block != p->decl_block->block); + LLVMValueRef ret = LLVMBuildCall(p->builder, value.value, args, arg_count, "");; lbValue res = {}; - res.value = LLVMBuildCall(p->builder, value.value, args, arg_count, ""); + res.value = ret; res.type = abi_rt; return res; } @@ -3504,7 +4171,7 @@ lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, for (isize i = 0; i < param_count; i++) { Entity *e = pt->Proc.params->Tuple.variables[i]; if (e->kind != Entity_Variable) { - array_add(&processed_args, args[i]); + // array_add(&processed_args, args[i]); continue; } GB_ASSERT(e->flags & EntityFlag_Param); @@ -3549,7 +4216,7 @@ lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, lbValue result = {}; - Type *abi_rt = pt->Proc.abi_compat_result_type; + Type *abi_rt = reduce_tuple_to_single_type(pt->Proc.abi_compat_result_type); Type *rt = reduce_tuple_to_single_type(results); if (pt->Proc.return_by_pointer) { lbValue return_ptr = {}; @@ -3567,39 +4234,39 @@ lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, lb_emit_call_internal(p, value, return_ptr, processed_args, nullptr, context_ptr, inlining); result = lb_emit_load(p, return_ptr); } else { - lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining); - if (abi_rt != results) { + result = lb_emit_call_internal(p, value, {}, processed_args, abi_rt, context_ptr, inlining); + if (abi_rt != rt) { result = lb_emit_transmute(p, result, rt); } } - // if (value->kind == irValue_Proc) { - // lbProcedure *the_proc = &value->Proc; - // Entity *e = the_proc->entity; - // if (e != nullptr && entity_has_deferred_procedure(e)) { - // DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind; - // Entity *deferred_entity = e->Procedure.deferred_procedure.entity; - // lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity)); - // GB_ASSERT(deferred_found != nullptr); - // lbValue deferred = *deferred_found; - - - // auto in_args = args; - // Array result_as_args = {}; - // switch (kind) { - // case DeferredProcedure_none: - // break; - // case DeferredProcedure_in: - // result_as_args = in_args; - // break; - // case DeferredProcedure_out: - // result_as_args = ir_value_to_array(p, result); - // break; - // } - - // ir_add_defer_proc(p, p->scope_index, deferred, result_as_args); - // } - // } + Entity **found = map_get(&p->module->procedure_values, hash_pointer(value.value)); + if (found != nullptr) { + Entity *e = *found; + if (e != nullptr && entity_has_deferred_procedure(e)) { + DeferredProcedureKind kind = e->Procedure.deferred_procedure.kind; + Entity *deferred_entity = e->Procedure.deferred_procedure.entity; + lbValue *deferred_found = map_get(&p->module->values, hash_entity(deferred_entity)); + GB_ASSERT(deferred_found != nullptr); + lbValue deferred = *deferred_found; + + + auto in_args = args; + Array result_as_args = {}; + switch (kind) { + case DeferredProcedure_none: + break; + case DeferredProcedure_in: + result_as_args = in_args; + break; + case DeferredProcedure_out: + result_as_args = lb_value_to_array(p, result); + break; + } + + lb_add_defer_proc(p, p->scope_index, deferred, result_as_args); + } + } return result; } @@ -3611,12 +4278,12 @@ lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) { GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st)); LLVMValueRef indices[2] = {}; - indices[0] = lb_zero32(p->module); + indices[0] = llvm_zero32(p->module); indices[1] = lb_emit_conv(p, index, t_i32).value; Type *ptr = base_array_type(st); lbValue res = {}; - res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, ptr), s.value, indices, 2, ""); + res.value = LLVMBuildGEP(p->builder, s.value, indices, 2, ""); res.type = alloc_type_pointer(ptr); return res; } @@ -3630,7 +4297,7 @@ lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, i32 index) { GB_ASSERT(0 <= index); Type *ptr = base_array_type(st); lbValue res = {}; - res.value = LLVMBuildStructGEP2(p->builder, lb_type(p->module, st), s.value, index, ""); + res.value = LLVMBuildStructGEP(p->builder, s.value, index, ""); res.type = alloc_type_pointer(ptr); return res; } @@ -3639,13 +4306,648 @@ lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) { LLVMValueRef indices[1] = {index.value}; lbValue res = {}; res.type = ptr.type; - res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, ptr.type), ptr.value, indices, 1, ""); + res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, type_deref(ptr.type)), ptr.value, indices, 1, ""); return res; } -void lb_fill_slice(lbProcedure *p, lbAddr slice, lbValue base_elem, lbValue len) { +void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) { + Type *t = lb_addr_type(slice); + GB_ASSERT(is_type_slice(t)); + lbValue ptr = lb_addr_get_ptr(p, slice); + lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem); + lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len); +} +void lb_fill_string(lbProcedure *p, lbAddr const &string, lbValue base_elem, lbValue len) { + Type *t = lb_addr_type(string); + GB_ASSERT(is_type_string(t)); + lbValue ptr = lb_addr_get_ptr(p, string); + lb_emit_store(p, lb_emit_struct_ep(p, ptr, 0), base_elem); + lb_emit_store(p, lb_emit_struct_ep(p, ptr, 1), len); +} + +lbValue lb_string_elem(lbProcedure *p, lbValue string) { + Type *t = base_type(string.type); + GB_ASSERT(t->kind == Type_Basic && t->Basic.kind == Basic_string); + return lb_emit_struct_ev(p, string, 0); +} +lbValue lb_string_len(lbProcedure *p, lbValue string) { + Type *t = base_type(string.type); + GB_ASSERT_MSG(t->kind == Type_Basic && t->Basic.kind == Basic_string, "%s", type_to_string(t)); + return lb_emit_struct_ev(p, string, 1); +} + +lbValue lb_cstring_len(lbProcedure *p, lbValue value) { + GB_ASSERT(is_type_cstring(value.type)); + auto args = array_make(heap_allocator(), 1); + args[0] = lb_emit_conv(p, value, t_cstring); + return lb_emit_runtime_call(p, "cstring_len", args); +} + + +lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr) { + Type *t = type_deref(array_ptr.type); + GB_ASSERT(is_type_array(t)); + return lb_emit_struct_ep(p, array_ptr, 0); +} + +lbValue lb_slice_elem(lbProcedure *p, lbValue slice) { + GB_ASSERT(is_type_slice(slice.type)); + return lb_emit_struct_ev(p, slice, 0); +} +lbValue lb_slice_len(lbProcedure *p, lbValue slice) { + GB_ASSERT(is_type_slice(slice.type)); + return lb_emit_struct_ev(p, slice, 1); +} +lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da) { + GB_ASSERT(is_type_dynamic_array(da.type)); + return lb_emit_struct_ev(p, da, 0); +} +lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da) { + GB_ASSERT(is_type_dynamic_array(da.type)); + return lb_emit_struct_ev(p, da, 1); +} +lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da) { + GB_ASSERT(is_type_dynamic_array(da.type)); + return lb_emit_struct_ev(p, da, 2); +} +lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da) { + GB_ASSERT(is_type_dynamic_array(da.type)); + return lb_emit_struct_ev(p, da, 3); +} + +lbValue lb_map_entries(lbProcedure *p, lbValue value) { + gbAllocator a = heap_allocator(); + Type *t = base_type(value.type); + GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t)); + init_map_internal_types(t); + Type *gst = t->Map.generated_struct_type; + i32 index = 1; + lbValue entries = lb_emit_struct_ev(p, value, index); + return entries; +} + +lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value) { + gbAllocator a = heap_allocator(); + Type *t = base_type(type_deref(value.type)); + GB_ASSERT_MSG(t->kind == Type_Map, "%s", type_to_string(t)); + init_map_internal_types(t); + Type *gst = t->Map.generated_struct_type; + i32 index = 1; + lbValue entries = lb_emit_struct_ep(p, value, index); + return entries; +} + +lbValue lb_map_len(lbProcedure *p, lbValue value) { + lbValue entries = lb_map_entries(p, value); + return lb_dynamic_array_len(p, entries); +} + +lbValue lb_map_cap(lbProcedure *p, lbValue value) { + lbValue entries = lb_map_entries(p, value); + return lb_dynamic_array_cap(p, entries); +} + +lbValue lb_soa_struct_len(lbProcedure *p, lbValue value) { + Type *t = base_type(value.type); + bool is_ptr = false; + if (is_type_pointer(t)) { + is_ptr = true; + t = base_type(type_deref(t)); + } + + + if (t->Struct.soa_kind == StructSoa_Fixed) { + return lb_const_int(p->module, t_int, t->Struct.soa_count); + } + + GB_ASSERT(t->Struct.soa_kind == StructSoa_Slice || + t->Struct.soa_kind == StructSoa_Dynamic); + + isize n = 0; + Type *elem = base_type(t->Struct.soa_elem); + if (elem->kind == Type_Struct) { + n = elem->Struct.fields.count; + } else if (elem->kind == Type_Array) { + n = elem->Array.count; + } else { + GB_PANIC("Unreachable"); + } + + if (is_ptr) { + lbValue v = lb_emit_struct_ep(p, value, cast(i32)n); + return lb_emit_load(p, v); + } + return lb_emit_struct_ev(p, value, cast(i32)n); +} + +lbValue lb_soa_struct_cap(lbProcedure *p, lbValue value) { + Type *t = base_type(value.type); + + bool is_ptr = false; + if (is_type_pointer(t)) { + is_ptr = true; + t = base_type(type_deref(t)); + } + + if (t->Struct.soa_kind == StructSoa_Fixed) { + return lb_const_int(p->module, t_int, t->Struct.soa_count); + } + + GB_ASSERT(t->Struct.soa_kind == StructSoa_Dynamic); + + isize n = 0; + Type *elem = base_type(t->Struct.soa_elem); + if (elem->kind == Type_Struct) { + n = elem->Struct.fields.count+1; + } else if (elem->kind == Type_Array) { + n = elem->Array.count+1; + } else { + GB_PANIC("Unreachable"); + } + + if (is_ptr) { + lbValue v = lb_emit_struct_ep(p, value, cast(i32)n); + return lb_emit_load(p, v); + } + return lb_emit_struct_ev(p, value, cast(i32)n); +} + + + + +lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, BuiltinProcId id) { + ast_node(ce, CallExpr, expr); + + switch (id) { + case BuiltinProc_DIRECTIVE: { + ast_node(bd, BasicDirective, ce->proc); + String name = bd->name; + GB_ASSERT(name == "location"); + String procedure = p->entity->token.string; + TokenPos pos = ast_token(ce->proc).pos; + if (ce->args.count > 0) { + Ast *ident = unselector_expr(ce->args[0]); + GB_ASSERT(ident->kind == Ast_Ident); + Entity *e = entity_of_ident(ident); + GB_ASSERT(e != nullptr); + + if (e->parent_proc_decl != nullptr && e->parent_proc_decl->entity != nullptr) { + procedure = e->parent_proc_decl->entity->token.string; + } else { + procedure = str_lit(""); + } + pos = e->token.pos; + + } + return lb_emit_source_code_location(p, procedure, pos); + } + + case BuiltinProc_type_info_of: { + Ast *arg = ce->args[0]; + TypeAndValue tav = type_and_value_of_expr(arg); + if (tav.mode == Addressing_Type) { + Type *t = default_type(type_of_expr(arg)); + return lb_type_info(p->module, t); + } + GB_ASSERT(is_type_typeid(tav.type)); + + auto args = array_make(heap_allocator(), 1); + args[0] = lb_build_expr(p, arg); + return lb_emit_runtime_call(p, "__type_info_of", args); + } + + case BuiltinProc_typeid_of: { + Ast *arg = ce->args[0]; + TypeAndValue tav = type_and_value_of_expr(arg); + if (tav.mode == Addressing_Type) { + Type *t = default_type(type_of_expr(arg)); + return lb_typeid(p->module, t); + } + Type *t = base_type(tav.type); + GB_ASSERT(are_types_identical(t, t_type_info_ptr)); + + auto args = array_make(heap_allocator(), 1); + args[0] = lb_emit_conv(p, lb_build_expr(p, arg), t_type_info_ptr); + return lb_emit_runtime_call(p, "__typeid_of", args); + } + + case BuiltinProc_len: { + lbValue v = lb_build_expr(p, ce->args[0]); + Type *t = base_type(v.type); + if (is_type_pointer(t)) { + // IMPORTANT TODO(bill): Should there be a nil pointer check? + v = lb_emit_load(p, v); + t = type_deref(t); + } + if (is_type_cstring(t)) { + return lb_cstring_len(p, v); + } else if (is_type_string(t)) { + return lb_string_len(p, v); + } else if (is_type_array(t)) { + GB_PANIC("Array lengths are constant"); + } 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); + } else if (is_type_map(t)) { + return lb_map_len(p, v); + } else if (is_type_soa_struct(t)) { + return lb_soa_struct_len(p, v); + } + + GB_PANIC("Unreachable"); + break; + } + + case BuiltinProc_cap: { + lbValue v = lb_build_expr(p, ce->args[0]); + Type *t = base_type(v.type); + if (is_type_pointer(t)) { + // IMPORTANT TODO(bill): Should there be a nil pointer check? + v = lb_emit_load(p, v); + t = type_deref(t); + } + if (is_type_string(t)) { + GB_PANIC("Unreachable"); + } else if (is_type_array(t)) { + GB_PANIC("Array lengths are constant"); + } 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); + } else if (is_type_map(t)) { + return lb_map_cap(p, v); + } else if (is_type_soa_struct(t)) { + return lb_soa_struct_cap(p, v); + } + + GB_PANIC("Unreachable"); + + break; + } + + case BuiltinProc_swizzle: { + lbAddr addr = lb_build_addr(p, ce->args[0]); + isize index_count = ce->args.count-1; + if (index_count == 0) { + return lb_addr_load(p, addr); + } + lbValue src = lb_addr_get_ptr(p, addr); + // TODO(bill): Should this be zeroed or not? + lbAddr dst = lb_add_local_generated(p, tv.type, true); + lbValue dst_ptr = lb_addr_get_ptr(p, dst); + + for (i32 i = 1; i < ce->args.count; i++) { + TypeAndValue tv = type_and_value_of_expr(ce->args[i]); + GB_ASSERT(is_type_integer(tv.type)); + GB_ASSERT(tv.value.kind == ExactValue_Integer); + + i32 src_index = cast(i32)big_int_to_i64(&tv.value.value_integer); + i32 dst_index = i-1; + + lbValue src_elem = lb_emit_array_epi(p, src, src_index); + lbValue dst_elem = lb_emit_array_epi(p, dst_ptr, dst_index); + + lb_emit_store(p, dst_elem, lb_emit_load(p, src_elem)); + } + return lb_addr_load(p, dst); + } + + case BuiltinProc_complex: { + lbValue real = lb_build_expr(p, ce->args[0]); + lbValue imag = lb_build_expr(p, ce->args[1]); + lbAddr dst_addr = lb_add_local_generated(p, tv.type, false); + lbValue dst = lb_addr_get_ptr(p, dst_addr); + + Type *ft = base_complex_elem_type(tv.type); + real = lb_emit_conv(p, real, ft); + imag = lb_emit_conv(p, imag, ft); + lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), real); + lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), imag); + + return lb_emit_load(p, dst); + } + + case BuiltinProc_quaternion: { + lbValue real = lb_build_expr(p, ce->args[0]); + lbValue imag = lb_build_expr(p, ce->args[1]); + lbValue jmag = lb_build_expr(p, ce->args[2]); + lbValue kmag = lb_build_expr(p, ce->args[3]); + + // @QuaternionLayout + lbAddr dst_addr = lb_add_local_generated(p, tv.type, false); + lbValue dst = lb_addr_get_ptr(p, dst_addr); + + Type *ft = base_complex_elem_type(tv.type); + real = lb_emit_conv(p, real, ft); + imag = lb_emit_conv(p, imag, ft); + jmag = lb_emit_conv(p, jmag, ft); + kmag = lb_emit_conv(p, kmag, ft); + lb_emit_store(p, lb_emit_struct_ep(p, dst, 3), real); + lb_emit_store(p, lb_emit_struct_ep(p, dst, 0), imag); + lb_emit_store(p, lb_emit_struct_ep(p, dst, 1), jmag); + lb_emit_store(p, lb_emit_struct_ep(p, dst, 2), kmag); + + return lb_emit_load(p, dst); + } + + case BuiltinProc_real: { + lbValue val = lb_build_expr(p, ce->args[0]); + if (is_type_complex(val.type)) { + lbValue real = lb_emit_struct_ev(p, val, 0); + return lb_emit_conv(p, real, tv.type); + } else if (is_type_quaternion(val.type)) { + // @QuaternionLayout + lbValue real = lb_emit_struct_ev(p, val, 3); + return lb_emit_conv(p, real, tv.type); + } + GB_PANIC("invalid type for real"); + return {}; + } + case BuiltinProc_imag: { + lbValue val = lb_build_expr(p, ce->args[0]); + if (is_type_complex(val.type)) { + lbValue imag = lb_emit_struct_ev(p, val, 1); + return lb_emit_conv(p, imag, tv.type); + } else if (is_type_quaternion(val.type)) { + // @QuaternionLayout + lbValue imag = lb_emit_struct_ev(p, val, 0); + return lb_emit_conv(p, imag, tv.type); + } + GB_PANIC("invalid type for imag"); + return {}; + } + case BuiltinProc_jmag: { + lbValue val = lb_build_expr(p, ce->args[0]); + if (is_type_quaternion(val.type)) { + // @QuaternionLayout + lbValue imag = lb_emit_struct_ev(p, val, 1); + return lb_emit_conv(p, imag, tv.type); + } + GB_PANIC("invalid type for jmag"); + return {}; + } + case BuiltinProc_kmag: { + lbValue val = lb_build_expr(p, ce->args[0]); + if (is_type_quaternion(val.type)) { + // @QuaternionLayout + lbValue imag = lb_emit_struct_ev(p, val, 2); + return lb_emit_conv(p, imag, tv.type); + } + GB_PANIC("invalid type for kmag"); + return {}; + } + + case BuiltinProc_conj: { + lbValue val = lb_build_expr(p, ce->args[0]); + lbValue res = {}; + Type *t = val.type; + if (is_type_complex(t)) { + res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false)); + lbValue real = lb_emit_struct_ev(p, val, 0); + lbValue imag = lb_emit_struct_ev(p, val, 1); + imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type); + lb_emit_store(p, lb_emit_struct_ep(p, res, 0), real); + lb_emit_store(p, lb_emit_struct_ep(p, res, 1), imag); + } else if (is_type_quaternion(t)) { + // @QuaternionLayout + res = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false)); + lbValue real = lb_emit_struct_ev(p, val, 3); + lbValue imag = lb_emit_struct_ev(p, val, 0); + lbValue jmag = lb_emit_struct_ev(p, val, 1); + lbValue kmag = lb_emit_struct_ev(p, val, 2); + imag = lb_emit_unary_arith(p, Token_Sub, imag, imag.type); + jmag = lb_emit_unary_arith(p, Token_Sub, jmag, jmag.type); + kmag = lb_emit_unary_arith(p, Token_Sub, kmag, kmag.type); + lb_emit_store(p, lb_emit_struct_ep(p, res, 3), real); + lb_emit_store(p, lb_emit_struct_ep(p, res, 0), imag); + lb_emit_store(p, lb_emit_struct_ep(p, res, 1), jmag); + lb_emit_store(p, lb_emit_struct_ep(p, res, 2), kmag); + } + return lb_emit_load(p, res); + } + + case BuiltinProc_expand_to_tuple: { + lbValue val = lb_build_expr(p, ce->args[0]); + Type *t = base_type(val.type); + + if (!is_type_tuple(tv.type)) { + if (t->kind == Type_Struct) { + GB_ASSERT(t->Struct.fields.count == 1); + return lb_emit_struct_ev(p, val, 0); + } else if (t->kind == Type_Array) { + GB_ASSERT(t->Array.count == 1); + return lb_emit_array_epi(p, val, 0); + } else { + GB_PANIC("Unknown type of expand_to_tuple"); + } + + } + + GB_ASSERT(is_type_tuple(tv.type)); + // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops + lbValue tuple = lb_addr_get_ptr(p, lb_add_local_generated(p, tv.type, false)); + if (t->kind == Type_Struct) { + for_array(src_index, t->Struct.fields) { + Entity *field = t->Struct.fields[src_index]; + i32 field_index = field->Variable.field_index; + lbValue f = lb_emit_struct_ev(p, val, field_index); + lbValue ep = lb_emit_struct_ep(p, tuple, cast(i32)src_index); + lb_emit_store(p, ep, f); + } + } else if (t->kind == Type_Array) { + // TODO(bill): Clean-up this code + lbValue ap = lb_address_from_load_or_generate_local(p, val); + for (i32 i = 0; i < cast(i32)t->Array.count; i++) { + lbValue f = lb_emit_load(p, lb_emit_array_epi(p, ap, i)); + lbValue ep = lb_emit_struct_ep(p, tuple, i); + lb_emit_store(p, ep, f); + } + } else { + GB_PANIC("Unknown type of expand_to_tuple"); + } + return lb_emit_load(p, tuple); + } + + case BuiltinProc_min: { + Type *t = type_of_expr(expr); + if (ce->args.count == 2) { + return lb_emit_min(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1])); + } else { + lbValue x = lb_build_expr(p, ce->args[0]); + for (isize i = 1; i < ce->args.count; i++) { + x = lb_emit_min(p, t, x, lb_build_expr(p, ce->args[i])); + } + return x; + } + } + case BuiltinProc_max: { + Type *t = type_of_expr(expr); + if (ce->args.count == 2) { + return lb_emit_max(p, t, lb_build_expr(p, ce->args[0]), lb_build_expr(p, ce->args[1])); + } else { + lbValue x = lb_build_expr(p, ce->args[0]); + for (isize i = 1; i < ce->args.count; i++) { + x = lb_emit_max(p, t, x, lb_build_expr(p, ce->args[i])); + } + return x; + } + } + + case BuiltinProc_abs: { + gbAllocator a = heap_allocator(); + lbValue x = lb_build_expr(p, ce->args[0]); + Type *t = x.type; + if (is_type_unsigned(t)) { + return x; + } + if (is_type_quaternion(t)) { + i64 sz = 8*type_size_of(t); + auto args = array_make(heap_allocator(), 1); + args[0] = x; + switch (sz) { + case 128: return lb_emit_runtime_call(p, "abs_quaternion128", args); + case 256: return lb_emit_runtime_call(p, "abs_quaternion256", args); + } + GB_PANIC("Unknown complex type"); + } else if (is_type_complex(t)) { + i64 sz = 8*type_size_of(t); + auto args = array_make(heap_allocator(), 1); + args[0] = x; + switch (sz) { + case 64: return lb_emit_runtime_call(p, "abs_complex64", args); + case 128: return lb_emit_runtime_call(p, "abs_complex128", args); + } + GB_PANIC("Unknown complex type"); + } else if (is_type_float(t)) { + i64 sz = 8*type_size_of(t); + auto args = array_make(heap_allocator(), 1); + args[0] = x; + switch (sz) { + case 32: return lb_emit_runtime_call(p, "abs_f32", args); + case 64: return lb_emit_runtime_call(p, "abs_f64", args); + } + GB_PANIC("Unknown float type"); + } + lbValue zero = lb_const_nil(p->module, t); + lbValue cond = lb_emit_comp(p, Token_Lt, x, zero); + lbValue neg = lb_emit_unary_arith(p, Token_Sub, x, t); + return lb_emit_select(p, cond, neg, x); + } + + case BuiltinProc_clamp: + return lb_emit_clamp(p, type_of_expr(expr), + lb_build_expr(p, ce->args[0]), + lb_build_expr(p, ce->args[1]), + lb_build_expr(p, ce->args[2])); + + + + #if 0 + // "Intrinsics" + case BuiltinProc_atomic_fence: + case BuiltinProc_atomic_fence_acq: + case BuiltinProc_atomic_fence_rel: + case BuiltinProc_atomic_fence_acqrel: + return lb_emit(p, lb_instr_atomic_fence(p, id)); + + case BuiltinProc_atomic_store: + case BuiltinProc_atomic_store_rel: + case BuiltinProc_atomic_store_relaxed: + case BuiltinProc_atomic_store_unordered: { + lbValue dst = lb_build_expr(p, ce->args[0]); + lbValue val = lb_build_expr(p, ce->args[1]); + val = lb_emit_conv(p, val, type_deref(ir_type(dst))); + return lb_emit(p, lb_instr_atomic_store(p, dst, val, id)); + } + + case BuiltinProc_atomic_load: + case BuiltinProc_atomic_load_acq: + case BuiltinProc_atomic_load_relaxed: + case BuiltinProc_atomic_load_unordered: { + lbValue dst = lb_build_expr(p, ce->args[0]); + return lb_emit(p, lb_instr_atomic_load(p, dst, id)); + } + + case BuiltinProc_atomic_add: + case BuiltinProc_atomic_add_acq: + case BuiltinProc_atomic_add_rel: + case BuiltinProc_atomic_add_acqrel: + case BuiltinProc_atomic_add_relaxed: + case BuiltinProc_atomic_sub: + case BuiltinProc_atomic_sub_acq: + case BuiltinProc_atomic_sub_rel: + case BuiltinProc_atomic_sub_acqrel: + case BuiltinProc_atomic_sub_relaxed: + case BuiltinProc_atomic_and: + case BuiltinProc_atomic_and_acq: + case BuiltinProc_atomic_and_rel: + case BuiltinProc_atomic_and_acqrel: + case BuiltinProc_atomic_and_relaxed: + case BuiltinProc_atomic_nand: + case BuiltinProc_atomic_nand_acq: + case BuiltinProc_atomic_nand_rel: + case BuiltinProc_atomic_nand_acqrel: + case BuiltinProc_atomic_nand_relaxed: + case BuiltinProc_atomic_or: + case BuiltinProc_atomic_or_acq: + case BuiltinProc_atomic_or_rel: + case BuiltinProc_atomic_or_acqrel: + case BuiltinProc_atomic_or_relaxed: + case BuiltinProc_atomic_xor: + case BuiltinProc_atomic_xor_acq: + case BuiltinProc_atomic_xor_rel: + case BuiltinProc_atomic_xor_acqrel: + case BuiltinProc_atomic_xor_relaxed: + case BuiltinProc_atomic_xchg: + case BuiltinProc_atomic_xchg_acq: + case BuiltinProc_atomic_xchg_rel: + case BuiltinProc_atomic_xchg_acqrel: + case BuiltinProc_atomic_xchg_relaxed: { + lbValue dst = lb_build_expr(p, ce->args[0]); + lbValue val = lb_build_expr(p, ce->args[1]); + val = lb_emit_conv(p, val, type_deref(ir_type(dst))); + return lb_emit(p, lb_instr_atomic_rmw(p, dst, val, id)); + } + + case BuiltinProc_atomic_cxchg: + case BuiltinProc_atomic_cxchg_acq: + case BuiltinProc_atomic_cxchg_rel: + case BuiltinProc_atomic_cxchg_acqrel: + case BuiltinProc_atomic_cxchg_relaxed: + case BuiltinProc_atomic_cxchg_failrelaxed: + case BuiltinProc_atomic_cxchg_failacq: + case BuiltinProc_atomic_cxchg_acq_failrelaxed: + case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: + case BuiltinProc_atomic_cxchgweak: + case BuiltinProc_atomic_cxchgweak_acq: + case BuiltinProc_atomic_cxchgweak_rel: + case BuiltinProc_atomic_cxchgweak_acqrel: + case BuiltinProc_atomic_cxchgweak_relaxed: + case BuiltinProc_atomic_cxchgweak_failrelaxed: + case BuiltinProc_atomic_cxchgweak_failacq: + case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: + case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: { + Type *type = expr->tav.type; + + lbValue address = lb_build_expr(p, ce->args[0]); + Type *elem = type_deref(ir_type(address)); + lbValue old_value = lb_build_expr(p, ce->args[1]); + lbValue new_value = lb_build_expr(p, ce->args[2]); + old_value = lb_emit_conv(p, old_value, elem); + new_value = lb_emit_conv(p, new_value, elem); + + return lb_emit(p, lb_instr_atomic_cxchg(p, type, address, old_value, new_value, id)); + } + #endif + + + } + + GB_PANIC("Unhandled built-in procedure"); + return {}; } @@ -3674,8 +4976,7 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { } else { id = BuiltinProc_DIRECTIVE; } - GB_PANIC("lb_build_builtin_proc"); - // return lb_build_builtin_proc(p, expr, tv, id); + return lb_build_builtin_proc(p, expr, tv, id); } // NOTE(bill): Regular call @@ -3900,7 +5201,10 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { for (isize i = 0; i < param_count; i++) { Entity *e = param_tuple->variables[i]; if (e->kind == Entity_Variable) { - GB_ASSERT(args[i].value != nullptr); + if (args[i].value == nullptr) { + continue; + } + GB_ASSERT_MSG(args[i].value != nullptr, "%.*s", LIT(e->token.string)); args[i] = lb_emit_conv(p, args[i], e->type); } } @@ -3963,6 +5267,10 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { bool lb_is_const(lbValue value) { LLVMValueRef v = value.value; + if (is_type_untyped_nil(value.type) || is_type_untyped_undef(value.type)) { + // TODO(bill): Is this correct behaviour? + return true; + } if (LLVMIsConstant(v)) { return true; } @@ -3992,20 +5300,14 @@ lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) { Type *vt = core_type(value.type); GB_ASSERT(type_size_of(vt) == type_size_of(platform_type)); // TODO(bill): lb_emit_byte_swap - return value; + lbValue res = {}; + res.type = platform_type; + res.value = value.value; + return res; } - -struct lbLoopData { - lbAddr idx_addr; - lbValue idx; - lbBlock *body; - lbBlock *done; - lbBlock *loop; -}; - -lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type=t_int) { +lbLoopData lb_loop_start(lbProcedure *p, isize count, Type *index_type) { lbLoopData data = {}; lbValue max = lb_const_int(p->module, t_int, count); @@ -4070,7 +5372,6 @@ lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) { return res; } } else if (is_type_slice(t)) { - gb_printf_err("HERE\n"); lbValue data = lb_emit_struct_ev(p, x, 0); lbValue cap = lb_emit_struct_ev(p, x, 1); if (op_kind == Token_CmpEq) { @@ -4118,7 +5419,7 @@ lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) { lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0)); return lb_emit_comp(p, op_kind, x, invalid_typeid); } else if (is_type_bit_field(t)) { - auto args = array_make(heap_allocator(), 2); + auto args = array_make(heap_allocator(), 2); lbValue lhs = lb_address_from_load_or_generate_local(p, x); args[0] = lb_emit_conv(p, lhs, t_rawptr); args[1] = lb_const_int(p->module, t_int, type_size_of(t)); @@ -4338,7 +5639,7 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri } GB_ASSERT(runtime_proc != nullptr); - auto args = array_make(heap_allocator(), 2); + auto args = array_make(heap_allocator(), 2); args[0] = left; args[1] = right; return lb_emit_runtime_call(p, runtime_proc, args); @@ -4363,7 +5664,7 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri } GB_ASSERT(runtime_proc != nullptr); - auto args = array_make(heap_allocator(), 2); + auto args = array_make(heap_allocator(), 2); args[0] = left; args[1] = right; return lb_emit_runtime_call(p, runtime_proc, args); @@ -4419,7 +5720,7 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri lbValue res = {}; res.type = t_llvm_bool; - if (is_type_integer(left.type) || is_type_boolean(left.type) || is_type_integer(left.type)) { + if (is_type_integer(left.type) || is_type_boolean(left.type) || is_type_pointer(left.type) || is_type_proc(left.type) || is_type_enum(left.type)) { LLVMIntPredicate pred = {}; if (is_type_unsigned(left.type)) { switch (op_kind) { @@ -4453,7 +5754,7 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri } res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, ""); } else { - GB_PANIC("Unhandled comparison kind"); + GB_PANIC("Unhandled comparison kind %s %.*s %s", type_to_string(left.type), LIT(token_strings[op_kind]), type_to_string(right.type)); } return res; @@ -4515,6 +5816,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { } + switch (expr->kind) { case_ast_node(bl, BasicLit, expr); TokenPos pos = bl->token.pos; @@ -4530,8 +5832,16 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { return lb_addr_load(p, lb_build_addr(p, expr)); case_end; - case_ast_node(u, Undef, expr); - return lbValue{LLVMGetUndef(lb_type(m, tv.type)), tv.type}; + case_ast_node(u, Undef, expr) + lbValue res = {}; + if (is_type_untyped(tv.type)) { + res.value = nullptr; + res.type = t_untyped_undef; + } else { + res.value = LLVMGetUndef(lb_type(m, tv.type)); + res.type = tv.type; + } + return res; case_end; case_ast_node(i, Ident, expr); @@ -4549,6 +5859,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { res.type = e->type; return res; } + GB_ASSERT(e->kind != Entity_ProcGroup); auto *found = map_get(&p->module->values, hash_entity(e)); if (found) { @@ -4561,7 +5872,8 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { } else if (e != nullptr && e->kind == Entity_Variable) { return lb_addr_load(p, lb_build_addr(p, expr)); } - GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s : %s @ %p", LIT(e->pkg->name), LIT(i->token.string), type_to_string(e->type), expr); + gb_printf_err("Error in: %.*s(%td:%td)\n", LIT(p->name), i->token.pos.line, i->token.pos.column); + GB_PANIC("nullptr value for expression from identifier: %.*s.%.*s (%p) : %s @ %p", LIT(e->pkg->name), LIT(e->token.string), e, type_to_string(e->type), expr); return {}; case_end; @@ -4655,82 +5967,82 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { case_end; case_ast_node(ue, UnaryExpr, expr); - #if 0 switch (ue->op.kind) { case Token_And: { Ast *ue_expr = unparen_expr(ue->expr); - if (ue_expr->kind == Ast_TypeAssertion) { - gbAllocator a = heap_allocator(); - GB_ASSERT(is_type_pointer(tv.type)); - - ast_node(ta, TypeAssertion, ue_expr); - TokenPos pos = ast_token(expr).pos; - Type *type = type_of_expr(ue_expr); - GB_ASSERT(!is_type_tuple(type)); - - lbValue e = lb_build_expr(p, ta->expr); - Type *t = type_deref(e.type); - if (is_type_union(t)) { - lbValue v = e; - if (!is_type_pointer(v.type)) { - v = lb_address_from_load_or_generate_local(p, v); - } - Type *src_type = type_deref(v.type); - Type *dst_type = type; - - lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v)); - lbValue dst_tag = lb_const_union_tag(src_type, dst_type); - - lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag); - auto args = array_make(heap_allocator(), 6); - args[0] = ok; - - args[1] = lb_find_or_add_entity_string(p->module, pos.file); - args[2] = lb_const_int(pos.line); - args[3] = lb_const_int(pos.column); - - args[4] = lb_typeid(p->module, src_type); - args[5] = lb_typeid(p->module, dst_type); - lb_emit_runtime_call(p, "type_assertion_check", args); - - lbValue data_ptr = v; - return ir_emit_conv(p, data_ptr, tv.type); - } else if (is_type_any(t)) { - lbValue v = e; - if (is_type_pointer(ir_type(v))) { - v = ir_emit_load(p, v); - } - - lbValue data_ptr = ir_emit_struct_ev(p, v, 0); - lbValue any_id = ir_emit_struct_ev(p, v, 1); - lbValue id = lb_typeid(p->module, type); - - - lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id); - auto args = array_make(ir_allocator(), 6); - args[0] = ok; - - args[1] = lb_find_or_add_entity_string(p->module, pos.file); - args[2] = lb_const_int(pos.line); - args[3] = ir_const_int(pos.column); - - args[4] = any_id; - args[5] = id; - lb_emit_runtime_call(p, "type_assertion_check", args); - - return ir_emit_conv(p, data_ptr, tv.type); - } else { - GB_PANIC("TODO(bill): type assertion %s", type_to_string(type)); - } - } else if (ue_expr->kind == Ast_IndexExpr) { - } + // if (ue_expr->kind == Ast_TypeAssertion) { + // gbAllocator a = heap_allocator(); + // GB_ASSERT(is_type_pointer(tv.type)); + + // ast_node(ta, TypeAssertion, ue_expr); + // TokenPos pos = ast_token(expr).pos; + // Type *type = type_of_expr(ue_expr); + // GB_ASSERT(!is_type_tuple(type)); + + // lbValue e = lb_build_expr(p, ta->expr); + // Type *t = type_deref(e.type); + // if (is_type_union(t)) { + // lbValue v = e; + // if (!is_type_pointer(v.type)) { + // v = lb_address_from_load_or_generate_local(p, v); + // } + // Type *src_type = type_deref(v.type); + // Type *dst_type = type; + + // lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v)); + // lbValue dst_tag = lb_const_union_tag(src_type, dst_type); + + // lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag); + // auto args = array_make(heap_allocator(), 6); + // args[0] = ok; + + // args[1] = lb_find_or_add_entity_string(p->module, pos.file); + // args[2] = lb_const_int(pos.line); + // args[3] = lb_const_int(pos.column); + + // args[4] = lb_typeid(p->module, src_type); + // args[5] = lb_typeid(p->module, dst_type); + // lb_emit_runtime_call(p, "type_assertion_check", args); + + // lbValue data_ptr = v; + // return lb_emit_conv(p, data_ptr, tv.type); + // } else if (is_type_any(t)) { + // lbValue v = e; + // if (is_type_pointer(ir_type(v))) { + // v = lb_emit_load(p, v); + // } + + // lbValue data_ptr = lb_emit_struct_ev(p, v, 0); + // lbValue any_id = lb_emit_struct_ev(p, v, 1); + // lbValue id = lb_typeid(p->module, type); + + + // lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id); + // auto args = array_make(heap_allocator(), 6); + // args[0] = ok; + + // args[1] = lb_find_or_add_entity_string(p->module, pos.file); + // args[2] = lb_const_int(pos.line); + // args[3] = lb_const_int(pos.column); + + // args[4] = any_id; + // args[5] = id; + // lb_emit_runtime_call(p, "type_assertion_check", args); + + // return lb_emit_conv(p, data_ptr, tv.type); + // } else { + // GB_PANIC("TODO(bill): type assertion %s", type_to_string(type)); + // } + // } return lb_build_addr_ptr(p, ue->expr); } default: - return lb_emit_unary_arith(p, ue->op.kind, lb_build_expr(p, ue->expr), tv.type); + { + lbValue v = lb_build_expr(p, ue->expr); + return lb_emit_unary_arith(p, ue->op.kind, v, tv.type); + } } - #endif case_end; case_ast_node(be, BinaryExpr, expr); @@ -4835,7 +6147,6 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } String name = i->token.string; Entity *e = entity_of_ident(expr); - // GB_ASSERT(name == e->token.string); return lb_build_addr_from_entity(p, e, expr); case_end; @@ -4863,17 +6174,17 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT(e->flags & EntityFlag_TypeField); String name = e->token.string; /*if (name == "names") { - lbValue ti_ptr = ir_type_info(proc, type); - lbValue variant = ir_emit_struct_ep(proc, ti_ptr, 2); + lbValue ti_ptr = lb_type_info(p, type); + lbValue variant = ir_emit_struct_ep(p, ti_ptr, 2); lbValue names_ptr = nullptr; if (is_type_enum(type)) { - lbValue enum_info = lb_emit_conv(proc, variant, t_type_info_enum_ptr); - names_ptr = ir_emit_struct_ep(proc, enum_info, 1); + lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr); + names_ptr = ir_emit_struct_ep(p, enum_info, 1); } else if (type->kind == Type_Struct) { - lbValue struct_info = lb_emit_conv(proc, variant, t_type_info_struct_ptr); - names_ptr = ir_emit_struct_ep(proc, struct_info, 1); + lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr); + names_ptr = ir_emit_struct_ep(p, struct_info, 1); } return ir_addr(names_ptr); } else */{ @@ -4954,44 +6265,43 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { case_ast_node(ta, TypeAssertion, expr); gbAllocator a = heap_allocator(); TokenPos pos = ast_token(expr).pos; - lbValue e = ir_build_expr(proc, ta->expr); + lbValue e = lb_build_expr(proc, ta->expr); Type *t = type_deref(ir_type(e)); if (is_type_union(t)) { Type *type = type_of_expr(expr); lbValue v = lb_add_local_generated(proc, type, false); ir_emit_comment(proc, str_lit("cast - union_cast")); - ir_emit_store(proc, v, ir_emit_union_cast(proc, ir_build_expr(proc, ta->expr), type, pos)); + lb_emit_store(proc, v, ir_emit_union_cast(proc, lb_build_expr(proc, ta->expr), type, pos)); return ir_addr(v); } else if (is_type_any(t)) { ir_emit_comment(proc, str_lit("cast - any_cast")); Type *type = type_of_expr(expr); - return ir_emit_any_cast_addr(proc, ir_build_expr(proc, ta->expr), type, pos); + return ir_emit_any_cast_addr(proc, lb_build_expr(proc, ta->expr), type, pos); } else { GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e))); } case_end; +#endif case_ast_node(ue, UnaryExpr, expr); switch (ue->op.kind) { case Token_And: { - return ir_build_addr(proc, ue->expr); + return lb_build_addr(p, ue->expr); } default: - GB_PANIC("Invalid unary expression for ir_build_addr"); + GB_PANIC("Invalid unary expression for lb_build_addr"); } case_end; - case_ast_node(be, BinaryExpr, expr); - lbValue v = ir_build_expr(proc, expr); - Type *t = ir_type(v); + lbValue v = lb_build_expr(p, expr); + Type *t = v.type; if (is_type_pointer(t)) { - return ir_addr(v); + return lb_addr(v); } - return ir_addr(ir_address_from_load_or_generate_local(proc, v)); + return lb_addr(lb_address_from_load_or_generate_local(p, v)); case_end; case_ast_node(ie, IndexExpr, expr); - ir_emit_comment(proc, str_lit("IndexExpr")); Type *t = base_type(type_of_expr(ie->expr)); gbAllocator a = heap_allocator(); @@ -4999,92 +6309,95 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { t = base_type(type_deref(t)); if (is_type_soa_struct(t)) { // SOA STRUCTURES!!!! - lbValue val = ir_build_addr_ptr(proc, ie->expr); - if (deref) { - val = ir_emit_load(proc, val); - } + GB_PANIC("SOA STRUCTURES!!!!"); + // lbValue val = lb_build_addr_ptr(p, ie->expr); + // if (deref) { + // val = lb_emit_load(p, val); + // } - lbValue index = ir_build_expr(proc, ie->index); - return ir_addr_soa_variable(val, index, ie->index); + // lbValue index = lb_build_expr(p, ie->index); + // return lb_addr_soa_variable(val, index, ie->index); } if (ie->expr->tav.mode == Addressing_SoaVariable) { // SOA Structures for slices/dynamic arrays GB_ASSERT(is_type_pointer(type_of_expr(ie->expr))); - lbValue field = ir_build_expr(proc, ie->expr); - lbValue index = ir_build_expr(proc, ie->index); + lbValue field = lb_build_expr(p, ie->expr); + lbValue index = lb_build_expr(p, ie->index); if (!build_context.no_bounds_check) { - // TODO HACK(bill): Clean up this hack to get the length for bounds checking - GB_ASSERT(field->kind == irValue_Instr); - irInstr *instr = &field->Instr; + GB_PANIC("HERE"); + // // TODO HACK(bill): Clean up this hack to get the length for bounds checking + // GB_ASSERT(LLVMIsALoadInst(field.value)); - GB_ASSERT(instr->kind == irInstr_Load); - lbValue a = instr->Load.address; + // lbValue a = {}; + // a.value = LLVMGetOperand(field.value, 0); + // a.type = alloc_type_pointer(field.type); - GB_ASSERT(a->kind == irValue_Instr); - irInstr *b = &a->Instr; - GB_ASSERT(b->kind == irInstr_StructElementPtr); - lbValue base_struct = b->StructElementPtr.address; + // irInstr *b = &a->Instr; + // GB_ASSERT(b->kind == irInstr_StructElementPtr); + // lbValue base_struct = b->StructElementPtr.address; - GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct)))); - lbValue len = ir_soa_struct_len(proc, base_struct); - ir_emit_bounds_check(proc, ast_token(ie->index), index, len); + // GB_ASSERT(is_type_soa_struct(type_deref(ir_type(base_struct)))); + // lbValue len = ir_soa_struct_len(p, base_struct); + // ir_emit_bounds_check(p, ast_token(ie->index), index, len); } - lbValue val = ir_emit_ptr_offset(proc, field, index); - return ir_addr(val); + lbValue val = lb_emit_ptr_offset(p, field, index); + return lb_addr(val); } GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr)); if (is_type_map(t)) { - lbValue map_val = ir_build_addr_ptr(proc, ie->expr); - if (deref) { - map_val = ir_emit_load(proc, map_val); - } + GB_PANIC("map index"); + // lbValue map_val = lb_build_addr_ptr(p, ie->expr); + // if (deref) { + // map_val = lb_emit_load(p, map_val); + // } - lbValue key = ir_build_expr(proc, ie->index); - key = lb_emit_conv(proc, key, t->Map.key); + // lbValue key = lb_build_expr(p, ie->index); + // key = lb_emit_conv(p, key, t->Map.key); - Type *result_type = type_of_expr(expr); - return ir_addr_map(map_val, key, t, result_type); + // Type *result_type = type_of_expr(expr); + // return lb_addr_map(map_val, key, t, result_type); } - lbValue using_addr = nullptr; + lbValue using_addr = {}; switch (t->kind) { case Type_Array: { - lbValue array = nullptr; - if (using_addr != nullptr) { + lbValue array = {}; + if (using_addr.value != nullptr) { array = using_addr; } else { - array = ir_build_addr_ptr(proc, ie->expr); + array = lb_build_addr_ptr(p, ie->expr); if (deref) { - array = ir_emit_load(proc, array); + array = lb_emit_load(p, array); } } - lbValue index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); - lbValue elem = ir_emit_array_ep(proc, array, index); + lbValue index = lb_build_expr(p, ie->index); + index = lb_emit_conv(p, index, t_int); + lbValue elem = lb_emit_array_ep(p, array, index); auto index_tv = type_and_value_of_expr(ie->index); if (index_tv.mode != Addressing_Constant) { - lbValue len = ir_const_int(t->Array.count); - ir_emit_bounds_check(proc, ast_token(ie->index), index, len); + // lbValue len = lb_const_int(p->module, t_int, t->Array.count); + // ir_emit_bounds_check(p, ast_token(ie->index), index, len); } - return ir_addr(elem); + return lb_addr(elem); } case Type_EnumeratedArray: { - lbValue array = nullptr; - if (using_addr != nullptr) { + lbValue array = {}; + if (using_addr.value != nullptr) { array = using_addr; } else { - array = ir_build_addr_ptr(proc, ie->expr); + array = lb_build_addr_ptr(p, ie->expr); if (deref) { - array = ir_emit_load(proc, array); + array = lb_emit_load(p, array); } } @@ -5092,62 +6405,62 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { auto index_tv = type_and_value_of_expr(ie->index); - lbValue index = nullptr; + lbValue index = {}; if (compare_exact_values(Token_NotEq, t->EnumeratedArray.min_value, exact_value_i64(0))) { if (index_tv.mode == Addressing_Constant) { ExactValue idx = exact_value_sub(index_tv.value, t->EnumeratedArray.min_value); - index = ir_value_constant(index_type, idx); + index = lb_const_value(p->module, index_type, idx); } else { - index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); - index = ir_emit_arith(proc, Token_Sub, index, ir_value_constant(index_type, t->EnumeratedArray.min_value), index_type); + index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int); + index = lb_emit_arith(p, Token_Sub, index, lb_const_value(p->module, index_type, t->EnumeratedArray.min_value), index_type); } } else { - index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); + index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int); } - lbValue elem = ir_emit_array_ep(proc, array, index); + lbValue elem = lb_emit_array_ep(p, array, index); if (index_tv.mode != Addressing_Constant) { - lbValue len = ir_const_int(t->EnumeratedArray.count); - ir_emit_bounds_check(proc, ast_token(ie->index), index, len); + // lbValue len = ir_const_int(t->EnumeratedArray.count); + // ir_emit_bounds_check(p, ast_token(ie->index), index, len); } - return ir_addr(elem); + return lb_addr(elem); } case Type_Slice: { - lbValue slice = nullptr; - if (using_addr != nullptr) { - slice = ir_emit_load(proc, using_addr); + lbValue slice = {}; + if (using_addr.value != nullptr) { + slice = lb_emit_load(p, using_addr); } else { - slice = ir_build_expr(proc, ie->expr); + slice = lb_build_expr(p, ie->expr); if (deref) { - slice = ir_emit_load(proc, slice); + slice = lb_emit_load(p, slice); } } - lbValue elem = ir_slice_elem(proc, slice); - lbValue index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); - lbValue len = ir_slice_len(proc, slice); - ir_emit_bounds_check(proc, ast_token(ie->index), index, len); - lbValue v = ir_emit_ptr_offset(proc, elem, index); - return ir_addr(v); + 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); + // ir_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_DynamicArray: { - lbValue dynamic_array = nullptr; - if (using_addr != nullptr) { - dynamic_array = ir_emit_load(proc, using_addr); + lbValue dynamic_array = {}; + if (using_addr.value != nullptr) { + dynamic_array = lb_emit_load(p, using_addr); } else { - dynamic_array = ir_build_expr(proc, ie->expr); + dynamic_array = lb_build_expr(p, ie->expr); if (deref) { - dynamic_array = ir_emit_load(proc, dynamic_array); + dynamic_array = lb_emit_load(p, dynamic_array); } } - lbValue elem = ir_dynamic_array_elem(proc, dynamic_array); - lbValue len = ir_dynamic_array_len(proc, dynamic_array); - lbValue index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); - ir_emit_bounds_check(proc, ast_token(ie->index), index, len); - lbValue v = ir_emit_ptr_offset(proc, elem, index); - return ir_addr(v); + lbValue elem = lb_dynamic_array_elem(p, dynamic_array); + lbValue len = lb_dynamic_array_len(p, dynamic_array); + lbValue index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int); + // lb_emit_bounds_check(p, ast_token(ie->index), index, len); + lbValue v = lb_emit_ptr_offset(p, elem, index); + return lb_addr(v); } @@ -5157,180 +6470,182 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue len; lbValue index; - if (using_addr != nullptr) { - str = ir_emit_load(proc, using_addr); + if (using_addr.value != nullptr) { + str = lb_emit_load(p, using_addr); } else { - str = ir_build_expr(proc, ie->expr); + str = lb_build_expr(p, ie->expr); if (deref) { - str = ir_emit_load(proc, str); + str = lb_emit_load(p, str); } } - elem = ir_string_elem(proc, str); - len = ir_string_len(proc, str); + elem = lb_string_elem(p, str); + len = lb_string_len(p, str); - index = lb_emit_conv(proc, ir_build_expr(proc, ie->index), t_int); - ir_emit_bounds_check(proc, ast_token(ie->index), index, len); + index = lb_emit_conv(p, lb_build_expr(p, ie->index), t_int); + // lb_emit_bounds_check(p, ast_token(ie->index), index, len); - return ir_addr(ir_emit_ptr_offset(proc, elem, index)); + return lb_addr(lb_emit_ptr_offset(p, elem, index)); } } case_end; case_ast_node(se, SliceExpr, expr); - ir_emit_comment(proc, str_lit("SliceExpr")); gbAllocator a = heap_allocator(); - lbValue low = v_zero; - lbValue high = nullptr; + lbValue low = lb_const_int(p->module, t_int, 0); + lbValue high = {}; - if (se->low != nullptr) low = ir_build_expr(proc, se->low); - if (se->high != nullptr) high = ir_build_expr(proc, se->high); + if (se->low != nullptr) low = lb_build_expr(p, se->low); + if (se->high != nullptr) high = lb_build_expr(p, se->high); bool no_indices = se->low == nullptr && se->high == nullptr; - lbValue addr = ir_build_addr_ptr(proc, se->expr); - lbValue base = ir_emit_load(proc, addr); - Type *type = base_type(ir_type(base)); + lbValue addr = lb_build_addr_ptr(p, se->expr); + lbValue base = lb_emit_load(p, addr); + Type *type = base_type(base.type); if (is_type_pointer(type)) { type = base_type(type_deref(type)); addr = base; - base = ir_emit_load(proc, base); + base = lb_emit_load(p, base); } // TODO(bill): Cleanup like mad! switch (type->kind) { case Type_Slice: { Type *slice_type = type; - lbValue len = ir_slice_len(proc, base); - if (high == nullptr) high = len; + lbValue len = lb_slice_len(p, base); + if (high.value == nullptr) high = len; if (!no_indices) { - ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); + // ir_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); } - lbValue elem = ir_emit_ptr_offset(proc, ir_slice_elem(proc, base), low); - lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + lbValue elem = lb_emit_ptr_offset(p, lb_slice_elem(p, base), low); + lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); - lbValue slice = lb_add_local_generated(proc, slice_type, false); - ir_fill_slice(proc, slice, elem, new_len); - return ir_addr(slice); + lbAddr slice = lb_add_local_generated(p, slice_type, false); + lb_fill_slice(p, slice, elem, new_len); + return slice; } case Type_DynamicArray: { Type *elem_type = type->DynamicArray.elem; Type *slice_type = alloc_type_slice(elem_type); - lbValue len = ir_dynamic_array_len(proc, base); - if (high == nullptr) high = len; + lbValue len = lb_dynamic_array_len(p, base); + if (high.value == nullptr) high = len; if (!no_indices) { - ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); } - lbValue elem = ir_emit_ptr_offset(proc, ir_dynamic_array_elem(proc, base), low); - lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + 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); - lbValue slice = lb_add_local_generated(proc, slice_type, false); - ir_fill_slice(proc, slice, elem, new_len); - return ir_addr(slice); + lbAddr slice = lb_add_local_generated(p, slice_type, false); + lb_fill_slice(p, slice, elem, new_len); + return slice; } case Type_Array: { Type *slice_type = alloc_type_slice(type->Array.elem); - lbValue len = ir_array_len(proc, base); + lbValue len = lb_const_int(p->module, t_int, type->Array.count); - if (high == nullptr) high = len; + 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) { - ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); } } - lbValue elem = ir_emit_ptr_offset(proc, ir_array_elem(proc, addr), low); - lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + lbValue elem = lb_emit_ptr_offset(p, lb_array_elem(p, addr), low); + lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); - lbValue slice = lb_add_local_generated(proc, slice_type, false); - ir_fill_slice(proc, slice, elem, new_len); - return ir_addr(slice); + lbAddr slice = lb_add_local_generated(p, slice_type, false); + lb_fill_slice(p, slice, elem, new_len); + return slice; } case Type_Basic: { GB_ASSERT(type == t_string); - lbValue len = ir_string_len(proc, base); - if (high == nullptr) high = len; + lbValue len = lb_string_len(p, base); + if (high.value == nullptr) high = len; if (!no_indices) { - ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); } - lbValue elem = ir_emit_ptr_offset(proc, ir_string_elem(proc, base), low); - lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); + 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); - lbValue str = lb_add_local_generated(proc, t_string, false); - ir_fill_string(proc, str, elem, new_len); - return ir_addr(str); + lbAddr str = lb_add_local_generated(p, t_string, false); + lb_fill_string(p, str, elem, new_len); + return str; } case Type_Struct: if (is_type_soa_struct(type)) { - lbValue len = ir_soa_struct_len(proc, addr); - if (high == nullptr) high = len; + lbValue len = lb_soa_struct_len(p, addr); + if (high.value == nullptr) high = len; if (!no_indices) { - ir_emit_slice_bounds_check(proc, se->open, low, high, len, se->low != nullptr); + // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); } + GB_PANIC("#soa struct slice"); + #if 0 - lbValue dst = lb_add_local_generated(proc, type_of_expr(expr), true); + 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 = ir_emit_struct_ep(proc, dst, i); - lbValue field_src = ir_emit_struct_ep(proc, addr, i); - field_src = ir_emit_array_ep(proc, field_src, low); - ir_emit_store(proc, field_dst, field_src); + lbValue field_dst = lb_emit_struct_ep(p, dst, i); + lbValue field_src = lb_emit_struct_ep(p, addr, i); + field_src = lb_emit_array_ep(p, field_src, low); + lb_emit_store(p, field_dst, field_src); } - lbValue len_dst = ir_emit_struct_ep(proc, dst, field_count); - lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); - ir_emit_store(proc, len_dst, new_len); + lbValue len_dst = lb_emit_struct_ep(p, dst, 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) { - ir_emit_store(proc, dst, base); + lb_emit_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 = ir_emit_struct_ep(proc, dst, i); - lbValue field_src = ir_emit_struct_ev(proc, base, i); - field_src = ir_emit_ptr_offset(proc, field_src, low); - ir_emit_store(proc, field_dst, field_src); + lbValue field_dst = lb_emit_struct_ep(p, dst, 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 = ir_emit_struct_ep(proc, dst, field_count); - lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); - ir_emit_store(proc, len_dst, new_len); + lbValue len_dst = lb_emit_struct_ep(p, dst, 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 = ir_emit_struct_ep(proc, dst, i); - lbValue field_src = ir_emit_struct_ev(proc, base, i); - field_src = ir_emit_ptr_offset(proc, field_src, low); - ir_emit_store(proc, field_dst, field_src); + lbValue field_dst = lb_emit_struct_ep(p, dst, 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 = ir_emit_struct_ep(proc, dst, field_count); - lbValue new_len = ir_emit_arith(proc, Token_Sub, high, low, t_int); - ir_emit_store(proc, len_dst, new_len); + lbValue len_dst = lb_emit_struct_ep(p, dst, field_count); + lbValue new_len = lb_emit_arith(p, Token_Sub, high, low, t_int); + lb_emit_store(p, len_dst, new_len); } - return ir_addr(dst); + return dst; + #endif } break; @@ -5341,38 +6656,36 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { case_ast_node(de, DerefExpr, expr); // TODO(bill): Is a ptr copy needed? - lbValue addr = ir_build_expr(proc, de->expr); - addr = ir_emit_ptr_offset(proc, addr, v_zero); - return ir_addr(addr); + lbValue addr = lb_build_expr(p, de->expr); + return lb_addr(addr); case_end; case_ast_node(ce, CallExpr, expr); // NOTE(bill): This is make sure you never need to have an 'array_ev' - lbValue e = ir_build_expr(proc, expr); - lbValue v = lb_add_local_generated(proc, ir_type(e), false); - ir_emit_store(proc, v, e); - return ir_addr(v); + lbValue e = lb_build_expr(p, expr); + lbAddr v = lb_add_local_generated(p, e.type, false); + lb_addr_store(p, v, e); + return v; case_end; case_ast_node(cl, CompoundLit, expr); - ir_emit_comment(proc, str_lit("CompoundLit")); Type *type = type_of_expr(expr); Type *bt = base_type(type); - lbValue v = lb_add_local_generated(proc, type, true); + lbAddr v = lb_add_local_generated(p, type, true); Type *et = nullptr; switch (bt->kind) { - case Type_Array: et = bt->Array.elem; break; + 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_Slice: et = bt->Slice.elem; break; + case Type_BitSet: et = bt->BitSet.elem; break; + case Type_SimdVector: et = bt->SimdVector.elem; break; } String proc_name = {}; - if (proc->entity) { - proc_name = proc->entity->token.string; + if (p->entity) { + proc_name = p->entity->token.string; } TokenPos pos = ast_token(expr).pos; @@ -5387,11 +6700,11 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT(is_type_struct(bt) || is_raw_union); TypeStruct *st = &bt->Struct; if (cl->elems.count > 0) { - ir_emit_store(proc, v, lb_const_value(proc->module, type, exact_value_compound(expr))); + lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr))); for_array(field_index, cl->elems) { Ast *elem = cl->elems[field_index]; - lbValue field_expr = nullptr; + lbValue field_expr = {}; Entity *field = nullptr; isize index = field_index; @@ -5410,26 +6723,27 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { field = st->fields[index]; Type *ft = field->type; - if (!is_raw_union && !is_type_typeid(ft) && ir_is_elem_const(proc->module, elem, ft)) { + if (!is_raw_union && !is_type_typeid(ft) && lb_is_elem_const(elem, ft)) { continue; } - field_expr = ir_build_expr(proc, elem); + field_expr = lb_build_expr(p, elem); - GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple); + Type *fet = field_expr.type; + GB_ASSERT(fet->kind != Type_Tuple); - Type *fet = ir_type(field_expr); // 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)); - lbValue gep = ir_emit_struct_ep(proc, v, cast(i32)index); - ir_emit_store_union_variant(proc, gep, field_expr, fet); + lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index); + // TODO(bill): lb_emit_store_union_variant + // lb_emit_store_union_variant(p, gep, field_expr, fet); } else { - lbValue fv = lb_emit_conv(proc, field_expr, ft); - lbValue gep = ir_emit_struct_ep(proc, v, cast(i32)index); - ir_emit_store(proc, gep, fv); + lbValue fv = lb_emit_conv(p, field_expr, ft); + lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index); + lb_emit_store(p, gep, fv); } } } @@ -5440,30 +6754,31 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (cl->elems.count == 0) { break; } - gbAllocator a = heap_allocator(); - { - auto args = array_make(a, 3); - args[0] = ir_gen_map_header(proc, v, type); - args[1] = ir_const_int(2*cl->elems.count); - args[2] = ir_emit_source_code_location(proc, proc_name, pos); - lb_emit_runtime_call(proc, "__dynamic_map_reserve", args); - } - for_array(field_index, cl->elems) { - Ast *elem = cl->elems[field_index]; - ast_node(fv, FieldValue, elem); + // TODO(bill): Map CompoundLit + // gbAllocator a = heap_allocator(); + // { + // auto args = array_make(a, 3); + // args[0] = ir_gen_map_header(proc, v, type); + // args[1] = ir_const_int(2*cl->elems.count); + // args[2] = ir_emit_source_code_location(proc, proc_name, pos); + // lb_emit_runtime_call(proc, "__dynamic_map_reserve", args); + // } + // for_array(field_index, cl->elems) { + // Ast *elem = cl->elems[field_index]; + // ast_node(fv, FieldValue, elem); - lbValue key = ir_build_expr(proc, fv->field); - lbValue value = ir_build_expr(proc, fv->value); - ir_insert_dynamic_map_key_and_value(proc, v, type, key, value); - } + // lbValue key = lb_build_expr(proc, fv->field); + // lbValue value = lb_build_expr(proc, fv->value); + // ir_insert_dynamic_map_key_and_value(proc, v, type, key, value); + // } break; } case Type_Array: { if (cl->elems.count > 0) { - ir_emit_store(proc, v, lb_const_value(proc->module, type, exact_value_compound(expr))); + lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr))); - auto temp_data = array_make(heap_allocator(), 0, cl->elems.count); + auto temp_data = array_make(heap_allocator(), 0, cl->elems.count); defer (array_free(&temp_data)); // NOTE(bill): Separate value, gep, store into their own chunks @@ -5471,7 +6786,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { Ast *elem = cl->elems[i]; if (elem->kind == Ast_FieldValue) { ast_node(fv, FieldValue, elem); - if (ir_is_elem_const(proc->module, fv->value, et)) { + if (lb_is_elem_const(fv->value, et)) { continue; } if (is_ast_range(fv->field)) { @@ -5488,10 +6803,10 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { hi += 1; } - lbValue value = ir_build_expr(proc, fv->value); + lbValue value = lb_build_expr(p, fv->value); for (i64 k = lo; k < hi; k++) { - irCompoundLitElemTempData data = {}; + lbCompoundLitElemTempData data = {}; data.value = value; data.elem_index = cast(i32)k; array_add(&temp_data, data); @@ -5502,18 +6817,19 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT(tav.mode == Addressing_Constant); i64 index = exact_value_to_i64(tav.value); - irCompoundLitElemTempData data = {}; - data.value = lb_emit_conv(proc, ir_build_expr(proc, fv->value), et); + lbValue value = lb_build_expr(p, fv->value); + lbCompoundLitElemTempData data = {}; + data.value = lb_emit_conv(p, value, et); data.expr = fv->value; data.elem_index = cast(i32)index; array_add(&temp_data, data); } } else { - if (ir_is_elem_const(proc->module, elem, et)) { + if (lb_is_elem_const(elem, et)) { continue; } - irCompoundLitElemTempData data = {}; + lbCompoundLitElemTempData data = {}; data.expr = elem; data.elem_index = cast(i32)i; array_add(&temp_data, data); @@ -5521,38 +6837,38 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } for_array(i, temp_data) { - temp_data[i].gep = ir_emit_array_epi(proc, v, temp_data[i].elem_index); + temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), temp_data[i].elem_index); } for_array(i, temp_data) { - auto return_ptr_hint_ast = proc->return_ptr_hint_ast; - auto return_ptr_hint_value = proc->return_ptr_hint_value; - auto return_ptr_hint_used = proc->return_ptr_hint_used; - defer (proc->return_ptr_hint_ast = return_ptr_hint_ast); - defer (proc->return_ptr_hint_value = return_ptr_hint_value); - defer (proc->return_ptr_hint_used = return_ptr_hint_used); + auto return_ptr_hint_ast = p->return_ptr_hint_ast; + auto return_ptr_hint_value = p->return_ptr_hint_value; + auto return_ptr_hint_used = p->return_ptr_hint_used; + defer (p->return_ptr_hint_ast = return_ptr_hint_ast); + defer (p->return_ptr_hint_value = return_ptr_hint_value); + defer (p->return_ptr_hint_used = return_ptr_hint_used); lbValue field_expr = temp_data[i].value; Ast *expr = temp_data[i].expr; - proc->return_ptr_hint_value = temp_data[i].gep; - proc->return_ptr_hint_ast = unparen_expr(expr); + p->return_ptr_hint_value = temp_data[i].gep; + p->return_ptr_hint_ast = unparen_expr(expr); - if (field_expr == nullptr) { - field_expr = ir_build_expr(proc, expr); + if (field_expr.value == nullptr) { + field_expr = lb_build_expr(p, expr); } - Type *t = ir_type(field_expr); + Type *t = field_expr.type; GB_ASSERT(t->kind != Type_Tuple); - lbValue ev = lb_emit_conv(proc, field_expr, et); + lbValue ev = lb_emit_conv(p, field_expr, et); - if (!proc->return_ptr_hint_used) { + if (!p->return_ptr_hint_used) { temp_data[i].value = ev; } } for_array(i, temp_data) { - if (temp_data[i].value != nullptr) { - ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false); + if (temp_data[i].value.value != nullptr) { + lb_emit_store(p, temp_data[i].gep, temp_data[i].value); } } } @@ -5560,9 +6876,9 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } case Type_EnumeratedArray: { if (cl->elems.count > 0) { - ir_emit_store(proc, v, lb_const_value(proc->module, type, exact_value_compound(expr))); + lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr))); - auto temp_data = array_make(heap_allocator(), 0, cl->elems.count); + auto temp_data = array_make(heap_allocator(), 0, cl->elems.count); defer (array_free(&temp_data)); // NOTE(bill): Separate value, gep, store into their own chunks @@ -5570,7 +6886,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { Ast *elem = cl->elems[i]; if (elem->kind == Ast_FieldValue) { ast_node(fv, FieldValue, elem); - if (ir_is_elem_const(proc->module, fv->value, et)) { + if (lb_is_elem_const(fv->value, et)) { continue; } if (is_ast_range(fv->field)) { @@ -5587,10 +6903,10 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { hi += 1; } - lbValue value = ir_build_expr(proc, fv->value); + lbValue value = lb_build_expr(p, fv->value); for (i64 k = lo; k < hi; k++) { - irCompoundLitElemTempData data = {}; + lbCompoundLitElemTempData data = {}; data.value = value; data.elem_index = cast(i32)k; array_add(&temp_data, data); @@ -5601,18 +6917,19 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT(tav.mode == Addressing_Constant); i64 index = exact_value_to_i64(tav.value); - irCompoundLitElemTempData data = {}; - data.value = lb_emit_conv(proc, ir_build_expr(proc, fv->value), et); + lbValue value = lb_build_expr(p, fv->value); + lbCompoundLitElemTempData data = {}; + data.value = lb_emit_conv(p, value, et); data.expr = fv->value; data.elem_index = cast(i32)index; array_add(&temp_data, data); } } else { - if (ir_is_elem_const(proc->module, elem, et)) { + if (lb_is_elem_const(elem, et)) { continue; } - irCompoundLitElemTempData data = {}; + lbCompoundLitElemTempData data = {}; data.expr = elem; data.elem_index = cast(i32)i; array_add(&temp_data, data); @@ -5624,38 +6941,38 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { for_array(i, temp_data) { i32 index = temp_data[i].elem_index - index_offset; - temp_data[i].gep = ir_emit_array_epi(proc, v, index); + temp_data[i].gep = lb_emit_array_epi(p, lb_addr_get_ptr(p, v), index); } for_array(i, temp_data) { - auto return_ptr_hint_ast = proc->return_ptr_hint_ast; - auto return_ptr_hint_value = proc->return_ptr_hint_value; - auto return_ptr_hint_used = proc->return_ptr_hint_used; - defer (proc->return_ptr_hint_ast = return_ptr_hint_ast); - defer (proc->return_ptr_hint_value = return_ptr_hint_value); - defer (proc->return_ptr_hint_used = return_ptr_hint_used); + auto return_ptr_hint_ast = p->return_ptr_hint_ast; + auto return_ptr_hint_value = p->return_ptr_hint_value; + auto return_ptr_hint_used = p->return_ptr_hint_used; + defer (p->return_ptr_hint_ast = return_ptr_hint_ast); + defer (p->return_ptr_hint_value = return_ptr_hint_value); + defer (p->return_ptr_hint_used = return_ptr_hint_used); lbValue field_expr = temp_data[i].value; Ast *expr = temp_data[i].expr; - proc->return_ptr_hint_value = temp_data[i].gep; - proc->return_ptr_hint_ast = unparen_expr(expr); + p->return_ptr_hint_value = temp_data[i].gep; + p->return_ptr_hint_ast = unparen_expr(expr); - if (field_expr == nullptr) { - field_expr = ir_build_expr(proc, expr); + if (field_expr.value == nullptr) { + field_expr = lb_build_expr(p, expr); } - Type *t = ir_type(field_expr); + Type *t = field_expr.type; GB_ASSERT(t->kind != Type_Tuple); - lbValue ev = lb_emit_conv(proc, field_expr, et); + lbValue ev = lb_emit_conv(p, field_expr, et); - if (!proc->return_ptr_hint_used) { + if (!p->return_ptr_hint_used) { temp_data[i].value = ev; } } for_array(i, temp_data) { - if (temp_data[i].value != nullptr) { - ir_emit_store(proc, temp_data[i].gep, temp_data[i].value, false); + if (temp_data[i].value.value != nullptr) { + lb_emit_store(p, temp_data[i].gep, temp_data[i].value); } } } @@ -5666,12 +6983,11 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { Type *elem_type = bt->Slice.elem; Type *elem_ptr_type = alloc_type_pointer(elem_type); Type *elem_ptr_ptr_type = alloc_type_pointer(elem_ptr_type); - lbValue slice = lb_const_value(proc->module, type, exact_value_compound(expr)); - GB_ASSERT(slice->kind == irValue_ConstantSlice); + lbValue slice = lb_const_value(p->module, type, exact_value_compound(expr)); - lbValue data = ir_emit_array_ep(proc, slice->ConstantSlice.backing_array, v_zero32); + lbValue data = lb_slice_elem(p, slice); - auto temp_data = array_make(heap_allocator(), 0, cl->elems.count); + auto temp_data = array_make(heap_allocator(), 0, cl->elems.count); defer (array_free(&temp_data)); for_array(i, cl->elems) { @@ -5679,7 +6995,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (elem->kind == Ast_FieldValue) { ast_node(fv, FieldValue, elem); - if (ir_is_elem_const(proc->module, fv->value, et)) { + if (lb_is_elem_const(fv->value, et)) { continue; } @@ -5697,10 +7013,10 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { hi += 1; } - lbValue value = lb_emit_conv(proc, ir_build_expr(proc, fv->value), et); + lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et); for (i64 k = lo; k < hi; k++) { - irCompoundLitElemTempData data = {}; + lbCompoundLitElemTempData data = {}; data.value = value; data.elem_index = cast(i32)k; array_add(&temp_data, data); @@ -5710,26 +7026,26 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT(fv->field->tav.mode == Addressing_Constant); i64 index = exact_value_to_i64(fv->field->tav.value); - lbValue field_expr = ir_build_expr(proc, fv->value); - GB_ASSERT(!is_type_tuple(ir_type(field_expr))); + lbValue field_expr = lb_build_expr(p, fv->value); + GB_ASSERT(!is_type_tuple(field_expr.type)); - lbValue ev = lb_emit_conv(proc, field_expr, et); + lbValue ev = lb_emit_conv(p, field_expr, et); - irCompoundLitElemTempData data = {}; + lbCompoundLitElemTempData data = {}; data.value = ev; data.elem_index = cast(i32)index; array_add(&temp_data, data); } } else { - if (ir_is_elem_const(proc->module, elem, et)) { + if (lb_is_elem_const(elem, et)) { continue; } - lbValue field_expr = ir_build_expr(proc, elem); - GB_ASSERT(!is_type_tuple(ir_type(field_expr))); + lbValue field_expr = lb_build_expr(p, elem); + GB_ASSERT(!is_type_tuple(field_expr.type)); - lbValue ev = lb_emit_conv(proc, field_expr, et); + lbValue ev = lb_emit_conv(p, field_expr, et); - irCompoundLitElemTempData data = {}; + lbCompoundLitElemTempData data = {}; data.value = ev; data.elem_index = cast(i32)i; array_add(&temp_data, data); @@ -5737,15 +7053,15 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } for_array(i, temp_data) { - temp_data[i].gep = ir_emit_ptr_offset(proc, data, ir_const_int(temp_data[i].elem_index)); + temp_data[i].gep = lb_emit_ptr_offset(p, data, lb_const_int(p->module, t_int, temp_data[i].elem_index)); } for_array(i, temp_data) { - ir_emit_store(proc, temp_data[i].gep, temp_data[i].value); + lb_emit_store(p, temp_data[i].gep, temp_data[i].value); } - lbValue count = ir_const_int(slice->ConstantSlice.count); - ir_fill_slice(proc, v, data, count); + // lbValue count = lb_const_int(p->module, t_int, slice->ConstantSlice.count); + // ir_fill_slice(p, v, data, count); } break; } @@ -5754,24 +7070,26 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (cl->elems.count == 0) { break; } + // TODO(bill): Type_DynamicArray + #if 0 Type *et = bt->DynamicArray.elem; gbAllocator a = heap_allocator(); - lbValue size = ir_const_int(type_size_of(et)); - lbValue align = ir_const_int(type_align_of(et)); + lbValue size = lb_const_int(p->module, t_int, type_size_of(et)); + lbValue align = lb_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(a, 5); - args[0] = lb_emit_conv(proc, v, t_rawptr); + auto args = array_make(a, 5); + args[0] = lb_emit_conv(p, lb_addr_get_ptr(p, v), t_rawptr); args[1] = size; args[2] = align; - args[3] = ir_const_int(2*item_count); // TODO(bill): Is this too much waste? - args[4] = ir_emit_source_code_location(proc, proc_name, pos); - lb_emit_runtime_call(proc, "__dynamic_array_reserve", args); + args[3] = lb_const_int(p->module, t_int, 2*item_count); // TODO(bill): Is this too much waste? + args[4] = lb_emit_source_code_location(p, proc_name, pos); + lb_emit_runtime_call(p, "__dynamic_array_reserve", args); } - lbValue items = ir_generate_array(proc->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr); + lbValue items = lb_generate_array(p->module, et, item_count, str_lit("dacl$"), cast(i64)cast(intptr)expr); for_array(i, cl->elems) { Ast *elem = cl->elems[i]; @@ -5791,31 +7109,31 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { hi += 1; } - lbValue value = lb_emit_conv(proc, ir_build_expr(proc, fv->value), et); + lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et); for (i64 k = lo; k < hi; k++) { - lbValue ep = ir_emit_array_epi(proc, items, cast(i32)k); - ir_emit_store(proc, ep, value); + lbValue ep = ir_emit_array_epi(p, items, cast(i32)k); + lb_emit_store(p, ep, value); } } else { GB_ASSERT(fv->field->tav.mode == Addressing_Constant); i64 field_index = exact_value_to_i64(fv->field->tav.value); - lbValue ev = ir_build_expr(proc, fv->value); - lbValue value = lb_emit_conv(proc, ev, et); - lbValue ep = ir_emit_array_epi(proc, items, cast(i32)field_index); - ir_emit_store(proc, ep, value); + lbValue ev = lb_build_expr(p, fv->value); + lbValue value = lb_emit_conv(p, ev, et); + lbValue ep = ir_emit_array_epi(p, items, cast(i32)field_index); + lb_emit_store(p, ep, value); } } else { - lbValue value = lb_emit_conv(proc, ir_build_expr(proc, elem), et); - lbValue ep = ir_emit_array_epi(proc, items, cast(i32)i); - ir_emit_store(proc, ep, value); + lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et); + lbValue ep = ir_emit_array_epi(p, items, cast(i32)i); + lb_emit_store(p, ep, value); } } { - auto args = array_make(a, 6); + auto args = array_make(a, 6); args[0] = lb_emit_conv(proc, v, t_rawptr); args[1] = size; args[2] = align; @@ -5824,13 +7142,14 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { args[5] = ir_emit_source_code_location(proc, proc_name, pos); lb_emit_runtime_call(proc, "__dynamic_array_append", args); } + #endif break; } case Type_Basic: { GB_ASSERT(is_type_any(bt)); if (cl->elems.count > 0) { - ir_emit_store(proc, v, lb_const_value(proc->module, type, exact_value_compound(expr))); + lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr))); String field_names[2] = { str_lit("data"), str_lit("id"), @@ -5843,7 +7162,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { for_array(field_index, cl->elems) { Ast *elem = cl->elems[field_index]; - lbValue field_expr = nullptr; + lbValue field_expr = {}; isize index = field_index; if (elem->kind == Ast_FieldValue) { @@ -5857,14 +7176,14 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { index = sel.index[0]; } - field_expr = ir_build_expr(proc, elem); + field_expr = lb_build_expr(p, elem); - GB_ASSERT(ir_type(field_expr)->kind != Type_Tuple); + GB_ASSERT(field_expr.type->kind != Type_Tuple); Type *ft = field_types[index]; - lbValue fv = lb_emit_conv(proc, field_expr, ft); - lbValue gep = ir_emit_struct_ep(proc, v, cast(i32)index); - ir_emit_store(proc, gep, fv); + lbValue fv = lb_emit_conv(p, field_expr, ft); + lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index); + lb_emit_store(p, gep, fv); } } @@ -5874,29 +7193,30 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { case Type_BitSet: { i64 sz = type_size_of(type); if (cl->elems.count > 0 && sz > 0) { - ir_emit_store(proc, v, lb_const_value(proc->module, type, exact_value_compound(expr))); + lb_addr_store(p, v, lb_const_value(p->module, type, exact_value_compound(expr))); - lbValue lower = ir_value_constant(t_int, exact_value_i64(bt->BitSet.lower)); + lbValue lower = lb_const_value(p->module, t_int, exact_value_i64(bt->BitSet.lower)); for_array(i, cl->elems) { Ast *elem = cl->elems[i]; GB_ASSERT(elem->kind != Ast_FieldValue); - if (ir_is_elem_const(proc->module, elem, et)) { + if (lb_is_elem_const(elem, et)) { continue; } - lbValue expr = ir_build_expr(proc, elem); - GB_ASSERT(ir_type(expr)->kind != Type_Tuple); + lbValue expr = lb_build_expr(p, elem); + GB_ASSERT(expr.type->kind != Type_Tuple); Type *it = bit_set_to_int(bt); - lbValue e = lb_emit_conv(proc, expr, it); - e = ir_emit_arith(proc, Token_Sub, e, lower, it); - e = ir_emit_arith(proc, Token_Shl, v_one, e, it); - - lbValue old_value = ir_emit_bitcast(proc, ir_emit_load(proc, v), it); - lbValue new_value = ir_emit_arith(proc, Token_Or, old_value, e, it); - new_value = ir_emit_bitcast(proc, new_value, type); - ir_emit_store(proc, v, new_value); + lbValue one = lb_const_value(p->module, it, exact_value_i64(1)); + lbValue e = lb_emit_conv(p, expr, it); + e = lb_emit_arith(p, Token_Sub, e, lower, it); + e = lb_emit_arith(p, Token_Shl, one, e, it); + + lbValue old_value = lb_emit_transmute(p, lb_addr_load(p, v), it); + lbValue new_value = lb_emit_arith(p, Token_Or, old_value, e, it); + new_value = lb_emit_transmute(p, new_value, type); + lb_addr_store(p, v, new_value); } } break; @@ -5904,32 +7224,31 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } - return ir_addr(v); + return v; case_end; case_ast_node(tc, TypeCast, expr); Type *type = type_of_expr(expr); - lbValue x = ir_build_expr(proc, tc->expr); - lbValue e = nullptr; + lbValue x = lb_build_expr(p, tc->expr); + lbValue e = {}; switch (tc->token.kind) { case Token_cast: - e = lb_emit_conv(proc, x, type); + e = lb_emit_conv(p, x, type); break; case Token_transmute: - e = lb_emit_transmute(proc, x, type); + e = lb_emit_transmute(p, x, type); break; default: GB_PANIC("Invalid AST TypeCast"); } - lbValue v = lb_add_local_generated(proc, type, false); - ir_emit_store(proc, v, e); - return ir_addr(v); + lbAddr v = lb_add_local_generated(p, type, false); + lb_addr_store(p, v, e); + return v; case_end; case_ast_node(ac, AutoCast, expr); - return ir_build_addr(proc, ac->expr); + return lb_build_addr(p, ac->expr); case_end; -#endif } TokenPos token_pos = ast_token(expr).pos; @@ -5996,6 +7315,7 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { map_init(&gen->module.types, a); map_init(&gen->module.values, a); map_init(&gen->module.members, a); + map_init(&gen->module.procedure_values, a); map_init(&gen->module.const_strings, a); map_init(&gen->module.const_string_byte_slices, a); map_init(&gen->module.anonymous_proc_lits, a); @@ -6022,6 +7342,8 @@ lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) { if (value.value != nullptr) { GB_ASSERT(LLVMIsConstant(value.value)); LLVMSetInitializer(g.value, value.value); + } else { + LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, type))); } lb_add_entity(m, e, g); @@ -6129,6 +7451,8 @@ void lb_generate_code(lbGenerator *gen) { } if (is_foreign) { LLVMSetExternallyInitialized(g.value, true); + } else { + LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, e->type))); } if (is_export) { LLVMSetLinkage(g.value, LLVMDLLExportLinkage); @@ -6183,6 +7507,9 @@ void lb_generate_code(lbGenerator *gen) { case Entity_Procedure: break; } + if (e->token.string == "RtlFillMemory") { + gb_printf_err("%.*s\n", LIT(e->token.string)); + } bool polymorphic_struct = false; if (e->type != nullptr && e->kind == Entity_TypeName) { @@ -6197,9 +7524,6 @@ void lb_generate_code(lbGenerator *gen) { continue; } - if (is_type_polymorphic(e->type)) { - continue; - } String mangled_name = lb_get_entity_name(m, e); @@ -6211,9 +7535,10 @@ void lb_generate_code(lbGenerator *gen) { { if (e->pkg->name == "demo") { + // } else if (e->pkg->name == "runtime") { // } else if (e->pkg->name == "os") { } else { - continue; + // continue; } lbProcedure *p = lb_create_procedure(m, e); @@ -6231,16 +7556,24 @@ void lb_generate_code(lbGenerator *gen) { lb_end_procedure_body(p); } lb_end_procedure(p); + + if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { + gb_printf_err("FAILED FOR: %.*s\n", LIT(p->name)); + LLVMDumpValue(p->value); + gb_printf_err("\n\n\n\n"); + LLVMVerifyFunction(p->value, LLVMAbortProcessAction); + + } } char *llvm_error = nullptr; defer (LLVMDisposeMessage(llvm_error)); - LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); + LLVMDumpModule(mod); + // LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); - LLVMDumpModule(mod); // char const *target_triple = "x86_64-pc-windows-msvc"; diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 2ee269bb6..e807e1c06 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -55,8 +55,9 @@ struct lbModule { Map types; // Key: Type * - Map values; // Key: Entity * - Map members; // Key: String + Map values; // Key: Entity * + Map members; // Key: String + Map procedure_values; // Key: LLVMValueRef Map const_strings; // Key: String Map const_string_byte_slices; // Key: String @@ -222,6 +223,8 @@ LLVMTypeRef lb_addr_lb_type(lbAddr const &addr); void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value); lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr); lbValue lb_emit_load(lbProcedure *p, lbValue v); +void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value); + void lb_build_stmt(lbProcedure *p, Ast *stmt); lbValue lb_build_expr(lbProcedure *p, Ast *expr); @@ -233,30 +236,35 @@ lbValue lb_build_gep(lbProcedure *p, lbValue const &value, i32 index) ; lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index); lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index); lbValue lb_emit_array_epi(lbProcedure *p, lbValue value, i32 index); - +lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index); +lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel); lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type); - +lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type); void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block); - +lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t); +lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right); +lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false); lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t); + lbValue lb_build_call_expr(lbProcedure *p, Ast *expr); -lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value={}); +lbAddr lb_find_or_generate_context_ptr(lbProcedure *p); +void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx); -lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr, bool zero_init=true, i32 param_index=0); -lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t); +lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value={}); +lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr, bool zero_init=true, i32 param_index=0); -lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right); -lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false); lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type=t_typeid); lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value); - lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt); +lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init); + +lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array const &args); enum lbCallingConventionKind { -- cgit v1.2.3 From 2180f4a475287546b9230745343ca3e0847525c6 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 23 Feb 2020 10:04:25 +0000 Subject: Basic work on obj generation --- LLVM-C.dll | Bin 0 -> 51116544 bytes build.bat | 7 +- core/mem/mem.odin | 6 +- core/runtime/internal.odin | 16 +-- core/runtime/procs_windows_amd64.odin | 18 +-- examples/llvm-demo/demo.odin | 80 ++++++------ src/checker.cpp | 2 + src/llvm_backend.cpp | 227 +++++++++++++++++++++++++++++----- src/llvm_backend.hpp | 11 ++ src/parser.hpp | 4 +- 10 files changed, 283 insertions(+), 88 deletions(-) create mode 100644 LLVM-C.dll (limited to 'src/llvm_backend.cpp') diff --git a/LLVM-C.dll b/LLVM-C.dll new file mode 100644 index 000000000..598db4d91 Binary files /dev/null and b/LLVM-C.dll differ diff --git a/build.bat b/build.bat index 58799c454..715171d7c 100644 --- a/build.bat +++ b/build.bat @@ -50,8 +50,13 @@ del *.ilk > NUL 2> NUL cl %compiler_settings% "src\main.cpp" ^ /link %linker_settings% -OUT:%exe_name% ^ && odin build examples/llvm-demo/demo.odin -llvm-api +if %errorlevel% neq 0 ( + goto end_of_build +) - rem && link -nologo llvm_demo.obj kernel32.lib -OUT:llvm_demo.exe +link llvm_demo.obj kernel32.lib user32.lib /OUT:llvm_demo.exe ^ + /nologo /incremental:no /opt:ref /subsystem:CONSOLE /defaultlib:libcmt -debug ^ + && llvm_demo del *.obj > NUL 2> NUL diff --git a/core/mem/mem.odin b/core/mem/mem.odin index 144ba07a8..c3aa76304 100644 --- a/core/mem/mem.odin +++ b/core/mem/mem.odin @@ -15,14 +15,14 @@ set :: proc "contextless" (data: rawptr, value: byte, len: int) -> rawptr { foreign _ { when size_of(rawptr) == 8 { @(link_name="llvm.memset.p0i8.i64") - llvm_memset :: proc(dst: rawptr, val: byte, len: int, align: i32, is_volatile: bool) ---; + llvm_memset :: proc(dst: rawptr, val: byte, len: int, is_volatile: bool) ---; } else { @(link_name="llvm.memset.p0i8.i32") - llvm_memset :: proc(dst: rawptr, val: byte, len: int, align: i32, is_volatile: bool) ---; + llvm_memset :: proc(dst: rawptr, val: byte, len: int, is_volatile: bool) ---; } } - llvm_memset(data, value, len, 1, false); + llvm_memset(data, value, len, false); return data; } zero :: inline proc "contextless" (data: rawptr, len: int) -> rawptr { diff --git a/core/runtime/internal.odin b/core/runtime/internal.odin index 60359fd6c..553920dc7 100644 --- a/core/runtime/internal.odin +++ b/core/runtime/internal.odin @@ -42,10 +42,10 @@ mem_zero :: proc "contextless" (data: rawptr, len: int) -> rawptr { foreign _ { when size_of(rawptr) == 8 { @(link_name="llvm.memset.p0i8.i64") - memset :: proc(dst: rawptr, val: byte, len: int, align: i32 = 1, is_volatile: bool = false) ---; + memset :: proc(dst: rawptr, val: byte, len: int, is_volatile: bool = false) ---; } else { @(link_name="llvm.memset.p0i8.i32") - memset :: proc(dst: rawptr, val: byte, len: int, align: i32 = 1, is_volatile: bool = false) ---; + memset :: proc(dst: rawptr, val: byte, len: int, is_volatile: bool = false) ---; } } } @@ -59,13 +59,13 @@ mem_copy :: proc "contextless" (dst, src: rawptr, len: int) -> rawptr { foreign _ { when size_of(rawptr) == 8 { @(link_name="llvm.memmove.p0i8.p0i8.i64") - llvm_memmove :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---; + llvm_memmove :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; } else { @(link_name="llvm.memmove.p0i8.p0i8.i32") - llvm_memmove :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---; + llvm_memmove :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; } } - llvm_memmove(dst, src, len, 1, false); + llvm_memmove(dst, src, len); return dst; } @@ -75,13 +75,13 @@ mem_copy_non_overlapping :: proc "contextless" (dst, src: rawptr, len: int) -> r foreign _ { when size_of(rawptr) == 8 { @(link_name="llvm.memcpy.p0i8.p0i8.i64") - llvm_memcpy :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---; + llvm_memcpy :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; } else { @(link_name="llvm.memcpy.p0i8.p0i8.i32") - llvm_memcpy :: proc(dst, src: rawptr, len: int, align: i32, is_volatile: bool) ---; + llvm_memcpy :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; } } - llvm_memcpy(dst, src, len, 1, false); + llvm_memcpy(dst, src, len); return dst; } diff --git a/core/runtime/procs_windows_amd64.odin b/core/runtime/procs_windows_amd64.odin index f5f582ccc..ebcbbe44e 100644 --- a/core/runtime/procs_windows_amd64.odin +++ b/core/runtime/procs_windows_amd64.odin @@ -2,15 +2,15 @@ package runtime foreign import kernel32 "system:Kernel32.lib" -@private -@(link_name="_tls_index") -_tls_index: u32; +// @private +// @(link_name="_tls_index") +// _tls_index: u32; -@private -@(link_name="_fltused") -_fltused: i32 = 0x9875; +// @private +// @(link_name="_fltused") +// _fltused: i32 = 0x9875; -@(link_name="memcpy") +// @(link_name="memcpy") memcpy :: proc "c" (dst, src: rawptr, len: int) -> rawptr { foreign kernel32 { RtlCopyMemory :: proc "c" (dst, src: rawptr, len: int) --- @@ -19,7 +19,7 @@ memcpy :: proc "c" (dst, src: rawptr, len: int) -> rawptr { return dst; } -@(link_name="memmove") +// @(link_name="memmove") memmove :: proc "c" (dst, src: rawptr, len: int) -> rawptr { foreign kernel32 { RtlMoveMemory :: proc "c" (dst, src: rawptr, len: int) --- @@ -28,7 +28,7 @@ memmove :: proc "c" (dst, src: rawptr, len: int) -> rawptr { return dst; } -@(link_name="memset") +// @(link_name="memset") memset :: proc "c" (ptr: rawptr, val: i32, len: int) -> rawptr { foreign kernel32 { RtlFillMemory :: proc "c" (dst: rawptr, len: int, fill: byte) --- diff --git a/examples/llvm-demo/demo.odin b/examples/llvm-demo/demo.odin index 578f98e0a..f89088005 100644 --- a/examples/llvm-demo/demo.odin +++ b/examples/llvm-demo/demo.odin @@ -1,56 +1,62 @@ package demo import "core:os" +import "core:sys/win32" -BarBar :: struct { - x, y: int, -}; -foo :: proc(x: int) -> (b: BarBar) { - b = {1, 2}; - return; +foreign import kernel32 "system:Kernel32.lib" +foreign import user32 "system:User32.lib" + +foreign user32 { + MessageBoxA :: proc "c" (hWnd: rawptr, text, caption: cstring, uType: u32) -> i32 --- } -main :: proc() { - Foo :: enum {A=1, B, C, D}; - Foo_Set :: bit_set[Foo]; - foo_set := Foo_Set{.A, .C}; +foreign kernel32 { + FlushFileBuffers :: proc "c" (hFile: win32.Handle) -> b32 --- +} - array := [4]int{3 = 1, 0 .. 1 = 3, 2 = 9}; - slice := []int{1, 2, 3, 4}; - x: ^int = nil; - y := slice != nil; - @thread_local a: int; +main :: proc() { + f := os.get_std_handle(win32.STD_OUTPUT_HANDLE); + os.write_string(f, "Hellope!\n"); + + // Foo :: enum {A=1, B, C, D}; + // Foo_Set :: bit_set[Foo]; + // foo_set := Foo_Set{.A, .C}; + + // array := [4]int{3 = 1, 0 .. 1 = 3, 2 = 9}; + // slice := []int{1, 2, 3, 4}; - if true { - foo(1); - } + // x: ^int = nil; + // y := slice != nil; - x1 := i32(1); - y1 := i32(2); - z1 := x1 + y1; - w1 := z1 - 2; + // @thread_local a: int; - f := foo; + // if true { + // foo(1); + // } - c := 1 + 2i; - q := 1 + 2i + 3j + 4k; + // x := i32(1); + // y := i32(2); + // z := x + y; + // w := z - 2; - s := "Hellope"; + // f := foo; - b := true; - aaa := b ? int(123) : int(34); - defer aaa = 333; + // c := 1 + 2i; + // q := 1 + 2i + 3j + 4k; - p := proc(x: int) {}; + // s := "Hellope"; + // b := true; + // aaa := b ? int(123) : int(34); + // defer aaa = 333; - bb := BarBar{1, 2}; - pc: proc "contextless" (x: i32) -> BarBar; - po: proc "odin" (x: i32) -> BarBar; - e: enum{A, B, C}; - u: union{i32, bool}; - u1: union{i32}; - um: union #maybe {^int}; + // bb := BarBar{1, 2}; + // pc: proc "contextless" (x: i32) -> BarBar; + // po: proc "odin" (x: i32) -> BarBar; + // e: enum{A, B, C}; + // u: union{i32, bool}; + // u1: union{i32}; + // um: union #maybe {^int}; } diff --git a/src/checker.cpp b/src/checker.cpp index bfd2d3149..23e27af87 100644 --- a/src/checker.cpp +++ b/src/checker.cpp @@ -1685,6 +1685,8 @@ void generate_minimum_dependency_set(Checker *c, Entity *start) { str_lit("udivti3"), str_lit("memset"), + str_lit("memcpy"), + str_lit("memmove"), str_lit("memory_compare"), str_lit("memory_compare_zero"), diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 8d4b47e78..fd7b7030d 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -199,6 +199,10 @@ lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) { } else if (addr.kind == lbAddr_SoaVariable) { GB_PANIC("lbAddr_SoaVariable"); } + + if (is_type_proc(addr.addr.type)) { + return addr.addr; + } return lb_emit_load(p, addr.addr); } @@ -831,7 +835,6 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { lb_add_entity(m, entity, proc_value); lb_add_member(m, p->name, proc_value); - LLVMContextRef ctx = LLVMGetModuleContext(m->mod); // NOTE(bill): offset==0 is the return value isize offset = 1; @@ -874,8 +877,29 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias"); lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull"); lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture"); + } + + { // Debug Information + unsigned line = cast(unsigned)entity->token.pos.line; + LLVMMetadataRef file = nullptr; + if (entity->file != nullptr) { + cast(LLVMMetadataRef)entity->file->llvm_metadata; + } + LLVMMetadataRef scope = nullptr; + + + LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope, + cast(char const *)entity->token.string.text, entity->token.string.len, + cast(char const *)p->name.text, p->name.len, + file, line, nullptr, + true, p->body == nullptr, + line, LLVMDIFlagZero, false + ); + GB_ASSERT(res != nullptr); + map_set(&m->debug_values, hash_pointer(p), res); } + return p; } @@ -3163,6 +3187,14 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { lb_addr_store(p, default_value, value); return lb_emit_conv(p, lb_addr_load(p, default_value), t_any); } else if (dst->kind == Type_Basic) { + if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) { + unsigned indices[1] = {0}; + LLVMValueRef data = LLVMConstExtractValue(value.value, indices, 1); + char const *text = nullptr; + size_t length = 0; + text = LLVMGetAsString(data, &length); + GB_PANIC("HERE %.*s", cast(int)length, text); + } // if (is_type_float(dst)) { // return value; // } else if (is_type_integer(dst)) { @@ -4110,7 +4142,7 @@ lbValue lb_emit_call_internal(lbProcedure *p, lbValue value, lbValue return_ptr, LLVMBasicBlockRef curr_block = LLVMGetInsertBlock(p->builder); GB_ASSERT(curr_block != p->decl_block->block); - LLVMValueRef ret = LLVMBuildCall(p->builder, value.value, args, arg_count, "");; + LLVMValueRef ret = LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(p->module, value.type)), value.value, args, arg_count, "");; lbValue res = {}; res.value = ret; res.type = abi_rt; @@ -7310,6 +7342,9 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { // gen->ctx = LLVMContextCreate(); gen->module.ctx = LLVMGetGlobalContext(); gen->module.mod = LLVMModuleCreateWithNameInContext("odin_module", gen->module.ctx); + gen->module.debug_builder = LLVMCreateDIBuilder(gen->module.mod); + + gb_mutex_init(&gen->module.mutex); gbAllocator a = heap_allocator(); map_init(&gen->module.types, a); @@ -7321,6 +7356,8 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { map_init(&gen->module.anonymous_proc_lits, a); array_init(&gen->module.procedures_to_generate, a); + map_init(&gen->module.debug_values, a); + return true; } @@ -7366,6 +7403,30 @@ void lb_generate_code(lbGenerator *gen) { auto *min_dep_set = &info->minimum_dependency_set; + { // Debug Info + for_array(i, info->files.entries) { + AstFile *f = info->files.entries[i].value; + String fullpath = f->fullpath; + String filename = filename_from_path(fullpath); + String directory = directory_from_path(fullpath); + LLVMMetadataRef res = LLVMDIBuilderCreateFile(m->debug_builder, + cast(char const *)filename.text, filename.len, + cast(char const *)directory.text, directory.len); + map_set(&m->debug_values, hash_pointer(f), res); + f->llvm_metadata = res; + } + + m->debug_compile_unit = LLVMDIBuilderCreateCompileUnit(m->debug_builder, LLVMDWARFSourceLanguageC, + cast(LLVMMetadataRef)m->info->files.entries[0].value->llvm_metadata, + "odin", 4, + false, "", 0, + 1, "", 0, + LLVMDWARFEmissionFull, 0, true, + true + ); + + } + isize global_variable_max_count = 0; Entity *entry_point = info->entry_point; @@ -7507,9 +7568,6 @@ void lb_generate_code(lbGenerator *gen) { case Entity_Procedure: break; } - if (e->token.string == "RtlFillMemory") { - gb_printf_err("%.*s\n", LIT(e->token.string)); - } bool polymorphic_struct = false; if (e->type != nullptr && e->kind == Entity_TypeName) { @@ -7533,14 +7591,6 @@ void lb_generate_code(lbGenerator *gen) { break; case Entity_Procedure: { - - if (e->pkg->name == "demo") { - // } else if (e->pkg->name == "runtime") { - // } else if (e->pkg->name == "os") { - } else { - // continue; - } - lbProcedure *p = lb_create_procedure(m, e); array_add(&m->procedures_to_generate, p); } @@ -7558,38 +7608,157 @@ void lb_generate_code(lbGenerator *gen) { lb_end_procedure(p); if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { - gb_printf_err("FAILED FOR: %.*s\n", LIT(p->name)); + gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name)); LLVMDumpValue(p->value); gb_printf_err("\n\n\n\n"); LLVMVerifyFunction(p->value, LLVMAbortProcessAction); + } + } + + + LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry(); + LLVMPassManagerRef function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod); + defer (LLVMDisposePassManager(function_pass_manager)); + + LLVMAddPromoteMemoryToRegisterPass(function_pass_manager); + LLVMAddMergedLoadStoreMotionPass(function_pass_manager); + LLVMAddAggressiveInstCombinerPass(function_pass_manager); + LLVMAddConstantPropagationPass(function_pass_manager); + LLVMAddAggressiveDCEPass(function_pass_manager); + LLVMAddDeadStoreEliminationPass(function_pass_manager); + LLVMAddLoopIdiomPass(function_pass_manager); + LLVMAddPromoteMemoryToRegisterPass(function_pass_manager); + // LLVMAddUnifyFunctionExitNodesPass(function_pass_manager); + + for_array(i, m->procedures_to_generate) { + lbProcedure *p = m->procedures_to_generate[i]; + if (p->body != nullptr) { // Build Procedure + LLVMRunFunctionPassManager(function_pass_manager, p->value); } } + LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager(); + defer (LLVMDisposePassManager(module_pass_manager)); + LLVMAddAlwaysInlinerPass(module_pass_manager); + LLVMAddStripDeadPrototypesPass(module_pass_manager); + + LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate(); + defer (LLVMPassManagerBuilderDispose(pass_manager_builder)); + LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, 0); + LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, 0); + + LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false); + LLVMRunPassManager(module_pass_manager, mod); + gb_printf_err("Done\n"); + + + + if (!(build_context.is_dll && !has_dll_main)) { + LLVMContextRef ctx = LLVMGetModuleContext(mod); + + LLVMTypeRef llvm_i32 = LLVMInt32TypeInContext(ctx); + + LLVMTypeRef ptr_cstr = LLVMPointerType(LLVMPointerType(LLVMInt8TypeInContext(ctx), 0), 0); + LLVMTypeRef params[2] = {llvm_i32, ptr_cstr}; + LLVMTypeRef func_type = LLVMFunctionType(llvm_i32, params, gb_count_of(params), false); + + LLVMValueRef fn = LLVMAddFunction(mod, "main", func_type); + + LLVMBuilderRef builder = LLVMCreateBuilder(); + LLVMBasicBlockRef block = LLVMAppendBasicBlockInContext(ctx, fn, "entry"); + LLVMPositionBuilderAtEnd(builder, block); + + // for_array(i, global_variables) { + // auto *var = &global_variables[i]; + // if (var->decl->init_expr != nullptr) { + // var->init = ir_build_expr(proc, var->decl->init_expr); + // } + + // Entity *e = var->var->Global.entity; + // GB_ASSERT(e->kind == Entity_Variable); + + // if (e->Variable.is_foreign) { + // Entity *fl = e->Procedure.foreign_library; + // ir_add_foreign_library_path(m, fl); + // } + + // if (e->flags & EntityFlag_Static) { + // var->var->Global.is_internal = true; + // } + + // if (var->init != nullptr) { + // Type *t = type_deref(ir_type(var->var)); + + // if (is_type_any(t)) { + // // NOTE(bill): Edge case for 'any' type + // Type *var_type = default_type(ir_type(var->init)); + // irValue *g = ir_add_global_generated(proc->module, var_type, var->init); + // ir_emit_store(proc, g, var->init); + + // irValue *data = ir_emit_struct_ep(proc, var->var, 0); + // irValue *ti = ir_emit_struct_ep(proc, var->var, 1); + // ir_emit_store(proc, data, ir_emit_conv(proc, g, t_rawptr)); + // ir_emit_store(proc, ti, ir_type_info(proc, var_type)); + // } else { + // ir_emit_store(proc, var->var, ir_emit_conv(proc, var->init, t)); + // } + // } + // } + + lbValue *found = map_get(&m->values, hash_entity(entry_point)); + GB_ASSERT(found != nullptr); + + LLVMBuildCall2(builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, ""); + LLVMBuildRet(builder, LLVMConstInt(llvm_i32, 0, false)); + + LLVMDisposeBuilder(builder); + + if (LLVMVerifyFunction(fn, LLVMReturnStatusAction)) { + gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main"); + LLVMDumpValue(fn); + gb_printf_err("\n\n\n\n"); + LLVMVerifyFunction(fn, LLVMAbortProcessAction); + } + + LLVMRunFunctionPassManager(function_pass_manager, fn); + + } + char *llvm_error = nullptr; defer (LLVMDisposeMessage(llvm_error)); - LLVMDumpModule(mod); - // LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); + LLVMDIBuilderFinalize(m->debug_builder); + LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); + llvm_error = nullptr; + LLVMBool failure = LLVMPrintModuleToFile(mod, "llvm_demo.ll", &llvm_error); + LLVMInitializeAllTargetInfos(); + LLVMInitializeAllTargets(); + LLVMInitializeAllTargetMCs(); + LLVMInitializeAllAsmPrinters(); + LLVMInitializeAllAsmParsers(); + LLVMInitializeAllDisassemblers(); + LLVMInitializeNativeTarget(); + char const *target_triple = "x86_64-pc-windows-msvc"; + char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; + LLVMSetTarget(mod, target_triple); - // char const *target_triple = "x86_64-pc-windows-msvc"; - // char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; - // LLVMSetTarget(mod, target_triple); + LLVMTargetRef target = {}; + LLVMGetTargetFromTriple(target_triple, &target, &llvm_error); + GB_ASSERT(target != nullptr); - // LLVMTargetRef target = {}; - // LLVMGetTargetFromTriple(target_triple, &target, &llvm_error); - // GB_ASSERT(target != nullptr); + LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault); + defer (LLVMDisposeTargetMachine(target_machine)); - // LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault); - // defer (LLVMDisposeTargetMachine(target_machine)); + LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, "llvm_demo.obj", LLVMObjectFile, &llvm_error); + if (ok) { + gb_printf_err("LLVM Error: %s\n", llvm_error); + return; + } + gb_printf_err(".obj generated\n"); - // LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, "llvm_demo.obj", LLVMObjectFile, &llvm_error); - // if (ok) { - // gb_printf_err("LLVM Error: %s\n", llvm_error); - // return; - // } } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index e807e1c06..47ff5962b 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -4,9 +4,14 @@ #include "llvm-c/Analysis.h" #include "llvm-c/Object.h" #include "llvm-c/BitWriter.h" +#include "llvm-c/DebugInfo.h" #include "llvm-c/Transforms/AggressiveInstCombine.h" #include "llvm-c/Transforms/InstCombine.h" #include "llvm-c/Transforms/IPO.h" +#include "llvm-c/Transforms/PassManagerBuilder.h" +#include "llvm-c/Transforms/Scalar.h" +#include "llvm-c/Transforms/Utils.h" +#include "llvm-c/Transforms/Vectorize.h" struct lbProcedure; @@ -49,6 +54,7 @@ struct lbAddr { struct lbModule { LLVMModuleRef mod; LLVMContextRef ctx; + CheckerInfo *info; gbMutex mutex; @@ -70,6 +76,11 @@ struct lbModule { u32 global_generated_index; Array procedures_to_generate; + + + LLVMDIBuilderRef debug_builder; + LLVMMetadataRef debug_compile_unit; + Map debug_values; // Key: Pointer }; struct lbGenerator { diff --git a/src/parser.hpp b/src/parser.hpp index 00366d79a..70ef82995 100644 --- a/src/parser.hpp +++ b/src/parser.hpp @@ -98,7 +98,6 @@ struct AstFile { Array imports; // 'import' 'using import' isize directive_count; - Ast * curr_proc; isize error_count; @@ -111,6 +110,9 @@ struct AstFile { #define PARSER_MAX_FIX_COUNT 6 isize fix_count; TokenPos fix_prev_pos; + + struct LLVMOpaqueMetadata *llvm_metadata; + struct LLVMOpaqueMetadata *llvm_metadata_scope; }; -- cgit v1.2.3 From b13423d7f7b8ef07cfb7e5e03b6520a63f0861e3 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 23 Feb 2020 16:25:11 +0000 Subject: Global variable initialization support --- build.bat | 4 +- examples/llvm-demo/demo.odin | 29 +-- src/llvm_backend.cpp | 422 ++++++++++++++++++++++++++++++------------- src/llvm_backend.hpp | 4 +- src/tokenizer.cpp | 4 + 5 files changed, 316 insertions(+), 147 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/build.bat b/build.bat index 715171d7c..67892a9c3 100644 --- a/build.bat +++ b/build.bat @@ -49,12 +49,12 @@ del *.ilk > NUL 2> NUL cl %compiler_settings% "src\main.cpp" ^ /link %linker_settings% -OUT:%exe_name% ^ - && odin build examples/llvm-demo/demo.odin -llvm-api + && odin build examples/llvm-demo/demo.odin -llvm-api -show-timings if %errorlevel% neq 0 ( goto end_of_build ) -link llvm_demo.obj kernel32.lib user32.lib /OUT:llvm_demo.exe ^ +link demo.obj kernel32.lib user32.lib /OUT:llvm_demo.exe ^ /nologo /incremental:no /opt:ref /subsystem:CONSOLE /defaultlib:libcmt -debug ^ && llvm_demo diff --git a/examples/llvm-demo/demo.odin b/examples/llvm-demo/demo.odin index f89088005..48a2f9255 100644 --- a/examples/llvm-demo/demo.odin +++ b/examples/llvm-demo/demo.odin @@ -1,24 +1,13 @@ package demo import "core:os" -import "core:sys/win32" - -foreign import kernel32 "system:Kernel32.lib" -foreign import user32 "system:User32.lib" - -foreign user32 { - MessageBoxA :: proc "c" (hWnd: rawptr, text, caption: cstring, uType: u32) -> i32 --- -} - -foreign kernel32 { - FlushFileBuffers :: proc "c" (hFile: win32.Handle) -> b32 --- -} +main :: proc() { + os.write_string(os.stdout, "Hellope\n"); + // BarBar :: struct {x, y: int}; -main :: proc() { - f := os.get_std_handle(win32.STD_OUTPUT_HANDLE); - os.write_string(f, "Hellope!\n"); + // foo :: proc(x: int) {} // Foo :: enum {A=1, B, C, D}; // Foo_Set :: bit_set[Foo]; @@ -36,10 +25,12 @@ main :: proc() { // foo(1); // } - // x := i32(1); - // y := i32(2); - // z := x + y; - // w := z - 2; + // { + // x := i32(1); + // y := i32(2); + // z := x + y; + // w := z - 2; + // } // f := foo; diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index fd7b7030d..d676e2148 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -761,6 +761,7 @@ void lb_add_procedure_value(lbModule *m, lbProcedure *p) { if (p->entity != nullptr) { map_set(&m->procedure_values, hash_pointer(p->value), p->entity); } + map_set(&m->procedures, hash_string(p->name), p); } @@ -784,12 +785,26 @@ void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *nam lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { GB_ASSERT(entity != nullptr); + String link_name = lb_get_entity_name(m, entity); + + { + HashKey key = hash_string(link_name); + lbValue *found = map_get(&m->members, key); + if (found) { + lb_add_entity(m, entity, *found); + lbProcedure **p_found = map_get(&m->procedures, key); + GB_ASSERT(p_found != nullptr); + return *p_found; + } + } + + lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure); p->module = m; entity->code_gen_module = m; p->entity = entity; - p->name = lb_get_entity_name(m, entity); + p->name = link_name; DeclInfo *decl = entity->decl_info; @@ -817,23 +832,17 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { p->context_stack.allocator = a; - char *name = alloc_cstring(heap_allocator(), p->name); + char *c_link_name = alloc_cstring(heap_allocator(), p->name); LLVMTypeRef func_ptr_type = lb_type(m, p->type); LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type); - p->value = LLVMAddFunction(m->mod, name, func_type); - - lbValue value = {}; - value.type = p->type; - value.value = p->value; - lb_add_entity(m, entity, value); - lb_add_procedure_value(m, p); - + p->value = LLVMAddFunction(m->mod, c_link_name, func_type); LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]); lbValue proc_value = {p->value, p->type}; lb_add_entity(m, entity, proc_value); lb_add_member(m, p->name, proc_value); + lb_add_procedure_value(m, p); // NOTE(bill): offset==0 is the return value @@ -887,12 +896,15 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { cast(LLVMMetadataRef)entity->file->llvm_metadata; } LLVMMetadataRef scope = nullptr; + LLVMMetadataRef type = nullptr; + + // type = LLVMDIBuilderCreateSubroutineType(m->debug_builder, file, nullptr, 0, LLVMDIFlagZero); LLVMMetadataRef res = LLVMDIBuilderCreateFunction(m->debug_builder, scope, cast(char const *)entity->token.string.text, entity->token.string.len, cast(char const *)p->name.text, p->name.len, - file, line, nullptr, + file, line, type, true, p->body == nullptr, line, LLVMDIFlagZero, false ); @@ -903,6 +915,97 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { return p; } +lbProcedure *lb_create_dummy_procedure(lbModule *m, String link_name, Type *type) { + { + HashKey key = hash_string(link_name); + lbValue *found = map_get(&m->members, key); + GB_ASSERT(found == nullptr); + } + + lbProcedure *p = gb_alloc_item(heap_allocator(), lbProcedure); + + p->module = m; + p->name = link_name; + + p->type = type; + p->type_expr = nullptr; + p->body = nullptr; + p->tags = 0; + p->inlining = ProcInlining_none; + p->is_foreign = false; + p->is_export = false; + p->is_entry_point = false; + + gbAllocator a = heap_allocator(); + p->children.allocator = a; + p->params.allocator = a; + p->defer_stmts.allocator = a; + p->blocks.allocator = a; + p->branch_blocks.allocator = a; + p->context_stack.allocator = a; + + + char *c_link_name = alloc_cstring(heap_allocator(), p->name); + LLVMTypeRef func_ptr_type = lb_type(m, p->type); + LLVMTypeRef func_type = LLVMGetElementType(func_ptr_type); + + p->value = LLVMAddFunction(m->mod, c_link_name, func_type); + + Type *pt = p->type; + + LLVMSetFunctionCallConv(p->value, lb_calling_convention_map[pt->Proc.calling_convention]); + lbValue proc_value = {p->value, p->type}; + lb_add_member(m, p->name, proc_value); + lb_add_procedure_value(m, p); + + + // NOTE(bill): offset==0 is the return value + isize offset = 1; + if (pt->Proc.return_by_pointer) { + lb_add_proc_attribute_at_index(p, 1, "sret"); + lb_add_proc_attribute_at_index(p, 1, "noalias"); + offset = 2; + } + + isize parameter_index = 0; + if (pt->Proc.param_count) { + TypeTuple *params = &pt->Proc.params->Tuple; + for (isize i = 0; i < pt->Proc.param_count; i++) { + Entity *e = params->variables[i]; + Type *original_type = e->type; + Type *abi_type = pt->Proc.abi_compat_params[i]; + if (e->kind != Entity_Variable) continue; + + if (i+1 == params->variables.count && pt->Proc.c_vararg) { + continue; + } + if (is_type_tuple(abi_type)) { + for_array(j, abi_type->Tuple.variables) { + Type *tft = abi_type->Tuple.variables[j]->type; + if (e->flags&EntityFlag_NoAlias) { + lb_add_proc_attribute_at_index(p, offset+parameter_index+j, "noalias"); + } + } + parameter_index += abi_type->Tuple.variables.count; + } else { + if (e->flags&EntityFlag_NoAlias) { + lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias"); + } + parameter_index += 1; + } + } + } + + if (pt->Proc.calling_convention == ProcCC_Odin) { + lb_add_proc_attribute_at_index(p, offset+parameter_index, "noalias"); + lb_add_proc_attribute_at_index(p, offset+parameter_index, "nonnull"); + lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture"); + } + + return p; +} + + lbValue lb_value_param(lbProcedure *p, Entity *e, Type *abi_type, i32 index, lbParamPasskind *kind_) { lbParamPasskind kind = lbParamPass_Value; @@ -1165,6 +1268,7 @@ void lb_end_procedure_body(lbProcedure *p) { if (p->type->Proc.result_count == 0) { LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block); if (!LLVMIsAReturnInst(instr)) { + lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr); LLVMBuildRetVoid(p->builder); } } @@ -1807,9 +1911,15 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { // lb_addr_store(p, lhs, new_value); } else { // TODO(bill): Assign op - // lbAddr lhs = lb_build_addr(p, as->lhs[0]); - // lbValue value = lb_build_expr(p, as->rhs[0]); - // lb_build_assign_op(p, lhs, value, cast(TokenKind)op); + lbAddr lhs = lb_build_addr(p, as->lhs[0]); + lbValue value = lb_build_expr(p, as->rhs[0]); + + lbValue 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, cast(TokenKind)op, old_value, change, type); + lb_addr_store(p, lhs, new_value); } return; } @@ -1887,6 +1997,8 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { res = lb_emit_load(p, res); } + lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr); + if (p->type->Proc.return_by_pointer) { if (res.value != nullptr) { lb_addr_store(p, p->return_ptr, res); @@ -2176,7 +2288,7 @@ lbValue lb_const_undef(lbModule *m, Type *type) { } -lbValue lb_const_int(lbModule *m, Type *type, u64 value) { +lbValue lb_const_int(lbModule *m, Type *type, unsigned long long value) { lbValue res = {}; res.value = LLVMConstInt(lb_type(m, type), value, !is_type_unsigned(type)); res.type = type; @@ -2489,7 +2601,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { return res; } - LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), len, true); + LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true); LLVMValueRef values[2] = {ptr, str_len}; res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); @@ -2506,6 +2618,9 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { res.value = LLVMConstBitCast(i, lb_type(m, original_type)); } else { res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); + if (value.value_integer.neg) { + res.value = LLVMConstNeg(res.value); + } } return res; case ExactValue_Float: @@ -3160,6 +3275,39 @@ lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { return {}; } + +String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) { + Type *prev_src = src; + // Type *prev_dst = dst; + src = base_type(type_deref(src)); + // dst = base_type(type_deref(dst)); + bool src_is_ptr = src != prev_src; + // bool dst_is_ptr = dst != prev_dst; + + GB_ASSERT(is_type_struct(src) || is_type_union(src)); + for_array(i, src->Struct.fields) { + Entity *f = src->Struct.fields[i]; + if (f->kind == Entity_Variable && f->flags & EntityFlag_Using) { + if (are_types_identical(dst, f->type)) { + return f->token.string; + } + if (src_is_ptr && is_type_pointer(dst)) { + if (are_types_identical(type_deref(dst), f->type)) { + return f->token.string; + } + } + if (is_type_struct(f->type)) { + String name = lookup_subtype_polymorphic_field(info, dst, f->type); + if (name.len > 0) { + return name; + } + } + } + } + return str_lit(""); +} + + lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { lbModule *m = p->module; t = reduce_tuple_to_single_type(t); @@ -3188,12 +3336,13 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { return lb_emit_conv(p, lb_addr_load(p, default_value), t_any); } else if (dst->kind == Type_Basic) { if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) { + // TODO(bill): This is kind of a hack unsigned indices[1] = {0}; - LLVMValueRef data = LLVMConstExtractValue(value.value, indices, 1); - char const *text = nullptr; - size_t length = 0; - text = LLVMGetAsString(data, &length); - GB_PANIC("HERE %.*s", cast(int)length, text); + LLVMValueRef data = LLVMConstExtractValue(value.value, indices, gb_count_of(indices)); + lbValue res = {}; + res.type = t; + res.value = data; + return res; } // if (is_type_float(dst)) { // return value; @@ -3343,58 +3492,61 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { return res; } -#if 0 if (is_type_complex(src) && is_type_complex(dst)) { Type *ft = base_complex_elem_type(dst); - lbValue gen = lb_add_local_generated(p, dst, false); - lbValue real = lb_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); - lbValue imag = lb_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); - lb_emit_store(p, ir_emit_struct_ep(p, gen, 0), real); - lb_emit_store(p, ir_emit_struct_ep(p, gen, 1), imag); - return lb_emit_load(p, gen); + lbAddr gen = lb_add_local_generated(p, dst, false); + lbValue gp = lb_addr_get_ptr(p, gen); + lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft); + lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft); + lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real); + lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), imag); + return lb_addr_load(p, gen); } if (is_type_quaternion(src) && is_type_quaternion(dst)) { // @QuaternionLayout Type *ft = base_complex_elem_type(dst); - lbValue gen = lb_add_local_generated(p, dst, false); - lbValue q0 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); - lbValue q1 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); - lbValue q2 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 2), ft); - lbValue q3 = lb_emit_conv(p, ir_emit_struct_ev(p, value, 3), ft); - lb_emit_store(p, ir_emit_struct_ep(p, gen, 0), q0); - lb_emit_store(p, ir_emit_struct_ep(p, gen, 1), q1); - lb_emit_store(p, ir_emit_struct_ep(p, gen, 2), q2); - lb_emit_store(p, ir_emit_struct_ep(p, gen, 3), q3); - return lb_emit_load(p, gen); + lbAddr gen = lb_add_local_generated(p, dst, false); + lbValue gp = lb_addr_get_ptr(p, gen); + lbValue q0 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft); + lbValue q1 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft); + lbValue q2 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 2), ft); + lbValue q3 = lb_emit_conv(p, lb_emit_struct_ev(p, value, 3), ft); + lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), q0); + lb_emit_store(p, lb_emit_struct_ep(p, gp, 1), q1); + lb_emit_store(p, lb_emit_struct_ep(p, gp, 2), q2); + lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), q3); + return lb_addr_load(p, gen); } if (is_type_float(src) && is_type_complex(dst)) { Type *ft = base_complex_elem_type(dst); - lbValue gen = lb_add_local_generated(p, dst, true); + lbAddr gen = lb_add_local_generated(p, dst, true); + lbValue gp = lb_addr_get_ptr(p, gen); lbValue real = lb_emit_conv(p, value, ft); - lb_emit_store(p, ir_emit_struct_ep(p, gen, 0), real); - return lb_emit_load(p, gen); + lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), real); + return lb_addr_load(p, gen); } if (is_type_float(src) && is_type_quaternion(dst)) { Type *ft = base_complex_elem_type(dst); - lbValue gen = lb_add_local_generated(p, dst, true); + lbAddr gen = lb_add_local_generated(p, dst, true); + lbValue gp = lb_addr_get_ptr(p, gen); lbValue real = lb_emit_conv(p, value, ft); // @QuaternionLayout - lb_emit_store(p, ir_emit_struct_ep(p, gen, 3), real); - return lb_emit_load(p, gen); + lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real); + return lb_addr_load(p, gen); } if (is_type_complex(src) && is_type_quaternion(dst)) { Type *ft = base_complex_elem_type(dst); - lbValue gen = lb_add_local_generated(p, dst, true); - lbValue real = lb_emit_conv(p, ir_emit_struct_ev(p, value, 0), ft); - lbValue imag = lb_emit_conv(p, ir_emit_struct_ev(p, value, 1), ft); + lbAddr gen = lb_add_local_generated(p, dst, true); + lbValue gp = lb_addr_get_ptr(p, gen); + lbValue real = lb_emit_conv(p, lb_emit_struct_ev(p, value, 0), ft); + lbValue imag = lb_emit_conv(p, lb_emit_struct_ev(p, value, 1), ft); // @QuaternionLayout - lb_emit_store(p, ir_emit_struct_ep(p, gen, 3), real); - lb_emit_store(p, ir_emit_struct_ep(p, gen, 0), imag); - return lb_emit_load(p, gen); + lb_emit_store(p, lb_emit_struct_ep(p, gp, 3), real); + lb_emit_store(p, lb_emit_struct_ep(p, gp, 0), imag); + return lb_addr_load(p, gen); } -#endif // float <-> integer if (is_type_float(src) && is_type_integer(dst)) { @@ -3444,6 +3596,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { } } } +#endif // NOTE(bill): This has to be done before 'Pointer <-> Pointer' as it's // subtype polymorphism casting @@ -3459,22 +3612,21 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { bool dt_is_ptr = type_deref(dt) != dt; GB_ASSERT(is_type_struct(st) || is_type_raw_union(st)); - String field_name = ir_lookup_subtype_polymorphic_field(p->module->info, t, src_type); + String field_name = lookup_subtype_polymorphic_field(p->module->info, t, src_type); if (field_name.len > 0) { // NOTE(bill): It can be casted Selection sel = lookup_field(st, field_name, false, true); if (sel.entity != nullptr) { - ir_emit_comment(p, str_lit("cast - polymorphism")); if (st_is_ptr) { lbValue res = lb_emit_deep_field_gep(p, value, sel); - Type *rt = ir_type(res); + Type *rt = res.type; if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) { res = lb_emit_load(p, res); } return res; } else { - if (is_type_pointer(ir_type(value))) { - Type *rt = ir_type(value); + if (is_type_pointer(value.type)) { + Type *rt = value.type; if (!are_types_identical(rt, dt) && are_types_identical(type_deref(rt), dt)) { value = lb_emit_load(p, value); } else { @@ -3483,7 +3635,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { } } - return ir_emit_deep_field_ev(p, value, sel); + return lb_emit_deep_field_ev(p, value, sel); } } else { @@ -3491,7 +3643,6 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { } } } -#endif @@ -3578,8 +3729,8 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { lbValue id = lb_typeid(p->module, st); - lb_emit_store(p, ir_emit_struct_ep(p, result, 0), data); - lb_emit_store(p, ir_emit_struct_ep(p, result, 1), id); + lb_emit_store(p, lb_emit_struct_ep(p, result, 0), data); + lb_emit_store(p, lb_emit_struct_ep(p, result, 1), id); return lb_emit_load(p, result); } @@ -4022,10 +4173,27 @@ lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) { } +lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel) { + lbValue ptr = lb_address_from_load_or_generate_local(p, e); + lbValue res = lb_emit_deep_field_gep(p, ptr, sel); + return lb_emit_load(p, res); +} + + + void lb_build_defer_stmt(lbProcedure *p, lbDefer d) { - lbBlock *b = lb_create_block(p, "defer"); // NOTE(bill): The prev block may defer injection before it's terminator LLVMValueRef last_instr = LLVMGetLastInstruction(p->curr_block->block); + if (last_instr != nullptr && LLVMIsAReturnInst(last_instr)) { + // NOTE(bill): ReturnStmt defer stuff will be handled previously + return; + } + + lbBlock *b = lb_create_block(p, "defer"); + if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) { + lb_emit_jump(p, b); + } + if (last_instr == nullptr || !LLVMIsATerminatorInst(last_instr)) { lb_emit_jump(p, b); } @@ -6207,16 +6375,16 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { String name = e->token.string; /*if (name == "names") { lbValue ti_ptr = lb_type_info(p, type); - lbValue variant = ir_emit_struct_ep(p, ti_ptr, 2); + lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2); lbValue names_ptr = nullptr; if (is_type_enum(type)) { lbValue enum_info = lb_emit_conv(p, variant, t_type_info_enum_ptr); - names_ptr = ir_emit_struct_ep(p, enum_info, 1); + names_ptr = lb_emit_struct_ep(p, enum_info, 1); } else if (type->kind == Type_Struct) { lbValue struct_info = lb_emit_conv(p, variant, t_type_info_struct_ptr); - names_ptr = ir_emit_struct_ep(p, struct_info, 1); + names_ptr = lb_emit_struct_ep(p, struct_info, 1); } return ir_addr(names_ptr); } else */{ @@ -7329,12 +7497,6 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { output_file_path = gb_string_appendc(output_file_path, ".obj"); defer (gb_string_free(output_file_path)); - gbFileError err = gb_file_create(&gen->output_file, output_file_path); - if (err != gbFileError_None) { - gb_printf_err("Failed to create file %s\n", output_file_path); - return false; - } - gen->info = &c->info; gen->module.info = &c->info; @@ -7351,6 +7513,7 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { map_init(&gen->module.values, a); map_init(&gen->module.members, a); map_init(&gen->module.procedure_values, a); + map_init(&gen->module.procedures, a); map_init(&gen->module.const_strings, a); map_init(&gen->module.const_string_byte_slices, a); map_init(&gen->module.anonymous_proc_lits, a); @@ -7600,10 +7763,14 @@ void lb_generate_code(lbGenerator *gen) { for_array(i, m->procedures_to_generate) { lbProcedure *p = m->procedures_to_generate[i]; + if (p->is_done) { + continue; + } if (p->body != nullptr) { // Build Procedure lb_begin_procedure_body(p); lb_build_stmt(p, p->body); lb_end_procedure_body(p); + p->is_done = true; } lb_end_procedure(p); @@ -7626,8 +7793,7 @@ void lb_generate_code(lbGenerator *gen) { LLVMAddAggressiveInstCombinerPass(function_pass_manager); LLVMAddConstantPropagationPass(function_pass_manager); LLVMAddAggressiveDCEPass(function_pass_manager); - LLVMAddDeadStoreEliminationPass(function_pass_manager); - LLVMAddLoopIdiomPass(function_pass_manager); + LLVMAddMergedLoadStoreMotionPass(function_pass_manager); LLVMAddPromoteMemoryToRegisterPass(function_pass_manager); // LLVMAddUnifyFunctionExitNodesPass(function_pass_manager); @@ -7650,90 +7816,97 @@ void lb_generate_code(lbGenerator *gen) { LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false); LLVMRunPassManager(module_pass_manager, mod); - gb_printf_err("Done\n"); - if (!(build_context.is_dll && !has_dll_main)) { LLVMContextRef ctx = LLVMGetModuleContext(mod); - LLVMTypeRef llvm_i32 = LLVMInt32TypeInContext(ctx); + Type *params = alloc_type_tuple(); + Type *results = alloc_type_tuple(); - LLVMTypeRef ptr_cstr = LLVMPointerType(LLVMPointerType(LLVMInt8TypeInContext(ctx), 0), 0); - LLVMTypeRef params[2] = {llvm_i32, ptr_cstr}; - LLVMTypeRef func_type = LLVMFunctionType(llvm_i32, params, gb_count_of(params), false); + array_init(¶ms->Tuple.variables, heap_allocator(), 2); + params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true); + params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true); - LLVMValueRef fn = LLVMAddFunction(mod, "main", func_type); + array_init(&results->Tuple.variables, heap_allocator(), 1); + results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true); - LLVMBuilderRef builder = LLVMCreateBuilder(); - LLVMBasicBlockRef block = LLVMAppendBasicBlockInContext(ctx, fn, "entry"); - LLVMPositionBuilderAtEnd(builder, block); + Type *proc_type = alloc_type_proc(nullptr, params, 2, results, 1, false, ProcCC_CDecl); - // for_array(i, global_variables) { - // auto *var = &global_variables[i]; - // if (var->decl->init_expr != nullptr) { - // var->init = ir_build_expr(proc, var->decl->init_expr); - // } + lbProcedure *p = lb_create_dummy_procedure(m, str_lit("main"), proc_type); - // Entity *e = var->var->Global.entity; - // GB_ASSERT(e->kind == Entity_Variable); + lb_begin_procedure_body(p); + for_array(i, global_variables) { + auto *var = &global_variables[i]; + if (var->decl->init_expr != nullptr) { + var->init = lb_build_expr(p, var->decl->init_expr); + } - // if (e->Variable.is_foreign) { - // Entity *fl = e->Procedure.foreign_library; - // ir_add_foreign_library_path(m, fl); - // } + Entity *e = var->decl->entity; + GB_ASSERT(e->kind == Entity_Variable); - // if (e->flags & EntityFlag_Static) { - // var->var->Global.is_internal = true; - // } + if (e->Variable.is_foreign) { + Entity *fl = e->Procedure.foreign_library; + // lb_add_foreign_library_path(m, fl); + } - // if (var->init != nullptr) { - // Type *t = type_deref(ir_type(var->var)); - - // if (is_type_any(t)) { - // // NOTE(bill): Edge case for 'any' type - // Type *var_type = default_type(ir_type(var->init)); - // irValue *g = ir_add_global_generated(proc->module, var_type, var->init); - // ir_emit_store(proc, g, var->init); - - // irValue *data = ir_emit_struct_ep(proc, var->var, 0); - // irValue *ti = ir_emit_struct_ep(proc, var->var, 1); - // ir_emit_store(proc, data, ir_emit_conv(proc, g, t_rawptr)); - // ir_emit_store(proc, ti, ir_type_info(proc, var_type)); - // } else { - // ir_emit_store(proc, var->var, ir_emit_conv(proc, var->init, t)); - // } - // } - // } + if (e->flags & EntityFlag_Static) { + LLVMSetLinkage(var->var.value, LLVMInternalLinkage); + } + + if (var->init.value != nullptr) { + Type *t = type_deref(var->var.type); + + if (is_type_any(t)) { + // NOTE(bill): Edge case for 'any' type + Type *var_type = default_type(var->init.type); + lbAddr g = lb_add_global_generated(m, var_type, var->init); + lb_addr_store(p, g, var->init); + lbValue gp = lb_addr_get_ptr(p, g); + + lbValue data = lb_emit_struct_ep(p, var->var, 0); + lbValue ti = lb_emit_struct_ep(p, var->var, 1); + lb_emit_store(p, data, lb_emit_conv(p, gp, t_rawptr)); + lb_emit_store(p, ti, lb_type_info(m, var_type)); + } else { + lb_emit_store(p, var->var, lb_emit_conv(p, var->init, t)); + } + } + } lbValue *found = map_get(&m->values, hash_entity(entry_point)); GB_ASSERT(found != nullptr); - LLVMBuildCall2(builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, ""); - LLVMBuildRet(builder, LLVMConstInt(llvm_i32, 0, false)); + LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, ""); + LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false)); - LLVMDisposeBuilder(builder); - if (LLVMVerifyFunction(fn, LLVMReturnStatusAction)) { + lb_end_procedure_body(p); + + if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main"); - LLVMDumpValue(fn); + LLVMDumpValue(p->value); gb_printf_err("\n\n\n\n"); - LLVMVerifyFunction(fn, LLVMAbortProcessAction); + LLVMVerifyFunction(p->value, LLVMAbortProcessAction); } - LLVMRunFunctionPassManager(function_pass_manager, fn); + LLVMRunFunctionPassManager(function_pass_manager, p->value); } char *llvm_error = nullptr; defer (LLVMDisposeMessage(llvm_error)); + String filepath_ll = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".ll")); + String filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".obj")); + defer (gb_free(heap_allocator(), filepath_ll.text)); + defer (gb_free(heap_allocator(), filepath_obj.text)); + LLVMDIBuilderFinalize(m->debug_builder); LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); llvm_error = nullptr; - LLVMBool failure = LLVMPrintModuleToFile(mod, "llvm_demo.ll", &llvm_error); - + LLVMBool failure = LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error); LLVMInitializeAllTargetInfos(); LLVMInitializeAllTargets(); @@ -7754,11 +7927,10 @@ void lb_generate_code(lbGenerator *gen) { LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault); defer (LLVMDisposeTargetMachine(target_machine)); - LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, "llvm_demo.obj", LLVMObjectFile, &llvm_error); + LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, LLVMObjectFile, &llvm_error); if (ok) { gb_printf_err("LLVM Error: %s\n", llvm_error); return; } - gb_printf_err(".obj generated\n"); } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 47ff5962b..90fc85ff2 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -63,6 +63,7 @@ struct lbModule { Map values; // Key: Entity * Map members; // Key: String + Map procedures; // Key: String Map procedure_values; // Key: LLVMValueRef Map const_strings; // Key: String @@ -87,7 +88,6 @@ struct lbGenerator { lbModule module; CheckerInfo *info; - gbFile output_file; String output_base; String output_name; }; @@ -180,6 +180,7 @@ struct lbProcedure { LLVMValueRef value; LLVMBuilderRef builder; + bool is_done; lbAddr return_ptr; Array params; @@ -249,6 +250,7 @@ lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index); lbValue lb_emit_array_epi(lbProcedure *p, lbValue value, i32 index); lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index); lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel); +lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel); lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type); lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type); diff --git a/src/tokenizer.cpp b/src/tokenizer.cpp index 1854020f9..5ac590b22 100644 --- a/src/tokenizer.cpp +++ b/src/tokenizer.cpp @@ -179,6 +179,10 @@ Token make_token_ident(String s) { Token t = {Token_Ident, s}; return t; } +Token make_token_ident(char const *s) { + Token t = {Token_Ident, make_string_c(s)}; + return t; +} struct ErrorCollector { -- cgit v1.2.3 From 470508adbc9fb8b0e79d8ef1c7ca6a92d4babfcd Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 26 Feb 2020 22:05:52 +0000 Subject: Clean-up initialization code --- src/ir.cpp | 2 +- src/llvm_backend.cpp | 649 ++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 619 insertions(+), 32 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/ir.cpp b/src/ir.cpp index 5568861de..8f6f60c5f 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -15,7 +15,7 @@ struct irModule { u64 state_flags; // String source_filename; - String layout; + // String layout; // String triple; PtrSet min_dep_set; diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index d676e2148..547d3b8f3 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -1,5 +1,7 @@ #include "llvm_backend.hpp" +gb_global lbValue lb_global_type_info_data = {}; + struct lbLoopData { lbAddr idx_addr; lbValue idx; @@ -1492,7 +1494,7 @@ void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) { String name = make_string(cast(u8 *)name_text, name_len-1); e->TypeName.ir_mangled_name = name; - // irValue *value = ir_value_type_name(name, e->type); + // lbValue value = ir_value_type_name(name, e->type); // ir_add_entity_name(m, e, name); // ir_gen_global_type_name(m, e, name); } else if (e->kind == Entity_Procedure) { @@ -3929,7 +3931,7 @@ lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { result_type = alloc_type_pointer(t->Struct.fields[index]->type); } else if (is_type_union(t)) { GB_ASSERT(index == -1); - // return ir_emit_union_tag_ptr(proc, s); + // return ir_emit_union_tag_ptr(p, s); GB_PANIC("ir_emit_union_tag_ptr"); } else if (is_type_tuple(t)) { GB_ASSERT(t->Tuple.variables.count > 0); @@ -4050,7 +4052,7 @@ lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) { break; case Type_Union: GB_ASSERT(index == -1); - // return lb_emit_union_tag_value(proc, s); + // return lb_emit_union_tag_value(p, s); GB_PANIC("lb_emit_union_tag_value"); case Type_Tuple: @@ -6465,18 +6467,18 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { case_ast_node(ta, TypeAssertion, expr); gbAllocator a = heap_allocator(); TokenPos pos = ast_token(expr).pos; - lbValue e = lb_build_expr(proc, ta->expr); + lbValue e = lb_build_expr(p, ta->expr); Type *t = type_deref(ir_type(e)); if (is_type_union(t)) { Type *type = type_of_expr(expr); - lbValue v = lb_add_local_generated(proc, type, false); - ir_emit_comment(proc, str_lit("cast - union_cast")); - lb_emit_store(proc, v, ir_emit_union_cast(proc, lb_build_expr(proc, ta->expr), type, pos)); + lbValue v = lb_add_local_generated(p, type, false); + ir_emit_comment(p, str_lit("cast - union_cast")); + lb_emit_store(p, v, ir_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos)); return ir_addr(v); } else if (is_type_any(t)) { - ir_emit_comment(proc, str_lit("cast - any_cast")); + ir_emit_comment(p, str_lit("cast - any_cast")); Type *type = type_of_expr(expr); - return ir_emit_any_cast_addr(proc, lb_build_expr(proc, ta->expr), type, pos); + return ir_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos); } else { GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e))); } @@ -6958,18 +6960,18 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { // gbAllocator a = heap_allocator(); // { // auto args = array_make(a, 3); - // args[0] = ir_gen_map_header(proc, v, type); + // args[0] = ir_gen_map_header(p, v, type); // args[1] = ir_const_int(2*cl->elems.count); - // args[2] = ir_emit_source_code_location(proc, proc_name, pos); - // lb_emit_runtime_call(proc, "__dynamic_map_reserve", args); + // args[2] = ir_emit_source_code_location(p, proc_name, pos); + // lb_emit_runtime_call(p, "__dynamic_map_reserve", args); // } // for_array(field_index, cl->elems) { // Ast *elem = cl->elems[field_index]; // ast_node(fv, FieldValue, elem); - // lbValue key = lb_build_expr(proc, fv->field); - // lbValue value = lb_build_expr(proc, fv->value); - // ir_insert_dynamic_map_key_and_value(proc, v, type, key, value); + // lbValue key = lb_build_expr(p, fv->field); + // lbValue value = lb_build_expr(p, fv->value); + // ir_insert_dynamic_map_key_and_value(p, v, type, key, value); // } break; } @@ -7334,13 +7336,13 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { { auto args = array_make(a, 6); - args[0] = lb_emit_conv(proc, v, t_rawptr); + args[0] = lb_emit_conv(p, v, t_rawptr); args[1] = size; args[2] = align; - args[3] = lb_emit_conv(proc, items, t_rawptr); + args[3] = lb_emit_conv(p, items, t_rawptr); args[4] = ir_const_int(item_count); - args[5] = ir_emit_source_code_location(proc, proc_name, pos); - lb_emit_runtime_call(proc, "__dynamic_array_append", args); + args[5] = ir_emit_source_code_location(p, proc_name, pos); + lb_emit_runtime_call(p, "__dynamic_array_append", args); } #endif break; @@ -7551,6 +7553,563 @@ lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) { return lb_addr(g); } +lbValue lb_find_global_variable(lbModule *m, String const &name) { + lbValue *found = map_get(&m->values, hash_string(name)); + GB_ASSERT_MSG(found != nullptr, "Unable to find global variable '%.*s'", LIT(name)); + lbValue value = *found; + return value; +} + + + +void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data + lbModule *m = p->module; + gbAllocator a = heap_allocator(); + CheckerInfo *info = m->info; + +#if 0 + if (true) { + lbValue global_type_table = lb_find_global_variable(m, str_lit("runtime.type_table")); + Type *type = base_type(type_deref(lb_global_type_info_data.type)); + GB_ASSERT(is_type_array(type)); + lbValue len = ir_const_int(type->Array.count); + ir_fill_slice(p, global_type_table, + ir_emit_array_epi(p, lb_global_type_info_data, 0), + len); + } + + + // Useful types + Type *t_i64_slice_ptr = alloc_type_pointer(alloc_type_slice(t_i64)); + Type *t_string_slice_ptr = alloc_type_pointer(alloc_type_slice(t_string)); + + i32 type_info_member_types_index = 0; + i32 type_info_member_names_index = 0; + i32 type_info_member_offsets_index = 0; + + for_array(type_info_type_index, info->type_info_types) { + Type *t = info->type_info_types[type_info_type_index]; + t = default_type(t); + if (t == t_invalid) { + continue; + } + + isize entry_index = ir_type_info_index(info, t, false); + if (entry_index <= 0) { + continue; + } + + lbValue tag = nullptr; + lbValue ti_ptr = ir_emit_array_epi(p, lb_global_type_info_data, cast(i32)entry_index); + lbValue variant_ptr = ir_emit_struct_ep(p, ti_ptr, 3); + + ir_emit_store(p, ir_emit_struct_ep(p, ti_ptr, 0), ir_const_int(type_size_of(t))); + ir_emit_store(p, ir_emit_struct_ep(p, ti_ptr, 1), ir_const_int(type_align_of(t))); + ir_emit_store(p, ir_emit_struct_ep(p, ti_ptr, 2), ir_typeid(proc->module, t)); + + + switch (t->kind) { + case Type_Named: { + ir_emit_comment(p, str_lit("Type_Info_Named")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_named_ptr); + + // TODO(bill): Which is better? The mangled name or actual name? + lbValue name = ir_const_string(proc->module, t->Named.type_name->token.string); + lbValue gtip = ir_get_type_info_ptr(p, t->Named.base); + + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), name); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 1), gtip); + break; + } + + case Type_Basic: + ir_emit_comment(p, str_lit("Type_Info_Basic")); + switch (t->Basic.kind) { + case Basic_bool: + case Basic_b8: + case Basic_b16: + case Basic_b32: + case Basic_b64: + tag = ir_emit_conv(p, variant_ptr, t_type_info_boolean_ptr); + 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 = ir_emit_conv(p, variant_ptr, t_type_info_integer_ptr); + lbValue is_signed = ir_const_bool((t->Basic.flags & BasicFlag_Unsigned) == 0); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), is_signed); + // 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; + } + lbValue endianness = ir_const_u8(endianness_value); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 1), endianness); + break; + } + + case Basic_rune: + tag = ir_emit_conv(p, variant_ptr, t_type_info_rune_ptr); + break; + + // case Basic_f16: + case Basic_f32: + case Basic_f64: + tag = ir_emit_conv(p, variant_ptr, t_type_info_float_ptr); + break; + + // case Basic_complex32: + case Basic_complex64: + case Basic_complex128: + tag = ir_emit_conv(p, variant_ptr, t_type_info_complex_ptr); + break; + + case Basic_quaternion128: + case Basic_quaternion256: + tag = ir_emit_conv(p, variant_ptr, t_type_info_quaternion_ptr); + break; + + case Basic_rawptr: + tag = ir_emit_conv(p, variant_ptr, t_type_info_pointer_ptr); + break; + + case Basic_string: + tag = ir_emit_conv(p, variant_ptr, t_type_info_string_ptr); + break; + + case Basic_cstring: + tag = ir_emit_conv(p, variant_ptr, t_type_info_string_ptr); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), v_true); // is_cstring + break; + + case Basic_any: + tag = ir_emit_conv(p, variant_ptr, t_type_info_any_ptr); + break; + + case Basic_typeid: + tag = ir_emit_conv(p, variant_ptr, t_type_info_typeid_ptr); + break; + } + break; + + case Type_Pointer: { + ir_emit_comment(p, str_lit("Type_Info_Pointer")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_pointer_ptr); + lbValue gep = ir_get_type_info_ptr(p, t->Pointer.elem); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), gep); + break; + } + case Type_Array: { + ir_emit_comment(p, str_lit("Type_Info_Array")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_array_ptr); + lbValue gep = ir_get_type_info_ptr(p, t->Array.elem); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), gep); + + i64 ez = type_size_of(t->Array.elem); + lbValue elem_size = ir_emit_struct_ep(p, tag, 1); + ir_emit_store(p, elem_size, ir_const_int(ez)); + + lbValue count = ir_emit_struct_ep(p, tag, 2); + ir_emit_store(p, count, ir_const_int(t->Array.count)); + + break; + } + case Type_EnumeratedArray: { + ir_emit_comment(p, str_lit("Type_Info_Enumerated_Array")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_enumerated_array_ptr); + lbValue elem = ir_get_type_info_ptr(p, t->EnumeratedArray.elem); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), elem); + + lbValue index = ir_get_type_info_ptr(p, t->EnumeratedArray.index); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 1), index); + + i64 ez = type_size_of(t->EnumeratedArray.elem); + lbValue elem_size = ir_emit_struct_ep(p, tag, 2); + ir_emit_store(p, elem_size, ir_const_int(ez)); + + lbValue count = ir_emit_struct_ep(p, tag, 3); + ir_emit_store(p, count, ir_const_int(t->EnumeratedArray.count)); + + lbValue min_value = ir_emit_struct_ep(p, tag, 4); + lbValue max_value = ir_emit_struct_ep(p, tag, 5); + + lbValue min_v = ir_value_constant(core_type(t->EnumeratedArray.index), t->EnumeratedArray.min_value); + lbValue max_v = ir_value_constant(core_type(t->EnumeratedArray.index), t->EnumeratedArray.max_value); + + ir_emit_store_union_variant(p, min_value, min_v, ir_type(min_v)); + ir_emit_store_union_variant(p, max_value, max_v, ir_type(max_v)); + break; + } + case Type_DynamicArray: { + ir_emit_comment(p, str_lit("Type_Info_Dynamic_Array")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_dynamic_array_ptr); + lbValue gep = ir_get_type_info_ptr(p, t->DynamicArray.elem); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), gep); + + i64 ez = type_size_of(t->DynamicArray.elem); + lbValue elem_size = ir_emit_struct_ep(p, tag, 1); + ir_emit_store(p, elem_size, ir_const_int(ez)); + break; + } + case Type_Slice: { + ir_emit_comment(p, str_lit("Type_Info_Slice")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_slice_ptr); + lbValue gep = ir_get_type_info_ptr(p, t->Slice.elem); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), gep); + + i64 ez = type_size_of(t->Slice.elem); + lbValue elem_size = ir_emit_struct_ep(p, tag, 1); + ir_emit_store(p, elem_size, ir_const_int(ez)); + break; + } + case Type_Proc: { + ir_emit_comment(p, str_lit("Type_Info_Proc")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_procedure_ptr); + + lbValue params = ir_emit_struct_ep(p, tag, 0); + lbValue results = ir_emit_struct_ep(p, tag, 1); + lbValue variadic = ir_emit_struct_ep(p, tag, 2); + lbValue convention = ir_emit_struct_ep(p, tag, 3); + + if (t->Proc.params != nullptr) { + ir_emit_store(p, params, ir_get_type_info_ptr(p, t->Proc.params)); + } + if (t->Proc.results != nullptr) { + ir_emit_store(p, results, ir_get_type_info_ptr(p, t->Proc.results)); + } + ir_emit_store(p, variadic, ir_const_bool(t->Proc.variadic)); + ir_emit_store(p, convention, ir_const_int(t->Proc.calling_convention)); + + // TODO(bill): TypeInfo for procedures + break; + } + case Type_Tuple: { + ir_emit_comment(p, str_lit("Type_Info_Tuple")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_tuple_ptr); + + lbValue memory_types = ir_type_info_member_types_offset(p, t->Tuple.variables.count); + lbValue memory_names = ir_type_info_member_names_offset(p, t->Tuple.variables.count); + + for_array(i, t->Tuple.variables) { + // NOTE(bill): offset is not used for tuples + Entity *f = t->Tuple.variables[i]; + + lbValue index = ir_const_int(i); + lbValue type_info = ir_emit_ptr_offset(p, memory_types, index); + + ir_emit_store(p, type_info, ir_type_info(p, f->type)); + if (f->token.string.len > 0) { + lbValue name = ir_emit_ptr_offset(p, memory_names, index); + ir_emit_store(p, name, ir_const_string(proc->module, f->token.string)); + } + } + + lbValue count = ir_const_int(t->Tuple.variables.count); + ir_fill_slice(p, ir_emit_struct_ep(p, tag, 0), memory_types, count); + ir_fill_slice(p, ir_emit_struct_ep(p, tag, 1), memory_names, count); + break; + } + case Type_Enum: + ir_emit_comment(p, str_lit("Type_Info_Enum")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_enum_ptr); + { + GB_ASSERT(t->Enum.base_type != nullptr); + lbValue base = ir_type_info(p, t->Enum.base_type); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), base); + + if (t->Enum.fields.count > 0) { + auto fields = t->Enum.fields; + lbValue name_array = ir_generate_array(m, t_string, fields.count, + str_lit("$enum_names"), cast(i64)entry_index); + lbValue value_array = ir_generate_array(m, t_type_info_enum_value, fields.count, + str_lit("$enum_values"), cast(i64)entry_index); + + GB_ASSERT(is_type_integer(t->Enum.base_type)); + + for_array(i, fields) { + lbValue name_ep = ir_emit_array_epi(p, name_array, cast(i32)i); + lbValue value_ep = ir_emit_array_epi(p, value_array, cast(i32)i); + + ExactValue value = fields[i]->Constant.value; + lbValue v = ir_value_constant(t->Enum.base_type, value); + + ir_emit_store_union_variant(p, value_ep, v, ir_type(v)); + ir_emit_store(p, name_ep, ir_const_string(proc->module, fields[i]->token.string)); + } + + lbValue v_count = ir_const_int(fields.count); + + lbValue names = ir_emit_struct_ep(p, tag, 1); + lbValue name_array_elem = ir_array_elem(p, name_array); + ir_fill_slice(p, names, name_array_elem, v_count); + + lbValue values = ir_emit_struct_ep(p, tag, 2); + lbValue value_array_elem = ir_array_elem(p, value_array); + ir_fill_slice(p, values, value_array_elem, v_count); + } + } + break; + + case Type_Union: { + ir_emit_comment(p, str_lit("Type_Info_Union")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_union_ptr); + + { + lbValue variant_types = ir_emit_struct_ep(p, tag, 0); + lbValue tag_offset_ptr = ir_emit_struct_ep(p, tag, 1); + lbValue tag_type_ptr = ir_emit_struct_ep(p, tag, 2); + lbValue custom_align_ptr = ir_emit_struct_ep(p, tag, 3); + lbValue no_nil_ptr = ir_emit_struct_ep(p, tag, 4); + lbValue maybe_ptr = ir_emit_struct_ep(p, tag, 5); + + isize variant_count = gb_max(0, t->Union.variants.count); + lbValue memory_types = ir_type_info_member_types_offset(p, variant_count); + + // NOTE(bill): Zeroth is nil so ignore it + for (isize variant_index = 0; variant_index < variant_count; variant_index++) { + Type *vt = t->Union.variants[variant_index]; + lbValue tip = ir_get_type_info_ptr(p, vt); + + lbValue index = ir_const_int(variant_index); + lbValue type_info = ir_emit_ptr_offset(p, memory_types, index); + ir_emit_store(p, type_info, ir_type_info(p, vt)); + } + + lbValue count = ir_const_int(variant_count); + ir_fill_slice(p, variant_types, memory_types, count); + + i64 tag_size = union_tag_size(t); + i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size); + + if (tag_size > 0) { + ir_emit_store(p, tag_offset_ptr, ir_const_uintptr(tag_offset)); + ir_emit_store(p, tag_type_ptr, ir_type_info(p, union_tag_type(t))); + } + + lbValue is_custom_align = ir_const_bool(t->Union.custom_align != 0); + ir_emit_store(p, custom_align_ptr, is_custom_align); + + ir_emit_store(p, no_nil_ptr, ir_const_bool(t->Union.no_nil)); + ir_emit_store(p, maybe_ptr, ir_const_bool(t->Union.maybe)); + } + + break; + } + + case Type_Struct: { + ir_emit_comment(p, str_lit("Type_Info_Struct")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_struct_ptr); + + { + lbValue is_packed = ir_const_bool(t->Struct.is_packed); + lbValue is_raw_union = ir_const_bool(t->Struct.is_raw_union); + lbValue is_custom_align = ir_const_bool(t->Struct.custom_align != 0); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 5), is_packed); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 6), is_raw_union); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 7), is_custom_align); + + if (t->Struct.soa_kind != StructSoa_None) { + lbValue kind = ir_emit_struct_ep(p, tag, 8); + Type *kind_type = type_deref(ir_type(kind)); + + lbValue soa_kind = ir_value_constant(kind_type, exact_value_i64(t->Struct.soa_kind)); + lbValue soa_type = ir_type_info(p, t->Struct.soa_elem); + lbValue soa_len = ir_const_int(t->Struct.soa_count); + + + ir_emit_store(p, kind, soa_kind); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 9), soa_type); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 10), soa_len); + } + } + + isize count = t->Struct.fields.count; + if (count > 0) { + lbValue memory_types = ir_type_info_member_types_offset (p, count); + lbValue memory_names = ir_type_info_member_names_offset (p, count); + lbValue memory_offsets = ir_type_info_member_offsets_offset(p, count); + lbValue memory_usings = ir_type_info_member_usings_offset (p, count); + lbValue memory_tags = ir_type_info_member_tags_offset (p, count); + + type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet + for (isize source_index = 0; source_index < count; source_index++) { + // TODO(bill): Order fields in source order not layout order + Entity *f = t->Struct.fields[source_index]; + lbValue tip = ir_get_type_info_ptr(p, f->type); + i64 foffset = 0; + if (!t->Struct.is_raw_union) { + foffset = t->Struct.offsets[f->Variable.field_index]; + } + GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field); + + lbValue index = ir_const_int(source_index); + lbValue type_info = ir_emit_ptr_offset(p, memory_types, index); + lbValue offset = ir_emit_ptr_offset(p, memory_offsets, index); + lbValue is_using = ir_emit_ptr_offset(p, memory_usings, index); + + ir_emit_store(p, type_info, ir_type_info(p, f->type)); + if (f->token.string.len > 0) { + lbValue name = ir_emit_ptr_offset(p, memory_names, index); + ir_emit_store(p, name, ir_const_string(proc->module, f->token.string)); + } + ir_emit_store(p, offset, ir_const_uintptr(foffset)); + ir_emit_store(p, is_using, ir_const_bool((f->flags&EntityFlag_Using) != 0)); + + if (t->Struct.tags.count > 0) { + String tag_string = t->Struct.tags[source_index]; + if (tag_string.len > 0) { + lbValue tag_ptr = ir_emit_ptr_offset(p, memory_tags, index); + ir_emit_store(p, tag_ptr, ir_const_string(proc->module, tag_string)); + } + } + + } + + lbValue cv = ir_const_int(count); + ir_fill_slice(p, ir_emit_struct_ep(p, tag, 0), memory_types, cv); + ir_fill_slice(p, ir_emit_struct_ep(p, tag, 1), memory_names, cv); + ir_fill_slice(p, ir_emit_struct_ep(p, tag, 2), memory_offsets, cv); + ir_fill_slice(p, ir_emit_struct_ep(p, tag, 3), memory_usings, cv); + ir_fill_slice(p, ir_emit_struct_ep(p, tag, 4), memory_tags, cv); + } + break; + } + case Type_Map: { + ir_emit_comment(p, str_lit("Type_Info_Map")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_map_ptr); + init_map_internal_types(t); + + lbValue key = ir_emit_struct_ep(p, tag, 0); + lbValue value = ir_emit_struct_ep(p, tag, 1); + lbValue generated_struct = ir_emit_struct_ep(p, tag, 2); + + ir_emit_store(p, key, ir_get_type_info_ptr(p, t->Map.key)); + ir_emit_store(p, value, ir_get_type_info_ptr(p, t->Map.value)); + ir_emit_store(p, generated_struct, ir_get_type_info_ptr(p, t->Map.generated_struct_type)); + break; + } + + case Type_BitField: { + ir_emit_comment(p, str_lit("Type_Info_Bit_Field")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_bit_field_ptr); + // names: []string; + // bits: []u32; + // offsets: []u32; + isize count = t->BitField.fields.count; + if (count > 0) { + auto fields = t->BitField.fields; + lbValue name_array = ir_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index); + lbValue bit_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index); + lbValue offset_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index); + + for (isize i = 0; i < count; i++) { + Entity *f = fields[i]; + GB_ASSERT(f->type != nullptr); + GB_ASSERT(f->type->kind == Type_BitFieldValue); + lbValue name_ep = ir_emit_array_epi(p, name_array, cast(i32)i); + lbValue bit_ep = ir_emit_array_epi(p, bit_array, cast(i32)i); + lbValue offset_ep = ir_emit_array_epi(p, offset_array, cast(i32)i); + + ir_emit_store(p, name_ep, ir_const_string(proc->module, f->token.string)); + ir_emit_store(p, bit_ep, ir_const_i32(f->type->BitFieldValue.bits)); + ir_emit_store(p, offset_ep, ir_const_i32(t->BitField.offsets[i])); + + } + + lbValue v_count = ir_const_int(count); + + lbValue names = ir_emit_struct_ep(p, tag, 0); + lbValue name_array_elem = ir_array_elem(p, name_array); + ir_fill_slice(p, names, name_array_elem, v_count); + + lbValue bits = ir_emit_struct_ep(p, tag, 1); + lbValue bit_array_elem = ir_array_elem(p, bit_array); + ir_fill_slice(p, bits, bit_array_elem, v_count); + + lbValue offsets = ir_emit_struct_ep(p, tag, 2); + lbValue offset_array_elem = ir_array_elem(p, offset_array); + ir_fill_slice(p, offsets, offset_array_elem, v_count); + } + break; + } + + case Type_BitSet: + ir_emit_comment(p, str_lit("Type_Info_Bit_Set")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_bit_set_ptr); + + GB_ASSERT(is_type_typed(t->BitSet.elem)); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), ir_get_type_info_ptr(p, t->BitSet.elem)); + if (t->BitSet.underlying != nullptr) { + ir_emit_store(p, ir_emit_struct_ep(p, tag, 1), ir_get_type_info_ptr(p, t->BitSet.underlying)); + } + ir_emit_store(p, ir_emit_struct_ep(p, tag, 2), ir_const_i64(t->BitSet.lower)); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 3), ir_const_i64(t->BitSet.upper)); + break; + + case Type_Opaque: + ir_emit_comment(p, str_lit("Type_Opaque")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_opaque_ptr); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), ir_get_type_info_ptr(p, t->Opaque.elem)); + break; + + case Type_SimdVector: + ir_emit_comment(p, str_lit("Type_SimdVector")); + tag = ir_emit_conv(p, variant_ptr, t_type_info_simd_vector_ptr); + if (t->SimdVector.is_x86_mmx) { + ir_emit_store(p, ir_emit_struct_ep(p, tag, 3), v_true); + } else { + ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), ir_get_type_info_ptr(p, t->SimdVector.elem)); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 1), ir_const_int(type_size_of(t->SimdVector.elem))); + ir_emit_store(p, ir_emit_struct_ep(p, tag, 2), ir_const_int(t->SimdVector.count)); + } + break; + } + + + if (tag != nullptr) { + Type *tag_type = type_deref(ir_type(tag)); + GB_ASSERT(is_type_named(tag_type)); + ir_emit_store_union_variant(p, variant_ptr, ir_emit_load(p, tag), tag_type); + } else { + if (t != t_llvm_bool) { + GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t)); + } + } + } +#endif +} + void lb_generate_code(lbGenerator *gen) { lbModule *m = &gen->module; @@ -7818,24 +8377,22 @@ void lb_generate_code(lbGenerator *gen) { LLVMRunPassManager(module_pass_manager, mod); - if (!(build_context.is_dll && !has_dll_main)) { - LLVMContextRef ctx = LLVMGetModuleContext(mod); - + lbProcedure *startup_runtime = nullptr; + { // Startup Runtime Type *params = alloc_type_tuple(); Type *results = alloc_type_tuple(); - array_init(¶ms->Tuple.variables, heap_allocator(), 2); - params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true); - params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true); + Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl); - array_init(&results->Tuple.variables, heap_allocator(), 1); - results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true); + lbProcedure *p = lb_create_dummy_procedure(m, str_lit("__$startup_runtime"), proc_type); + startup_runtime = p; - Type *proc_type = alloc_type_proc(nullptr, params, 2, results, 1, false, ProcCC_CDecl); + lb_begin_procedure_body(p); - lbProcedure *p = lb_create_dummy_procedure(m, str_lit("main"), proc_type); + lb_emit_init_context(p); + + lb_setup_type_info_data(p); - lb_begin_procedure_body(p); for_array(i, global_variables) { auto *var = &global_variables[i]; if (var->decl->init_expr != nullptr) { @@ -7874,13 +8431,42 @@ void lb_generate_code(lbGenerator *gen) { } } + lb_end_procedure_body(p); + + if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { + gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main"); + LLVMDumpValue(p->value); + gb_printf_err("\n\n\n\n"); + LLVMVerifyFunction(p->value, LLVMAbortProcessAction); + } + + LLVMRunFunctionPassManager(function_pass_manager, p->value); + } + + if (!(build_context.is_dll && !has_dll_main)) { + Type *params = alloc_type_tuple(); + Type *results = alloc_type_tuple(); + + array_init(¶ms->Tuple.variables, heap_allocator(), 2); + params->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("argc"), t_i32, false, true); + params->Tuple.variables[1] = alloc_entity_param(nullptr, make_token_ident("argv"), alloc_type_pointer(t_cstring), false, true); + + array_init(&results->Tuple.variables, heap_allocator(), 1); + results->Tuple.variables[0] = alloc_entity_param(nullptr, make_token_ident("_"), t_i32, false, true); + + Type *proc_type = alloc_type_proc(nullptr, params, 2, results, 1, false, ProcCC_CDecl); + + lbProcedure *p = lb_create_dummy_procedure(m, str_lit("main"), proc_type); + + lb_begin_procedure_body(p); + lbValue *found = map_get(&m->values, hash_entity(entry_point)); GB_ASSERT(found != nullptr); + LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, ""); LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, ""); LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false)); - lb_end_procedure_body(p); if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { @@ -7930,6 +8516,7 @@ void lb_generate_code(lbGenerator *gen) { LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, LLVMObjectFile, &llvm_error); if (ok) { gb_printf_err("LLVM Error: %s\n", llvm_error); + gb_exit(1); return; } -- cgit v1.2.3 From a27c68f5260695714a907cb4938970b39fa4cc37 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 29 Feb 2020 11:12:37 +0000 Subject: Type_Info initialization --- core/runtime/core.odin | 2 +- src/llvm_backend.cpp | 711 ++++++++++++++++++++++++++++++++----------------- src/llvm_backend.hpp | 12 +- 3 files changed, 472 insertions(+), 253 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/core/runtime/core.odin b/core/runtime/core.odin index 75ee84908..a727aa05f 100644 --- a/core/runtime/core.odin +++ b/core/runtime/core.odin @@ -24,7 +24,7 @@ import "intrinsics" // implemented within the compiler rather than in this "preload" file // NOTE(bill): This must match the compiler's -Calling_Convention :: enum { +Calling_Convention :: enum u8 { Invalid = 0, Odin = 1, Contextless = 2, diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 547d3b8f3..1d03ccf1f 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -1,6 +1,19 @@ #include "llvm_backend.hpp" -gb_global lbValue lb_global_type_info_data = {}; +gb_global lbAddr lb_global_type_info_data = {}; +gb_global lbAddr lb_global_type_info_member_types = {}; +gb_global lbAddr lb_global_type_info_member_names = {}; +gb_global lbAddr lb_global_type_info_member_offsets = {}; +gb_global lbAddr lb_global_type_info_member_usings = {}; +gb_global lbAddr lb_global_type_info_member_tags = {}; + +gb_global isize lb_global_type_info_data_index = 0; +gb_global isize lb_global_type_info_member_types_index = 0; +gb_global isize lb_global_type_info_member_names_index = 0; +gb_global isize lb_global_type_info_member_offsets_index = 0; +gb_global isize lb_global_type_info_member_usings_index = 0; +gb_global isize lb_global_type_info_member_tags_index = 0; + struct lbLoopData { lbAddr idx_addr; @@ -139,8 +152,12 @@ void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) { // NOTE(bill): There are multiple sized booleans, thus force a conversion (if necessarily) value = lb_emit_conv(p, value, a); } - - GB_ASSERT(are_types_identical(a, value.type)); + Type *ca = core_type(a); + if (ca->kind == Type_Basic) { + GB_ASSERT_MSG(are_types_identical(ca, core_type(value.type)), "%s != %s", type_to_string(a), type_to_string(value.type)); + } else { + GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type)); + } LLVMValueRef v = LLVMBuildStore(p->builder, value.value, ptr.value); } @@ -208,6 +225,41 @@ lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) { return lb_emit_load(p, addr.addr); } +lbValue lb_const_union_tag(lbModule *m, Type *u, Type *v) { + return lb_const_value(m, union_tag_type(u), exact_value_i64(union_variant_index(u, v))); +} + +lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) { + Type *t = u.type; + GB_ASSERT_MSG(is_type_pointer(t) && + is_type_union(type_deref(t)), "%s", type_to_string(t)); + Type *ut = type_deref(t); + GB_ASSERT(!is_type_union_maybe_pointer(ut)); + GB_ASSERT(type_size_of(ut) > 0); + Type *tag_type = union_tag_type(ut); + + lbValue tag_ptr = {}; + tag_ptr.value = LLVMBuildStructGEP2(p->builder, lb_type(p->module, type_deref(u.type)), u.value, 2, ""); + tag_ptr.type = alloc_type_pointer(tag_type); + return tag_ptr; +} + +void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) { + gbAllocator a = heap_allocator(); + lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type)); + + lb_emit_store(p, underlying, variant); + + Type *t = type_deref(parent.type); + + if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) { + // No tag needed! + } else { + lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent); + lb_emit_store(p, tag_ptr, lb_const_union_tag(p->module, t, variant_type)); + } +} + void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) { unsigned field_count = LLVMCountStructElementTypes(src); @@ -1523,7 +1575,7 @@ void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) { String name = original_name; if (e->Procedure.is_foreign) { - // lb_add_foreign_library_path(proc->module, e->Procedure.foreign_library); + // lb_add_foreign_library_path(p->module, e->Procedure.foreign_library); } if (e->Procedure.link_name.len > 0) { @@ -2297,6 +2349,11 @@ lbValue lb_const_int(lbModule *m, Type *type, unsigned long long value) { return res; } +lbValue lb_const_string(lbModule *m, String const &value) { + return lb_const_value(m, t_string, exact_value_string(value)); +} + + lbValue lb_const_bool(lbModule *m, Type *type, bool value) { lbValue res = {}; res.value = LLVMConstInt(lb_type(m, type), value, false); @@ -2467,8 +2524,21 @@ lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type) { } lbValue lb_type_info(lbModule *m, Type *type) { - GB_PANIC("TODO(bill): lb_type_info"); - return {}; + type = default_type(type); + + isize index = lb_type_info_index(m->info, type); + GB_ASSERT(index >= 0); + + LLVMTypeRef it = lb_type(m, t_int); + LLVMValueRef indices[2] = { + LLVMConstInt(it, 0, false), + LLVMConstInt(it, index, true), + }; + + lbValue value = {}; + value.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)); + value.type = t_type_info_ptr; + return value; } @@ -3586,15 +3656,14 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { return res; } -#if 0 +#if 1 if (is_type_union(dst)) { for_array(i, dst->Union.variants) { Type *vt = dst->Union.variants[i]; if (are_types_identical(vt, src_type)) { - gbAllocator a = heap_allocator(); - lbValue parent = lb_add_local_generated(p, t, true); - lb_emit_store_union_variant(p, parent, value, vt); - return lb_emit_load(p, parent); + lbAddr parent = lb_add_local_generated(p, t, true); + lb_emit_store_union_variant(p, parent.addr, value, vt); + return lb_addr_load(p, parent); } } } @@ -4490,7 +4559,7 @@ lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) { return res; } -lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, i32 index) { +lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) { Type *t = s.type; GB_ASSERT(is_type_pointer(t)); Type *st = base_type(type_deref(t)); @@ -4498,8 +4567,15 @@ lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, i32 index) { GB_ASSERT(0 <= index); Type *ptr = base_array_type(st); + + + LLVMValueRef indices[2] = { + LLVMConstInt(lb_type(p->module, t_int), 0, false), + LLVMConstInt(lb_type(p->module, t_int), index, true), + }; + lbValue res = {}; - res.value = LLVMBuildStructGEP(p->builder, s.value, index, ""); + res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), ""); res.type = alloc_type_pointer(ptr); return res; } @@ -6376,7 +6452,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT(e->flags & EntityFlag_TypeField); String name = e->token.string; /*if (name == "names") { - lbValue ti_ptr = lb_type_info(p, type); + lbValue ti_ptr = lb_type_info(m, type); lbValue variant = lb_emit_struct_ep(p, ti_ptr, 2); lbValue names_ptr = nullptr; @@ -6940,8 +7016,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT_MSG(union_variant_index(ft, fet) > 0, "%s", type_to_string(fet)); lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index); - // TODO(bill): lb_emit_store_union_variant - // lb_emit_store_union_variant(p, gep, field_expr, fet); + lb_emit_store_union_variant(p, gep, field_expr, fet); } else { lbValue fv = lb_emit_conv(p, field_expr, ft); lbValue gep = lb_emit_struct_ep(p, lb_addr_get_ptr(p, v), cast(i32)index); @@ -7553,29 +7628,95 @@ lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value) { return lb_addr(g); } -lbValue lb_find_global_variable(lbModule *m, String const &name) { - lbValue *found = map_get(&m->values, hash_string(name)); - GB_ASSERT_MSG(found != nullptr, "Unable to find global variable '%.*s'", LIT(name)); +lbValue lb_find_runtime_value(lbModule *m, String const &name) { + AstPackage *p = m->info->runtime_package; + Entity *e = scope_lookup_current(p->scope, name); + lbValue *found = map_get(&m->values, hash_entity(e)); + GB_ASSERT_MSG(found != nullptr, "Unable to find runtime value '%.*s'", LIT(name)); lbValue value = *found; return value; } +lbValue lb_get_type_info_ptr(lbProcedure *p, Type *type) { + i32 index = cast(i32)lb_type_info_index(p->module->info, type); + // gb_printf_err("%d %s\n", index, type_to_string(type)); + lbValue ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, index); + return lb_emit_transmute(p, ptr, t_type_info_ptr); +} + + +lbValue lb_type_info_member_types_offset(lbProcedure *p, isize count) { + lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_types.addr, lb_global_type_info_member_types_index); + lb_global_type_info_member_types_index += cast(i32)count; + return offset; +} +lbValue lb_type_info_member_names_offset(lbProcedure *p, isize count) { + lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_names.addr, lb_global_type_info_member_names_index); + lb_global_type_info_member_names_index += cast(i32)count; + return offset; +} +lbValue lb_type_info_member_offsets_offset(lbProcedure *p, isize count) { + lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_offsets.addr, lb_global_type_info_member_offsets_index); + lb_global_type_info_member_offsets_index += cast(i32)count; + return offset; +} +lbValue lb_type_info_member_usings_offset(lbProcedure *p, isize count) { + lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_usings.addr, lb_global_type_info_member_usings_index); + lb_global_type_info_member_usings_index += cast(i32)count; + return offset; +} +lbValue lb_type_info_member_tags_offset(lbProcedure *p, isize count) { + lbValue offset = lb_emit_array_epi(p, lb_global_type_info_member_tags.addr, lb_global_type_info_member_tags_index); + lb_global_type_info_member_tags_index += cast(i32)count; + return offset; +} + + +lbValue lb_generate_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id) { + gbAllocator a = heap_allocator(); + Token token = {Token_Ident}; + isize name_len = prefix.len + 1 + 20; + + auto suffix_id = cast(unsigned long long)id; + char *text = gb_alloc_array(a, char, name_len+1); + gb_snprintf(text, name_len, + "%.*s-%llu", LIT(prefix), suffix_id); + text[name_len] = 0; + + String s = make_string_c(text); + + Type *t = alloc_type_array(elem_type, count); + lbValue g = {}; + g.value = LLVMAddGlobal(m->mod, lb_type(m, t), text); + g.type = alloc_type_pointer(t); + LLVMSetInitializer(g.value, LLVMConstNull(lb_type(m, t))); + LLVMSetLinkage(g.value, LLVMInternalLinkage); + map_set(&m->members, hash_string(s), g); + return g; +} + void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info data lbModule *m = p->module; + LLVMContextRef ctx = m->ctx; gbAllocator a = heap_allocator(); CheckerInfo *info = m->info; -#if 0 - if (true) { - lbValue global_type_table = lb_find_global_variable(m, str_lit("runtime.type_table")); - Type *type = base_type(type_deref(lb_global_type_info_data.type)); + { + // NOTE(bill): Set the type_table slice with the global backing array + lbValue global_type_table = lb_find_runtime_value(m, str_lit("type_table")); + Type *type = base_type(lb_addr_type(lb_global_type_info_data)); GB_ASSERT(is_type_array(type)); - lbValue len = ir_const_int(type->Array.count); - ir_fill_slice(p, global_type_table, - ir_emit_array_epi(p, lb_global_type_info_data, 0), - len); + + LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)}; + LLVMValueRef values[2] = { + LLVMConstInBoundsGEP(lb_global_type_info_data.addr.value, indices, gb_count_of(indices)), + LLVMConstInt(lb_type(m, t_int), type->Array.count, true), + }; + LLVMValueRef slice = LLVMConstStructInContext(ctx, values, gb_count_of(values), false); + + LLVMSetInitializer(global_type_table.value, slice); } @@ -7594,43 +7735,41 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da continue; } - isize entry_index = ir_type_info_index(info, t, false); + isize entry_index = lb_type_info_index(info, t, false); if (entry_index <= 0) { continue; } + gb_printf_err("%s @ %td | %.*s\n", type_to_string(t), entry_index, LIT(type_strings[t->kind])); - lbValue tag = nullptr; - lbValue ti_ptr = ir_emit_array_epi(p, lb_global_type_info_data, cast(i32)entry_index); - lbValue variant_ptr = ir_emit_struct_ep(p, ti_ptr, 3); + lbValue tag = {}; + lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index); + lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 3); - ir_emit_store(p, ir_emit_struct_ep(p, ti_ptr, 0), ir_const_int(type_size_of(t))); - ir_emit_store(p, ir_emit_struct_ep(p, ti_ptr, 1), ir_const_int(type_align_of(t))); - ir_emit_store(p, ir_emit_struct_ep(p, ti_ptr, 2), ir_typeid(proc->module, t)); + lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 0), lb_const_int(m, t_int, type_size_of(t))); + lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 1), lb_const_int(m, t_int, type_align_of(t))); + lb_emit_store(p, lb_emit_struct_ep(p, ti_ptr, 2), lb_typeid(m, t)); switch (t->kind) { case Type_Named: { - ir_emit_comment(p, str_lit("Type_Info_Named")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_named_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_named_ptr); - // TODO(bill): Which is better? The mangled name or actual name? - lbValue name = ir_const_string(proc->module, t->Named.type_name->token.string); - lbValue gtip = ir_get_type_info_ptr(p, t->Named.base); + lbValue name = lb_const_string(p->module, t->Named.type_name->token.string); + lbValue gtip = lb_get_type_info_ptr(p, t->Named.base); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), name); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 1), gtip); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), name); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), gtip); break; } case Type_Basic: - ir_emit_comment(p, str_lit("Type_Info_Basic")); switch (t->Basic.kind) { case Basic_bool: case Basic_b8: case Basic_b16: case Basic_b32: case Basic_b64: - tag = ir_emit_conv(p, variant_ptr, t_type_info_boolean_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_boolean_ptr); break; case Basic_i8: @@ -7664,9 +7803,9 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da case Basic_int: case Basic_uint: case Basic_uintptr: { - tag = ir_emit_conv(p, variant_ptr, t_type_info_integer_ptr); - lbValue is_signed = ir_const_bool((t->Basic.flags & BasicFlag_Unsigned) == 0); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), is_signed); + tag = lb_emit_conv(p, variant_ptr, t_type_info_integer_ptr); + lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), is_signed); // NOTE(bill): This is matches the runtime layout u8 endianness_value = 0; if (t->Basic.flags & BasicFlag_EndianLittle) { @@ -7674,440 +7813,425 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da } else if (t->Basic.flags & BasicFlag_EndianBig) { endianness_value = 2; } - lbValue endianness = ir_const_u8(endianness_value); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 1), endianness); + lbValue endianness = lb_const_int(m, t_u8, endianness_value); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), endianness); break; } case Basic_rune: - tag = ir_emit_conv(p, variant_ptr, t_type_info_rune_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_rune_ptr); break; // case Basic_f16: case Basic_f32: case Basic_f64: - tag = ir_emit_conv(p, variant_ptr, t_type_info_float_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_float_ptr); break; // case Basic_complex32: case Basic_complex64: case Basic_complex128: - tag = ir_emit_conv(p, variant_ptr, t_type_info_complex_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_complex_ptr); break; case Basic_quaternion128: case Basic_quaternion256: - tag = ir_emit_conv(p, variant_ptr, t_type_info_quaternion_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_quaternion_ptr); break; case Basic_rawptr: - tag = ir_emit_conv(p, variant_ptr, t_type_info_pointer_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_pointer_ptr); break; case Basic_string: - tag = ir_emit_conv(p, variant_ptr, t_type_info_string_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_string_ptr); break; case Basic_cstring: - tag = ir_emit_conv(p, variant_ptr, t_type_info_string_ptr); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), v_true); // is_cstring + tag = lb_emit_conv(p, variant_ptr, t_type_info_string_ptr); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_const_bool(m, t_bool, true)); // is_cstring break; case Basic_any: - tag = ir_emit_conv(p, variant_ptr, t_type_info_any_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_any_ptr); break; case Basic_typeid: - tag = ir_emit_conv(p, variant_ptr, t_type_info_typeid_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_typeid_ptr); break; } break; case Type_Pointer: { - ir_emit_comment(p, str_lit("Type_Info_Pointer")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_pointer_ptr); - lbValue gep = ir_get_type_info_ptr(p, t->Pointer.elem); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), gep); + tag = lb_emit_conv(p, variant_ptr, t_type_info_pointer_ptr); + lbValue gep = lb_get_type_info_ptr(p, t->Pointer.elem); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep); break; } case Type_Array: { - ir_emit_comment(p, str_lit("Type_Info_Array")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_array_ptr); - lbValue gep = ir_get_type_info_ptr(p, t->Array.elem); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), gep); + tag = lb_emit_conv(p, variant_ptr, t_type_info_array_ptr); + lbValue gep = lb_get_type_info_ptr(p, t->Array.elem); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep); i64 ez = type_size_of(t->Array.elem); - lbValue elem_size = ir_emit_struct_ep(p, tag, 1); - ir_emit_store(p, elem_size, ir_const_int(ez)); + lbValue elem_size = lb_emit_struct_ep(p, tag, 1); + lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez)); - lbValue count = ir_emit_struct_ep(p, tag, 2); - ir_emit_store(p, count, ir_const_int(t->Array.count)); + lbValue count = lb_emit_struct_ep(p, tag, 2); + lb_emit_store(p, count, lb_const_int(m, t_int, t->Array.count)); break; } case Type_EnumeratedArray: { - ir_emit_comment(p, str_lit("Type_Info_Enumerated_Array")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_enumerated_array_ptr); - lbValue elem = ir_get_type_info_ptr(p, t->EnumeratedArray.elem); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), elem); + tag = lb_emit_conv(p, variant_ptr, t_type_info_enumerated_array_ptr); + lbValue elem = lb_get_type_info_ptr(p, t->EnumeratedArray.elem); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), elem); - lbValue index = ir_get_type_info_ptr(p, t->EnumeratedArray.index); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 1), index); + lbValue index = lb_get_type_info_ptr(p, t->EnumeratedArray.index); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), index); i64 ez = type_size_of(t->EnumeratedArray.elem); - lbValue elem_size = ir_emit_struct_ep(p, tag, 2); - ir_emit_store(p, elem_size, ir_const_int(ez)); + lbValue elem_size = lb_emit_struct_ep(p, tag, 2); + lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez)); - lbValue count = ir_emit_struct_ep(p, tag, 3); - ir_emit_store(p, count, ir_const_int(t->EnumeratedArray.count)); + lbValue count = lb_emit_struct_ep(p, tag, 3); + lb_emit_store(p, count, lb_const_int(m, t_int, t->EnumeratedArray.count)); - lbValue min_value = ir_emit_struct_ep(p, tag, 4); - lbValue max_value = ir_emit_struct_ep(p, tag, 5); + lbValue min_value = lb_emit_struct_ep(p, tag, 4); + lbValue max_value = lb_emit_struct_ep(p, tag, 5); - lbValue min_v = ir_value_constant(core_type(t->EnumeratedArray.index), t->EnumeratedArray.min_value); - lbValue max_v = ir_value_constant(core_type(t->EnumeratedArray.index), t->EnumeratedArray.max_value); + lbValue min_v = lb_const_value(m, core_type(t->EnumeratedArray.index), t->EnumeratedArray.min_value); + lbValue max_v = lb_const_value(m, core_type(t->EnumeratedArray.index), t->EnumeratedArray.max_value); - ir_emit_store_union_variant(p, min_value, min_v, ir_type(min_v)); - ir_emit_store_union_variant(p, max_value, max_v, ir_type(max_v)); + lb_emit_store_union_variant(p, min_value, min_v, min_v.type); + lb_emit_store_union_variant(p, max_value, max_v, max_v.type); break; } case Type_DynamicArray: { - ir_emit_comment(p, str_lit("Type_Info_Dynamic_Array")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_dynamic_array_ptr); - lbValue gep = ir_get_type_info_ptr(p, t->DynamicArray.elem); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), gep); + tag = lb_emit_conv(p, variant_ptr, t_type_info_dynamic_array_ptr); + lbValue gep = lb_get_type_info_ptr(p, t->DynamicArray.elem); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep); i64 ez = type_size_of(t->DynamicArray.elem); - lbValue elem_size = ir_emit_struct_ep(p, tag, 1); - ir_emit_store(p, elem_size, ir_const_int(ez)); + lbValue elem_size = lb_emit_struct_ep(p, tag, 1); + lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez)); break; } case Type_Slice: { - ir_emit_comment(p, str_lit("Type_Info_Slice")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_slice_ptr); - lbValue gep = ir_get_type_info_ptr(p, t->Slice.elem); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), gep); + tag = lb_emit_conv(p, variant_ptr, t_type_info_slice_ptr); + lbValue gep = lb_get_type_info_ptr(p, t->Slice.elem); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep); i64 ez = type_size_of(t->Slice.elem); - lbValue elem_size = ir_emit_struct_ep(p, tag, 1); - ir_emit_store(p, elem_size, ir_const_int(ez)); + lbValue elem_size = lb_emit_struct_ep(p, tag, 1); + lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez)); break; } case Type_Proc: { - ir_emit_comment(p, str_lit("Type_Info_Proc")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_procedure_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_procedure_ptr); - lbValue params = ir_emit_struct_ep(p, tag, 0); - lbValue results = ir_emit_struct_ep(p, tag, 1); - lbValue variadic = ir_emit_struct_ep(p, tag, 2); - lbValue convention = ir_emit_struct_ep(p, tag, 3); + lbValue params = lb_emit_struct_ep(p, tag, 0); + lbValue results = lb_emit_struct_ep(p, tag, 1); + lbValue variadic = lb_emit_struct_ep(p, tag, 2); + lbValue convention = lb_emit_struct_ep(p, tag, 3); if (t->Proc.params != nullptr) { - ir_emit_store(p, params, ir_get_type_info_ptr(p, t->Proc.params)); + lb_emit_store(p, params, lb_get_type_info_ptr(p, t->Proc.params)); } if (t->Proc.results != nullptr) { - ir_emit_store(p, results, ir_get_type_info_ptr(p, t->Proc.results)); + lb_emit_store(p, results, lb_get_type_info_ptr(p, t->Proc.results)); } - ir_emit_store(p, variadic, ir_const_bool(t->Proc.variadic)); - ir_emit_store(p, convention, ir_const_int(t->Proc.calling_convention)); + lb_emit_store(p, variadic, lb_const_bool(m, t_bool, t->Proc.variadic)); + lb_emit_store(p, convention, lb_const_int(m, t_u8, t->Proc.calling_convention)); // TODO(bill): TypeInfo for procedures break; } case Type_Tuple: { - ir_emit_comment(p, str_lit("Type_Info_Tuple")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_tuple_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_tuple_ptr); - lbValue memory_types = ir_type_info_member_types_offset(p, t->Tuple.variables.count); - lbValue memory_names = ir_type_info_member_names_offset(p, t->Tuple.variables.count); + lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count); + lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count); for_array(i, t->Tuple.variables) { // NOTE(bill): offset is not used for tuples Entity *f = t->Tuple.variables[i]; - lbValue index = ir_const_int(i); - lbValue type_info = ir_emit_ptr_offset(p, memory_types, index); + lbValue index = lb_const_int(m, t_int, i); + lbValue type_info = lb_emit_ptr_offset(p, memory_types, index); - ir_emit_store(p, type_info, ir_type_info(p, f->type)); + lb_emit_store(p, type_info, lb_type_info(m, f->type)); if (f->token.string.len > 0) { - lbValue name = ir_emit_ptr_offset(p, memory_names, index); - ir_emit_store(p, name, ir_const_string(proc->module, f->token.string)); + lbValue name = lb_emit_ptr_offset(p, memory_names, index); + lb_emit_store(p, name, lb_const_string(m, f->token.string)); } } - lbValue count = ir_const_int(t->Tuple.variables.count); - ir_fill_slice(p, ir_emit_struct_ep(p, tag, 0), memory_types, count); - ir_fill_slice(p, ir_emit_struct_ep(p, tag, 1), memory_names, count); + lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count); + lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 0)), memory_types, count); + lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 1)), memory_names, count); break; } + case Type_Enum: - ir_emit_comment(p, str_lit("Type_Info_Enum")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_enum_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_enum_ptr); { GB_ASSERT(t->Enum.base_type != nullptr); - lbValue base = ir_type_info(p, t->Enum.base_type); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), base); + lbValue base = lb_type_info(m, t->Enum.base_type); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), base); if (t->Enum.fields.count > 0) { auto fields = t->Enum.fields; - lbValue name_array = ir_generate_array(m, t_string, fields.count, - str_lit("$enum_names"), cast(i64)entry_index); - lbValue value_array = ir_generate_array(m, t_type_info_enum_value, fields.count, - str_lit("$enum_values"), cast(i64)entry_index); + lbValue name_array = lb_generate_array(m, t_string, fields.count, + str_lit("$enum_names"), cast(i64)entry_index); + lbValue value_array = lb_generate_array(m, t_type_info_enum_value, fields.count, + str_lit("$enum_values"), cast(i64)entry_index); GB_ASSERT(is_type_integer(t->Enum.base_type)); for_array(i, fields) { - lbValue name_ep = ir_emit_array_epi(p, name_array, cast(i32)i); - lbValue value_ep = ir_emit_array_epi(p, value_array, cast(i32)i); + lbValue name_ep = lb_emit_array_epi(p, name_array, i); + lbValue value_ep = lb_emit_array_epi(p, value_array, i); ExactValue value = fields[i]->Constant.value; - lbValue v = ir_value_constant(t->Enum.base_type, value); + lbValue v = lb_const_value(m, t->Enum.base_type, value); - ir_emit_store_union_variant(p, value_ep, v, ir_type(v)); - ir_emit_store(p, name_ep, ir_const_string(proc->module, fields[i]->token.string)); + lb_emit_store_union_variant(p, value_ep, v, v.type); + lb_emit_store(p, name_ep, lb_const_string(m, fields[i]->token.string)); } - lbValue v_count = ir_const_int(fields.count); + lbValue v_count = lb_const_int(m, t_int, fields.count); - lbValue names = ir_emit_struct_ep(p, tag, 1); - lbValue name_array_elem = ir_array_elem(p, name_array); - ir_fill_slice(p, names, name_array_elem, v_count); + lbValue names = lb_emit_struct_ep(p, tag, 1); + lbValue name_array_elem = lb_array_elem(p, name_array); + lb_fill_slice(p, lb_addr(names), name_array_elem, v_count); - lbValue values = ir_emit_struct_ep(p, tag, 2); - lbValue value_array_elem = ir_array_elem(p, value_array); - ir_fill_slice(p, values, value_array_elem, v_count); + lbValue values = lb_emit_struct_ep(p, tag, 2); + lbValue value_array_elem = lb_array_elem(p, value_array); + lb_fill_slice(p, lb_addr(values), value_array_elem, v_count); } } break; case Type_Union: { - ir_emit_comment(p, str_lit("Type_Info_Union")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_union_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_union_ptr); { - lbValue variant_types = ir_emit_struct_ep(p, tag, 0); - lbValue tag_offset_ptr = ir_emit_struct_ep(p, tag, 1); - lbValue tag_type_ptr = ir_emit_struct_ep(p, tag, 2); - lbValue custom_align_ptr = ir_emit_struct_ep(p, tag, 3); - lbValue no_nil_ptr = ir_emit_struct_ep(p, tag, 4); - lbValue maybe_ptr = ir_emit_struct_ep(p, tag, 5); + lbValue variant_types = lb_emit_struct_ep(p, tag, 0); + lbValue tag_offset_ptr = lb_emit_struct_ep(p, tag, 1); + lbValue tag_type_ptr = lb_emit_struct_ep(p, tag, 2); + lbValue custom_align_ptr = lb_emit_struct_ep(p, tag, 3); + lbValue no_nil_ptr = lb_emit_struct_ep(p, tag, 4); + lbValue maybe_ptr = lb_emit_struct_ep(p, tag, 5); isize variant_count = gb_max(0, t->Union.variants.count); - lbValue memory_types = ir_type_info_member_types_offset(p, variant_count); + lbValue memory_types = lb_type_info_member_types_offset(p, variant_count); // NOTE(bill): Zeroth is nil so ignore it for (isize variant_index = 0; variant_index < variant_count; variant_index++) { Type *vt = t->Union.variants[variant_index]; - lbValue tip = ir_get_type_info_ptr(p, vt); + lbValue tip = lb_get_type_info_ptr(p, vt); - lbValue index = ir_const_int(variant_index); - lbValue type_info = ir_emit_ptr_offset(p, memory_types, index); - ir_emit_store(p, type_info, ir_type_info(p, vt)); + lbValue index = lb_const_int(m, t_int, variant_index); + lbValue type_info = lb_emit_ptr_offset(p, memory_types, index); + lb_emit_store(p, type_info, lb_type_info(m, vt)); } - lbValue count = ir_const_int(variant_count); - ir_fill_slice(p, variant_types, memory_types, count); + lbValue count = lb_const_int(m, t_int, variant_count); + lb_fill_slice(p, lb_addr(variant_types), memory_types, count); i64 tag_size = union_tag_size(t); i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size); if (tag_size > 0) { - ir_emit_store(p, tag_offset_ptr, ir_const_uintptr(tag_offset)); - ir_emit_store(p, tag_type_ptr, ir_type_info(p, union_tag_type(t))); + lb_emit_store(p, tag_offset_ptr, lb_const_int(m, t_uintptr, tag_offset)); + lb_emit_store(p, tag_type_ptr, lb_type_info(m, union_tag_type(t))); } - lbValue is_custom_align = ir_const_bool(t->Union.custom_align != 0); - ir_emit_store(p, custom_align_ptr, is_custom_align); + lbValue is_custom_align = lb_const_bool(m, t_bool, t->Union.custom_align != 0); + lb_emit_store(p, custom_align_ptr, is_custom_align); - ir_emit_store(p, no_nil_ptr, ir_const_bool(t->Union.no_nil)); - ir_emit_store(p, maybe_ptr, ir_const_bool(t->Union.maybe)); + lb_emit_store(p, no_nil_ptr, lb_const_bool(m, t_bool, t->Union.no_nil)); + lb_emit_store(p, maybe_ptr, lb_const_bool(m, t_bool, t->Union.maybe)); } break; } case Type_Struct: { - ir_emit_comment(p, str_lit("Type_Info_Struct")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_struct_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_struct_ptr); { - lbValue is_packed = ir_const_bool(t->Struct.is_packed); - lbValue is_raw_union = ir_const_bool(t->Struct.is_raw_union); - lbValue is_custom_align = ir_const_bool(t->Struct.custom_align != 0); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 5), is_packed); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 6), is_raw_union); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 7), is_custom_align); + lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed); + lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union); + lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 5), is_packed); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 6), is_raw_union); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 7), is_custom_align); if (t->Struct.soa_kind != StructSoa_None) { - lbValue kind = ir_emit_struct_ep(p, tag, 8); - Type *kind_type = type_deref(ir_type(kind)); + lbValue kind = lb_emit_struct_ep(p, tag, 8); + Type *kind_type = type_deref(kind.type); - lbValue soa_kind = ir_value_constant(kind_type, exact_value_i64(t->Struct.soa_kind)); - lbValue soa_type = ir_type_info(p, t->Struct.soa_elem); - lbValue soa_len = ir_const_int(t->Struct.soa_count); + lbValue soa_kind = lb_const_value(m, kind_type, exact_value_i64(t->Struct.soa_kind)); + lbValue soa_type = lb_type_info(m, t->Struct.soa_elem); + lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count); - ir_emit_store(p, kind, soa_kind); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 9), soa_type); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 10), soa_len); + lb_emit_store(p, kind, soa_kind); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 9), soa_type); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 10), soa_len); } } isize count = t->Struct.fields.count; if (count > 0) { - lbValue memory_types = ir_type_info_member_types_offset (p, count); - lbValue memory_names = ir_type_info_member_names_offset (p, count); - lbValue memory_offsets = ir_type_info_member_offsets_offset(p, count); - lbValue memory_usings = ir_type_info_member_usings_offset (p, count); - lbValue memory_tags = ir_type_info_member_tags_offset (p, count); + lbValue memory_types = lb_type_info_member_types_offset (p, count); + lbValue memory_names = lb_type_info_member_names_offset (p, count); + lbValue memory_offsets = lb_type_info_member_offsets_offset(p, count); + lbValue memory_usings = lb_type_info_member_usings_offset (p, count); + lbValue memory_tags = lb_type_info_member_tags_offset (p, count); type_set_offsets(t); // NOTE(bill): Just incase the offsets have not been set yet for (isize source_index = 0; source_index < count; source_index++) { // TODO(bill): Order fields in source order not layout order Entity *f = t->Struct.fields[source_index]; - lbValue tip = ir_get_type_info_ptr(p, f->type); + lbValue tip = lb_get_type_info_ptr(p, f->type); i64 foffset = 0; if (!t->Struct.is_raw_union) { foffset = t->Struct.offsets[f->Variable.field_index]; } GB_ASSERT(f->kind == Entity_Variable && f->flags & EntityFlag_Field); - lbValue index = ir_const_int(source_index); - lbValue type_info = ir_emit_ptr_offset(p, memory_types, index); - lbValue offset = ir_emit_ptr_offset(p, memory_offsets, index); - lbValue is_using = ir_emit_ptr_offset(p, memory_usings, index); + lbValue index = lb_const_int(m, t_int, source_index); + lbValue type_info = lb_emit_ptr_offset(p, memory_types, index); + lbValue offset = lb_emit_ptr_offset(p, memory_offsets, index); + lbValue is_using = lb_emit_ptr_offset(p, memory_usings, index); - ir_emit_store(p, type_info, ir_type_info(p, f->type)); + lb_emit_store(p, type_info, lb_type_info(m, f->type)); if (f->token.string.len > 0) { - lbValue name = ir_emit_ptr_offset(p, memory_names, index); - ir_emit_store(p, name, ir_const_string(proc->module, f->token.string)); + lbValue name = lb_emit_ptr_offset(p, memory_names, index); + lb_emit_store(p, name, lb_const_string(m, f->token.string)); } - ir_emit_store(p, offset, ir_const_uintptr(foffset)); - ir_emit_store(p, is_using, ir_const_bool((f->flags&EntityFlag_Using) != 0)); + lb_emit_store(p, offset, lb_const_int(m, t_uintptr, foffset)); + lb_emit_store(p, is_using, lb_const_bool(m, t_bool, (f->flags&EntityFlag_Using) != 0)); if (t->Struct.tags.count > 0) { String tag_string = t->Struct.tags[source_index]; if (tag_string.len > 0) { - lbValue tag_ptr = ir_emit_ptr_offset(p, memory_tags, index); - ir_emit_store(p, tag_ptr, ir_const_string(proc->module, tag_string)); + lbValue tag_ptr = lb_emit_ptr_offset(p, memory_tags, index); + lb_emit_store(p, tag_ptr, lb_const_string(m, tag_string)); } } } - lbValue cv = ir_const_int(count); - ir_fill_slice(p, ir_emit_struct_ep(p, tag, 0), memory_types, cv); - ir_fill_slice(p, ir_emit_struct_ep(p, tag, 1), memory_names, cv); - ir_fill_slice(p, ir_emit_struct_ep(p, tag, 2), memory_offsets, cv); - ir_fill_slice(p, ir_emit_struct_ep(p, tag, 3), memory_usings, cv); - ir_fill_slice(p, ir_emit_struct_ep(p, tag, 4), memory_tags, cv); + lbValue cv = lb_const_int(m, t_int, count); + lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 0)), memory_types, cv); + lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 1)), memory_names, cv); + lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 2)), memory_offsets, cv); + lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 3)), memory_usings, cv); + lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 4)), memory_tags, cv); } break; } + case Type_Map: { - ir_emit_comment(p, str_lit("Type_Info_Map")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_map_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_map_ptr); init_map_internal_types(t); - lbValue key = ir_emit_struct_ep(p, tag, 0); - lbValue value = ir_emit_struct_ep(p, tag, 1); - lbValue generated_struct = ir_emit_struct_ep(p, tag, 2); + lbValue key = lb_emit_struct_ep(p, tag, 0); + lbValue value = lb_emit_struct_ep(p, tag, 1); + lbValue generated_struct = lb_emit_struct_ep(p, tag, 2); - ir_emit_store(p, key, ir_get_type_info_ptr(p, t->Map.key)); - ir_emit_store(p, value, ir_get_type_info_ptr(p, t->Map.value)); - ir_emit_store(p, generated_struct, ir_get_type_info_ptr(p, t->Map.generated_struct_type)); + lb_emit_store(p, key, lb_get_type_info_ptr(p, t->Map.key)); + lb_emit_store(p, value, lb_get_type_info_ptr(p, t->Map.value)); + lb_emit_store(p, generated_struct, lb_get_type_info_ptr(p, t->Map.generated_struct_type)); break; } case Type_BitField: { - ir_emit_comment(p, str_lit("Type_Info_Bit_Field")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_bit_field_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_bit_field_ptr); // names: []string; // bits: []u32; // offsets: []u32; isize count = t->BitField.fields.count; if (count > 0) { auto fields = t->BitField.fields; - lbValue name_array = ir_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index); - lbValue bit_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index); - lbValue offset_array = ir_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index); + lbValue name_array = lb_generate_array(m, t_string, count, str_lit("$bit_field_names"), cast(i64)entry_index); + lbValue bit_array = lb_generate_array(m, t_i32, count, str_lit("$bit_field_bits"), cast(i64)entry_index); + lbValue offset_array = lb_generate_array(m, t_i32, count, str_lit("$bit_field_offsets"), cast(i64)entry_index); for (isize i = 0; i < count; i++) { Entity *f = fields[i]; GB_ASSERT(f->type != nullptr); GB_ASSERT(f->type->kind == Type_BitFieldValue); - lbValue name_ep = ir_emit_array_epi(p, name_array, cast(i32)i); - lbValue bit_ep = ir_emit_array_epi(p, bit_array, cast(i32)i); - lbValue offset_ep = ir_emit_array_epi(p, offset_array, cast(i32)i); + lbValue name_ep = lb_emit_array_epi(p, name_array, cast(i32)i); + lbValue bit_ep = lb_emit_array_epi(p, bit_array, cast(i32)i); + lbValue offset_ep = lb_emit_array_epi(p, offset_array, cast(i32)i); - ir_emit_store(p, name_ep, ir_const_string(proc->module, f->token.string)); - ir_emit_store(p, bit_ep, ir_const_i32(f->type->BitFieldValue.bits)); - ir_emit_store(p, offset_ep, ir_const_i32(t->BitField.offsets[i])); + lb_emit_store(p, name_ep, lb_const_string(m, f->token.string)); + lb_emit_store(p, bit_ep, lb_const_int(m, t_i32, f->type->BitFieldValue.bits)); + lb_emit_store(p, offset_ep, lb_const_int(m, t_i32, t->BitField.offsets[i])); } - lbValue v_count = ir_const_int(count); + lbValue v_count = lb_const_int(m, t_int, count); - lbValue names = ir_emit_struct_ep(p, tag, 0); - lbValue name_array_elem = ir_array_elem(p, name_array); - ir_fill_slice(p, names, name_array_elem, v_count); + lbValue names = lb_emit_struct_ep(p, tag, 0); + lbValue name_array_elem = lb_array_elem(p, name_array); + lb_fill_slice(p, lb_addr(names), name_array_elem, v_count); - lbValue bits = ir_emit_struct_ep(p, tag, 1); - lbValue bit_array_elem = ir_array_elem(p, bit_array); - ir_fill_slice(p, bits, bit_array_elem, v_count); + lbValue bits = lb_emit_struct_ep(p, tag, 1); + lbValue bit_array_elem = lb_array_elem(p, bit_array); + lb_fill_slice(p, lb_addr(bits), bit_array_elem, v_count); - lbValue offsets = ir_emit_struct_ep(p, tag, 2); - lbValue offset_array_elem = ir_array_elem(p, offset_array); - ir_fill_slice(p, offsets, offset_array_elem, v_count); + lbValue offsets = lb_emit_struct_ep(p, tag, 2); + lbValue offset_array_elem = lb_array_elem(p, offset_array); + lb_fill_slice(p, lb_addr(offsets), offset_array_elem, v_count); } break; } case Type_BitSet: - ir_emit_comment(p, str_lit("Type_Info_Bit_Set")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_bit_set_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_bit_set_ptr); GB_ASSERT(is_type_typed(t->BitSet.elem)); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), ir_get_type_info_ptr(p, t->BitSet.elem)); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->BitSet.elem)); if (t->BitSet.underlying != nullptr) { - ir_emit_store(p, ir_emit_struct_ep(p, tag, 1), ir_get_type_info_ptr(p, t->BitSet.underlying)); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), lb_get_type_info_ptr(p, t->BitSet.underlying)); } - ir_emit_store(p, ir_emit_struct_ep(p, tag, 2), ir_const_i64(t->BitSet.lower)); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 3), ir_const_i64(t->BitSet.upper)); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 2), lb_const_int(m, t_i64, t->BitSet.lower)); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 3), lb_const_int(m, t_i64, t->BitSet.upper)); break; case Type_Opaque: - ir_emit_comment(p, str_lit("Type_Opaque")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_opaque_ptr); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), ir_get_type_info_ptr(p, t->Opaque.elem)); + tag = lb_emit_conv(p, variant_ptr, t_type_info_opaque_ptr); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->Opaque.elem)); break; - case Type_SimdVector: - ir_emit_comment(p, str_lit("Type_SimdVector")); - tag = ir_emit_conv(p, variant_ptr, t_type_info_simd_vector_ptr); + tag = lb_emit_conv(p, variant_ptr, t_type_info_simd_vector_ptr); if (t->SimdVector.is_x86_mmx) { - ir_emit_store(p, ir_emit_struct_ep(p, tag, 3), v_true); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 3), lb_const_bool(m, t_bool, true)); } else { - ir_emit_store(p, ir_emit_struct_ep(p, tag, 0), ir_get_type_info_ptr(p, t->SimdVector.elem)); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 1), ir_const_int(type_size_of(t->SimdVector.elem))); - ir_emit_store(p, ir_emit_struct_ep(p, tag, 2), ir_const_int(t->SimdVector.count)); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->SimdVector.elem)); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), lb_const_int(m, t_int, type_size_of(t->SimdVector.elem))); + lb_emit_store(p, lb_emit_struct_ep(p, tag, 2), lb_const_int(m, t_int, t->SimdVector.count)); } break; } - if (tag != nullptr) { - Type *tag_type = type_deref(ir_type(tag)); + if (tag.value != nullptr) { + Type *tag_type = type_deref(tag.type); GB_ASSERT(is_type_named(tag_type)); - ir_emit_store_union_variant(p, variant_ptr, ir_emit_load(p, tag), tag_type); + lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type); } else { if (t != t_llvm_bool) { GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t)); } } } -#endif } @@ -8146,7 +8270,92 @@ void lb_generate_code(lbGenerator *gen) { LLVMDWARFEmissionFull, 0, true, true ); + } + { + { // Add type info data + isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1; + Type *t = alloc_type_array(t_type_info, max_type_info_count); + LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME); + LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t))); + LLVMSetLinkage(g, LLVMInternalLinkage); + + lbValue value = {}; + value.value = g; + value.type = alloc_type_pointer(t); + lb_global_type_info_data = lb_addr(value); + } + { // Type info member buffer + // NOTE(bill): Removes need for heap allocation by making it global memory + isize count = 0; + + for_array(entry_index, m->info->type_info_types) { + Type *t = m->info->type_info_types[entry_index]; + + isize index = lb_type_info_index(m->info, t, false); + if (index < 0) { + continue; + } + + switch (t->kind) { + case Type_Union: + count += t->Union.variants.count; + break; + case Type_Struct: + count += t->Struct.fields.count; + break; + case Type_Tuple: + count += t->Tuple.variables.count; + break; + } + } + + if (count > 0) { + { + char const *name = LB_TYPE_INFO_TYPES_NAME; + Type *t = alloc_type_array(t_type_info_ptr, count); + LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name); + LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t))); + LLVMSetLinkage(g, LLVMInternalLinkage); + lb_global_type_info_member_types = lb_addr({g, alloc_type_pointer(t)}); + + } + { + char const *name = LB_TYPE_INFO_NAMES_NAME; + Type *t = alloc_type_array(t_string, count); + LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name); + LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t))); + LLVMSetLinkage(g, LLVMInternalLinkage); + lb_global_type_info_member_names = lb_addr({g, alloc_type_pointer(t)}); + } + { + char const *name = LB_TYPE_INFO_OFFSETS_NAME; + Type *t = alloc_type_array(t_uintptr, count); + LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name); + LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t))); + LLVMSetLinkage(g, LLVMInternalLinkage); + lb_global_type_info_member_offsets = lb_addr({g, alloc_type_pointer(t)}); + } + + { + char const *name = LB_TYPE_INFO_USINGS_NAME; + Type *t = alloc_type_array(t_bool, count); + LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name); + LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t))); + LLVMSetLinkage(g, LLVMInternalLinkage); + lb_global_type_info_member_usings = lb_addr({g, alloc_type_pointer(t)}); + } + + { + char const *name = LB_TYPE_INFO_TAGS_NAME; + Type *t = alloc_type_array(t_string, count); + LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), name); + LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t))); + LLVMSetLinkage(g, LLVMInternalLinkage); + lb_global_type_info_member_tags = lb_addr({g, alloc_type_pointer(t)}); + } + } + } } @@ -8384,12 +8593,12 @@ void lb_generate_code(lbGenerator *gen) { Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl); - lbProcedure *p = lb_create_dummy_procedure(m, str_lit("__$startup_runtime"), proc_type); + lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type); startup_runtime = p; lb_begin_procedure_body(p); - lb_emit_init_context(p); + lb_emit_init_context(p, {}); lb_setup_type_info_data(p); diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 90fc85ff2..2c577b712 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -247,7 +247,7 @@ lbValue lb_build_gep(lbProcedure *p, lbValue const &value, i32 index) ; lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index); lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index); -lbValue lb_emit_array_epi(lbProcedure *p, lbValue value, i32 index); +lbValue lb_emit_array_epi(lbProcedure *p, lbValue value, isize index); lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index); lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel); lbValue lb_emit_deep_field_ev(lbProcedure *p, lbValue e, Selection sel); @@ -280,6 +280,16 @@ lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init); lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array const &args); +#define LB_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime" +#define LB_TYPE_INFO_DATA_NAME "__$type_info_data" +#define LB_TYPE_INFO_TYPES_NAME "__$type_info_types_data" +#define LB_TYPE_INFO_NAMES_NAME "__$type_info_names_data" +#define LB_TYPE_INFO_OFFSETS_NAME "__$type_info_offsets_data" +#define LB_TYPE_INFO_USINGS_NAME "__$type_info_usings_data" +#define LB_TYPE_INFO_TAGS_NAME "__$type_info_tags_data" + + + enum lbCallingConventionKind { lbCallingConvention_C = 0, lbCallingConvention_Fast = 8, -- cgit v1.2.3 From f83e1b8b0a2acb5cf0f4bec36665211af0cc9a01 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 29 Feb 2020 12:24:52 +0000 Subject: Fix `any` type and casting to `any`; Fix `switch` statement --- src/llvm_backend.cpp | 133 ++++++++++++++++++++++++++------------------------- 1 file changed, 69 insertions(+), 64 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 1d03ccf1f..a56991a9a 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -239,7 +239,7 @@ lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) { Type *tag_type = union_tag_type(ut); lbValue tag_ptr = {}; - tag_ptr.value = LLVMBuildStructGEP2(p->builder, lb_type(p->module, type_deref(u.type)), u.value, 2, ""); + tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, ""); tag_ptr.type = alloc_type_pointer(tag_type); return tag_ptr; } @@ -475,7 +475,7 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { { LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..any"); LLVMTypeRef fields[2] = { - LLVMPointerType(lb_type(m, t_rawptr), 0), + lb_type(m, t_rawptr), lb_type(m, t_typeid), }; LLVMStructSetBody(type, fields, 2, false); @@ -2174,9 +2174,6 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(ss, SwitchStmt, node); - if (true) { - return; - } if (ss->init != nullptr) { lb_build_stmt(p, ss->init); } @@ -2259,7 +2256,6 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { lb_emit_if(p, cond, body, next_cond); lb_start_block(p, next_cond); } - lb_emit_jump(p, body); lb_start_block(p, body); lb_push_target_list(p, ss->label, done, nullptr, fall); @@ -2269,7 +2265,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { lb_pop_target_list(p); lb_emit_jump(p, done); - p->curr_block = next_cond; + lb_start_block(p, next_cond); } if (default_block != nullptr) { @@ -2282,6 +2278,7 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { lb_close_scope(p, lbDeferExit_Default, default_block); lb_pop_target_list(p); } + lb_emit_jump(p, done); lb_start_block(p, done); case_end; @@ -3403,9 +3400,18 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (LLVMIsConstant(value.value)) { if (is_type_any(dst)) { - lbAddr default_value = lb_add_local_generated(p, default_type(src_type), false); + Type *st = default_type(src_type); + lbAddr default_value = lb_add_local_generated(p, st, false); lb_addr_store(p, default_value, value); - return lb_emit_conv(p, lb_addr_load(p, default_value), t_any); + lbValue data = lb_emit_conv(p, default_value.addr, t_rawptr); + lbValue id = lb_typeid(m, st); + + lbAddr res = lb_add_local_generated(p, t, false); + lbValue a0 = lb_emit_struct_ep(p, res.addr, 0); + lbValue a1 = lb_emit_struct_ep(p, res.addr, 1); + lb_emit_store(p, a0, data); + lb_emit_store(p, a1, id); + return lb_addr_load(p, res); } else if (dst->kind == Type_Basic) { if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) { // TODO(bill): This is kind of a hack @@ -3721,7 +3727,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (is_type_pointer(src) && is_type_pointer(dst)) { lbValue res = {}; res.type = t; - res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(m, t), ""); + res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), ""); return res; } @@ -3731,7 +3737,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (is_type_proc(src) && is_type_proc(dst)) { lbValue res = {}; res.type = t; - res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(m, t), ""); + res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), ""); return res; } @@ -3739,73 +3745,67 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (is_type_pointer(src) && is_type_proc(dst)) { lbValue res = {}; res.type = t; - res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(m, t), ""); + res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), ""); return res; } // proc -> pointer if (is_type_proc(src) && is_type_pointer(dst)) { lbValue res = {}; res.type = t; - res.value = LLVMBuildBitCast(p->builder, value.value, lb_type(m, t), ""); + res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(m, t), ""); return res; } -#if 0 // []byte/[]u8 <-> string if (is_type_u8_slice(src) && is_type_string(dst)) { - lbValue elem = ir_slice_elem(p, value); - lbValue len = ir_slice_len(p, value); - return ir_emit_string(p, elem, len); + return lb_emit_transmute(p, value, t); } if (is_type_string(src) && is_type_u8_slice(dst)) { - lbValue elem = ir_string_elem(p, value); - lbValue elem_ptr = lb_add_local_generated(p, ir_type(elem), false); - lb_emit_store(p, elem_ptr, elem); - - lbValue len = ir_string_len(p, value); - lbValue slice = ir_add_local_slice(p, t, elem_ptr, v_zero, len); - return lb_emit_load(p, slice); + return lb_emit_transmute(p, value, t); } if (is_type_array(dst)) { Type *elem = dst->Array.elem; lbValue e = lb_emit_conv(p, value, elem); // NOTE(bill): Doesn't need to be zero because it will be initialized in the loops - lbValue v = lb_add_local_generated(p, t, false); + lbAddr v = lb_add_local_generated(p, t, false); isize index_count = cast(isize)dst->Array.count; - for (i32 i = 0; i < index_count; i++) { - lbValue elem = ir_emit_array_epi(p, v, i); + for (isize i = 0; i < index_count; i++) { + lbValue elem = lb_emit_array_epi(p, v.addr, i); lb_emit_store(p, elem, e); } - return lb_emit_load(p, v); + return lb_addr_load(p, v); } if (is_type_any(dst)) { - lbValue result = lb_add_local_generated(p, t_any, true); - if (is_type_untyped_nil(src)) { - return lb_emit_load(p, result); + return lb_const_nil(p->module, t); + } + if (is_type_untyped_undef(src)) { + return lb_const_undef(p->module, t); } + lbAddr result = lb_add_local_generated(p, t, true); + Type *st = default_type(src_type); - lbValue data = ir_address_from_load_or_generate_local(p, value); - GB_ASSERT_MSG(is_type_pointer(ir_type(data)), type_to_string(ir_type(data))); + lbValue data = lb_address_from_load_or_generate_local(p, value); + GB_ASSERT_MSG(is_type_pointer(data.type), "%s", type_to_string(data.type)); GB_ASSERT_MSG(is_type_typed(st), "%s", type_to_string(st)); data = lb_emit_conv(p, data, t_rawptr); - lbValue id = lb_typeid(p->module, st); + lbValue any_data = lb_emit_struct_ep(p, result.addr, 0); + lbValue any_id = lb_emit_struct_ep(p, result.addr, 1); - lb_emit_store(p, lb_emit_struct_ep(p, result, 0), data); - lb_emit_store(p, lb_emit_struct_ep(p, result, 1), id); + lb_emit_store(p, any_data, data); + lb_emit_store(p, any_id, id); - return lb_emit_load(p, result); + return lb_addr_load(p, result); } -#endif if (is_type_untyped(src)) { if (is_type_string(src) && is_type_string(dst)) { @@ -3915,6 +3915,11 @@ lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) { return res; } + if (is_type_pointer(src) && is_type_pointer(dst)) { + res.value = LLVMBuildPointerCast(p->builder, value.value, lb_type(p->module, t), ""); + return res; + } + if (lb_is_type_aggregate(src) || lb_is_type_aggregate(dst)) { lbValue s = lb_address_from_load_or_generate_local(p, value); lbValue d = lb_emit_transmute(p, s, alloc_type_pointer(t)); @@ -3997,60 +4002,59 @@ lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { } if (is_type_struct(t)) { - result_type = alloc_type_pointer(t->Struct.fields[index]->type); + result_type = t->Struct.fields[index]->type; } else if (is_type_union(t)) { GB_ASSERT(index == -1); - // return ir_emit_union_tag_ptr(p, s); - GB_PANIC("ir_emit_union_tag_ptr"); + return lb_emit_union_tag_ptr(p, s); } else if (is_type_tuple(t)) { GB_ASSERT(t->Tuple.variables.count > 0); - result_type = alloc_type_pointer(t->Tuple.variables[index]->type); + result_type = t->Tuple.variables[index]->type; } else if (is_type_complex(t)) { Type *ft = base_complex_elem_type(t); switch (index) { - case 0: result_type = alloc_type_pointer(ft); break; - case 1: result_type = alloc_type_pointer(ft); break; + case 0: result_type = ft; break; + case 1: result_type = ft; break; } } else if (is_type_quaternion(t)) { Type *ft = base_complex_elem_type(t); switch (index) { - case 0: result_type = alloc_type_pointer(ft); break; - case 1: result_type = alloc_type_pointer(ft); break; - case 2: result_type = alloc_type_pointer(ft); break; - case 3: result_type = alloc_type_pointer(ft); break; + case 0: result_type = ft; break; + case 1: result_type = ft; break; + case 2: result_type = ft; break; + case 3: result_type = ft; break; } } else if (is_type_slice(t)) { switch (index) { - case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->Slice.elem)); break; - case 1: result_type = alloc_type_pointer(t_int); break; + case 0: result_type = alloc_type_pointer(t->Slice.elem); break; + case 1: result_type = t_int; break; } } else if (is_type_string(t)) { switch (index) { - case 0: result_type = alloc_type_pointer(t_u8_ptr); break; - case 1: result_type = alloc_type_pointer(t_int); break; + case 0: result_type = t_u8_ptr; break; + case 1: result_type = t_int; break; } } else if (is_type_any(t)) { switch (index) { - case 0: result_type = alloc_type_pointer(t_rawptr); break; - case 1: result_type = alloc_type_pointer(t_typeid); break; + case 0: result_type = t_rawptr; break; + case 1: result_type = t_typeid; break; } } else if (is_type_dynamic_array(t)) { switch (index) { - case 0: result_type = alloc_type_pointer(alloc_type_pointer(t->DynamicArray.elem)); break; - case 1: result_type = t_int_ptr; break; - case 2: result_type = t_int_ptr; break; - case 3: result_type = t_allocator_ptr; break; + case 0: result_type = alloc_type_pointer(t->DynamicArray.elem); break; + case 1: result_type = t_int; break; + case 2: result_type = t_int; break; + case 3: result_type = t_allocator; break; } } else if (is_type_map(t)) { init_map_internal_types(t); - Type *itp = alloc_type_pointer(t->Map.internal_type); + Type *itp = (t->Map.internal_type); s = lb_emit_transmute(p, s, itp); Type *gst = t->Map.internal_type; GB_ASSERT(gst->kind == Type_Struct); switch (index) { - case 0: result_type = alloc_type_pointer(gst->Struct.fields[0]->type); break; - case 1: result_type = alloc_type_pointer(gst->Struct.fields[1]->type); break; + case 0: result_type = gst->Struct.fields[0]->type; break; + case 1: result_type = gst->Struct.fields[1]->type; break; } } else if (is_type_array(t)) { return lb_emit_array_epi(p, s, index); @@ -4061,8 +4065,8 @@ lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index); lbValue res = {}; - res.value = LLVMBuildStructGEP2(p->builder, lb_type(p->module, type_deref(s.type)), s.value, cast(unsigned)index, ""); - res.type = result_type; + res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, ""); + res.type = alloc_type_pointer(result_type); return res; } @@ -7739,7 +7743,8 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da if (entry_index <= 0) { continue; } - gb_printf_err("%s @ %td | %.*s\n", type_to_string(t), entry_index, LIT(type_strings[t->kind])); + + // gb_printf_err("%s @ %td | %.*s\n", type_to_string(t), entry_index, LIT(type_strings[t->kind lbValue tag = {}; lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index); -- cgit v1.2.3 From 56240240f6c040df5ecdd10f8050ce03040f8c87 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 29 Feb 2020 14:29:47 +0000 Subject: Range Statement support --- src/llvm_backend.cpp | 643 ++++++++++++++++++++++++++++++++++++++++++++++++++- src/llvm_backend.hpp | 23 ++ 2 files changed, 659 insertions(+), 7 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index a56991a9a..60f02e611 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -820,6 +820,13 @@ void lb_add_procedure_value(lbModule *m, lbProcedure *p) { +lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) { + lbAddr res = lb_add_local_generated(p, t_string, false); + lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem); + lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len); + return lb_addr_load(p, res); +} + LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) { unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name)); return LLVMCreateEnumAttribute(ctx, kind, value); @@ -836,6 +843,7 @@ void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *nam + lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { GB_ASSERT(entity != nullptr); @@ -1738,6 +1746,627 @@ void lb_build_when_stmt(lbProcedure *p, AstWhenStmt *ws) { } } + + +void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValue count_ptr, + lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) { + lbModule *m = p->module; + + lbValue count = {}; + Type *expr_type = base_type(type_deref(expr.type)); + switch (expr_type->kind) { + case Type_Array: + count = lb_const_int(m, t_int, expr_type->Array.count); + break; + } + + lbValue val = {}; + lbValue idx = {}; + lbBlock *loop = nullptr; + lbBlock *done = nullptr; + lbBlock *body = nullptr; + + + lbAddr index = lb_add_local_generated(p, t_int, false); + lb_addr_store(p, index, lb_const_int(m, t_int, cast(u64)-1)); + + loop = lb_create_block(p, "for.index.loop"); + lb_emit_jump(p, loop); + lb_start_block(p, loop); + + lbValue incr = lb_emit_arith(p, Token_Add, lb_addr_load(p, index), lb_const_int(m, t_int, 1), t_int); + lb_addr_store(p, index, incr); + + body = lb_create_block(p, "for.index.body"); + done = lb_create_block(p, "for.index.done"); + if (count.value == nullptr) { + GB_ASSERT(count_ptr.value != nullptr); + count = lb_emit_load(p, count_ptr); + } + lbValue cond = lb_emit_comp(p, Token_Lt, incr, count); + lb_emit_if(p, cond, body, done); + lb_start_block(p, body); + + idx = lb_addr_load(p, index); + switch (expr_type->kind) { + case Type_Array: { + if (val_type != nullptr) { + val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx)); + } + break; + } + case Type_EnumeratedArray: { + if (val_type != nullptr) { + val = lb_emit_load(p, lb_emit_array_ep(p, expr, idx)); + // NOTE(bill): Override the idx value for the enumeration + Type *index_type = expr_type->EnumeratedArray.index; + if (compare_exact_values(Token_NotEq, expr_type->EnumeratedArray.min_value, exact_value_u64(0))) { + idx = lb_emit_arith(p, Token_Add, idx, lb_const_value(m, index_type, expr_type->EnumeratedArray.min_value), index_type); + } + } + break; + } + case Type_Slice: { + if (val_type != nullptr) { + lbValue elem = lb_slice_elem(p, expr); + val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx)); + } + break; + } + case Type_DynamicArray: { + if (val_type != nullptr) { + lbValue elem = lb_emit_struct_ep(p, expr, 0); + elem = lb_emit_load(p, elem); + val = lb_emit_load(p, lb_emit_ptr_offset(p, elem, idx)); + } + break; + } + case Type_Map: { + lbAddr key = lb_add_local_generated(p, expr_type->Map.key, true); + + lbValue entries = lb_map_entries_ptr(p, expr); + lbValue elem = lb_emit_struct_ep(p, entries, 0); + elem = lb_emit_load(p, elem); + + lbValue entry = lb_emit_ptr_offset(p, elem, idx); + val = lb_emit_load(p, lb_emit_struct_ep(p, entry, 2)); + + lbValue hash = lb_emit_struct_ep(p, entry, 0); + if (is_type_string(expr_type->Map.key)) { + lbValue str = lb_emit_struct_ep(p, hash, 1); + lb_addr_store(p, key, lb_emit_load(p, str)); + } else { + lbValue hash_ptr = lb_emit_struct_ep(p, hash, 0); + hash_ptr = lb_emit_conv(p, hash_ptr, lb_addr_type(key)); + lb_addr_store(p, key, lb_emit_load(p, hash_ptr)); + } + + idx = lb_addr_load(p, key); + + break; + } + default: + GB_PANIC("Cannot do range_indexed of %s", type_to_string(expr_type)); + break; + } + + if (val_) *val_ = val; + if (idx_) *idx_ = idx; + if (loop_) *loop_ = loop; + if (done_) *done_ = done; +} + + +void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type, + lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) { + lbModule *m = p->module; + lbValue count = lb_const_int(m, t_int, 0); + Type *expr_type = base_type(expr.type); + switch (expr_type->kind) { + case Type_Basic: + count = lb_string_len(p, expr); + break; + default: + GB_PANIC("Cannot do range_string of %s", type_to_string(expr_type)); + break; + } + + lbValue val = {}; + lbValue idx = {}; + lbBlock *loop = nullptr; + lbBlock *done = nullptr; + lbBlock *body = nullptr; + + + lbAddr offset_ = lb_add_local_generated(p, t_int, false); + lb_addr_store(p, offset_, lb_const_int(m, t_int, 0)); + + loop = lb_create_block(p, "for.string.loop"); + lb_emit_jump(p, loop); + lb_start_block(p, loop); + + + + body = lb_create_block(p, "for.string.body"); + done = lb_create_block(p, "for.string.done"); + + lbValue offset = lb_addr_load(p, offset_); + lbValue cond = lb_emit_comp(p, Token_Lt, offset, count); + lb_emit_if(p, cond, body, done); + lb_start_block(p, body); + + + lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset); + lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int); + auto args = array_make(heap_allocator(), 1); + args[0] = lb_emit_string(p, str_elem, str_len); + lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args); + lbValue len = lb_emit_struct_ev(p, rune_and_len, 1); + lb_addr_store(p, offset_, lb_emit_arith(p, Token_Add, offset, len, t_int)); + + + idx = offset; + if (val_type != nullptr) { + val = lb_emit_struct_ev(p, rune_and_len, 0); + } + + if (val_) *val_ = val; + if (idx_) *idx_ = idx; + if (loop_) *loop_ = loop; + if (done_) *done_ = done; +} + + +void lb_build_range_interval(lbProcedure *p, AstBinaryExpr *node, Type *val_type, + lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) { + lbModule *m = p->module; + + // TODO(bill): How should the behaviour work for lower and upper bounds checking for iteration? + // If 'lower' is changed, should 'val' do so or is that not typical behaviour? + + lbValue lower = lb_build_expr(p, node->left); + lbValue upper = {}; + + lbValue val = {}; + lbValue idx = {}; + lbBlock *loop = nullptr; + lbBlock *done = nullptr; + lbBlock *body = nullptr; + + if (val_type == nullptr) { + val_type = lower.type; + } + lbAddr value = lb_add_local_generated(p, val_type, false); + lb_addr_store(p, value, lower); + + lbAddr index = lb_add_local_generated(p, t_int, false); + lb_addr_store(p, index, lb_const_int(m, t_int, 0)); + + loop = lb_create_block(p, "for.interval.loop"); + lb_emit_jump(p, loop); + lb_start_block(p, loop); + + body = lb_create_block(p, "for.interval.body"); + done = lb_create_block(p, "for.interval.done"); + + + TokenKind op = Token_Lt; + switch (node->op.kind) { + case Token_Ellipsis: op = Token_LtEq; break; + case Token_RangeHalf: op = Token_Lt; break; + default: GB_PANIC("Invalid interval operator"); break; + } + + upper = lb_build_expr(p, node->right); + + lbValue curr_value = lb_addr_load(p, value); + lbValue cond = lb_emit_comp(p, op, curr_value, upper); + lb_emit_if(p, cond, body, done); + lb_start_block(p, body); + + val = lb_addr_load(p, value); + idx = lb_addr_load(p, index); + + lb_emit_increment(p, value.addr); + lb_emit_increment(p, index.addr); + + if (val_) *val_ = val; + if (idx_) *idx_ = idx; + if (loop_) *loop_ = loop; + if (done_) *done_ = done; +} + +void lb_build_range_enum(lbProcedure *p, Type *enum_type, Type *val_type, lbValue *val_, lbValue *idx_, lbBlock **loop_, lbBlock **done_) { + lbModule *m = p->module; + + Type *t = enum_type; + GB_ASSERT(is_type_enum(t)); + Type *enum_ptr = alloc_type_pointer(t); + t = base_type(t); + Type *core_elem = core_type(t); + GB_ASSERT(t->kind == Type_Enum); + i64 enum_count = t->Enum.fields.count; + lbValue max_count = lb_const_int(m, t_int, enum_count); + + lbValue ti = lb_type_info(m, t); + lbValue variant = lb_emit_struct_ep(p, ti, 3); + lbValue eti_ptr = lb_emit_conv(p, variant, t_type_info_enum_ptr); + lbValue values = lb_emit_load(p, lb_emit_struct_ep(p, eti_ptr, 2)); + lbValue values_data = lb_slice_elem(p, values); + + lbAddr offset_ = lb_add_local_generated(p, t_int, false); + lb_addr_store(p, offset_, lb_const_int(m, t_int, 0)); + + lbBlock *loop = lb_create_block(p, "for.enum.loop"); + lb_emit_jump(p, loop); + lb_start_block(p, loop); + + lbBlock *body = lb_create_block(p, "for.enum.body"); + lbBlock *done = lb_create_block(p, "for.enum.done"); + + lbValue offset = lb_addr_load(p, offset_); + lbValue cond = lb_emit_comp(p, Token_Lt, offset, max_count); + lb_emit_if(p, cond, body, done); + lb_start_block(p, body); + + lbValue val_ptr = lb_emit_ptr_offset(p, values_data, offset); + lb_emit_increment(p, offset_.addr); + + lbValue val = {}; + if (val_type != nullptr) { + GB_ASSERT(are_types_identical(enum_type, val_type)); + + if (is_type_integer(core_elem)) { + lbValue i = lb_emit_load(p, lb_emit_conv(p, val_ptr, t_i64_ptr)); + val = lb_emit_conv(p, i, t); + } else { + GB_PANIC("TODO(bill): enum core type %s", type_to_string(core_elem)); + } + } + + if (val_) *val_ = val; + if (idx_) *idx_ = offset; + if (loop_) *loop_ = loop; + if (done_) *done_ = done; +} + +void lb_build_range_tuple(lbProcedure *p, Ast *expr, Type *val0_type, Type *val1_type, + lbValue *val0_, lbValue *val1_, lbBlock **loop_, lbBlock **done_) { + lbBlock *loop = lb_create_block(p, "for.tuple.loop"); + lb_emit_jump(p, loop); + lb_start_block(p, loop); + + lbBlock *body = lb_create_block(p, "for.tuple.body"); + lbBlock *done = lb_create_block(p, "for.tuple.done"); + + lbValue tuple_value = lb_build_expr(p, expr); + Type *tuple = tuple_value.type; + GB_ASSERT(tuple->kind == Type_Tuple); + i32 tuple_count = cast(i32)tuple->Tuple.variables.count; + i32 cond_index = tuple_count-1; + + lbValue cond = lb_emit_struct_ev(p, tuple_value, cond_index); + lb_emit_if(p, cond, body, done); + lb_start_block(p, body); + + + if (val0_) *val0_ = lb_emit_struct_ev(p, tuple_value, 0); + if (val1_) *val1_ = lb_emit_struct_ev(p, tuple_value, 1); + if (loop_) *loop_ = loop; + if (done_) *done_ = done; +} + +void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) { + lb_open_scope(p); + + Type *val0_type = nullptr; + Type *val1_type = nullptr; + if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) { + val0_type = type_of_expr(rs->val0); + } + if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) { + val1_type = type_of_expr(rs->val1); + } + + if (val0_type != nullptr) { + Entity *e = entity_of_ident(rs->val0); + lb_add_local(p, e->type, e, true); + } + if (val1_type != nullptr) { + Entity *e = entity_of_ident(rs->val1); + lb_add_local(p, e->type, e, true); + } + + lbValue val = {}; + lbValue key = {}; + lbBlock *loop = nullptr; + lbBlock *done = nullptr; + Ast *expr = unparen_expr(rs->expr); + bool is_map = false; + + TypeAndValue tav = type_and_value_of_expr(expr); + + if (is_ast_range(expr)) { + lb_build_range_interval(p, &expr->BinaryExpr, val0_type, &val, &key, &loop, &done); + } else if (tav.mode == Addressing_Type) { + lb_build_range_enum(p, type_deref(tav.type), val0_type, &val, &key, &loop, &done); + } else { + Type *expr_type = type_of_expr(expr); + Type *et = base_type(type_deref(expr_type)); + switch (et->kind) { + case Type_Map: { + is_map = true; + gbAllocator a = heap_allocator(); + lbAddr addr = lb_build_addr(p, expr); + lbValue map = lb_addr_get_ptr(p, addr); + if (is_type_pointer(type_deref(lb_addr_type(addr)))) { + map = lb_addr_load(p, addr); + } + lbValue entries_ptr = lb_map_entries_ptr(p, map); + lbValue count_ptr = lb_emit_struct_ep(p, entries_ptr, 1); + lb_build_range_indexed(p, map, val1_type, count_ptr, &val, &key, &loop, &done); + break; + } + case Type_Array: { + lbValue array = lb_build_addr_ptr(p, expr); + if (is_type_pointer(type_deref(array.type))) { + array = lb_emit_load(p, array); + } + lbAddr count_ptr = lb_add_local_generated(p, t_int, false); + lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->Array.count)); + lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done); + break; + } + case Type_EnumeratedArray: { + lbValue array = lb_build_addr_ptr(p, expr); + if (is_type_pointer(type_deref(array.type))) { + array = lb_emit_load(p, array); + } + lbAddr count_ptr = lb_add_local_generated(p, t_int, false); + lb_addr_store(p, count_ptr, lb_const_int(p->module, t_int, et->EnumeratedArray.count)); + lb_build_range_indexed(p, array, val0_type, count_ptr.addr, &val, &key, &loop, &done); + break; + } + case Type_DynamicArray: { + lbValue count_ptr = {}; + lbValue array = lb_build_addr_ptr(p, expr); + if (is_type_pointer(type_deref(array.type))) { + array = lb_emit_load(p, array); + } + count_ptr = lb_emit_struct_ep(p, array, 1); + lb_build_range_indexed(p, array, val0_type, count_ptr, &val, &key, &loop, &done); + break; + } + case Type_Slice: { + lbValue count_ptr = {}; + lbValue slice = lb_build_expr(p, expr); + if (is_type_pointer(slice.type)) { + count_ptr = lb_emit_struct_ep(p, slice, 1); + slice = lb_emit_load(p, slice); + } else { + count_ptr = lb_add_local_generated(p, t_int, false).addr; + lb_emit_store(p, count_ptr, lb_slice_len(p, slice)); + } + lb_build_range_indexed(p, slice, val0_type, count_ptr, &val, &key, &loop, &done); + break; + } + case Type_Basic: { + lbValue string = lb_build_expr(p, expr); + if (is_type_pointer(string.type)) { + string = lb_emit_load(p, string); + } + if (is_type_untyped(expr_type)) { + lbAddr s = lb_add_local_generated(p, default_type(string.type), false); + lb_addr_store(p, s, string); + string = lb_addr_load(p, s); + } + Type *t = base_type(string.type); + GB_ASSERT(!is_type_cstring(t)); + lb_build_range_string(p, string, val0_type, &val, &key, &loop, &done); + break; + } + case Type_Tuple: + lb_build_range_tuple(p, expr, val0_type, val1_type, &val, &key, &loop, &done); + break; + default: + GB_PANIC("Cannot range over %s", type_to_string(expr_type)); + break; + } + } + + + lbAddr val0_addr = {}; + lbAddr val1_addr = {}; + if (val0_type) val0_addr = lb_build_addr(p, rs->val0); + if (val1_type) val1_addr = lb_build_addr(p, rs->val1); + + if (is_map) { + if (val0_type) lb_addr_store(p, val0_addr, key); + if (val1_type) lb_addr_store(p, val1_addr, val); + } else { + if (val0_type) lb_addr_store(p, val0_addr, val); + if (val1_type) lb_addr_store(p, val1_addr, key); + } + + lb_push_target_list(p, rs->label, done, loop, nullptr); + + lb_build_stmt(p, rs->body); + + lb_close_scope(p, lbDeferExit_Default, nullptr); + lb_pop_target_list(p); + lb_emit_jump(p, loop); + lb_start_block(p, done); +} + +void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) { + lbModule *m = p->module; + + lb_open_scope(p); // Open scope here + + Type *val0_type = nullptr; + Type *val1_type = nullptr; + if (rs->val0 != nullptr && !is_blank_ident(rs->val0)) { + val0_type = type_of_expr(rs->val0); + } + if (rs->val1 != nullptr && !is_blank_ident(rs->val1)) { + val1_type = type_of_expr(rs->val1); + } + + if (val0_type != nullptr) { + Entity *e = entity_of_ident(rs->val0); + lb_add_local(p, e->type, e, true); + } + if (val1_type != nullptr) { + Entity *e = entity_of_ident(rs->val1); + lb_add_local(p, e->type, e, true); + } + + lbValue val = {}; + lbValue key = {}; + lbBlock *loop = nullptr; + lbBlock *done = nullptr; + Ast *expr = unparen_expr(rs->expr); + + TypeAndValue tav = type_and_value_of_expr(expr); + + if (is_ast_range(expr)) { + + lbAddr val0_addr = {}; + lbAddr val1_addr = {}; + if (val0_type) val0_addr = lb_build_addr(p, rs->val0); + if (val1_type) val1_addr = lb_build_addr(p, rs->val1); + + TokenKind op = expr->BinaryExpr.op.kind; + Ast *start_expr = expr->BinaryExpr.left; + Ast *end_expr = expr->BinaryExpr.right; + GB_ASSERT(start_expr->tav.mode == Addressing_Constant); + GB_ASSERT(end_expr->tav.mode == Addressing_Constant); + + ExactValue start = start_expr->tav.value; + ExactValue end = end_expr->tav.value; + if (op == Token_Ellipsis) { // .. [start, end] + ExactValue index = exact_value_i64(0); + for (ExactValue val = start; + compare_exact_values(Token_LtEq, val, end); + val = exact_value_increment_one(val), index = exact_value_increment_one(index)) { + + if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val)); + if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index)); + + lb_build_stmt(p, rs->body); + } + } else if (op == Token_RangeHalf) { // ..< [start, end) + ExactValue index = exact_value_i64(0); + for (ExactValue val = start; + compare_exact_values(Token_Lt, val, end); + val = exact_value_increment_one(val), index = exact_value_increment_one(index)) { + + if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, val)); + if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, index)); + + lb_build_stmt(p, rs->body); + } + } + + + } else if (tav.mode == Addressing_Type) { + GB_ASSERT(is_type_enum(type_deref(tav.type))); + Type *et = type_deref(tav.type); + Type *bet = base_type(et); + + lbAddr val0_addr = {}; + lbAddr val1_addr = {}; + if (val0_type) val0_addr = lb_build_addr(p, rs->val0); + if (val1_type) val1_addr = lb_build_addr(p, rs->val1); + + for_array(i, bet->Enum.fields) { + Entity *field = bet->Enum.fields[i]; + GB_ASSERT(field->kind == Entity_Constant); + if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, field->Constant.value)); + if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i))); + + lb_build_stmt(p, rs->body); + } + } else { + lbAddr val0_addr = {}; + lbAddr val1_addr = {}; + if (val0_type) val0_addr = lb_build_addr(p, rs->val0); + if (val1_type) val1_addr = lb_build_addr(p, rs->val1); + + GB_ASSERT(expr->tav.mode == Addressing_Constant); + + Type *t = base_type(expr->tav.type); + + + switch (t->kind) { + case Type_Basic: + GB_ASSERT(is_type_string(t)); + { + ExactValue value = expr->tav.value; + GB_ASSERT(value.kind == ExactValue_String); + String str = value.value_string; + Rune codepoint = 0; + isize offset = 0; + do { + isize width = gb_utf8_decode(str.text+offset, str.len-offset, &codepoint); + if (val0_type) lb_addr_store(p, val0_addr, lb_const_value(m, val0_type, exact_value_i64(codepoint))); + if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(offset))); + lb_build_stmt(p, rs->body); + + offset += width; + } while (offset < str.len); + } + break; + case Type_Array: + if (t->Array.count > 0) { + lbValue val = lb_build_expr(p, expr); + lbValue val_addr = lb_address_from_load_or_generate_local(p, val); + + for (i64 i = 0; i < t->Array.count; i++) { + if (val0_type) { + // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32 + lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i); + lb_addr_store(p, val0_addr, lb_emit_load(p, elem)); + } + if (val1_type) lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, exact_value_i64(i))); + + lb_build_stmt(p, rs->body); + } + + } + break; + case Type_EnumeratedArray: + if (t->EnumeratedArray.count > 0) { + lbValue val = lb_build_expr(p, expr); + lbValue val_addr = lb_address_from_load_or_generate_local(p, val); + + for (i64 i = 0; i < t->EnumeratedArray.count; i++) { + if (val0_type) { + // NOTE(bill): Due to weird legacy issues in LLVM, this needs to be an i32 + lbValue elem = lb_emit_array_epi(p, val_addr, cast(i32)i); + lb_addr_store(p, val0_addr, lb_emit_load(p, elem)); + } + if (val1_type) { + ExactValue idx = exact_value_add(exact_value_i64(i), t->EnumeratedArray.min_value); + lb_addr_store(p, val1_addr, lb_const_value(m, val1_type, idx)); + } + + lb_build_stmt(p, rs->body); + } + + } + break; + default: + GB_PANIC("Invalid inline for type"); + break; + } + } + + + lb_close_scope(p, lbDeferExit_Default, nullptr); +} + + void lb_build_stmt(lbProcedure *p, Ast *node) { switch (node->kind) { case_ast_node(bs, EmptyStmt, node); @@ -2166,11 +2795,11 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(rs, RangeStmt, node); - // TODO(bill): RangeStmt + lb_build_range_stmt(p, rs); case_end; case_ast_node(rs, InlineRangeStmt, node); - // TODO(bill): InlineRangeStmt + lb_build_inline_range_stmt(p, rs); case_end; case_ast_node(ss, SwitchStmt, node); @@ -2339,9 +2968,9 @@ lbValue lb_const_undef(lbModule *m, Type *type) { } -lbValue lb_const_int(lbModule *m, Type *type, unsigned long long value) { +lbValue lb_const_int(lbModule *m, Type *type, u64 value) { lbValue res = {}; - res.value = LLVMConstInt(lb_type(m, type), value, !is_type_unsigned(type)); + res.value = LLVMConstInt(lb_type(m, type), cast(unsigned long long)value, !is_type_unsigned(type)); res.type = type; return res; } @@ -3441,8 +4070,8 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { // ev = exact_value_to_integer(ev); // } else if (is_type_pointer(dst)) { // // IMPORTANT NOTE(bill): LLVM doesn't support pointer constants expect 'null' - // lbValue i = ir_add_module_constant(p->module, t_uintptr, ev); - // return ir_emit(p, ir_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst)); + // lbValue i = lb_add_module_constant(p->module, t_uintptr, ev); + // return lb_emit(p, lb_instr_conv(p, irConv_inttoptr, i, t_uintptr, dst)); // } // return lb_const_value(p->module, t, ev); } @@ -5141,7 +5770,7 @@ lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, case BuiltinProc_atomic_store_unordered: { lbValue dst = lb_build_expr(p, ce->args[0]); lbValue val = lb_build_expr(p, ce->args[1]); - val = lb_emit_conv(p, val, type_deref(ir_type(dst))); + val = lb_emit_conv(p, val, type_deref(lb_type(dst))); return lb_emit(p, lb_instr_atomic_store(p, dst, val, id)); } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 2c577b712..15ee3c3e1 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -280,6 +280,29 @@ lbAddr lb_add_local_generated(lbProcedure *p, Type *type, bool zero_init); lbValue lb_emit_runtime_call(lbProcedure *p, char const *c_name, Array const &args); +lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index); +lbValue lb_string_elem(lbProcedure *p, lbValue string); +lbValue lb_string_len(lbProcedure *p, lbValue string); +lbValue lb_cstring_len(lbProcedure *p, lbValue value); +lbValue lb_array_elem(lbProcedure *p, lbValue array_ptr); +lbValue lb_slice_elem(lbProcedure *p, lbValue slice); +lbValue lb_slice_len(lbProcedure *p, lbValue slice); +lbValue lb_dynamic_array_elem(lbProcedure *p, lbValue da); +lbValue lb_dynamic_array_len(lbProcedure *p, lbValue da); +lbValue lb_dynamic_array_cap(lbProcedure *p, lbValue da); +lbValue lb_dynamic_array_allocator(lbProcedure *p, lbValue da); +lbValue lb_map_entries(lbProcedure *p, lbValue value); +lbValue lb_map_entries_ptr(lbProcedure *p, lbValue value); +lbValue lb_map_len(lbProcedure *p, lbValue value); +lbValue lb_map_cap(lbProcedure *p, lbValue value); +lbValue lb_soa_struct_len(lbProcedure *p, lbValue value); + +void lb_emit_increment(lbProcedure *p, lbValue addr); + + +lbValue lb_type_info(lbModule *m, Type *type); + + #define LB_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime" #define LB_TYPE_INFO_DATA_NAME "__$type_info_data" #define LB_TYPE_INFO_TYPES_NAME "__$type_info_types_data" -- cgit v1.2.3 From 10cde925ca6da00d035d2ef669d30febe086171a Mon Sep 17 00:00:00 2001 From: gingerBill Date: Mon, 2 Mar 2020 18:48:52 +0000 Subject: Add checks for pre-existing type declarations. --- src/llvm_backend.cpp | 768 ++++++++++++++++++++++++++++++++++++++++----------- src/map.cpp | 2 + 2 files changed, 606 insertions(+), 164 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 60f02e611..b4231d61a 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -375,6 +375,8 @@ String lb_get_entity_name(lbModule *m, Entity *e, String default_name) { } LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { + Type *original_type = type; + LLVMContextRef ctx = m->ctx; i64 size = type_size_of(type); // Check size @@ -410,7 +412,12 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { // Basic_complex32, case Basic_complex64: { - LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..complex64"); + char const *name = "..complex64"; + LLVMTypeRef type = LLVMGetTypeByName(m->mod, name); + if (type != nullptr) { + return type; + } + type = LLVMStructCreateNamed(ctx, name); LLVMTypeRef fields[2] = { lb_type(m, t_f32), lb_type(m, t_f32), @@ -420,7 +427,12 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { } case Basic_complex128: { - LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..complex128"); + char const *name = "..complex128"; + LLVMTypeRef type = LLVMGetTypeByName(m->mod, name); + if (type != nullptr) { + return type; + } + type = LLVMStructCreateNamed(ctx, name); LLVMTypeRef fields[2] = { lb_type(m, t_f64), lb_type(m, t_f64), @@ -431,7 +443,12 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { case Basic_quaternion128: { - LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..quaternion128"); + char const *name = "..quaternion128"; + LLVMTypeRef type = LLVMGetTypeByName(m->mod, name); + if (type != nullptr) { + return type; + } + type = LLVMStructCreateNamed(ctx, name); LLVMTypeRef fields[4] = { lb_type(m, t_f32), lb_type(m, t_f32), @@ -443,7 +460,12 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { } case Basic_quaternion256: { - LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..quaternion256"); + char const *name = "..quaternion256"; + LLVMTypeRef type = LLVMGetTypeByName(m->mod, name); + if (type != nullptr) { + return type; + } + type = LLVMStructCreateNamed(ctx, name); LLVMTypeRef fields[4] = { lb_type(m, t_f64), lb_type(m, t_f64), @@ -462,7 +484,12 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { case Basic_rawptr: return LLVMPointerType(LLVMInt8Type(), 0); case Basic_string: { - LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..string"); + char const *name = "..string"; + LLVMTypeRef type = LLVMGetTypeByName(m->mod, name); + if (type != nullptr) { + return type; + } + type = LLVMStructCreateNamed(ctx, name); LLVMTypeRef fields[2] = { LLVMPointerType(lb_type(m, t_u8), 0), lb_type(m, t_int), @@ -473,7 +500,12 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { case Basic_cstring: return LLVMPointerType(LLVMInt8Type(), 0); case Basic_any: { - LLVMTypeRef type = LLVMStructCreateNamed(ctx, "..any"); + char const *name = "..any"; + LLVMTypeRef type = LLVMGetTypeByName(m->mod, name); + if (type != nullptr) { + return type; + } + type = LLVMStructCreateNamed(ctx, name); LLVMTypeRef fields[2] = { lb_type(m, t_rawptr), lb_type(m, t_typeid), @@ -1333,6 +1365,14 @@ void lb_end_procedure_body(lbProcedure *p) { lb_emit_defer_stmts(p, lbDeferExit_Return, nullptr); LLVMBuildRetVoid(p->builder); } + } else { + if (p->curr_block->preds.count == 0) { + LLVMValueRef instr = LLVMGetLastInstruction(p->curr_block->block); + if (instr == nullptr) { + // NOTE(bill): Remove dead trailing block + LLVMDeleteBasicBlock(p->curr_block->block); + } + } } p->curr_block = nullptr; @@ -1425,7 +1465,7 @@ lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *f // v = lb_emit_conv(p, v, t_bool); v = lb_emit_conv(p, v, t_llvm_bool); - LLVMBuildCondBr(p->builder, v.value, true_block->block, false_block->block); + lb_emit_if(p, v, true_block, false_block); return v; } @@ -2367,6 +2407,304 @@ void lb_build_inline_range_stmt(lbProcedure *p, AstInlineRangeStmt *rs) { } +void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) { + if (ss->init != nullptr) { + lb_build_stmt(p, ss->init); + } + lbValue tag = lb_const_bool(p->module, t_llvm_bool, true); + if (ss->tag != nullptr) { + tag = lb_build_expr(p, ss->tag); + } + lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later + + ast_node(body, BlockStmt, ss->body); + + Array default_stmts = {}; + lbBlock *default_fall = nullptr; + lbBlock *default_block = nullptr; + + lbBlock *fall = nullptr; + bool append_fall = false; + + isize case_count = body->stmts.count; + for_array(i, body->stmts) { + Ast *clause = body->stmts[i]; + lbBlock *body = fall; + + ast_node(cc, CaseClause, clause); + + if (body == nullptr) { + if (cc->list.count == 0) { + body = lb_create_block(p, "switch.dflt.body"); + } else { + body = lb_create_block(p, "switch.case.body"); + } + } + if (append_fall && body == fall) { + append_fall = false; + } + + fall = done; + if (i+1 < case_count) { + append_fall = true; + fall = lb_create_block(p, "switch.fall.body"); + } + + if (cc->list.count == 0) { + // default case + default_stmts = cc->stmts; + default_fall = fall; + default_block = body; + continue; + } + + lbBlock *next_cond = nullptr; + for_array(j, cc->list) { + Ast *expr = unparen_expr(cc->list[j]); + next_cond = lb_create_block(p, "switch.case.next"); + lbValue cond = lb_const_bool(p->module, t_llvm_bool, false); + 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_RangeHalf: op = Token_Lt; break; + default: GB_PANIC("Invalid interval operator"); break; + } + lbValue lhs = lb_build_expr(p, ie->left); + lbValue rhs = lb_build_expr(p, ie->right); + // TODO(bill): do short circuit here + lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag); + lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs); + cond = lb_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)); + lbValue e = lb_typeid(p->module, expr->tav.type); + e = lb_emit_conv(p, e, tag.type); + cond = lb_emit_comp(p, Token_CmpEq, tag, e); + } else { + cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr)); + } + } + lb_emit_if(p, cond, body, next_cond); + lb_start_block(p, next_cond); + } + lb_start_block(p, body); + + lb_push_target_list(p, ss->label, done, nullptr, fall); + lb_open_scope(p); + lb_build_stmt_list(p, cc->stmts); + lb_close_scope(p, lbDeferExit_Default, body); + lb_pop_target_list(p); + + lb_emit_jump(p, done); + lb_start_block(p, next_cond); + } + + if (default_block != nullptr) { + lb_emit_jump(p, default_block); + lb_start_block(p, default_block); + + lb_push_target_list(p, ss->label, done, nullptr, default_fall); + lb_open_scope(p); + lb_build_stmt_list(p, default_stmts); + lb_close_scope(p, lbDeferExit_Default, default_block); + lb_pop_target_list(p); + } + + lb_emit_jump(p, done); + lb_start_block(p, done); +} + +void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) { + Entity *e = implicit_entity_of_node(clause); + GB_ASSERT(e != nullptr); + lbAddr x = lb_add_local(p, e->type, e, false); + lb_addr_store(p, x, value); +} + +void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) { + ast_node(cc, CaseClause, clause); + + lb_push_target_list(p, label, done, nullptr, nullptr); + lb_open_scope(p); + lb_build_stmt_list(p, cc->stmts); + lb_close_scope(p, lbDeferExit_Default, body); + lb_pop_target_list(p); + + lb_emit_jump(p, done); +} + + + +void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) { + lbModule *m = p->module; + + ast_node(as, AssignStmt, ss->tag); + GB_ASSERT(as->lhs.count == 1); + GB_ASSERT(as->rhs.count == 1); + + lbValue parent = lb_build_expr(p, as->rhs[0]); + bool is_parent_ptr = is_type_pointer(parent.type); + + TypeSwitchKind switch_kind = check_valid_type_switch_type(parent.type); + GB_ASSERT(switch_kind != TypeSwitch_Invalid); + + lbValue parent_value = parent; + + lbValue parent_ptr = parent; + if (!is_parent_ptr) { + parent_ptr = lb_address_from_load_or_generate_local(p, parent_ptr); + } + + lbValue tag_index = {}; + lbValue union_data = {}; + if (switch_kind == TypeSwitch_Union) { + tag_index = lb_emit_load(p, lb_emit_union_tag_ptr(p, parent_ptr)); + union_data = lb_emit_conv(p, parent_ptr, t_rawptr); + } + + lbBlock *start_block = lb_create_block(p, "typeswitch.case.first"); + lb_emit_jump(p, start_block); + lb_start_block(p, start_block); + + // NOTE(bill): Append this later + lbBlock *done = lb_create_block(p, "typeswitch.done"); + Ast *default_ = nullptr; + + ast_node(body, BlockStmt, ss->body); + + gb_local_persist i32 weird_count = 0; + + for_array(i, body->stmts) { + Ast *clause = body->stmts[i]; + ast_node(cc, CaseClause, clause); + if (cc->list.count == 0) { + default_ = clause; + continue; + } + + lbBlock *body = lb_create_block(p, "typeswitch.body"); + lbBlock *next = nullptr; + Type *case_type = nullptr; + for_array(type_index, cc->list) { + next = lb_create_block(p, "typeswitch.next"); + case_type = type_of_expr(cc->list[type_index]); + lbValue cond = {}; + if (switch_kind == TypeSwitch_Union) { + Type *ut = base_type(type_deref(parent.type)); + lbValue variant_tag = lb_const_union_tag(m, ut, case_type); + cond = lb_emit_comp(p, Token_CmpEq, tag_index, variant_tag); + } else if (switch_kind == TypeSwitch_Any) { + lbValue any_typeid = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 1)); + lbValue case_typeid = lb_typeid(m, case_type); + cond = lb_emit_comp(p, Token_CmpEq, any_typeid, case_typeid); + } + GB_ASSERT(cond.value != nullptr); + + lb_emit_if(p, cond, body, next); + lb_start_block(p, next); + } + + Entity *case_entity = implicit_entity_of_node(clause); + + lbValue value = parent_value; + + lb_start_block(p, body); + + // bool any_or_not_ptr = is_type_any(type_deref(parent.type)) || !is_parent_ptr; + bool any_or_not_ptr = !is_parent_ptr; + if (cc->list.count == 1) { + + Type *ct = case_entity->type; + if (any_or_not_ptr) { + ct = alloc_type_pointer(ct); + } + GB_ASSERT_MSG(is_type_pointer(ct), "%s", type_to_string(ct)); + lbValue data = {}; + if (switch_kind == TypeSwitch_Union) { + data = union_data; + } else if (switch_kind == TypeSwitch_Any) { + lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0)); + data = any_data; + } + value = lb_emit_conv(p, data, ct); + if (any_or_not_ptr) { + value = lb_emit_load(p, value); + } + } + + lb_store_type_case_implicit(p, clause, value); + lb_type_case_body(p, ss->label, clause, body, done); + lb_start_block(p, next); + } + + if (default_ != nullptr) { + lb_store_type_case_implicit(p, default_, parent_value); + lb_type_case_body(p, ss->label, default_, p->curr_block, done); + } else { + lb_emit_jump(p, done); + } + lb_start_block(p, done); +} + + +lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast *right, Type *type) { + lbModule *m = p->module; + + lbBlock *rhs = lb_create_block(p, "logical.cmp.rhs"); + lbBlock *done = lb_create_block(p, "logical.cmp.done"); + + type = default_type(type); + + lbValue short_circuit = {}; + if (op == Token_CmpAnd) { + lb_build_cond(p, left, rhs, done); + short_circuit = lb_const_bool(m, type, false); + } else if (op == Token_CmpOr) { + lb_build_cond(p, left, done, rhs); + short_circuit = lb_const_bool(m, type, true); + } + + if (rhs->preds.count == 0) { + lb_start_block(p, done); + return short_circuit; + } + + if (done->preds.count == 0) { + lb_start_block(p, rhs); + return lb_build_expr(p, right); + } + + Array incoming_values = {}; + Array incoming_blocks = {}; + array_init(&incoming_values, heap_allocator(), done->preds.count+1); + array_init(&incoming_blocks, heap_allocator(), done->preds.count+1); + + for_array(i, done->preds) { + incoming_values[i] = short_circuit.value; + incoming_blocks[i] = done->preds[i]->block; + } + + lb_start_block(p, rhs); + lbValue edge = lb_build_expr(p, right); + incoming_values[done->preds.count] = edge.value; + incoming_blocks[done->preds.count] = rhs->block; + + lb_emit_jump(p, done); + lb_start_block(p, done); + + lbValue res = {}; + res.type = type; + res.value = LLVMBuildPhi(p->builder, lb_type(m, type), ""); + + LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count); + + return res; +} + + void lb_build_stmt(lbProcedure *p, Ast *node) { switch (node->kind) { case_ast_node(bs, EmptyStmt, node); @@ -2587,11 +2925,11 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { op += Token_Add - Token_AddEq; // Convert += to + if (op == Token_CmpAnd || op == Token_CmpOr) { // TODO(bill): assign op - // Type *type = as->lhs[0]->tav.type; - // lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type); + Type *type = as->lhs[0]->tav.type; + lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type); - // lbAddr lhs = lb_build_addr(p, as->lhs[0]); - // lb_addr_store(p, lhs, new_value); + lbAddr lhs = lb_build_addr(p, as->lhs[0]); + lb_addr_store(p, lhs, new_value); } else { // TODO(bill): Assign op lbAddr lhs = lb_build_addr(p, as->lhs[0]); @@ -2803,117 +3141,11 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { case_end; case_ast_node(ss, SwitchStmt, node); - if (ss->init != nullptr) { - lb_build_stmt(p, ss->init); - } - lbValue tag = lb_const_bool(p->module, t_llvm_bool, true); - if (ss->tag != nullptr) { - tag = lb_build_expr(p, ss->tag); - } - lbBlock *done = lb_create_block(p, "switch.done"); // NOTE(bill): Append later - - ast_node(body, BlockStmt, ss->body); - - Array default_stmts = {}; - lbBlock *default_fall = nullptr; - lbBlock *default_block = nullptr; - - lbBlock *fall = nullptr; - bool append_fall = false; - - isize case_count = body->stmts.count; - for_array(i, body->stmts) { - Ast *clause = body->stmts[i]; - lbBlock *body = fall; - - ast_node(cc, CaseClause, clause); - - if (body == nullptr) { - if (cc->list.count == 0) { - body = lb_create_block(p, "switch.dflt.body"); - } else { - body = lb_create_block(p, "switch.case.body"); - } - } - if (append_fall && body == fall) { - append_fall = false; - } - - fall = done; - if (i+1 < case_count) { - append_fall = true; - fall = lb_create_block(p, "switch.fall.body"); - } - - if (cc->list.count == 0) { - // default case - default_stmts = cc->stmts; - default_fall = fall; - default_block = body; - continue; - } - - lbBlock *next_cond = nullptr; - for_array(j, cc->list) { - Ast *expr = unparen_expr(cc->list[j]); - next_cond = lb_create_block(p, "switch.case.next"); - lbValue cond = lb_const_bool(p->module, t_llvm_bool, false); - 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_RangeHalf: op = Token_Lt; break; - default: GB_PANIC("Invalid interval operator"); break; - } - lbValue lhs = lb_build_expr(p, ie->left); - lbValue rhs = lb_build_expr(p, ie->right); - // TODO(bill): do short circuit here - lbValue cond_lhs = lb_emit_comp(p, Token_LtEq, lhs, tag); - lbValue cond_rhs = lb_emit_comp(p, op, tag, rhs); - cond = lb_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)); - lbValue e = lb_typeid(p->module, expr->tav.type); - e = lb_emit_conv(p, e, tag.type); - cond = lb_emit_comp(p, Token_CmpEq, tag, e); - } else { - cond = lb_emit_comp(p, Token_CmpEq, tag, lb_build_expr(p, expr)); - } - } - lb_emit_if(p, cond, body, next_cond); - lb_start_block(p, next_cond); - } - lb_start_block(p, body); - - lb_push_target_list(p, ss->label, done, nullptr, fall); - lb_open_scope(p); - lb_build_stmt_list(p, cc->stmts); - lb_close_scope(p, lbDeferExit_Default, body); - lb_pop_target_list(p); - - lb_emit_jump(p, done); - lb_start_block(p, next_cond); - } - - if (default_block != nullptr) { - lb_emit_jump(p, default_block); - lb_start_block(p, default_block); - - lb_push_target_list(p, ss->label, done, nullptr, default_fall); - lb_open_scope(p); - lb_build_stmt_list(p, default_stmts); - lb_close_scope(p, lbDeferExit_Default, default_block); - lb_pop_target_list(p); - } - - lb_emit_jump(p, done); - lb_start_block(p, done); + lb_build_switch_stmt(p, ss); case_end; case_ast_node(ss, TypeSwitchStmt, node); - // TODO(bill): TypeSwitchStmt + lb_build_type_switch_stmt(p, ss); case_end; case_ast_node(bs, BranchStmt, node); @@ -3183,6 +3415,10 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { return lb_typeid(m, value.value_typeid, original_type); } + if (value.kind == ExactValue_Invalid) { + return lb_const_nil(m, type); + } + // GB_ASSERT_MSG(is_type_typed(type), "%s", type_to_string(type)); if (is_type_slice(type)) { @@ -3960,11 +4196,64 @@ lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { case Token_CmpAnd: case Token_CmpOr: - GB_PANIC("TODO(bill): && ||"); + return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type); break; + case Token_in: case Token_not_in: - GB_PANIC("TODO(bill): in/not_in"); + { + lbValue left = lb_build_expr(p, be->left); + Type *type = default_type(tv.type); + lbValue right = lb_build_expr(p, be->right); + Type *rt = base_type(right.type); + switch (rt->kind) { + case Type_Map: + { + GB_PANIC("map in/not_in"); + // lbValue addr = lb_address_from_load_or_generate_local(p, right); + // lbValue h = lb_gen_map_header(p, addr, rt); + // lbValue key = ir_gen_map_key(p, left, rt->Map.key); + + // auto args = array_make(heap_allocator(), 2); + // args[0] = h; + // args[1] = key; + + // lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args); + // if (be->op.kind == Token_in) { + // return ir_emit_conv(p, ir_emit_comp(p, Token_NotEq, ptr, v_raw_nil), t_bool); + // } else { + // return ir_emit_conv(p, ir_emit_comp(p, Token_CmpEq, ptr, v_raw_nil), t_bool); + // } + } + break; + case Type_BitSet: + { + Type *key_type = rt->BitSet.elem; + GB_ASSERT(are_types_identical(left.type, key_type)); + + Type *it = bit_set_to_int(rt); + left = lb_emit_conv(p, left, it); + + lbValue lower = lb_const_value(p->module, it, exact_value_i64(rt->BitSet.lower)); + lbValue key = lb_emit_arith(p, Token_Sub, left, lower, it); + lbValue bit = lb_emit_arith(p, Token_Shl, lb_const_int(p->module, it, 1), key, it); + bit = lb_emit_conv(p, bit, it); + + lbValue old_value = lb_emit_transmute(p, right, it); + lbValue new_value = lb_emit_arith(p, Token_And, old_value, bit, it); + + if (be->op.kind == Token_in) { + return lb_emit_conv(p, lb_emit_comp(p, Token_NotEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool); + } else { + return lb_emit_conv(p, lb_emit_comp(p, Token_CmpEq, new_value, lb_const_int(p->module, new_value.type, 0)), t_bool); + } + } + break; + default: + GB_PANIC("Invalid 'in' type"); + } + break; + } break; default: GB_PANIC("Invalid binary expression"); @@ -4121,11 +4410,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { // NOTE(bill): Copy the value just for type correctness op = LLVMBitCast; } else if (dz > sz) { - if (is_type_unsigned(src)) { - op = LLVMZExt; // zero extent - } else { - op = LLVMSExt; // sign extent - } + op = is_type_unsigned(src) ? LLVMZExt : LLVMSExt; // zero extent } if (dz > 1 && is_type_different_to_arch_endianness(dst)) { @@ -4147,7 +4432,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { if (is_type_boolean(src) && (is_type_boolean(dst) || is_type_integer(dst))) { LLVMValueRef b = LLVMBuildICmp(p->builder, LLVMIntNE, value.value, LLVMConstNull(lb_type(m, value.type)), ""); lbValue res = {}; - res.value = LLVMBuildZExt(p->builder, value.value, lb_type(m, t), ""); + res.value = LLVMBuildIntCast2(p->builder, value.value, lb_type(m, t), false, ""); res.type = t; return res; } @@ -6514,71 +6799,71 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri right = lb_emit_conv(p, right, t_string); } - char const *runtime_proc = nullptr; + char const *runtime_procedure = nullptr; switch (op_kind) { - case Token_CmpEq: runtime_proc = "string_eq"; break; - case Token_NotEq: runtime_proc = "string_ne"; break; - case Token_Lt: runtime_proc = "string_lt"; break; - case Token_Gt: runtime_proc = "string_gt"; break; - case Token_LtEq: runtime_proc = "string_le"; break; - case Token_GtEq: runtime_proc = "string_gt"; break; + case Token_CmpEq: runtime_procedure = "string_eq"; break; + case Token_NotEq: runtime_procedure = "string_ne"; break; + case Token_Lt: runtime_procedure = "string_lt"; break; + case Token_Gt: runtime_procedure = "string_gt"; break; + case Token_LtEq: runtime_procedure = "string_le"; break; + case Token_GtEq: runtime_procedure = "string_gt"; break; } - GB_ASSERT(runtime_proc != nullptr); + GB_ASSERT(runtime_procedure != nullptr); auto args = array_make(heap_allocator(), 2); args[0] = left; args[1] = right; - return lb_emit_runtime_call(p, runtime_proc, args); + return lb_emit_runtime_call(p, runtime_procedure, args); } if (is_type_complex(a)) { - char const *runtime_proc = ""; + char const *runtime_procedure = ""; i64 sz = 8*type_size_of(a); switch (sz) { case 64: switch (op_kind) { - case Token_CmpEq: runtime_proc = "complex64_eq"; break; - case Token_NotEq: runtime_proc = "complex64_ne"; break; + case Token_CmpEq: runtime_procedure = "complex64_eq"; break; + case Token_NotEq: runtime_procedure = "complex64_ne"; break; } break; case 128: switch (op_kind) { - case Token_CmpEq: runtime_proc = "complex128_eq"; break; - case Token_NotEq: runtime_proc = "complex128_ne"; break; + case Token_CmpEq: runtime_procedure = "complex128_eq"; break; + case Token_NotEq: runtime_procedure = "complex128_ne"; break; } break; } - GB_ASSERT(runtime_proc != nullptr); + GB_ASSERT(runtime_procedure != nullptr); auto args = array_make(heap_allocator(), 2); args[0] = left; args[1] = right; - return lb_emit_runtime_call(p, runtime_proc, args); + return lb_emit_runtime_call(p, runtime_procedure, args); } if (is_type_quaternion(a)) { - char const *runtime_proc = ""; + char const *runtime_procedure = ""; i64 sz = 8*type_size_of(a); switch (sz) { case 128: switch (op_kind) { - case Token_CmpEq: runtime_proc = "quaternion128_eq"; break; - case Token_NotEq: runtime_proc = "quaternion128_ne"; break; + case Token_CmpEq: runtime_procedure = "quaternion128_eq"; break; + case Token_NotEq: runtime_procedure = "quaternion128_ne"; break; } break; case 256: switch (op_kind) { - case Token_CmpEq: runtime_proc = "quaternion256_eq"; break; - case Token_NotEq: runtime_proc = "quaternion256_ne"; break; + case Token_CmpEq: runtime_procedure = "quaternion256_eq"; break; + case Token_NotEq: runtime_procedure = "quaternion256_ne"; break; } break; } - GB_ASSERT(runtime_proc != nullptr); + GB_ASSERT(runtime_procedure != nullptr); auto args = array_make(heap_allocator(), 2); args[0] = left; args[1] = right; - return lb_emit_runtime_call(p, runtime_proc, args); + return lb_emit_runtime_call(p, runtime_procedure, args); } if (is_type_bit_set(a)) { @@ -6664,6 +6949,17 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri case Token_NotEq: pred = LLVMRealONE; break; } res.value = LLVMBuildFCmp(p->builder, pred, left.value, right.value, ""); + } else if (is_type_typeid(left.type)) { + LLVMIntPredicate pred = {}; + switch (op_kind) { + case Token_Gt: pred = LLVMIntUGT; break; + case Token_GtEq: pred = LLVMIntUGE; break; + case Token_Lt: pred = LLVMIntULT; break; + case Token_LtEq: pred = LLVMIntULE; break; + case Token_CmpEq: pred = LLVMIntEQ; break; + case Token_NotEq: pred = LLVMIntNE; break; + } + res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, ""); } else { GB_PANIC("Unhandled comparison kind %s %.*s %s", type_to_string(left.type), LIT(token_strings[op_kind]), type_to_string(right.type)); } @@ -6712,6 +7008,156 @@ lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, A return value; } +lbValue lb_emit_union_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos, bool do_conversion_check=true) { + lbModule *m = p->module; + + 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); + } + + lbAddr v = lb_add_local_generated(p, tuple, true); + + if (is_ptr) { + value = lb_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; + + lbValue value_ = lb_address_from_load_or_generate_local(p, value); + + lbValue tag = {}; + lbValue dst_tag = {}; + lbValue cond = {}; + lbValue data = {}; + + lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0); + lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1); + + if (is_type_union_maybe_pointer(src)) { + data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type)); + } else { + tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, value_)); + dst_tag = lb_const_union_tag(m, src, dst); + } + + lbBlock *ok_block = lb_create_block(p, "union_cast.ok"); + lbBlock *end_block = lb_create_block(p, "union_cast.end"); + + if (data.value != nullptr) { + GB_ASSERT(is_type_union_maybe_pointer(src)); + cond = lb_emit_comp_against_nil(p, Token_NotEq, data); + } else { + cond = lb_emit_comp(p, Token_CmpEq, tag, dst_tag); + } + + lb_emit_if(p, cond, ok_block, end_block); + lb_start_block(p, ok_block); + + + + if (data.value == nullptr) { + data = lb_emit_load(p, lb_emit_conv(p, value_, gep0.type)); + } + lb_emit_store(p, gep0, data); + lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true)); + + lb_emit_jump(p, end_block); + lb_start_block(p, end_block); + + if (!is_tuple) { + if (do_conversion_check) { + // NOTE(bill): Panic on invalid conversion + Type *dst_type = tuple->Tuple.variables[0]->type; + + lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1)); + auto args = array_make(heap_allocator(), 6); + args[0] = ok; + + args[1] = lb_const_string(m, pos.file); + args[2] = lb_const_int(m, t_int, pos.line); + args[3] = lb_const_int(m, t_int, pos.column); + + args[4] = lb_typeid(m, src_type); + args[5] = lb_typeid(m, dst_type); + lb_emit_runtime_call(p, "type_assertion_check", args); + } + + return lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 0)); + } + return lb_addr_load(p, v); +} + +lbAddr lb_emit_any_cast_addr(lbProcedure *p, lbValue value, Type *type, TokenPos pos) { + lbModule *m = p->module; + + Type *src_type = value.type; + + if (is_type_pointer(src_type)) { + value = lb_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; + + lbAddr v = lb_add_local_generated(p, tuple, true); + + lbValue dst_typeid = lb_typeid(m, dst_type); + lbValue any_typeid = lb_emit_struct_ev(p, value, 1); + + + lbBlock *ok_block = lb_create_block(p, "any_cast.ok"); + lbBlock *end_block = lb_create_block(p, "any_cast.end"); + lbValue cond = lb_emit_comp(p, Token_CmpEq, any_typeid, dst_typeid); + lb_emit_if(p, cond, ok_block, end_block); + lb_start_block(p, ok_block); + + lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0); + lbValue gep1 = lb_emit_struct_ep(p, v.addr, 1); + + lbValue any_data = lb_emit_struct_ev(p, value, 0); + lbValue ptr = lb_emit_conv(p, any_data, alloc_type_pointer(dst_type)); + lb_emit_store(p, gep0, lb_emit_load(p, ptr)); + lb_emit_store(p, gep1, lb_const_bool(m, t_bool, true)); + + lb_emit_jump(p, end_block); + lb_start_block(p, end_block); + + if (!is_tuple) { + // NOTE(bill): Panic on invalid conversion + + lbValue ok = lb_emit_load(p, lb_emit_struct_ep(p, v.addr, 1)); + auto args = array_make(heap_allocator(), 6); + args[0] = ok; + + args[1] = lb_const_string(m, pos.file); + args[2] = lb_const_int(m, t_int, pos.line); + args[3] = lb_const_int(m, t_int, pos.column); + + args[4] = any_typeid; + args[5] = dst_typeid; + lb_emit_runtime_call(p, "type_assertion_check", args); + + return lb_addr(lb_emit_struct_ep(p, v.addr, 0)); + } + return v; +} +lbValue lb_emit_any_cast(lbProcedure *p, lbValue value, Type *type, TokenPos pos) { + return lb_addr_load(p, lb_emit_any_cast_addr(p, value, type, pos)); +} + + lbValue lb_build_expr(lbProcedure *p, Ast *expr) { lbModule *m = p->module; @@ -6852,11 +7298,9 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { lbValue e = lb_build_expr(p, ta->expr); Type *t = type_deref(e.type); if (is_type_union(t)) { - GB_PANIC("cast - union_cast"); - // return lb_emit_union_cast(p, e, type, pos); + return lb_emit_union_cast(p, e, type, pos); } else if (is_type_any(t)) { - GB_PANIC("cast - any_cast"); - // return lb_emit_any_cast(p, e, type, pos); + return lb_emit_any_cast(p, e, type, pos); } else { GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type)); } @@ -7172,28 +7616,24 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { } case_end; -#if 0 case_ast_node(ta, TypeAssertion, expr); gbAllocator a = heap_allocator(); TokenPos pos = ast_token(expr).pos; lbValue e = lb_build_expr(p, ta->expr); - Type *t = type_deref(ir_type(e)); + Type *t = type_deref(e.type); if (is_type_union(t)) { Type *type = type_of_expr(expr); - lbValue v = lb_add_local_generated(p, type, false); - ir_emit_comment(p, str_lit("cast - union_cast")); - lb_emit_store(p, v, ir_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos)); - return ir_addr(v); + lbAddr v = lb_add_local_generated(p, type, false); + lb_addr_store(p, v, lb_emit_union_cast(p, lb_build_expr(p, ta->expr), type, pos)); + return v; } else if (is_type_any(t)) { - ir_emit_comment(p, str_lit("cast - any_cast")); Type *type = type_of_expr(expr); - return ir_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos); + return lb_emit_any_cast_addr(p, lb_build_expr(p, ta->expr), type, pos); } else { - GB_PANIC("TODO(bill): type assertion %s", type_to_string(ir_type(e))); + GB_PANIC("TODO(bill): type assertion %s", type_to_string(e.type)); } case_end; -#endif case_ast_node(ue, UnaryExpr, expr); switch (ue->op.kind) { case Token_And: { diff --git a/src/map.cpp b/src/map.cpp index aa4152696..03ac924fe 100644 --- a/src/map.cpp +++ b/src/map.cpp @@ -55,12 +55,14 @@ gb_inline HashKey hash_string(String s) { gb_inline HashKey hash_pointer(void *ptr) { HashKey h = {HashKey_Ptr}; h.key = cast(u64)cast(uintptr)ptr; + // h.key = gb_fnv64a(&ptr, gb_size_of(void *)); h.ptr = ptr; return h; } gb_inline HashKey hash_ptr_and_id(void *ptr, u64 id) { HashKey h = {HashKey_PtrAndId}; h.key = cast(u64)cast(uintptr)ptr; + // h.key = gb_fnv64a(&ptr, gb_size_of(void *)); h.ptr_and_id.ptr = ptr; h.ptr_and_id.id = id; return h; -- cgit v1.2.3 From e1da631d2620d87085f1a288e57ba39e1d7e92e5 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Wed, 4 Mar 2020 22:09:58 +0000 Subject: General functionality without `context` --- examples/llvm-demo/demo.odin | 4 +- src/llvm_backend.cpp | 227 ++++++++++++++++++++++++++++++++++++++----- src/llvm_backend.hpp | 3 +- src/string.cpp | 8 ++ 4 files changed, 218 insertions(+), 24 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/examples/llvm-demo/demo.odin b/examples/llvm-demo/demo.odin index 48a2f9255..874302d02 100644 --- a/examples/llvm-demo/demo.odin +++ b/examples/llvm-demo/demo.odin @@ -1,9 +1,11 @@ package demo import "core:os" +import "core:fmt" main :: proc() { - os.write_string(os.stdout, "Hellope\n"); + fmt.fprintln(os.stdout, "Hellope!", 123, true, 1.3); +} // BarBar :: struct {x, y: int}; diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index b4231d61a..3657eec60 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -1196,13 +1196,17 @@ lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 i return {}; } - void lb_start_block(lbProcedure *p, lbBlock *b) { GB_ASSERT(b != nullptr); - p->curr_block = b; + if (!b->appended) { + b->appended = true; + LLVMAppendExistingBasicBlock(p->value, b->block); + } LLVMPositionBuilderAtEnd(p->builder, b->block); + p->curr_block = b; } + void lb_begin_procedure_body(lbProcedure *p) { DeclInfo *decl = decl_info_of_entity(p->entity); if (decl != nullptr) { @@ -1215,8 +1219,8 @@ void lb_begin_procedure_body(lbProcedure *p) { p->builder = LLVMCreateBuilder(); - p->decl_block = lb_create_block(p, "decls"); - p->entry_block = lb_create_block(p, "entry"); + p->decl_block = lb_create_block(p, "decls", true); + p->entry_block = lb_create_block(p, "entry", true); lb_start_block(p, p->entry_block); GB_ASSERT(p->type != nullptr); @@ -1391,9 +1395,15 @@ void lb_add_edge(lbBlock *from, lbBlock *to) { } -lbBlock *lb_create_block(lbProcedure *p, char const *name) { +lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append) { lbBlock *b = gb_alloc_item(heap_allocator(), lbBlock); - b->block = LLVMAppendBasicBlockInContext(p->module->ctx, p->value, name); + b->block = LLVMCreateBasicBlockInContext(p->module->ctx, name); + b->appended = false; + if (append) { + b->appended = true; + LLVMAppendExistingBasicBlock(p->value, b->block); + } + b->scope = p->curr_scope; b->scope_index = p->scope_index; @@ -1431,7 +1441,10 @@ void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *fals lb_add_edge(b, true_block); lb_add_edge(b, false_block); - LLVMBuildCondBr(p->builder, cond.value, true_block->block, false_block->block); + + LLVMValueRef cv = cond.value; + cv = LLVMBuildTruncOrBitCast(p->builder, cv, lb_type(p->module, t_llvm_bool), ""); + LLVMBuildCondBr(p->builder, cv, true_block->block, false_block->block); } lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) { @@ -2689,8 +2702,9 @@ lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast lb_start_block(p, rhs); lbValue edge = lb_build_expr(p, right); + incoming_values[done->preds.count] = edge.value; - incoming_blocks[done->preds.count] = rhs->block; + incoming_blocks[done->preds.count] = p->curr_block->block; lb_emit_jump(p, done); lb_start_block(p, done); @@ -2698,10 +2712,10 @@ lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast lbValue res = {}; res.type = type; res.value = LLVMBuildPhi(p->builder, lb_type(m, type), ""); - + GB_ASSERT(incoming_values.count == incoming_blocks.count); LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count); - return res; + return short_circuit; } @@ -4031,11 +4045,8 @@ lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) switch (op) { case Token_Not: // Boolean not - res.value = LLVMBuildNot(p->builder, x.value, ""); - res.type = x.type; - return res; case Token_Xor: // Bitwise not - res.value = LLVMBuildXor(p->builder, x.value, LLVMConstAllOnes(lb_type(p->module, x.type)), ""); + res.value = LLVMBuildNot(p->builder, x.value, ""); res.type = x.type; return res; case Token_Sub: // Number negation @@ -4058,14 +4069,172 @@ lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Type *type) { lbModule *m = p->module; + if (is_type_array(lhs.type) || is_type_array(rhs.type)) { + lhs = lb_emit_conv(p, lhs, type); + rhs = lb_emit_conv(p, rhs, type); + + lbValue x = lb_address_from_load_or_generate_local(p, lhs); + lbValue y = lb_address_from_load_or_generate_local(p, rhs); + + GB_ASSERT(is_type_array(type)); + Type *elem_type = base_array_type(type); + + lbAddr res = lb_add_local_generated(p, type, false); + i64 count = base_type(type)->Array.count; + + bool inline_array_arith = type_size_of(type) <= build_context.max_align; + + if (inline_array_arith) { + for (i64 i = 0; i < count; i++) { + lbValue a = lb_emit_load(p, lb_emit_array_epi(p, x, i)); + lbValue b = lb_emit_load(p, lb_emit_array_epi(p, y, i)); + lbValue c = lb_emit_arith(p, op, a, b, elem_type); + lb_emit_store(p, lb_emit_array_epi(p, res.addr, i), c); + } + } else { + auto loop_data = lb_loop_start(p, count); + + lbValue a = lb_emit_load(p, lb_emit_array_ep(p, x, loop_data.idx)); + lbValue b = lb_emit_load(p, lb_emit_array_ep(p, y, loop_data.idx)); + lbValue c = lb_emit_arith(p, op, a, b, elem_type); + lb_emit_store(p, lb_emit_array_ep(p, res.addr, loop_data.idx), c); + + lb_loop_end(p, loop_data); + } + + return lb_addr_load(p, res); + } else if (is_type_complex(type)) { + lhs = lb_emit_conv(p, lhs, type); + rhs = lb_emit_conv(p, rhs, type); + + Type *ft = base_complex_elem_type(type); + + if (op == Token_Quo) { + auto args = array_make(heap_allocator(), 2); + args[0] = lhs; + args[1] = rhs; + + switch (type_size_of(ft)) { + case 4: return lb_emit_runtime_call(p, "quo_complex64", args); + case 8: return lb_emit_runtime_call(p, "quo_complex128", args); + default: GB_PANIC("Unknown float type"); break; + } + } + + lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later + lbValue a = lb_emit_struct_ev(p, lhs, 0); + lbValue b = lb_emit_struct_ev(p, lhs, 1); + lbValue c = lb_emit_struct_ev(p, rhs, 0); + lbValue d = lb_emit_struct_ev(p, rhs, 1); + + lbValue real = {}; + lbValue imag = {}; + + switch (op) { + case Token_Add: + real = lb_emit_arith(p, Token_Add, a, c, ft); + imag = lb_emit_arith(p, Token_Add, b, d, ft); + break; + case Token_Sub: + real = lb_emit_arith(p, Token_Sub, a, c, ft); + imag = lb_emit_arith(p, Token_Sub, b, d, ft); + break; + case Token_Mul: { + lbValue x = lb_emit_arith(p, Token_Mul, a, c, ft); + lbValue y = lb_emit_arith(p, Token_Mul, b, d, ft); + real = lb_emit_arith(p, Token_Sub, x, y, ft); + lbValue z = lb_emit_arith(p, Token_Mul, b, c, ft); + lbValue w = lb_emit_arith(p, Token_Mul, a, d, ft); + imag = lb_emit_arith(p, Token_Add, z, w, ft); + break; + } + } + + lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), real); + lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), imag); + + return lb_addr_load(p, res); + } else if (is_type_quaternion(type)) { + lhs = lb_emit_conv(p, lhs, type); + rhs = lb_emit_conv(p, rhs, type); + + Type *ft = base_complex_elem_type(type); + + if (op == Token_Add || op == Token_Sub) { + lbAddr res = lb_add_local_generated(p, type, false); // NOTE: initialized in full later + lbValue x0 = lb_emit_struct_ev(p, lhs, 0); + lbValue x1 = lb_emit_struct_ev(p, lhs, 1); + lbValue x2 = lb_emit_struct_ev(p, lhs, 2); + lbValue x3 = lb_emit_struct_ev(p, lhs, 3); + + lbValue y0 = lb_emit_struct_ev(p, rhs, 0); + lbValue y1 = lb_emit_struct_ev(p, rhs, 1); + lbValue y2 = lb_emit_struct_ev(p, rhs, 2); + lbValue y3 = lb_emit_struct_ev(p, rhs, 3); + + lbValue z0 = lb_emit_arith(p, op, x0, y0, ft); + lbValue z1 = lb_emit_arith(p, op, x1, y1, ft); + lbValue z2 = lb_emit_arith(p, op, x2, y2, ft); + lbValue z3 = lb_emit_arith(p, op, x3, y3, ft); + + lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), z0); + lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), z1); + lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 2), z2); + lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 3), z3); + + return lb_addr_load(p, res); + } else if (op == Token_Mul) { + auto args = array_make(heap_allocator(), 2); + args[0] = lhs; + args[1] = rhs; + + switch (8*type_size_of(ft)) { + case 32: return lb_emit_runtime_call(p, "mul_quaternion128", args); + case 64: return lb_emit_runtime_call(p, "mul_quaternion256", args); + default: GB_PANIC("Unknown float type"); break; + } + } else if (op == Token_Quo) { + auto args = array_make(heap_allocator(), 2); + args[0] = lhs; + args[1] = rhs; + + switch (8*type_size_of(ft)) { + case 32: return lb_emit_runtime_call(p, "quo_quaternion128", args); + case 64: return lb_emit_runtime_call(p, "quo_quaternion256", args); + default: GB_PANIC("Unknown float type"); break; + } + } + } + + if (is_type_integer(type) && is_type_different_to_arch_endianness(type)) { + switch (op) { + case Token_AndNot: + case Token_And: + case Token_Or: + case Token_Xor: + goto handle_op; + } + + Type *platform_type = integer_endian_type_to_platform_type(type); + lbValue x = lb_emit_byte_swap(p, lhs, integer_endian_type_to_platform_type(lhs.type)); + lbValue y = lb_emit_byte_swap(p, rhs, integer_endian_type_to_platform_type(rhs.type)); + + lbValue res = lb_emit_arith(p, op, x, y, platform_type); + + return lb_emit_byte_swap(p, res, type); + } + + + +handle_op: lhs = lb_emit_conv(p, lhs, type); rhs = lb_emit_conv(p, rhs, type); - lbValue res = {}; res.type = type; + switch (op) { case Token_Add: if (is_type_float(type)) { @@ -4143,8 +4312,7 @@ lbValue lb_emit_arith(lbProcedure *p, TokenKind op, lbValue lhs, lbValue rhs, Ty return res; case Token_AndNot: { - LLVMValueRef all_ones = LLVMConstAllOnes(lb_type(m, type)); - LLVMValueRef new_rhs = LLVMBuildXor(p->builder, all_ones, rhs.value, ""); + LLVMValueRef new_rhs = LLVMBuildNot(p->builder, rhs.value, ""); res.value = LLVMBuildAnd(p->builder, lhs.value, new_rhs, ""); return res; } @@ -4852,7 +5020,7 @@ void lb_emit_init_context(lbProcedure *p, lbValue c) { gbAllocator a = heap_allocator(); auto args = array_make(a, 1); args[0] = c.value != nullptr ? c : m->global_default_context.addr; - // lb_emit_runtime_call(p, "__init_context", args); + lb_emit_runtime_call(p, "__init_context", args); } void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) { @@ -4866,10 +5034,6 @@ lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) { return p->context_stack[p->context_stack.count-1].ctx; } - // lbBlock *tmp_block = p->curr_block; - // p->curr_block = p->blocks[0]; - // defer (p->curr_block = tmp_block); - lbAddr c = lb_add_local_generated(p, t_context, false); c.kind = lbAddr_Context; lb_push_context_onto_stack(p, c); @@ -6495,10 +6659,29 @@ void lb_emit_increment(lbProcedure *p, lbValue addr) { lbValue lb_emit_byte_swap(lbProcedure *p, lbValue value, Type *platform_type) { Type *vt = core_type(value.type); GB_ASSERT(type_size_of(vt) == type_size_of(platform_type)); + GB_ASSERT(is_type_integer(vt)); + // TODO(bill): lb_emit_byte_swap lbValue res = {}; res.type = platform_type; res.value = value.value; + + // int sz = cast(int)type_size_of(vt); + // if (sz > 1) { + // char buf[32] = {}; + // gb_snprintf(buf, gb_count_of(buf), "llvm.bswap.i%d", sz*8); + // unsigned id = LLVMLookupIntrinsicID(buf, gb_strlen(buf)); + // gb_printf(">>> %s %u\n", buf, id); + + // LLVMTypeRef types[2] = {}; + // types[0] = lb_type(p->module, value.type); + // types[1] = lb_type(p->module, value.type); + + // LLVMValueRef fn = LLVMGetIntrinsicDeclaration(p->module->mod, id, types, gb_count_of(types)); + + // res.value = LLVMBuildCall(p->builder, fn, &value.value, 1, ""); + // } + return res; } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 15ee3c3e1..01da51529 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -97,6 +97,7 @@ struct lbBlock { LLVMBasicBlockRef block; Scope *scope; isize scope_index; + bool appended; Array preds; Array succs; @@ -220,7 +221,7 @@ void lb_end_procedure(lbProcedure *p); LLVMTypeRef lb_type(lbModule *m, Type *type); -lbBlock *lb_create_block(lbProcedure *p, char const *name); +lbBlock *lb_create_block(lbProcedure *p, char const *name, bool append=false); lbValue lb_const_nil(lbModule *m, Type *type); lbValue lb_const_undef(lbModule *m, Type *type); diff --git a/src/string.cpp b/src/string.cpp index 9551821aa..724733ce7 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -101,6 +101,14 @@ char *alloc_cstring(gbAllocator a, String s) { return c_str; } +char *cstring_duplicate(gbAllocator a, char const *s) { + isize len = gb_strlen(s); + char *c_str = gb_alloc_array(a, char, len+1); + gb_memmove(c_str, s, len); + c_str[len] = '\0'; + return c_str; +} + gb_inline bool str_eq_ignore_case(String const &a, String const &b) { -- cgit v1.2.3 From 7d93dd60240a58834c950f341ec9761050784b3b Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 5 Mar 2020 19:00:23 +0000 Subject: Move module pass to after all function passes --- src/llvm_backend.cpp | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 3657eec60..cce2d594b 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -9829,19 +9829,6 @@ void lb_generate_code(lbGenerator *gen) { } } - LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager(); - defer (LLVMDisposePassManager(module_pass_manager)); - LLVMAddAlwaysInlinerPass(module_pass_manager); - LLVMAddStripDeadPrototypesPass(module_pass_manager); - - LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate(); - defer (LLVMPassManagerBuilderDispose(pass_manager_builder)); - LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, 0); - LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, 0); - - LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false); - LLVMRunPassManager(module_pass_manager, mod); - lbProcedure *startup_runtime = nullptr; { // Startup Runtime @@ -9943,9 +9930,25 @@ void lb_generate_code(lbGenerator *gen) { } LLVMRunFunctionPassManager(function_pass_manager, p->value); - } + + LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager(); + defer (LLVMDisposePassManager(module_pass_manager)); + LLVMAddAlwaysInlinerPass(module_pass_manager); + LLVMAddStripDeadPrototypesPass(module_pass_manager); + + LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate(); + defer (LLVMPassManagerBuilderDispose(pass_manager_builder)); + LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, 3); + LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, 3); + + LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false); + LLVMRunPassManager(module_pass_manager, mod); + + + + char *llvm_error = nullptr; defer (LLVMDisposeMessage(llvm_error)); @@ -9958,7 +9961,7 @@ void lb_generate_code(lbGenerator *gen) { LLVMDIBuilderFinalize(m->debug_builder); LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); llvm_error = nullptr; - LLVMBool failure = LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error); + // LLVMBool failure = LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error); LLVMInitializeAllTargetInfos(); LLVMInitializeAllTargets(); -- cgit v1.2.3 From 8d2ad0da0e81f8f7a6c7f67f48992f404dc41566 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 5 Mar 2020 22:01:07 +0000 Subject: Fill in more of the llvm_backend code generation --- examples/llvm-demo/demo.odin | 50 +--- src/ir.cpp | 1 - src/llvm_backend.cpp | 588 +++++++++++++++++++++++++++++++++---------- src/llvm_backend.hpp | 17 ++ 4 files changed, 471 insertions(+), 185 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/examples/llvm-demo/demo.odin b/examples/llvm-demo/demo.odin index 874302d02..03ea5fbb4 100644 --- a/examples/llvm-demo/demo.odin +++ b/examples/llvm-demo/demo.odin @@ -1,55 +1,7 @@ package demo -import "core:os" import "core:fmt" main :: proc() { - fmt.fprintln(os.stdout, "Hellope!", 123, true, 1.3); -} - - // BarBar :: struct {x, y: int}; - - // foo :: proc(x: int) {} - - // Foo :: enum {A=1, B, C, D}; - // Foo_Set :: bit_set[Foo]; - // foo_set := Foo_Set{.A, .C}; - - // array := [4]int{3 = 1, 0 .. 1 = 3, 2 = 9}; - // slice := []int{1, 2, 3, 4}; - - // x: ^int = nil; - // y := slice != nil; - - // @thread_local a: int; - - // if true { - // foo(1); - // } - - // { - // x := i32(1); - // y := i32(2); - // z := x + y; - // w := z - 2; - // } - - // f := foo; - - // c := 1 + 2i; - // q := 1 + 2i + 3j + 4k; - - // s := "Hellope"; - - // b := true; - // aaa := b ? int(123) : int(34); - // defer aaa = 333; - - // bb := BarBar{1, 2}; - // pc: proc "contextless" (x: i32) -> BarBar; - // po: proc "odin" (x: i32) -> BarBar; - // e: enum{A, B, C}; - // u: union{i32, bool}; - // u1: union{i32}; - // um: union #maybe {^int}; + fmt.println("Hellope!", 123, true, 1.3); } diff --git a/src/ir.cpp b/src/ir.cpp index 5528ccee8..c5b140991 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -3762,7 +3762,6 @@ irValue *ir_addr_load(irProcedure *proc, irAddr const &addr) { } if (addr.kind == irAddr_Map) { - // TODO(bill): map lookup Type *map_type = base_type(addr.map_type); irValue *v = ir_add_local_generated(proc, map_type->Map.lookup_result_type, true); irValue *h = ir_gen_map_header(proc, addr.addr, map_type); diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index cce2d594b..165d63be7 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -46,6 +46,32 @@ lbAddr lb_addr(lbValue addr) { return v; } + +lbAddr lb_addr_map(lbValue addr, lbValue map_key, Type *map_type, Type *map_result) { + lbAddr v = {lbAddr_Map, addr}; + v.map.key = map_key; + v.map.type = map_type; + v.map.result = map_result; + return v; +} + + +lbAddr lb_addr_soa_variable(lbValue addr, lbValue index, Ast *index_expr) { + lbAddr v = {lbAddr_SoaVariable, addr}; + v.soa.index = index; + v.soa.index_expr = index_expr; + return v; +} + +lbAddr lb_addr_bit_field(lbValue value, i32 index) { + lbAddr addr = {}; + addr.kind = lbAddr_BitField; + addr.addr = value; + addr.bit_field.value_index = index; + return addr; +} + + Type *lb_addr_type(lbAddr const &addr) { if (addr.addr.value == nullptr) { return nullptr; @@ -87,13 +113,6 @@ lbValue lb_build_addr_ptr(lbProcedure *p, Ast *expr) { return lb_addr_get_ptr(p, addr); } -lbAddr lb_addr_bit_field(lbValue value, i32 index) { - lbAddr addr = {}; - addr.kind = lbAddr_BitField; - addr.addr = value; - addr.bit_field.value_index = index; - return addr; -} void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value) { @@ -113,9 +132,26 @@ void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value) { if (addr.kind == lbAddr_Map) { - GB_PANIC("lbAddr_Map"); + lb_insert_dynamic_map_key_and_value(p, addr, addr.map.type, addr.map.key, value); + return; } else if (addr.kind == lbAddr_BitField) { - GB_PANIC("lbAddr_BitField"); + Type *bft = base_type(type_deref(addr.addr.type)); + GB_ASSERT(is_type_bit_field(bft)); + + unsigned value_index = cast(unsigned)addr.bit_field.value_index; + i32 size_in_bits = bft->BitField.fields[value_index]->type->BitFieldValue.bits; + if (size_in_bits == 0) { + return; + } + i32 size_in_bytes = next_pow2((size_in_bits+7)/8); + + LLVMTypeRef dst_type = LLVMIntTypeInContext(p->module->ctx, size_in_bits); + LLVMValueRef src = LLVMBuildIntCast2(p->builder, value.value, dst_type, false, ""); + + LLVMValueRef internal_data = LLVMBuildStructGEP(p->builder, addr.addr.value, 1, ""); + LLVMValueRef field_ptr = LLVMBuildStructGEP(p->builder, internal_data, value_index, ""); + LLVMBuildStore(p->builder, src, field_ptr); + return; } else if (addr.kind == lbAddr_Context) { lbValue old = lb_addr_load(p, lb_find_or_generate_context_ptr(p)); lbAddr next_addr = lb_add_local_generated(p, t_context, true); @@ -135,7 +171,27 @@ void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value) { return; } else if (addr.kind == lbAddr_SoaVariable) { - GB_PANIC("lbAddr_SoaVariable"); + Type *t = type_deref(addr.addr.type); + t = base_type(t); + GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None); + value = lb_emit_conv(p, value, t->Struct.soa_elem); + + lbValue index = addr.soa.index; + if (!lb_is_const(index) || t->Struct.soa_kind != StructSoa_Fixed) { + Type *t = base_type(type_deref(addr.addr.type)); + GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None); + i64 count = t->Struct.soa_count; + lbValue len = lb_const_int(p->module, t_int, count); + // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), index, len); + } + + for_array(i, t->Struct.fields) { + lbValue dst = lb_emit_struct_ep(p, addr.addr, cast(i32)i); + dst = lb_emit_array_ep(p, dst, index); + lbValue src = lb_emit_struct_ev(p, value, cast(i32)i); + lb_emit_store(p, dst, src); + } + return; } GB_ASSERT(value.value != nullptr); @@ -174,7 +230,40 @@ lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) { GB_ASSERT(addr.addr.value != nullptr); if (addr.kind == lbAddr_Map) { - GB_PANIC("lbAddr_Map"); + Type *map_type = base_type(addr.map.type); + lbAddr v = lb_add_local_generated(p, map_type->Map.lookup_result_type, true); + lbValue h = lb_gen_map_header(p, addr.addr, map_type); + lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key); + + auto args = array_make(heap_allocator(), 2); + args[0] = h; + args[1] = key; + + lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args); + lbValue ok = lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool); + lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), ok); + + lbBlock *then = lb_create_block(p, "map.get.then"); + lbBlock *done = lb_create_block(p, "map.get.done"); + lb_emit_if(p, ok, then, done); + lb_start_block(p, then); + { + // TODO(bill): mem copy it instead? + lbValue gep0 = lb_emit_struct_ep(p, v.addr, 0); + lbValue value = lb_emit_conv(p, ptr, gep0.type); + lb_emit_store(p, gep0, lb_emit_load(p, value)); + } + lb_emit_jump(p, done); + lb_start_block(p, done); + + + if (is_type_tuple(addr.map.result)) { + return lb_addr_load(p, v); + } else { + lbValue single = lb_emit_struct_ep(p, v.addr, 0); + return lb_emit_load(p, single); + } + } else if (addr.kind == lbAddr_BitField) { Type *bft = base_type(type_deref(addr.addr.type)); GB_ASSERT(is_type_bit_field(bft)); @@ -216,7 +305,60 @@ lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) { return lb_emit_load(p, b); } } else if (addr.kind == lbAddr_SoaVariable) { - GB_PANIC("lbAddr_SoaVariable"); + Type *t = type_deref(addr.addr.type); + t = base_type(t); + GB_ASSERT(t->kind == Type_Struct && t->Struct.soa_kind != StructSoa_None); + Type *elem = t->Struct.soa_elem; + + lbValue len = {}; + if (t->Struct.soa_kind == StructSoa_Fixed) { + len = lb_const_int(p->module, t_int, t->Struct.soa_count); + } else { + lbValue v = lb_emit_load(p, addr.addr); + len = lb_soa_struct_len(p, v); + } + + lbAddr res = lb_add_local_generated(p, elem, true); + + if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) { + // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len); + } + + if (t->Struct.soa_kind == StructSoa_Fixed) { + for_array(i, t->Struct.fields) { + Entity *field = t->Struct.fields[i]; + Type *base_type = field->type; + GB_ASSERT(base_type->kind == Type_Array); + + lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i); + lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i); + src_ptr = lb_emit_array_ep(p, src_ptr, addr.soa.index); + lbValue src = lb_emit_load(p, src_ptr); + lb_emit_store(p, dst, src); + } + } else { + isize field_count = t->Struct.fields.count; + if (t->Struct.soa_kind == StructSoa_Slice) { + field_count -= 1; + } else if (t->Struct.soa_kind == StructSoa_Dynamic) { + field_count -= 3; + } + for (isize i = 0; i < field_count; i++) { + Entity *field = t->Struct.fields[i]; + Type *base_type = field->type; + GB_ASSERT(base_type->kind == Type_Pointer); + Type *elem = base_type->Pointer.elem; + + lbValue dst = lb_emit_struct_ep(p, res.addr, cast(i32)i); + lbValue src_ptr = lb_emit_struct_ep(p, addr.addr, cast(i32)i); + src_ptr = lb_emit_ptr_offset(p, src_ptr, addr.soa.index); + lbValue src = lb_emit_load(p, src_ptr); + src = lb_emit_load(p, src); + lb_emit_store(p, dst, src); + } + } + + return lb_addr_load(p, res); } if (is_type_proc(addr.addr.type)) { @@ -1951,7 +2093,7 @@ void lb_build_range_string(lbProcedure *p, lbValue expr, Type *val_type, lbValue str_elem = lb_emit_ptr_offset(p, lb_string_elem(p, expr), offset); lbValue str_len = lb_emit_arith(p, Token_Sub, count, offset, t_int); - auto args = array_make(heap_allocator(), 1); + auto args = array_make(heap_allocator(), 1); args[0] = lb_emit_string(p, str_elem, str_len); lbValue rune_and_len = lb_emit_runtime_call(p, "string_decode_rune", args); lbValue len = lb_emit_struct_ev(p, rune_and_len, 1); @@ -2938,14 +3080,12 @@ void lb_build_stmt(lbProcedure *p, Ast *node) { i32 op = cast(i32)as->op.kind; op += Token_Add - Token_AddEq; // Convert += to + if (op == Token_CmpAnd || op == Token_CmpOr) { - // TODO(bill): assign op Type *type = as->lhs[0]->tav.type; lbValue new_value = lb_emit_logical_binary_expr(p, cast(TokenKind)op, as->lhs[0], as->rhs[0], type); lbAddr lhs = lb_build_addr(p, as->lhs[0]); lb_addr_store(p, lhs, new_value); } else { - // TODO(bill): Assign op lbAddr lhs = lb_build_addr(p, as->lhs[0]); lbValue value = lb_build_expr(p, as->rhs[0]); @@ -3974,6 +4114,19 @@ lbValue lb_emit_source_code_location(lbProcedure *p, String const &procedure, To return res; } +lbValue lb_emit_source_code_location(lbProcedure *p, Ast *node) { + String proc_name = {}; + if (p->entity) { + proc_name = p->entity->token.string; + } + TokenPos pos = {}; + if (node) { + pos = ast_token(node).pos; + } + return lb_emit_source_code_location(p, proc_name, pos); +} + + lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) { switch (op) { case Token_Add: @@ -4388,9 +4541,9 @@ lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { // lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args); // if (be->op.kind == Token_in) { - // return ir_emit_conv(p, ir_emit_comp(p, Token_NotEq, ptr, v_raw_nil), t_bool); + // return lb_emit_conv(p, ir_emit_comp(p, Token_NotEq, ptr, v_raw_nil), t_bool); // } else { - // return ir_emit_conv(p, ir_emit_comp(p, Token_CmpEq, ptr, v_raw_nil), t_bool); + // return lb_emit_conv(p, ir_emit_comp(p, Token_CmpEq, ptr, v_raw_nil), t_bool); // } } break; @@ -5367,9 +5520,6 @@ void lb_emit_defer_stmts(lbProcedure *p, lbDeferExitKind kind, lbBlock *block) { isize i = count; while (i --> 0) { lbDefer d = p->defer_stmts[i]; - if (p->context_stack.count >= d.context_stack_count) { - p->context_stack.count = d.context_stack_count; - } if (kind == lbDeferExit_Default) { if (p->scope_index == d.scope_index && @@ -5402,7 +5552,7 @@ lbDefer lb_add_defer_node(lbProcedure *p, isize scope_index, Ast *stmt) { return d; } -lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array const &result_as_args) { +lbDefer lb_add_defer_proc(lbProcedure *p, isize scope_index, lbValue deferred, Array const &result_as_args) { lbDefer d = {lbDefer_Proc}; d.scope_index = p->scope_index; d.block = p->curr_block; @@ -6648,6 +6798,25 @@ bool lb_is_const_nil(lbValue value) { return false; } +String lb_get_const_string(lbModule *m, lbValue value) { + GB_ASSERT(lb_is_const(value)); + + Type *t = base_type(value.type); + GB_ASSERT(are_types_identical(t, t_string)); + + unsigned ptr_indices[2] = {0, 0}; + unsigned len_indices[2] = {0, 1}; + LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices)); + LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices)); + + size_t length = 0; + char const *text = LLVMGetAsString(underlying_ptr, &length); + isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len); + + return make_string(cast(u8 const *)text, real_length); +} + + void lb_emit_increment(lbProcedure *p, lbValue addr) { GB_ASSERT(is_type_pointer(addr.type)); Type *type = type_deref(addr.type); @@ -7475,6 +7644,58 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { return res; case_end; + case_ast_node(te, TernaryIfExpr, expr); + LLVMValueRef incoming_values[2] = {}; + LLVMBasicBlockRef incoming_blocks[2] = {}; + + GB_ASSERT(te->y != nullptr); + lbBlock *then = lb_create_block(p, "if.then"); + lbBlock *done = lb_create_block(p, "if.done"); // NOTE(bill): Append later + lbBlock *else_ = lb_create_block(p, "if.else"); + + lbValue cond = lb_build_cond(p, te->cond, then, else_); + lb_start_block(p, then); + + Type *type = type_of_expr(expr); + + lb_open_scope(p); + incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value; + lb_close_scope(p, lbDeferExit_Default, nullptr); + + lb_emit_jump(p, done); + lb_start_block(p, else_); + + lb_open_scope(p); + incoming_values[1] = lb_emit_conv(p, lb_build_expr(p, te->y), type).value; + lb_close_scope(p, lbDeferExit_Default, nullptr); + + lb_emit_jump(p, done); + lb_start_block(p, done); + + lbValue res = {}; + res.value = LLVMBuildPhi(p->builder, lb_type(p->module, type), ""); + res.type = type; + + GB_ASSERT(p->curr_block->preds.count >= 2); + incoming_blocks[0] = p->curr_block->preds[0]->block; + incoming_blocks[1] = p->curr_block->preds[1]->block; + + LLVMAddIncoming(res.value, incoming_values, incoming_blocks, 2); + + return res; + 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 lb_build_expr(p, te->x); + } else { + return lb_build_expr(p, te->y); + } + case_end; + case_ast_node(ta, TypeAssertion, expr); TokenPos pos = ast_token(expr).pos; Type *type = tv.type; @@ -7508,70 +7729,70 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { switch (ue->op.kind) { case Token_And: { Ast *ue_expr = unparen_expr(ue->expr); - // if (ue_expr->kind == Ast_TypeAssertion) { - // gbAllocator a = heap_allocator(); - // GB_ASSERT(is_type_pointer(tv.type)); - - // ast_node(ta, TypeAssertion, ue_expr); - // TokenPos pos = ast_token(expr).pos; - // Type *type = type_of_expr(ue_expr); - // GB_ASSERT(!is_type_tuple(type)); - - // lbValue e = lb_build_expr(p, ta->expr); - // Type *t = type_deref(e.type); - // if (is_type_union(t)) { - // lbValue v = e; - // if (!is_type_pointer(v.type)) { - // v = lb_address_from_load_or_generate_local(p, v); - // } - // Type *src_type = type_deref(v.type); - // Type *dst_type = type; - - // lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v)); - // lbValue dst_tag = lb_const_union_tag(src_type, dst_type); - - // lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag); - // auto args = array_make(heap_allocator(), 6); - // args[0] = ok; - - // args[1] = lb_find_or_add_entity_string(p->module, pos.file); - // args[2] = lb_const_int(pos.line); - // args[3] = lb_const_int(pos.column); - - // args[4] = lb_typeid(p->module, src_type); - // args[5] = lb_typeid(p->module, dst_type); - // lb_emit_runtime_call(p, "type_assertion_check", args); - - // lbValue data_ptr = v; - // return lb_emit_conv(p, data_ptr, tv.type); - // } else if (is_type_any(t)) { - // lbValue v = e; - // if (is_type_pointer(ir_type(v))) { - // v = lb_emit_load(p, v); - // } - - // lbValue data_ptr = lb_emit_struct_ev(p, v, 0); - // lbValue any_id = lb_emit_struct_ev(p, v, 1); - // lbValue id = lb_typeid(p->module, type); - - - // lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id); - // auto args = array_make(heap_allocator(), 6); - // args[0] = ok; - - // args[1] = lb_find_or_add_entity_string(p->module, pos.file); - // args[2] = lb_const_int(pos.line); - // args[3] = lb_const_int(pos.column); - - // args[4] = any_id; - // args[5] = id; - // lb_emit_runtime_call(p, "type_assertion_check", args); - - // return lb_emit_conv(p, data_ptr, tv.type); - // } else { - // GB_PANIC("TODO(bill): type assertion %s", type_to_string(type)); - // } - // } + if (ue_expr->kind == Ast_TypeAssertion) { + gbAllocator a = heap_allocator(); + GB_ASSERT(is_type_pointer(tv.type)); + + ast_node(ta, TypeAssertion, ue_expr); + TokenPos pos = ast_token(expr).pos; + Type *type = type_of_expr(ue_expr); + GB_ASSERT(!is_type_tuple(type)); + + lbValue e = lb_build_expr(p, ta->expr); + Type *t = type_deref(e.type); + if (is_type_union(t)) { + lbValue v = e; + if (!is_type_pointer(v.type)) { + v = lb_address_from_load_or_generate_local(p, v); + } + Type *src_type = type_deref(v.type); + Type *dst_type = type; + + lbValue src_tag = lb_emit_load(p, lb_emit_union_tag_ptr(p, v)); + lbValue dst_tag = lb_const_union_tag(p->module, src_type, dst_type); + + lbValue ok = lb_emit_comp(p, Token_CmpEq, src_tag, dst_tag); + auto args = array_make(heap_allocator(), 6); + args[0] = ok; + + args[1] = lb_find_or_add_entity_string(p->module, pos.file); + args[2] = lb_const_int(p->module, t_int, pos.line); + args[3] = lb_const_int(p->module, t_int, pos.column); + + args[4] = lb_typeid(p->module, src_type); + args[5] = lb_typeid(p->module, dst_type); + lb_emit_runtime_call(p, "type_assertion_check", args); + + lbValue data_ptr = v; + return lb_emit_conv(p, data_ptr, tv.type); + } else if (is_type_any(t)) { + lbValue v = e; + if (is_type_pointer(v.type)) { + v = lb_emit_load(p, v); + } + + lbValue data_ptr = lb_emit_struct_ev(p, v, 0); + lbValue any_id = lb_emit_struct_ev(p, v, 1); + lbValue id = lb_typeid(p->module, type); + + + lbValue ok = lb_emit_comp(p, Token_CmpEq, any_id, id); + auto args = array_make(heap_allocator(), 6); + args[0] = ok; + + args[1] = lb_find_or_add_entity_string(p->module, pos.file); + args[2] = lb_const_int(p->module, t_int, pos.line); + args[3] = lb_const_int(p->module, t_int, pos.column); + + args[4] = any_id; + args[5] = id; + lb_emit_runtime_call(p, "type_assertion_check", args); + + return lb_emit_conv(p, data_ptr, tv.type); + } else { + GB_PANIC("TODO(bill): type assertion %s", type_to_string(type)); + } + } return lb_build_addr_ptr(p, ue->expr); } @@ -7662,6 +7883,103 @@ lbAddr lb_build_addr_from_entity(lbProcedure *p, Entity *e, Ast *expr) { return lb_addr(v); } +lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) { + GB_ASSERT_MSG(is_type_pointer(map_val_ptr.type), "%s", type_to_string(map_val_ptr.type)); + gbAllocator a = heap_allocator(); + lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later + map_type = base_type(map_type); + + Type *key_type = map_type->Map.key; + Type *val_type = map_type->Map.value; + + // NOTE(bill): Removes unnecessary allocation if split gep + lbValue gep0 = lb_emit_struct_ep(p, h.addr, 0); + lbValue m = lb_emit_conv(p, map_val_ptr, type_deref(gep0.type)); + lb_emit_store(p, gep0, m); + + lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 1), lb_const_bool(p->module, t_bool, is_type_string(key_type))); + + i64 entry_size = type_size_of (map_type->Map.entry_type); + i64 entry_align = type_align_of (map_type->Map.entry_type); + i64 value_offset = type_offset_of(map_type->Map.entry_type, 2); + i64 value_size = type_size_of (map_type->Map.value); + + lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 2), lb_const_int(p->module, t_int, entry_size)); + lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 3), lb_const_int(p->module, t_int, entry_align)); + lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 4), lb_const_int(p->module, t_uintptr, value_offset)); + lb_emit_store(p, lb_emit_struct_ep(p, h.addr, 5), lb_const_int(p->module, t_int, value_size)); + + return lb_addr_load(p, h); +} + +lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) { + Type *hash_type = t_u64; + lbAddr v = lb_add_local_generated(p, t_map_key, true); + Type *t = base_type(key.type); + key = lb_emit_conv(p, key, key_type); + if (is_type_integer(t)) { + lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, key, hash_type)); + } else if (is_type_enum(t)) { + lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, key, hash_type)); + } else if (is_type_typeid(t)) { + lbValue i = lb_emit_transmute(p, key, t_uint); + lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, i, hash_type)); + } else if (is_type_pointer(t)) { + lbValue ptr = lb_emit_conv(p, key, t_uintptr); + lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, ptr, hash_type)); + } else if (is_type_float(t)) { + lbValue bits = {}; + i64 size = type_size_of(t); + switch (8*size) { + case 32: bits = lb_emit_transmute(p, key, t_u32); break; + case 64: bits = lb_emit_transmute(p, key, t_u64); break; + default: GB_PANIC("Unhandled float size: %lld bits", size); break; + } + + lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), lb_emit_conv(p, bits, hash_type)); + } else if (is_type_string(t)) { + lbValue str = lb_emit_conv(p, key, t_string); + lbValue hashed_str = {}; + + if (lb_is_const(str)) { + + String value = lb_get_const_string(p->module, str); + u64 hs = fnv64a(value.text, value.len); + hashed_str = lb_const_value(p->module, t_u64, exact_value_u64(hs)); + } else { + auto args = array_make(heap_allocator(), 1); + args[0] = str; + hashed_str = lb_emit_runtime_call(p, "default_hash_string", args); + } + lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 0), hashed_str); + lb_emit_store(p, lb_emit_struct_ep(p, v.addr, 1), str); + } else { + GB_PANIC("Unhandled map key type"); + } + + return lb_addr_load(p, v); +} + +lbValue lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, + lbValue map_key, lbValue map_value) { + map_type = base_type(map_type); + + lbValue h = lb_gen_map_header(p, addr.addr, map_type); + lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key); + lbValue v = lb_emit_conv(p, map_value, map_type->Map.value); + + lbAddr ptr = lb_add_local_generated(p, v.type, false); + lb_addr_store(p, ptr, v); + + auto args = array_make(heap_allocator(), 4); + args[0] = h; + args[1] = key; + args[2] = lb_emit_conv(p, ptr.addr, t_rawptr); + args[3] = lb_emit_source_code_location(p, nullptr); + return lb_emit_runtime_call(p, "__dynamic_map_set", args); +} + + lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { expr = unparen_expr(expr); @@ -7773,10 +8091,10 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT(is_type_soa_struct(t)); // TODO(bill): Bounds check - // if (addr.soa.index->kind != irValue_Constant || t->Struct.soa_kind != StructSoa_Fixed) { - // lbValue len = ir_soa_struct_len(p, addr.addr); - // ir_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len); - // } + if (!lb_is_const(addr.soa.index) || t->Struct.soa_kind != StructSoa_Fixed) { + lbValue len = lb_soa_struct_len(p, addr.addr); + // lb_emit_bounds_check(p, ast_token(addr.soa.index_expr), addr.soa.index, len); + } lbValue item = {}; @@ -7844,13 +8162,13 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (is_type_soa_struct(t)) { // SOA STRUCTURES!!!! GB_PANIC("SOA STRUCTURES!!!!"); - // lbValue val = lb_build_addr_ptr(p, ie->expr); - // if (deref) { - // val = lb_emit_load(p, val); - // } + lbValue val = lb_build_addr_ptr(p, ie->expr); + if (deref) { + val = lb_emit_load(p, val); + } - // lbValue index = lb_build_expr(p, ie->index); - // return lb_addr_soa_variable(val, index, ie->index); + lbValue index = lb_build_expr(p, ie->index); + return lb_addr_soa_variable(val, index, ie->index); } if (ie->expr->tav.mode == Addressing_SoaVariable) { @@ -7862,7 +8180,6 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (!build_context.no_bounds_check) { - GB_PANIC("HERE"); // // TODO HACK(bill): Clean up this hack to get the length for bounds checking // GB_ASSERT(LLVMIsALoadInst(field.value)); @@ -7886,17 +8203,16 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { GB_ASSERT_MSG(is_type_indexable(t), "%s %s", type_to_string(t), expr_to_string(expr)); if (is_type_map(t)) { - GB_PANIC("map index"); - // lbValue map_val = lb_build_addr_ptr(p, ie->expr); - // if (deref) { - // map_val = lb_emit_load(p, map_val); - // } + lbValue map_val = lb_build_addr_ptr(p, ie->expr); + if (deref) { + map_val = lb_emit_load(p, map_val); + } - // lbValue key = lb_build_expr(p, ie->index); - // key = lb_emit_conv(p, key, t->Map.key); + lbValue key = lb_build_expr(p, ie->index); + key = lb_emit_conv(p, key, t->Map.key); - // Type *result_type = type_of_expr(expr); - // return lb_addr_map(map_val, key, t, result_type); + Type *result_type = type_of_expr(expr); + return lb_addr_map(map_val, key, t, result_type); } lbValue using_addr = {}; @@ -8189,7 +8505,6 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { case_end; case_ast_node(de, DerefExpr, expr); - // TODO(bill): Is a ptr copy needed? lbValue addr = lb_build_expr(p, de->expr); return lb_addr(addr); case_end; @@ -8287,23 +8602,22 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (cl->elems.count == 0) { break; } - // TODO(bill): Map CompoundLit - // gbAllocator a = heap_allocator(); - // { - // auto args = array_make(a, 3); - // args[0] = ir_gen_map_header(p, v, type); - // args[1] = ir_const_int(2*cl->elems.count); - // args[2] = ir_emit_source_code_location(p, proc_name, pos); - // lb_emit_runtime_call(p, "__dynamic_map_reserve", args); - // } - // for_array(field_index, cl->elems) { - // Ast *elem = cl->elems[field_index]; - // ast_node(fv, FieldValue, elem); + gbAllocator a = heap_allocator(); + { + auto args = array_make(a, 3); + args[0] = lb_gen_map_header(p, v.addr, type); + args[1] = lb_const_int(p->module, t_int, 2*cl->elems.count); + args[2] = lb_emit_source_code_location(p, proc_name, pos); + lb_emit_runtime_call(p, "__dynamic_map_reserve", args); + } + for_array(field_index, cl->elems) { + Ast *elem = cl->elems[field_index]; + ast_node(fv, FieldValue, elem); - // lbValue key = lb_build_expr(p, fv->field); - // lbValue value = lb_build_expr(p, fv->value); - // ir_insert_dynamic_map_key_and_value(p, v, type, key, value); - // } + lbValue key = lb_build_expr(p, fv->field); + lbValue value = lb_build_expr(p, fv->value); + lb_insert_dynamic_map_key_and_value(p, v, type, key, value); + } break; } @@ -8593,8 +8907,15 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lb_emit_store(p, temp_data[i].gep, temp_data[i].value); } - // lbValue count = lb_const_int(p->module, t_int, slice->ConstantSlice.count); - // ir_fill_slice(p, v, data, count); + { + GB_ASSERT(lb_is_const(slice)); + unsigned indices[1] = {1}; + + lbValue count = {}; + count.type = t_int; + count.value = LLVMConstExtractValue(slice.value, indices, gb_count_of(indices)); + lb_fill_slice(p, v, data, count); + } } break; } @@ -8603,8 +8924,6 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (cl->elems.count == 0) { break; } - // TODO(bill): Type_DynamicArray - #if 0 Type *et = bt->DynamicArray.elem; gbAllocator a = heap_allocator(); lbValue size = lb_const_int(p->module, t_int, type_size_of(et)); @@ -8645,7 +8964,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue value = lb_emit_conv(p, lb_build_expr(p, fv->value), et); for (i64 k = lo; k < hi; k++) { - lbValue ep = ir_emit_array_epi(p, items, cast(i32)k); + lbValue ep = lb_emit_array_epi(p, items, cast(i32)k); lb_emit_store(p, ep, value); } } else { @@ -8655,27 +8974,26 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { lbValue ev = lb_build_expr(p, fv->value); lbValue value = lb_emit_conv(p, ev, et); - lbValue ep = ir_emit_array_epi(p, items, cast(i32)field_index); + lbValue ep = lb_emit_array_epi(p, items, cast(i32)field_index); lb_emit_store(p, ep, value); } } else { lbValue value = lb_emit_conv(p, lb_build_expr(p, elem), et); - lbValue ep = ir_emit_array_epi(p, items, cast(i32)i); + lbValue ep = lb_emit_array_epi(p, items, cast(i32)i); lb_emit_store(p, ep, value); } } { auto args = array_make(a, 6); - args[0] = lb_emit_conv(p, v, t_rawptr); + args[0] = lb_emit_conv(p, v.addr, t_rawptr); args[1] = size; args[2] = align; args[3] = lb_emit_conv(p, items, t_rawptr); - args[4] = ir_const_int(item_count); - args[5] = ir_emit_source_code_location(p, proc_name, pos); + args[4] = lb_const_int(p->module, t_int, item_count); + args[5] = lb_emit_source_code_location(p, proc_name, pos); lb_emit_runtime_call(p, "__dynamic_array_append", args); } - #endif break; } @@ -9842,8 +10160,6 @@ void lb_generate_code(lbGenerator *gen) { lb_begin_procedure_body(p); - lb_emit_init_context(p, {}); - lb_setup_type_info_data(p); for_array(i, global_variables) { @@ -9884,6 +10200,8 @@ void lb_generate_code(lbGenerator *gen) { } } + lb_emit_init_context(p, {}); + lb_end_procedure_body(p); if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 01da51529..0f28e664a 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -260,6 +260,11 @@ lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t); lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue right); lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, ProcInlining inlining = ProcInlining_none, bool use_return_ptr_hint = false); lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t); +lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x); + +void lb_emit_jump(lbProcedure *p, lbBlock *target_block); +void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *false_block); +void lb_start_block(lbProcedure *p, lbBlock *b); lbValue lb_build_call_expr(lbProcedure *p, Ast *expr); @@ -303,6 +308,18 @@ void lb_emit_increment(lbProcedure *p, lbValue addr); lbValue lb_type_info(lbModule *m, Type *type); +lbValue lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, lbValue map_key, lbValue map_value); + + +bool lb_is_const(lbValue value); +bool lb_is_const_nil(lbValue value); +String lb_get_const_string(lbModule *m, lbValue value); + +lbValue lb_generate_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id); +lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type); +lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type); +lbValue lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, lbValue map_key, lbValue map_value); + #define LB_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime" #define LB_TYPE_INFO_DATA_NAME "__$type_info_data" -- cgit v1.2.3 From f92334a769876bb3f455c07e3285ee70a16239e4 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sat, 7 Mar 2020 10:38:14 +0000 Subject: Basic functionality, except for `map` and correct nested typename mangling --- build.bat | 3 +- examples/demo/demo.odin | 15 +- src/llvm_backend.cpp | 518 ++++++++++++++++++++++++++++++++--------------- src/llvm_backend.hpp | 6 +- src/main.cpp | 528 ++++++++++++++++++++++++------------------------ 5 files changed, 630 insertions(+), 440 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/build.bat b/build.bat index 67892a9c3..4f3f665f2 100644 --- a/build.bat +++ b/build.bat @@ -49,7 +49,8 @@ del *.ilk > NUL 2> NUL cl %compiler_settings% "src\main.cpp" ^ /link %linker_settings% -OUT:%exe_name% ^ - && odin build examples/llvm-demo/demo.odin -llvm-api -show-timings + && odin build examples/demo/demo.odin -llvm-api -show-timings + rem && odin build examples/llvm-demo/demo.odin -llvm-api -show-timings if %errorlevel% neq 0 ( goto end_of_build ) diff --git a/examples/demo/demo.odin b/examples/demo/demo.odin index 9704d3e36..601f1b27a 100644 --- a/examples/demo/demo.odin +++ b/examples/demo/demo.odin @@ -1245,7 +1245,7 @@ implicit_selector_expression :: proc() { switch f { case .A: - fmt.println("HERE"); + fmt.println("HITHER"); case .B: fmt.println("NEVER"); case .C: @@ -1742,6 +1742,7 @@ range_statements_with_multiple_return_values :: proc() { } } + soa_struct_layout :: proc() { // IMPORTANT NOTE(bill, 2019-11-03): This feature is subject to be changed/removed // NOTE(bill): Most likely #soa [N]T @@ -1933,22 +1934,22 @@ union_maybe :: proc() { main :: proc() { when true { the_basics(); - control_flow(); + // control_flow(); named_proc_return_parameters(); explicit_procedure_overloading(); struct_type(); union_type(); using_statement(); - implicit_context_system(); + // implicit_context_system(); parametric_polymorphism(); array_programming(); - map_type(); - implicit_selector_expression(); + // map_type(); + // implicit_selector_expression(); partial_switch(); cstring_example(); bit_set_type(); deferred_procedure_associations(); - reflection(); + // reflection(); quaternions(); inline_for_statement(); where_clauses(); @@ -1957,7 +1958,7 @@ main :: proc() { deprecated_attribute(); range_statements_with_multiple_return_values(); threading_example(); - soa_struct_layout(); + // soa_struct_layout(); constant_literal_expressions(); union_maybe(); } diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 165d63be7..4b16a2d3c 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -376,10 +376,17 @@ lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) { GB_ASSERT_MSG(is_type_pointer(t) && is_type_union(type_deref(t)), "%s", type_to_string(t)); Type *ut = type_deref(t); + + GB_ASSERT(!is_type_union_maybe_pointer_original_alignment(ut)); GB_ASSERT(!is_type_union_maybe_pointer(ut)); GB_ASSERT(type_size_of(ut) > 0); + Type *tag_type = union_tag_type(ut); + LLVMTypeRef uvt = LLVMGetElementType(LLVMTypeOf(u.value)); + unsigned element_count = LLVMCountStructElementTypes(uvt); + GB_ASSERT_MSG(element_count == 3, "(%s) != (%s)", type_to_string(ut), LLVMPrintTypeToString(uvt)); + lbValue tag_ptr = {}; tag_ptr.value = LLVMBuildStructGEP(p->builder, u.value, 2, ""); tag_ptr.type = alloc_type_pointer(tag_type); @@ -455,6 +462,13 @@ String lb_mangle_name(lbModule *m, Entity *e) { isize max_len = pkgn.len + 1 + name.len + 1; bool require_suffix_id = is_type_polymorphic(e->type, true); + + if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) { + require_suffix_id = true; + } else { + require_suffix_id = true; + } + if (require_suffix_id) { max_len += 21; } @@ -471,7 +485,7 @@ String lb_mangle_name(lbModule *m, Entity *e) { new_name_len += extra-1; } - return make_string((u8 *)new_name, new_name_len-1); + return make_string((u8 const *)new_name, new_name_len-1); } String lb_get_entity_name(lbModule *m, Entity *e, String default_name) { @@ -727,9 +741,15 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { if (found) { LLVMTypeKind kind = LLVMGetTypeKind(*found); if (kind == LLVMStructTypeKind) { - LLVMTypeRef llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name))); + char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name)); + LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name); + if (llvm_type != nullptr) { + return llvm_type; + } + llvm_type = LLVMStructCreateNamed(ctx, name); map_set(&m->types, hash_type(type), llvm_type); lb_clone_struct_type(llvm_type, *found); + return llvm_type; } } @@ -738,7 +758,12 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { case Type_Union: case Type_BitField: { - LLVMTypeRef llvm_type = LLVMStructCreateNamed(ctx, alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name))); + char const *name = alloc_cstring(heap_allocator(), lb_get_entity_name(m, type->Named.type_name)); + LLVMTypeRef llvm_type = LLVMGetTypeByName(m->mod, name); + if (llvm_type != nullptr) { + return llvm_type; + } + llvm_type = LLVMStructCreateNamed(ctx, name); map_set(&m->types, hash_type(type), llvm_type); lb_clone_struct_type(llvm_type, lb_type(m, base)); return llvm_type; @@ -1008,7 +1033,7 @@ LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) { LLVMContextRef ctx = LLVMGetModuleContext(p->module->mod); - LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, lb_create_enum_attribute(ctx, name, value)); + // LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, lb_create_enum_attribute(ctx, name, value)); } void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) { @@ -1633,7 +1658,7 @@ lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e, bool zero_init, i32 p char const *name = ""; if (e != nullptr) { - name = alloc_cstring(heap_allocator(), e->token.string); + // name = alloc_cstring(heap_allocator(), e->token.string); } LLVMTypeRef llvm_type = lb_type(p->module, type); @@ -1702,6 +1727,41 @@ void lb_build_nested_proc(lbProcedure *p, AstProcLit *pd, Entity *e) { array_add(&m->procedures_to_generate, nested_proc); } + +void lb_add_foreign_library_path(lbModule *m, Entity *e) { + if (e == nullptr) { + return; + } + GB_ASSERT(e->kind == Entity_LibraryName); + GB_ASSERT(e->flags & EntityFlag_Used); + + for_array(i, e->LibraryName.paths) { + String library_path = e->LibraryName.paths[i]; + if (library_path.len == 0) { + continue; + } + + bool ok = true; + for_array(path_index, m->foreign_library_paths) { + String path = m->foreign_library_paths[path_index]; + #if defined(GB_SYSTEM_WINDOWS) + if (str_eq_ignore_case(path, library_path)) { + #else + if (str_eq(path, library_path)) { + #endif + ok = false; + break; + } + } + + if (ok) { + array_add(&m->foreign_library_paths, library_path); + } + } +} + + + void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) { if (vd == nullptr || vd->is_mutable) { return; @@ -1709,104 +1769,109 @@ void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) { auto *min_dep_set = &p->module->info->minimum_dependency_set; + static i32 global_guid = 0; for_array(i, vd->names) { Ast *ident = vd->names[i]; GB_ASSERT(ident->kind == Ast_Ident); Entity *e = entity_of_ident(ident); GB_ASSERT(e != nullptr); - switch (e->kind) { - case Entity_TypeName: - case Entity_Procedure: - break; - default: + if (e->kind != Entity_TypeName) { continue; } - if (e->kind == Entity_TypeName) { - 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; - } + 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 (!polymorphic_struct && !ptr_set_exists(min_dep_set, e)) { + continue; + } - // NOTE(bill): Generate a new name - // parent_proc.name-guid - String ts_name = e->token.string; - - lbModule *m = p->module; - isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1; - char *name_text = gb_alloc_array(heap_allocator(), char, name_len); - i32 guid = cast(i32)m->members.entries.count; - name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%d", LIT(p->name), LIT(ts_name), guid); - - String name = make_string(cast(u8 *)name_text, name_len-1); - e->TypeName.ir_mangled_name = name; - - // lbValue value = ir_value_type_name(name, e->type); - // ir_add_entity_name(m, e, name); - // ir_gen_global_type_name(m, e, name); - } else if (e->kind == Entity_Procedure) { - CheckerInfo *info = p->module->info; - DeclInfo *decl = decl_info_of_entity(e); - ast_node(pl, ProcLit, decl->proc_lit); - if (pl->body != nullptr) { - auto *found = map_get(&info->gen_procs, hash_pointer(ident)); - if (found) { - auto procs = *found; - for_array(i, procs) { - Entity *e = procs[i]; - if (!ptr_set_exists(min_dep_set, e)) { - continue; - } - DeclInfo *d = decl_info_of_entity(e); - lb_build_nested_proc(p, &d->proc_lit->ProcLit, e); + // NOTE(bill): Generate a new name + // parent_proc.name-guid + String ts_name = e->token.string; + + lbModule *m = p->module; + isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1; + char *name_text = gb_alloc_array(heap_allocator(), char, name_len); + u32 guid = ++p->module->nested_type_name_guid; + name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid); + + String name = make_string(cast(u8 *)name_text, name_len-1); + e->TypeName.ir_mangled_name = name; + + // lbValue value = ir_value_type_name(name, e->type); + // ir_add_entity_name(m, e, name); + // ir_gen_global_type_name(m, e, name); + } + + for_array(i, vd->names) { + Ast *ident = vd->names[i]; + GB_ASSERT(ident->kind == Ast_Ident); + Entity *e = entity_of_ident(ident); + GB_ASSERT(e != nullptr); + if (e->kind != Entity_Procedure) { + continue; + } + + CheckerInfo *info = p->module->info; + DeclInfo *decl = decl_info_of_entity(e); + ast_node(pl, ProcLit, decl->proc_lit); + if (pl->body != nullptr) { + auto *found = map_get(&info->gen_procs, hash_pointer(ident)); + if (found) { + auto procs = *found; + for_array(i, procs) { + Entity *e = procs[i]; + if (!ptr_set_exists(min_dep_set, e)) { + continue; } - } else { - lb_build_nested_proc(p, pl, e); + DeclInfo *d = decl_info_of_entity(e); + lb_build_nested_proc(p, &d->proc_lit->ProcLit, e); } } else { + lb_build_nested_proc(p, pl, e); + } + } else { - // FFI - Foreign function interace - String original_name = e->token.string; - String name = original_name; + // FFI - Foreign function interace + String original_name = e->token.string; + String name = original_name; - if (e->Procedure.is_foreign) { - // lb_add_foreign_library_path(p->module, e->Procedure.foreign_library); - } + if (e->Procedure.is_foreign) { + lb_add_foreign_library_path(p->module, e->Procedure.foreign_library); + } - if (e->Procedure.link_name.len > 0) { - name = e->Procedure.link_name; - } + if (e->Procedure.link_name.len > 0) { + name = e->Procedure.link_name; + } - HashKey key = hash_string(name); - lbValue *prev_value = map_get(&p->module->members, key); - if (prev_value != nullptr) { - // NOTE(bill): Don't do mutliple declarations in the IR - return; - } + HashKey key = hash_string(name); + lbValue *prev_value = map_get(&p->module->members, key); + if (prev_value != nullptr) { + // NOTE(bill): Don't do mutliple declarations in the IR + return; + } - set_procedure_abi_types(heap_allocator(), e->type); - e->Procedure.link_name = name; + set_procedure_abi_types(heap_allocator(), e->type); + e->Procedure.link_name = name; - lbProcedure *nested_proc = lb_create_procedure(p->module, e); + lbProcedure *nested_proc = lb_create_procedure(p->module, e); - lbValue value = {}; - value.value = nested_proc->value; - value.type = nested_proc->type; + lbValue value = {}; + value.value = nested_proc->value; + value.type = nested_proc->type; - array_add(&p->module->procedures_to_generate, nested_proc); - if (p != nullptr) { - array_add(&p->children, nested_proc); - } else { - map_set(&p->module->members, hash_string(name), value); - } + array_add(&p->module->procedures_to_generate, nested_proc); + if (p != nullptr) { + array_add(&p->children, nested_proc); + } else { + map_set(&p->module->members, hash_string(name), value); } } } @@ -2710,13 +2775,14 @@ void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) { lbValue parent_ptr = parent; if (!is_parent_ptr) { - parent_ptr = lb_address_from_load_or_generate_local(p, parent_ptr); + parent_ptr = lb_address_from_load_or_generate_local(p, parent); } lbValue tag_index = {}; lbValue union_data = {}; if (switch_kind == TypeSwitch_Union) { - tag_index = lb_emit_load(p, lb_emit_union_tag_ptr(p, parent_ptr)); + lbValue tag_ptr = lb_emit_union_tag_ptr(p, parent_ptr); + tag_index = lb_emit_load(p, tag_ptr); union_data = lb_emit_conv(p, parent_ptr, t_rawptr); } @@ -3429,25 +3495,34 @@ lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue m lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) { HashKey key = hash_string(str); - lbValue *found = map_get(&m->const_strings, key); + LLVMValueRef *found = map_get(&m->const_strings, key); if (found != nullptr) { - return *found; + LLVMValueRef ptr = *found; + LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true); + LLVMValueRef values[2] = {ptr, str_len}; + + lbValue res = {}; + res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2); + res.type = t_string; + return res; } - lbValue v = lb_const_value(m, t_string, exact_value_string(str)); - map_set(&m->const_strings, key, v); - return v; + return lb_const_value(m, t_string, exact_value_string(str)); } lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) { HashKey key = hash_string(str); - lbValue *found = map_get(&m->const_string_byte_slices, key); + LLVMValueRef *found = map_get(&m->const_strings, key); if (found != nullptr) { - return *found; + LLVMValueRef ptr = *found; + LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true); + LLVMValueRef values[2] = {ptr, len}; + + lbValue res = {}; + res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2); + res.type = t_u8_slice; + return res; } - Type *t = t_u8_slice; - lbValue v = lb_const_value(m, t, exact_value_string(str)); - map_set(&m->const_string_byte_slices, key, v); - return v; + return lb_const_value(m, t_u8_slice, exact_value_string(str)); } isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) { @@ -3659,10 +3734,20 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { case ExactValue_String: { HashKey key = hash_string(value.value_string); - lbValue *found = map_get(&m->const_strings, key); + LLVMValueRef *found = map_get(&m->const_strings, key); if (found != nullptr) { - res.value = found->value; + LLVMValueRef ptr = *found; + lbValue res = {}; res.type = default_type(original_type); + if (is_type_cstring(res.type)) { + res.value = ptr; + } else { + LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true); + LLVMValueRef values[2] = {ptr, str_len}; + + res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); + } + return res; } @@ -3695,7 +3780,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); res.type = default_type(original_type); - map_set(&m->const_strings, key, res); + map_set(&m->const_strings, key, ptr); return res; } @@ -3703,7 +3788,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { case ExactValue_Integer: if (is_type_pointer(type)) { LLVMValueRef i = LLVMConstIntOfArbitraryPrecision(lb_type(m, t_uintptr), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); - res.value = LLVMConstBitCast(i, lb_type(m, original_type)); + res.value = LLVMConstIntToPtr(i, lb_type(m, original_type)); } else { res.value = LLVMConstIntOfArbitraryPrecision(lb_type(m, original_type), cast(unsigned)value.value_integer.len, big_int_ptr(&value.value_integer)); if (value.value_integer.neg) { @@ -3763,7 +3848,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { break; case ExactValue_Pointer: - res.value = LLVMConstBitCast(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type)); + res.value = LLVMConstIntToPtr(LLVMConstInt(lb_type(m, t_uintptr), value.value_pointer, false), lb_type(m, original_type)); return res; case ExactValue_Compound: @@ -4530,21 +4615,20 @@ lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { switch (rt->kind) { case Type_Map: { - GB_PANIC("map in/not_in"); - // lbValue addr = lb_address_from_load_or_generate_local(p, right); - // lbValue h = lb_gen_map_header(p, addr, rt); - // lbValue key = ir_gen_map_key(p, left, rt->Map.key); - - // auto args = array_make(heap_allocator(), 2); - // args[0] = h; - // args[1] = key; - - // lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args); - // if (be->op.kind == Token_in) { - // return lb_emit_conv(p, ir_emit_comp(p, Token_NotEq, ptr, v_raw_nil), t_bool); - // } else { - // return lb_emit_conv(p, ir_emit_comp(p, Token_CmpEq, ptr, v_raw_nil), t_bool); - // } + lbValue addr = lb_address_from_load_or_generate_local(p, right); + lbValue h = lb_gen_map_header(p, addr, rt); + lbValue key = lb_gen_map_key(p, left, rt->Map.key); + + auto args = array_make(heap_allocator(), 2); + args[0] = h; + args[1] = key; + + lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args); + if (be->op.kind == Token_in) { + return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_NotEq, ptr), t_bool); + } else { + return lb_emit_conv(p, lb_emit_comp_against_nil(p, Token_CmpEq, ptr), t_bool); + } } break; case Type_BitSet: @@ -4628,8 +4712,6 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { Type *src = core_type(src_type); Type *dst = core_type(t); - - // if (is_type_untyped_nil(src) && type_has_nil(dst)) { if (is_type_untyped_nil(src)) { return lb_const_nil(m, t); } @@ -4653,12 +4735,10 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { return lb_addr_load(p, res); } else if (dst->kind == Type_Basic) { if (src->Basic.kind == Basic_string && dst->Basic.kind == Basic_cstring) { - // TODO(bill): This is kind of a hack - unsigned indices[1] = {0}; - LLVMValueRef data = LLVMConstExtractValue(value.value, indices, gb_count_of(indices)); + String str = lb_get_const_string(m, value); lbValue res = {}; res.type = t; - res.value = data; + res.value = LLVMConstString(cast(char const *)str.text, cast(unsigned)str.len, false); return res; } // if (is_type_float(dst)) { @@ -5278,7 +5358,7 @@ lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { } } else if (is_type_map(t)) { init_map_internal_types(t); - Type *itp = (t->Map.internal_type); + Type *itp = alloc_type_pointer(t->Map.internal_type); s = lb_emit_transmute(p, s, itp); Type *gst = t->Map.internal_type; @@ -6355,13 +6435,19 @@ lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, - #if 0 // "Intrinsics" case BuiltinProc_atomic_fence: + LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, ""); + return {}; case BuiltinProc_atomic_fence_acq: + LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquire, false, ""); + return {}; case BuiltinProc_atomic_fence_rel: + LLVMBuildFence(p->builder, LLVMAtomicOrderingRelease, false, ""); + return {}; case BuiltinProc_atomic_fence_acqrel: - return lb_emit(p, lb_instr_atomic_fence(p, id)); + LLVMBuildFence(p->builder, LLVMAtomicOrderingAcquireRelease, false, ""); + return {}; case BuiltinProc_atomic_store: case BuiltinProc_atomic_store_rel: @@ -6369,8 +6455,19 @@ lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, case BuiltinProc_atomic_store_unordered: { lbValue dst = lb_build_expr(p, ce->args[0]); lbValue val = lb_build_expr(p, ce->args[1]); - val = lb_emit_conv(p, val, type_deref(lb_type(dst))); - return lb_emit(p, lb_instr_atomic_store(p, dst, val, id)); + val = lb_emit_conv(p, val, type_deref(dst.type)); + + LLVMValueRef instr = LLVMBuildStore(p->builder, val.value, dst.value); + switch (id) { + case BuiltinProc_atomic_store: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break; + case BuiltinProc_atomic_store_rel: LLVMSetOrdering(instr, LLVMAtomicOrderingRelease); break; + case BuiltinProc_atomic_store_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break; + case BuiltinProc_atomic_store_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break; + } + + LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type))); + + return {}; } case BuiltinProc_atomic_load: @@ -6378,7 +6475,20 @@ lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, case BuiltinProc_atomic_load_relaxed: case BuiltinProc_atomic_load_unordered: { lbValue dst = lb_build_expr(p, ce->args[0]); - return lb_emit(p, lb_instr_atomic_load(p, dst, id)); + + LLVMValueRef instr = LLVMBuildLoad(p->builder, dst.value, ""); + switch (id) { + case BuiltinProc_atomic_load: LLVMSetOrdering(instr, LLVMAtomicOrderingSequentiallyConsistent); break; + case BuiltinProc_atomic_load_acq: LLVMSetOrdering(instr, LLVMAtomicOrderingAcquire); break; + case BuiltinProc_atomic_load_relaxed: LLVMSetOrdering(instr, LLVMAtomicOrderingMonotonic); break; + case BuiltinProc_atomic_load_unordered: LLVMSetOrdering(instr, LLVMAtomicOrderingUnordered); break; + } + LLVMSetAlignment(instr, cast(unsigned)type_align_of(type_deref(dst.type))); + + lbValue res = {}; + res.value = instr; + res.type = type_deref(dst.type); + return res; } case BuiltinProc_atomic_add: @@ -6418,8 +6528,51 @@ lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, case BuiltinProc_atomic_xchg_relaxed: { lbValue dst = lb_build_expr(p, ce->args[0]); lbValue val = lb_build_expr(p, ce->args[1]); - val = lb_emit_conv(p, val, type_deref(ir_type(dst))); - return lb_emit(p, lb_instr_atomic_rmw(p, dst, val, id)); + val = lb_emit_conv(p, val, type_deref(dst.type)); + + LLVMAtomicRMWBinOp op = {}; + LLVMAtomicOrdering ordering = {}; + + switch (id) { + case BuiltinProc_atomic_add: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break; + case BuiltinProc_atomic_add_acq: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquire; break; + case BuiltinProc_atomic_add_rel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingRelease; break; + case BuiltinProc_atomic_add_acqrel: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingAcquireRelease; break; + case BuiltinProc_atomic_add_relaxed: op = LLVMAtomicRMWBinOpAdd; ordering = LLVMAtomicOrderingMonotonic; break; + case BuiltinProc_atomic_sub: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingSequentiallyConsistent; break; + case BuiltinProc_atomic_sub_acq: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquire; break; + case BuiltinProc_atomic_sub_rel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingRelease; break; + case BuiltinProc_atomic_sub_acqrel: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingAcquireRelease; break; + case BuiltinProc_atomic_sub_relaxed: op = LLVMAtomicRMWBinOpSub; ordering = LLVMAtomicOrderingMonotonic; break; + case BuiltinProc_atomic_and: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingSequentiallyConsistent; break; + case BuiltinProc_atomic_and_acq: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquire; break; + case BuiltinProc_atomic_and_rel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingRelease; break; + case BuiltinProc_atomic_and_acqrel: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingAcquireRelease; break; + case BuiltinProc_atomic_and_relaxed: op = LLVMAtomicRMWBinOpAnd; ordering = LLVMAtomicOrderingMonotonic; break; + case BuiltinProc_atomic_nand: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingSequentiallyConsistent; break; + case BuiltinProc_atomic_nand_acq: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquire; break; + case BuiltinProc_atomic_nand_rel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingRelease; break; + case BuiltinProc_atomic_nand_acqrel: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingAcquireRelease; break; + case BuiltinProc_atomic_nand_relaxed: op = LLVMAtomicRMWBinOpNand; ordering = LLVMAtomicOrderingMonotonic; break; + case BuiltinProc_atomic_or: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingSequentiallyConsistent; break; + case BuiltinProc_atomic_or_acq: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquire; break; + case BuiltinProc_atomic_or_rel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingRelease; break; + case BuiltinProc_atomic_or_acqrel: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingAcquireRelease; break; + case BuiltinProc_atomic_or_relaxed: op = LLVMAtomicRMWBinOpOr; ordering = LLVMAtomicOrderingMonotonic; break; + case BuiltinProc_atomic_xor: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingSequentiallyConsistent; break; + case BuiltinProc_atomic_xor_acq: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquire; break; + case BuiltinProc_atomic_xor_rel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingRelease; break; + case BuiltinProc_atomic_xor_acqrel: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingAcquireRelease; break; + case BuiltinProc_atomic_xor_relaxed: op = LLVMAtomicRMWBinOpXor; ordering = LLVMAtomicOrderingMonotonic; break; + case BuiltinProc_atomic_xchg: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingSequentiallyConsistent; break; + case BuiltinProc_atomic_xchg_acq: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquire; break; + case BuiltinProc_atomic_xchg_rel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingRelease; break; + case BuiltinProc_atomic_xchg_acqrel: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingAcquireRelease; break; + case BuiltinProc_atomic_xchg_relaxed: op = LLVMAtomicRMWBinOpXchg; ordering = LLVMAtomicOrderingMonotonic; break; + } + + LLVMValueRef instr = LLVMBuildAtomicRMW(p->builder, op, dst.value, val.value, ordering, false); + return {}; } case BuiltinProc_atomic_cxchg: @@ -6443,20 +6596,53 @@ lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, Type *type = expr->tav.type; lbValue address = lb_build_expr(p, ce->args[0]); - Type *elem = type_deref(ir_type(address)); + Type *elem = type_deref(address.type); lbValue old_value = lb_build_expr(p, ce->args[1]); lbValue new_value = lb_build_expr(p, ce->args[2]); old_value = lb_emit_conv(p, old_value, elem); new_value = lb_emit_conv(p, new_value, elem); - return lb_emit(p, lb_instr_atomic_cxchg(p, type, address, old_value, new_value, id)); + LLVMAtomicOrdering success_ordering = {}; + LLVMAtomicOrdering failure_ordering = {}; + LLVMBool weak = false; + + switch (id) { + case BuiltinProc_atomic_cxchg: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break; + case BuiltinProc_atomic_cxchg_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break; + case BuiltinProc_atomic_cxchg_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break; + case BuiltinProc_atomic_cxchg_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break; + case BuiltinProc_atomic_cxchg_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break; + case BuiltinProc_atomic_cxchg_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break; + case BuiltinProc_atomic_cxchg_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = false; break; + case BuiltinProc_atomic_cxchg_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break; + case BuiltinProc_atomic_cxchg_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = false; break; + case BuiltinProc_atomic_cxchgweak: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = false; break; + case BuiltinProc_atomic_cxchgweak_acq: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break; + case BuiltinProc_atomic_cxchgweak_rel: success_ordering = LLVMAtomicOrderingRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break; + case BuiltinProc_atomic_cxchgweak_acqrel: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingSequentiallyConsistent; weak = true; break; + case BuiltinProc_atomic_cxchgweak_relaxed: success_ordering = LLVMAtomicOrderingMonotonic; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break; + case BuiltinProc_atomic_cxchgweak_failrelaxed: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break; + case BuiltinProc_atomic_cxchgweak_failacq: success_ordering = LLVMAtomicOrderingSequentiallyConsistent; failure_ordering = LLVMAtomicOrderingAcquire; weak = true; break; + case BuiltinProc_atomic_cxchgweak_acq_failrelaxed: success_ordering = LLVMAtomicOrderingAcquire; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break; + case BuiltinProc_atomic_cxchgweak_acqrel_failrelaxed: success_ordering = LLVMAtomicOrderingAcquireRelease; failure_ordering = LLVMAtomicOrderingMonotonic; weak = true; break; + } + + // TODO(bill): Figure out how to make it weak + LLVMBool single_threaded = !weak; + + LLVMValueRef instr = LLVMBuildAtomicCmpXchg(p->builder, address.value, + old_value.value, new_value.value, + success_ordering, + failure_ordering, + single_threaded); + + return {}; } - #endif } - GB_PANIC("Unhandled built-in procedure"); + GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name)); return {}; } @@ -6804,8 +6990,8 @@ String lb_get_const_string(lbModule *m, lbValue value) { Type *t = base_type(value.type); GB_ASSERT(are_types_identical(t, t_string)); - unsigned ptr_indices[2] = {0, 0}; - unsigned len_indices[2] = {0, 1}; + unsigned ptr_indices[1] = {0}; + unsigned len_indices[1] = {1}; LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices)); LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices)); @@ -8161,7 +8347,6 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { t = base_type(type_deref(t)); if (is_type_soa_struct(t)) { // SOA STRUCTURES!!!! - GB_PANIC("SOA STRUCTURES!!!!"); lbValue val = lb_build_addr_ptr(p, ie->expr); if (deref) { val = lb_emit_load(p, val); @@ -8446,50 +8631,49 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { if (!no_indices) { // lb_emit_slice_bounds_check(p, se->open, low, high, len, se->low != nullptr); } - GB_PANIC("#soa struct slice"); - #if 0 + #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, i); + lbValue field_dst = lb_emit_struct_ep(p, dst.addr, i); lbValue field_src = lb_emit_struct_ep(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, field_count); + 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_emit_store(p, dst, base); + 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, 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, field_count); + 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, 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, field_count); + 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); } @@ -9113,6 +9297,28 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { return {}; } +void lb_init_module(lbModule *m, Checker *c) { + m->info = &c->info; + + m->ctx = LLVMGetGlobalContext(); + m->mod = LLVMModuleCreateWithNameInContext("odin_module", m->ctx); + m->debug_builder = LLVMCreateDIBuilder(m->mod); + + gb_mutex_init(&m->mutex); + gbAllocator a = heap_allocator(); + map_init(&m->types, a); + map_init(&m->values, a); + map_init(&m->members, a); + map_init(&m->procedure_values, a); + map_init(&m->procedures, a); + map_init(&m->const_strings, a); + map_init(&m->anonymous_proc_lits, a); + array_init(&m->procedures_to_generate, a); + array_init(&m->foreign_library_paths, a); + + map_init(&m->debug_values, a); + +} bool lb_init_generator(lbGenerator *gen, Checker *c) { @@ -9148,29 +9354,9 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { output_file_path = gb_string_appendc(output_file_path, ".obj"); defer (gb_string_free(output_file_path)); - gen->info = &c->info; - gen->module.info = &c->info; - // gen->ctx = LLVMContextCreate(); - gen->module.ctx = LLVMGetGlobalContext(); - gen->module.mod = LLVMModuleCreateWithNameInContext("odin_module", gen->module.ctx); - gen->module.debug_builder = LLVMCreateDIBuilder(gen->module.mod); - - - gb_mutex_init(&gen->module.mutex); - gbAllocator a = heap_allocator(); - map_init(&gen->module.types, a); - map_init(&gen->module.values, a); - map_init(&gen->module.members, a); - map_init(&gen->module.procedure_values, a); - map_init(&gen->module.procedures, a); - map_init(&gen->module.const_strings, a); - map_init(&gen->module.const_string_byte_slices, a); - map_init(&gen->module.anonymous_proc_lits, a); - array_init(&gen->module.procedures_to_generate, a); - - map_init(&gen->module.debug_values, a); + lb_init_module(&gen->module, c); return true; } @@ -10173,7 +10359,7 @@ void lb_generate_code(lbGenerator *gen) { if (e->Variable.is_foreign) { Entity *fl = e->Procedure.foreign_library; - // lb_add_foreign_library_path(m, fl); + lb_add_foreign_library_path(m, fl); } if (e->flags & EntityFlag_Static) { @@ -10276,10 +10462,10 @@ void lb_generate_code(lbGenerator *gen) { defer (gb_free(heap_allocator(), filepath_obj.text)); + LLVMBool failure = LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error); LLVMDIBuilderFinalize(m->debug_builder); LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); llvm_error = nullptr; - // LLVMBool failure = LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error); LLVMInitializeAllTargetInfos(); LLVMInitializeAllTargets(); diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 0f28e664a..5e91d2efc 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -66,8 +66,7 @@ struct lbModule { Map procedures; // Key: String Map procedure_values; // Key: LLVMValueRef - Map const_strings; // Key: String - Map const_string_byte_slices; // Key: String + Map const_strings; // Key: String Map anonymous_proc_lits; // Key: Ast * @@ -75,8 +74,11 @@ struct lbModule { u32 global_array_index; u32 global_generated_index; + u32 nested_type_name_guid; Array procedures_to_generate; + Array foreign_library_paths; + LLVMDIBuilderRef debug_builder; diff --git a/src/main.cpp b/src/main.cpp index 53b2c7174..9f79b7912 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1300,333 +1300,333 @@ int main(int arg_count, char const **arg_ptr) { show_timings(&checker, timings); } return 0; - } + } else { + irGen ir_gen = {0}; + if (!ir_gen_init(&ir_gen, &checker)) { + return 1; + } + // defer (ir_gen_destroy(&ir_gen)); - irGen ir_gen = {0}; - if (!ir_gen_init(&ir_gen, &checker)) { - return 1; - } - // defer (ir_gen_destroy(&ir_gen)); + timings_start_section(timings, str_lit("llvm ir gen")); + ir_gen_tree(&ir_gen); - timings_start_section(timings, str_lit("llvm ir gen")); - ir_gen_tree(&ir_gen); + timings_start_section(timings, str_lit("llvm ir opt tree")); + ir_opt_tree(&ir_gen); - timings_start_section(timings, str_lit("llvm ir opt tree")); - ir_opt_tree(&ir_gen); + timings_start_section(timings, str_lit("llvm ir print")); + print_llvm_ir(&ir_gen); - timings_start_section(timings, str_lit("llvm ir print")); - print_llvm_ir(&ir_gen); + String output_name = ir_gen.output_name; + String output_base = ir_gen.output_base; - String output_name = ir_gen.output_name; - String output_base = ir_gen.output_base; + build_context.optimization_level = gb_clamp(build_context.optimization_level, 0, 3); - build_context.optimization_level = gb_clamp(build_context.optimization_level, 0, 3); + i32 exit_code = 0; - i32 exit_code = 0; + timings_start_section(timings, str_lit("llvm-opt")); + exit_code = exec_llvm_opt(output_base); + if (exit_code != 0) { + return exit_code; + } - timings_start_section(timings, str_lit("llvm-opt")); - exit_code = exec_llvm_opt(output_base); - if (exit_code != 0) { - return exit_code; - } + timings_start_section(timings, str_lit("llvm-llc")); + exit_code = exec_llvm_llc(output_base); + if (exit_code != 0) { + return exit_code; + } - timings_start_section(timings, str_lit("llvm-llc")); - exit_code = exec_llvm_llc(output_base); - if (exit_code != 0) { - return exit_code; - } + if (build_context.cross_compiling && selected_target_metrics->metrics == &target_essence_amd64) { + #ifdef GB_SYSTEM_UNIX + system_exec_command_line_app("linker", "x86_64-essence-gcc \"%.*s.o\" -o \"%.*s\" %.*s", + LIT(output_base), LIT(output_base), LIT(build_context.link_flags)); + #else + gb_printf_err("Don't know how to cross compile to selected target.\n"); + #endif + } else { + #if defined(GB_SYSTEM_WINDOWS) + timings_start_section(timings, str_lit("msvc-link")); - if (build_context.cross_compiling && selected_target_metrics->metrics == &target_essence_amd64) { -#ifdef GB_SYSTEM_UNIX - system_exec_command_line_app("linker", "x86_64-essence-gcc \"%.*s.o\" -o \"%.*s\" %.*s", - LIT(output_base), LIT(output_base), LIT(build_context.link_flags)); -#else - gb_printf_err("Don't know how to cross compile to selected target.\n"); -#endif - } else { - #if defined(GB_SYSTEM_WINDOWS) - timings_start_section(timings, str_lit("msvc-link")); + gbString lib_str = gb_string_make(heap_allocator(), ""); + defer (gb_string_free(lib_str)); + char lib_str_buf[1024] = {0}; - gbString lib_str = gb_string_make(heap_allocator(), ""); - defer (gb_string_free(lib_str)); - char lib_str_buf[1024] = {0}; + char const *output_ext = "exe"; + gbString link_settings = gb_string_make_reserve(heap_allocator(), 256); + defer (gb_string_free(link_settings)); - char const *output_ext = "exe"; - gbString link_settings = gb_string_make_reserve(heap_allocator(), 256); - defer (gb_string_free(link_settings)); + // NOTE(ic): It would be nice to extend this so that we could specify the Visual Studio version that we want instead of defaulting to the latest. + Find_Result_Utf8 find_result = find_visual_studio_and_windows_sdk_utf8(); - // NOTE(ic): It would be nice to extend this so that we could specify the Visual Studio version that we want instead of defaulting to the latest. - Find_Result_Utf8 find_result = find_visual_studio_and_windows_sdk_utf8(); + if (find_result.windows_sdk_version == 0) { + gb_printf_err("Windows SDK not found.\n"); + return 1; + } - if (find_result.windows_sdk_version == 0) { - gb_printf_err("Windows SDK not found.\n"); - return 1; - } + // Add library search paths. + if (find_result.vs_library_path.len > 0) { + GB_ASSERT(find_result.windows_sdk_um_library_path.len > 0); + GB_ASSERT(find_result.windows_sdk_ucrt_library_path.len > 0); - // Add library search paths. - if (find_result.vs_library_path.len > 0) { - GB_ASSERT(find_result.windows_sdk_um_library_path.len > 0); - GB_ASSERT(find_result.windows_sdk_ucrt_library_path.len > 0); + String path = {}; + auto add_path = [&](String path) { + if (path[path.len-1] == '\\') { + path.len -= 1; + } + link_settings = gb_string_append_fmt(link_settings, " /LIBPATH:\"%.*s\"", LIT(path)); + }; + add_path(find_result.windows_sdk_um_library_path); + add_path(find_result.windows_sdk_ucrt_library_path); + add_path(find_result.vs_library_path); + } - String path = {}; - auto add_path = [&](String path) { - if (path[path.len-1] == '\\') { - path.len -= 1; - } - link_settings = gb_string_append_fmt(link_settings, " /LIBPATH:\"%.*s\"", LIT(path)); - }; - add_path(find_result.windows_sdk_um_library_path); - add_path(find_result.windows_sdk_ucrt_library_path); - add_path(find_result.vs_library_path); - } + for_array(i, ir_gen.module.foreign_library_paths) { + String lib = ir_gen.module.foreign_library_paths[i]; + GB_ASSERT(lib.len < gb_count_of(lib_str_buf)-1); + isize len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf), + " \"%.*s\"", LIT(lib)); + lib_str = gb_string_appendc(lib_str, lib_str_buf); + } - for_array(i, ir_gen.module.foreign_library_paths) { - String lib = ir_gen.module.foreign_library_paths[i]; - GB_ASSERT(lib.len < gb_count_of(lib_str_buf)-1); - isize len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf), - " \"%.*s\"", LIT(lib)); - lib_str = gb_string_appendc(lib_str, lib_str_buf); - } + if (build_context.is_dll) { + output_ext = "dll"; + link_settings = gb_string_append_fmt(link_settings, "/DLL"); + } else { + link_settings = gb_string_append_fmt(link_settings, "/ENTRY:mainCRTStartup"); + } - if (build_context.is_dll) { - output_ext = "dll"; - link_settings = gb_string_append_fmt(link_settings, "/DLL"); - } else { - link_settings = gb_string_append_fmt(link_settings, "/ENTRY:mainCRTStartup"); - } + if (build_context.pdb_filepath != "") { + link_settings = gb_string_append_fmt(link_settings, " /PDB:%.*s", LIT(build_context.pdb_filepath)); + } - if (build_context.pdb_filepath != "") { - link_settings = gb_string_append_fmt(link_settings, " /PDB:%.*s", LIT(build_context.pdb_filepath)); - } + if (build_context.no_crt) { + link_settings = gb_string_append_fmt(link_settings, " /nodefaultlib"); + } else { + link_settings = gb_string_append_fmt(link_settings, " /defaultlib:libcmt"); + } - if (build_context.no_crt) { - link_settings = gb_string_append_fmt(link_settings, " /nodefaultlib"); - } else { - link_settings = gb_string_append_fmt(link_settings, " /defaultlib:libcmt"); - } + if (ir_gen.module.generate_debug_info) { + link_settings = gb_string_append_fmt(link_settings, " /DEBUG"); + } - if (ir_gen.module.generate_debug_info) { - link_settings = gb_string_append_fmt(link_settings, " /DEBUG"); - } + char const *subsystem_str = build_context.use_subsystem_windows ? "WINDOWS" : "CONSOLE"; + if (!build_context.use_lld) { // msvc + if (build_context.has_resource) { + exit_code = system_exec_command_line_app("msvc-link", + "\"%.*src.exe\" /nologo /fo \"%.*s.res\" \"%.*s.rc\"", + LIT(find_result.vs_exe_path), + LIT(output_base), + LIT(build_context.resource_filepath) + ); - char const *subsystem_str = build_context.use_subsystem_windows ? "WINDOWS" : "CONSOLE"; - if (!build_context.use_lld) { // msvc - if (build_context.has_resource) { - exit_code = system_exec_command_line_app("msvc-link", - "\"%.*src.exe\" /nologo /fo \"%.*s.res\" \"%.*s.rc\"", - LIT(find_result.vs_exe_path), - LIT(output_base), - LIT(build_context.resource_filepath) - ); + if (exit_code != 0) { + return exit_code; + } - if (exit_code != 0) { - return exit_code; + exit_code = system_exec_command_line_app("msvc-link", + "\"%.*slink.exe\" \"%.*s.obj\" \"%.*s.res\" -OUT:\"%.*s.%s\" %s " + "/nologo /incremental:no /opt:ref /subsystem:%s " + " %.*s " + " %s " + "", + LIT(find_result.vs_exe_path), LIT(output_base), LIT(output_base), LIT(output_base), output_ext, + link_settings, + subsystem_str, + LIT(build_context.link_flags), + lib_str + ); + } else { + exit_code = system_exec_command_line_app("msvc-link", + "\"%.*slink.exe\" \"%.*s.obj\" -OUT:\"%.*s.%s\" %s " + "/nologo /incremental:no /opt:ref /subsystem:%s " + " %.*s " + " %s " + "", + LIT(find_result.vs_exe_path), LIT(output_base), LIT(output_base), output_ext, + link_settings, + subsystem_str, + LIT(build_context.link_flags), + lib_str + ); } - + } else { // lld exit_code = system_exec_command_line_app("msvc-link", - "\"%.*slink.exe\" \"%.*s.obj\" \"%.*s.res\" -OUT:\"%.*s.%s\" %s " + "\"%.*s\\bin\\lld-link\" \"%.*s.obj\" -OUT:\"%.*s.%s\" %s " "/nologo /incremental:no /opt:ref /subsystem:%s " " %.*s " " %s " "", - LIT(find_result.vs_exe_path), LIT(output_base), LIT(output_base), LIT(output_base), output_ext, - link_settings, - subsystem_str, - LIT(build_context.link_flags), - lib_str - ); - } else { - exit_code = system_exec_command_line_app("msvc-link", - "\"%.*slink.exe\" \"%.*s.obj\" -OUT:\"%.*s.%s\" %s " - "/nologo /incremental:no /opt:ref /subsystem:%s " - " %.*s " - " %s " - "", - LIT(find_result.vs_exe_path), LIT(output_base), LIT(output_base), output_ext, + LIT(build_context.ODIN_ROOT), + LIT(output_base), LIT(output_base), output_ext, link_settings, subsystem_str, LIT(build_context.link_flags), lib_str ); } - } else { // lld - exit_code = system_exec_command_line_app("msvc-link", - "\"%.*s\\bin\\lld-link\" \"%.*s.obj\" -OUT:\"%.*s.%s\" %s " - "/nologo /incremental:no /opt:ref /subsystem:%s " - " %.*s " - " %s " - "", - LIT(build_context.ODIN_ROOT), - LIT(output_base), LIT(output_base), output_ext, - link_settings, - subsystem_str, - LIT(build_context.link_flags), - lib_str - ); - } - - if (exit_code != 0) { - return exit_code; - } - if (build_context.show_timings) { - show_timings(&checker, timings); - } - - remove_temp_files(output_base); + if (exit_code != 0) { + return exit_code; + } - if (run_output) { - return system_exec_command_line_app("odin run", "%.*s.exe %.*s", LIT(output_base), LIT(run_args_string)); - } - #else - timings_start_section(timings, str_lit("ld-link")); + if (build_context.show_timings) { + show_timings(&checker, timings); + } - // NOTE(vassvik): get cwd, for used for local shared libs linking, since those have to be relative to the exe - char cwd[256]; - getcwd(&cwd[0], 256); - //printf("%s\n", cwd); + remove_temp_files(output_base); - // NOTE(vassvik): needs to add the root to the library search paths, so that the full filenames of the library - // files can be passed with -l: - gbString lib_str = gb_string_make(heap_allocator(), "-L/"); - defer (gb_string_free(lib_str)); + if (run_output) { + return system_exec_command_line_app("odin run", "%.*s.exe %.*s", LIT(output_base), LIT(run_args_string)); + } + #else + timings_start_section(timings, str_lit("ld-link")); + + // NOTE(vassvik): get cwd, for used for local shared libs linking, since those have to be relative to the exe + char cwd[256]; + getcwd(&cwd[0], 256); + //printf("%s\n", cwd); + + // NOTE(vassvik): needs to add the root to the library search paths, so that the full filenames of the library + // files can be passed with -l: + gbString lib_str = gb_string_make(heap_allocator(), "-L/"); + defer (gb_string_free(lib_str)); + + for_array(i, ir_gen.module.foreign_library_paths) { + String lib = ir_gen.module.foreign_library_paths[i]; + + // NOTE(zangent): Sometimes, you have to use -framework on MacOS. + // This allows you to specify '-f' in a #foreign_system_library, + // without having to implement any new syntax specifically for MacOS. + #if defined(GB_SYSTEM_OSX) + if (string_ends_with(lib, str_lit(".framework"))) { + // framework thingie + String lib_name = lib; + lib_name = remove_extension_from_path(lib_name); + lib_str = gb_string_append_fmt(lib_str, " -framework %.*s ", LIT(lib_name)); + } else if (string_ends_with(lib, str_lit(".a"))) { + // static libs, absolute full path relative to the file in which the lib was imported from + lib_str = gb_string_append_fmt(lib_str, " %.*s ", LIT(lib)); + } else if (string_ends_with(lib, str_lit(".dylib"))) { + // dynamic lib + lib_str = gb_string_append_fmt(lib_str, " %.*s ", LIT(lib)); + } else { + // dynamic or static system lib, just link regularly searching system library paths + lib_str = gb_string_append_fmt(lib_str, " -l%.*s ", LIT(lib)); + } + #else + // NOTE(vassvik): static libraries (.a files) in linux can be linked to directly using the full path, + // since those are statically linked to at link time. shared libraries (.so) has to be + // available at runtime wherever the executable is run, so we make require those to be + // local to the executable (unless the system collection is used, in which case we search + // the system library paths for the library file). + if (string_ends_with(lib, str_lit(".a"))) { + // static libs, absolute full path relative to the file in which the lib was imported from + lib_str = gb_string_append_fmt(lib_str, " -l:\"%.*s\" ", LIT(lib)); + } else if (string_ends_with(lib, str_lit(".so"))) { + // dynamic lib, relative path to executable + // NOTE(vassvik): it is the user's responsibility to make sure the shared library files are visible + // at runtimeto the executable + lib_str = gb_string_append_fmt(lib_str, " -l:\"%s/%.*s\" ", cwd, LIT(lib)); + } else { + // dynamic or static system lib, just link regularly searching system library paths + lib_str = gb_string_append_fmt(lib_str, " -l%.*s ", LIT(lib)); + } + #endif + } - for_array(i, ir_gen.module.foreign_library_paths) { - String lib = ir_gen.module.foreign_library_paths[i]; + // Unlike the Win32 linker code, the output_ext includes the dot, because + // typically executable files on *NIX systems don't have extensions. + String output_ext = {}; + char const *link_settings = ""; + char const *linker; + if (build_context.is_dll) { + // Shared libraries are .dylib on MacOS and .so on Linux. + #if defined(GB_SYSTEM_OSX) + output_ext = STR_LIT(".dylib"); + link_settings = "-dylib -dynamic"; + #else + output_ext = STR_LIT(".so"); + link_settings = "-shared"; + #endif + } else { + // TODO: Do I need anything here? + link_settings = ""; + } - // NOTE(zangent): Sometimes, you have to use -framework on MacOS. - // This allows you to specify '-f' in a #foreign_system_library, - // without having to implement any new syntax specifically for MacOS. - #if defined(GB_SYSTEM_OSX) - if (string_ends_with(lib, str_lit(".framework"))) { - // framework thingie - String lib_name = lib; - lib_name = remove_extension_from_path(lib_name); - lib_str = gb_string_append_fmt(lib_str, " -framework %.*s ", LIT(lib_name)); - } else if (string_ends_with(lib, str_lit(".a"))) { - // static libs, absolute full path relative to the file in which the lib was imported from - lib_str = gb_string_append_fmt(lib_str, " %.*s ", LIT(lib)); - } else if (string_ends_with(lib, str_lit(".dylib"))) { - // dynamic lib - lib_str = gb_string_append_fmt(lib_str, " %.*s ", LIT(lib)); - } else { - // dynamic or static system lib, just link regularly searching system library paths - lib_str = gb_string_append_fmt(lib_str, " -l%.*s ", LIT(lib)); + if (build_context.out_filepath.len > 0) { + //NOTE(thebirk): We have a custom -out arguments, so we should use the extension from that + isize pos = string_extension_position(build_context.out_filepath); + if (pos > 0) { + output_ext = substring(build_context.out_filepath, pos, build_context.out_filepath.len); } - #else - // NOTE(vassvik): static libraries (.a files) in linux can be linked to directly using the full path, - // since those are statically linked to at link time. shared libraries (.so) has to be - // available at runtime wherever the executable is run, so we make require those to be - // local to the executable (unless the system collection is used, in which case we search - // the system library paths for the library file). - if (string_ends_with(lib, str_lit(".a"))) { - // static libs, absolute full path relative to the file in which the lib was imported from - lib_str = gb_string_append_fmt(lib_str, " -l:\"%.*s\" ", LIT(lib)); - } else if (string_ends_with(lib, str_lit(".so"))) { - // dynamic lib, relative path to executable - // NOTE(vassvik): it is the user's responsibility to make sure the shared library files are visible - // at runtimeto the executable - lib_str = gb_string_append_fmt(lib_str, " -l:\"%s/%.*s\" ", cwd, LIT(lib)); - } else { - // dynamic or static system lib, just link regularly searching system library paths - lib_str = gb_string_append_fmt(lib_str, " -l%.*s ", LIT(lib)); - } - #endif - } + } - // Unlike the Win32 linker code, the output_ext includes the dot, because - // typically executable files on *NIX systems don't have extensions. - String output_ext = {}; - char const *link_settings = ""; - char const *linker; - if (build_context.is_dll) { - // Shared libraries are .dylib on MacOS and .so on Linux. #if defined(GB_SYSTEM_OSX) - output_ext = STR_LIT(".dylib"); - link_settings = "-dylib -dynamic"; + linker = "ld"; #else - output_ext = STR_LIT(".so"); - link_settings = "-shared"; + // TODO(zangent): Figure out how to make ld work on Linux. + // It probably has to do with including the entire CRT, but + // that's quite a complicated issue to solve while remaining distro-agnostic. + // Clang can figure out linker flags for us, and that's good enough _for now_. + linker = "clang -Wno-unused-command-line-argument"; #endif - } else { - // TODO: Do I need anything here? - link_settings = ""; - } - if (build_context.out_filepath.len > 0) { - //NOTE(thebirk): We have a custom -out arguments, so we should use the extension from that - isize pos = string_extension_position(build_context.out_filepath); - if (pos > 0) { - output_ext = substring(build_context.out_filepath, pos, build_context.out_filepath.len); + exit_code = system_exec_command_line_app("ld-link", + "%s \"%.*s.o\" -o \"%.*s%.*s\" %s " + " %s " + " %.*s " + " %s " + #if defined(GB_SYSTEM_OSX) + // This sets a requirement of Mountain Lion and up, but the compiler doesn't work without this limit. + // NOTE: If you change this (although this minimum is as low as you can go with Odin working) + // make sure to also change the 'mtriple' param passed to 'opt' + " -macosx_version_min 10.8.0 " + // This points the linker to where the entry point is + " -e _main " + #endif + , linker, LIT(output_base), LIT(output_base), LIT(output_ext), + lib_str, + "-lc -lm", + LIT(build_context.link_flags), + link_settings); + if (exit_code != 0) { + return exit_code; } - } #if defined(GB_SYSTEM_OSX) - linker = "ld"; - #else - // TODO(zangent): Figure out how to make ld work on Linux. - // It probably has to do with including the entire CRT, but - // that's quite a complicated issue to solve while remaining distro-agnostic. - // Clang can figure out linker flags for us, and that's good enough _for now_. - linker = "clang -Wno-unused-command-line-argument"; - #endif - - exit_code = system_exec_command_line_app("ld-link", - "%s \"%.*s.o\" -o \"%.*s%.*s\" %s " - " %s " - " %.*s " - " %s " - #if defined(GB_SYSTEM_OSX) - // This sets a requirement of Mountain Lion and up, but the compiler doesn't work without this limit. - // NOTE: If you change this (although this minimum is as low as you can go with Odin working) - // make sure to also change the 'mtriple' param passed to 'opt' - " -macosx_version_min 10.8.0 " - // This points the linker to where the entry point is - " -e _main " - #endif - , linker, LIT(output_base), LIT(output_base), LIT(output_ext), - lib_str, - "-lc -lm", - LIT(build_context.link_flags), - link_settings); - if (exit_code != 0) { - return exit_code; - } - - #if defined(GB_SYSTEM_OSX) - if (build_context.ODIN_DEBUG) { - // NOTE: macOS links DWARF symbols dynamically. Dsymutil will map the stubs in the exe - // to the symbols in the object file - exit_code = system_exec_command_line_app("dsymutil", - "dsymutil %.*s%.*s", LIT(output_base), LIT(output_ext) - ); + if (build_context.ODIN_DEBUG) { + // NOTE: macOS links DWARF symbols dynamically. Dsymutil will map the stubs in the exe + // to the symbols in the object file + exit_code = system_exec_command_line_app("dsymutil", + "dsymutil %.*s%.*s", LIT(output_base), LIT(output_ext) + ); - if (exit_code != 0) { - return exit_code; + if (exit_code != 0) { + return exit_code; + } } - } - #endif + #endif - if (build_context.show_timings) { - show_timings(&checker, timings); - } + if (build_context.show_timings) { + show_timings(&checker, timings); + } - remove_temp_files(output_base); + remove_temp_files(output_base); - if (run_output) { - //NOTE(thebirk): This whole thing is a little leaky - String complete_path = concatenate_strings(heap_allocator(), output_base, output_ext); - complete_path = path_to_full_path(heap_allocator(), complete_path); - return system_exec_command_line_app("odin run", "\"%.*s\" %.*s", LIT(complete_path), LIT(run_args_string)); + if (run_output) { + //NOTE(thebirk): This whole thing is a little leaky + String complete_path = concatenate_strings(heap_allocator(), output_base, output_ext); + complete_path = path_to_full_path(heap_allocator(), complete_path); + return system_exec_command_line_app("odin run", "\"%.*s\" %.*s", LIT(complete_path), LIT(run_args_string)); + } + #endif } - #endif } return 0; -- cgit v1.2.3 From c584456a21f81a7927939e26d84fa661d10eceae Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 8 Mar 2020 10:43:00 +0000 Subject: Fix logical binary expressions --- examples/demo/demo.odin | 8 ++++---- src/llvm_backend.cpp | 20 ++++++++++---------- src/llvm_backend.hpp | 3 +-- 3 files changed, 15 insertions(+), 16 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/examples/demo/demo.odin b/examples/demo/demo.odin index 601f1b27a..da56c9e64 100644 --- a/examples/demo/demo.odin +++ b/examples/demo/demo.odin @@ -1934,7 +1934,7 @@ union_maybe :: proc() { main :: proc() { when true { the_basics(); - // control_flow(); + control_flow(); named_proc_return_parameters(); explicit_procedure_overloading(); struct_type(); @@ -1943,13 +1943,13 @@ main :: proc() { // implicit_context_system(); parametric_polymorphism(); array_programming(); - // map_type(); - // implicit_selector_expression(); + map_type(); + implicit_selector_expression(); partial_switch(); cstring_example(); bit_set_type(); deferred_procedure_associations(); - // reflection(); + reflection(); quaternions(); inline_for_statement(); where_clauses(); diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 4b16a2d3c..d98a20aac 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -2923,7 +2923,7 @@ lbValue lb_emit_logical_binary_expr(lbProcedure *p, TokenKind op, Ast *left, Ast GB_ASSERT(incoming_values.count == incoming_blocks.count); LLVMAddIncoming(res.value, incoming_values.data, incoming_blocks.data, cast(unsigned)incoming_values.count); - return short_circuit; + return res; } @@ -4603,7 +4603,6 @@ lbValue lb_build_binary_expr(lbProcedure *p, Ast *expr) { case Token_CmpAnd: case Token_CmpOr: return lb_emit_logical_binary_expr(p, be->op.kind, be->left, be->right, tv.type); - break; case Token_in: case Token_not_in: @@ -8074,6 +8073,7 @@ lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type) { gbAllocator a = heap_allocator(); lbAddr h = lb_add_local_generated(p, t_map_header, false); // all the values will be initialzed later map_type = base_type(map_type); + GB_ASSERT(map_type->kind == Type_Map); Type *key_type = map_type->Map.key; Type *val_type = map_type->Map.value; @@ -8127,8 +8127,7 @@ lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) { lbValue str = lb_emit_conv(p, key, t_string); lbValue hashed_str = {}; - if (lb_is_const(str)) { - + if (false && lb_is_const(str)) { String value = lb_get_const_string(p->module, str); u64 hs = fnv64a(value.text, value.len); hashed_str = lb_const_value(p->module, t_u64, exact_value_u64(hs)); @@ -8146,23 +8145,24 @@ lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type) { return lb_addr_load(p, v); } -lbValue lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, - lbValue map_key, lbValue map_value) { +void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, + lbValue map_key, lbValue map_value) { map_type = base_type(map_type); + GB_ASSERT(map_type->kind == Type_Map); lbValue h = lb_gen_map_header(p, addr.addr, map_type); lbValue key = lb_gen_map_key(p, map_key, map_type->Map.key); lbValue v = lb_emit_conv(p, map_value, map_type->Map.value); - lbAddr ptr = lb_add_local_generated(p, v.type, false); - lb_addr_store(p, ptr, v); + lbAddr value_addr = lb_add_local_generated(p, v.type, false); + lb_addr_store(p, value_addr, v); auto args = array_make(heap_allocator(), 4); args[0] = h; args[1] = key; - args[2] = lb_emit_conv(p, ptr.addr, t_rawptr); + args[2] = lb_emit_conv(p, value_addr.addr, t_rawptr); args[3] = lb_emit_source_code_location(p, nullptr); - return lb_emit_runtime_call(p, "__dynamic_map_set", args); + lb_emit_runtime_call(p, "__dynamic_map_set", args); } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 5e91d2efc..3a532f195 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -310,7 +310,6 @@ void lb_emit_increment(lbProcedure *p, lbValue addr); lbValue lb_type_info(lbModule *m, Type *type); -lbValue lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, lbValue map_key, lbValue map_value); bool lb_is_const(lbValue value); @@ -320,7 +319,7 @@ String lb_get_const_string(lbModule *m, lbValue value); lbValue lb_generate_array(lbModule *m, Type *elem_type, i64 count, String prefix, i64 id); lbValue lb_gen_map_header(lbProcedure *p, lbValue map_val_ptr, Type *map_type); lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type); -lbValue lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, lbValue map_key, lbValue map_value); +void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, lbValue map_key, lbValue map_value); #define LB_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime" -- cgit v1.2.3 From 8dc74a004c7dcac3ed0d1fd0b218e7f8dd79efa6 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 8 Mar 2020 11:46:05 +0000 Subject: Fix nested type declarations name generation, to be internally consistent --- examples/demo/demo.odin | 2 +- src/check_decl.cpp | 1 + src/checker.hpp | 1 + src/entity.cpp | 4 ++- src/llvm_backend.cpp | 88 +++++++++++++++++++++++++++++++++++++------------ 5 files changed, 73 insertions(+), 23 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/examples/demo/demo.odin b/examples/demo/demo.odin index da56c9e64..ed39eba8d 100644 --- a/examples/demo/demo.odin +++ b/examples/demo/demo.odin @@ -1958,7 +1958,7 @@ main :: proc() { deprecated_attribute(); range_statements_with_multiple_return_values(); threading_example(); - // soa_struct_layout(); + soa_struct_layout(); constant_literal_expressions(); union_maybe(); } diff --git a/src/check_decl.cpp b/src/check_decl.cpp index ece38e84f..8a231fe36 100644 --- a/src/check_decl.cpp +++ b/src/check_decl.cpp @@ -625,6 +625,7 @@ void check_proc_decl(CheckerContext *ctx, Entity *e, DeclInfo *d) { check_open_scope(ctx, pl->type); defer (check_close_scope(ctx)); + ctx->scope->procedure_entity = e; Type *decl_type = nullptr; diff --git a/src/checker.hpp b/src/checker.hpp index 8ad0c0481..e1330478e 100644 --- a/src/checker.hpp +++ b/src/checker.hpp @@ -182,6 +182,7 @@ struct Scope { union { AstPackage *pkg; AstFile * file; + Entity * procedure_entity; }; }; diff --git a/src/entity.cpp b/src/entity.cpp index 49ecd65dc..49bce00df 100644 --- a/src/entity.cpp +++ b/src/entity.cpp @@ -3,6 +3,7 @@ struct Checker; struct Type; struct DeclInfo; struct lbModule; +struct lbProcedure; #define ENTITY_KINDS \ @@ -106,7 +107,8 @@ struct Entity { Entity * using_parent; Ast * using_expr; - lbModule * code_gen_module; + lbModule * code_gen_module; + lbProcedure *code_gen_procedure; isize order_in_src; String deprecated_message; diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index d98a20aac..8ddd37677 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -485,18 +485,68 @@ String lb_mangle_name(lbModule *m, Entity *e) { new_name_len += extra-1; } - return make_string((u8 const *)new_name, new_name_len-1); + String mangled_name = make_string((u8 const *)new_name, new_name_len-1); + return mangled_name; } +String lb_set_nested_type_name_ir_mangled_name(Entity *e, lbProcedure *p) { + // NOTE(bill, 2020-03-08): A polymorphic procedure may take a nested type declaration + // and as a result, the declaration does not have time to determine what it should be + + GB_ASSERT(e != nullptr && e->kind == Entity_TypeName); + if (e->TypeName.ir_mangled_name.len != 0) { + return e->TypeName.ir_mangled_name; + } + GB_ASSERT((e->scope->flags & ScopeFlag_File) == 0); + + if (p == nullptr) { + Entity *proc = nullptr; + if (e->parent_proc_decl != nullptr) { + proc = e->parent_proc_decl->entity; + } else { + Scope *scope = e->scope; + while (scope != nullptr && (scope->flags & ScopeFlag_Proc) == 0) { + scope = scope->parent; + } + GB_ASSERT(scope != nullptr); + GB_ASSERT(scope->flags & ScopeFlag_Proc); + proc = scope->procedure_entity; + } + GB_ASSERT(proc->kind == Entity_Procedure); + GB_ASSERT(proc->code_gen_procedure != nullptr); + p = proc->code_gen_procedure; + } + + // NOTE(bill): Generate a new name + // parent_proc.name-guid + String ts_name = e->token.string; + + lbModule *m = p->module; + isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1; + char *name_text = gb_alloc_array(heap_allocator(), char, name_len); + u32 guid = ++p->module->nested_type_name_guid; + name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid); + + String name = make_string(cast(u8 *)name_text, name_len-1); + e->TypeName.ir_mangled_name = name; + return name; +} + + String lb_get_entity_name(lbModule *m, Entity *e, String default_name) { if (e != nullptr && e->kind == Entity_TypeName && e->TypeName.ir_mangled_name.len != 0) { return e->TypeName.ir_mangled_name; } + GB_ASSERT(e != nullptr); if (e->pkg == nullptr) { return e->token.string; } + if (e->kind == Entity_TypeName && (e->scope->flags & ScopeFlag_File) == 0) { + return lb_set_nested_type_name_ir_mangled_name(e, nullptr); + } + String name = {}; bool no_name_mangle = false; @@ -521,9 +571,13 @@ String lb_get_entity_name(lbModule *m, Entity *e, String default_name) { name = e->token.string; } - if (e != nullptr && e->kind == Entity_TypeName) { + if (e->kind == Entity_TypeName) { + if ((e->scope->flags & ScopeFlag_File) == 0) { + gb_printf_err("<<< %.*s %.*s %p\n", LIT(e->token.string), LIT(name), e); + } + e->TypeName.ir_mangled_name = name; - } else if (e != nullptr && e->kind == Entity_Procedure) { + } else if (e->kind == Entity_Procedure) { e->Procedure.link_name = name; } @@ -1064,6 +1118,7 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { p->module = m; entity->code_gen_module = m; + entity->code_gen_procedure = p; p->entity = entity; p->name = link_name; @@ -1792,22 +1847,12 @@ void lb_build_constant_value_decl(lbProcedure *p, AstValueDecl *vd) { continue; } - // NOTE(bill): Generate a new name - // parent_proc.name-guid - String ts_name = e->token.string; - - lbModule *m = p->module; - isize name_len = p->name.len + 1 + ts_name.len + 1 + 10 + 1; - char *name_text = gb_alloc_array(heap_allocator(), char, name_len); - u32 guid = ++p->module->nested_type_name_guid; - name_len = gb_snprintf(name_text, name_len, "%.*s.%.*s-%u", LIT(p->name), LIT(ts_name), guid); - - String name = make_string(cast(u8 *)name_text, name_len-1); - e->TypeName.ir_mangled_name = name; + if (e->TypeName.ir_mangled_name.len != 0) { + // NOTE(bill): Already set + continue; + } - // lbValue value = ir_value_type_name(name, e->type); - // ir_add_entity_name(m, e, name); - // ir_gen_global_type_name(m, e, name); + lb_set_nested_type_name_ir_mangled_name(e, p); } for_array(i, vd->names) { @@ -10305,9 +10350,10 @@ void lb_generate_code(lbGenerator *gen) { if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name)); - LLVMDumpValue(p->value); - gb_printf_err("\n\n\n\n"); - LLVMVerifyFunction(p->value, LLVMAbortProcessAction); + // LLVMDumpValue(p->value); + // gb_printf_err("\n\n\n\n"); + // LLVMVerifyFunction(p->value, LLVMAbortProcessAction); + exit(1); } } -- cgit v1.2.3 From 28502ba53b32a0e5eb9aa7d8c41424fa090ff7ef Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 8 Mar 2020 12:34:36 +0000 Subject: Fix `context` system; add more to -show-more-timings for LLVM API; Add `ODIN_USE_LLVM_API` global constant --- build.bat | 7 ++--- core/runtime/internal.odin | 40 +++++++++++++++++++------- examples/demo/demo.odin | 2 +- src/checker.cpp | 1 + src/ir.cpp | 2 +- src/llvm_backend.cpp | 70 ++++++++++++++++++++++++---------------------- 6 files changed, 73 insertions(+), 49 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/build.bat b/build.bat index 4f3f665f2..436e7852f 100644 --- a/build.bat +++ b/build.bat @@ -49,15 +49,14 @@ del *.ilk > NUL 2> NUL cl %compiler_settings% "src\main.cpp" ^ /link %linker_settings% -OUT:%exe_name% ^ - && odin build examples/demo/demo.odin -llvm-api -show-timings - rem && odin build examples/llvm-demo/demo.odin -llvm-api -show-timings + && odin build examples/demo/demo.odin -llvm-api -show-more-timings if %errorlevel% neq 0 ( goto end_of_build ) link demo.obj kernel32.lib user32.lib /OUT:llvm_demo.exe ^ - /nologo /incremental:no /opt:ref /subsystem:CONSOLE /defaultlib:libcmt -debug ^ - && llvm_demo + /nologo /incremental:no /opt:ref /subsystem:CONSOLE /defaultlib:libcmt -debug + rem && llvm_demo del *.obj > NUL 2> NUL diff --git a/core/runtime/internal.odin b/core/runtime/internal.odin index 01b9ed616..bcc91eb6b 100644 --- a/core/runtime/internal.odin +++ b/core/runtime/internal.odin @@ -57,12 +57,22 @@ mem_copy :: proc "contextless" (dst, src: rawptr, len: int) -> rawptr { if src == nil do return dst; // NOTE(bill): This _must_ be implemented like C's memmove foreign _ { - when size_of(rawptr) == 8 { - @(link_name="llvm.memmove.p0i8.p0i8.i64") - llvm_memmove :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; + when ODIN_USE_LLVM_API { + when size_of(rawptr) == 8 { + @(link_name="llvm.memmove.p0i8.p0i8.i64") + llvm_memmove :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; + } else { + @(link_name="llvm.memmove.p0i8.p0i8.i32") + llvm_memmove :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; + } } else { - @(link_name="llvm.memmove.p0i8.p0i8.i32") - llvm_memmove :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; + when size_of(rawptr) == 8 { + @(link_name="llvm.memmove.p0i8.p0i8.i64") + llvm_memmove :: proc(dst, src: rawptr, len: int, align: i32 = 1, is_volatile: bool = false) ---; + } else { + @(link_name="llvm.memmove.p0i8.p0i8.i32") + llvm_memmove :: proc(dst, src: rawptr, len: int, align: i32 = 1, is_volatile: bool = false) ---; + } } } llvm_memmove(dst, src, len); @@ -73,12 +83,22 @@ mem_copy_non_overlapping :: proc "contextless" (dst, src: rawptr, len: int) -> r if src == nil do return dst; // NOTE(bill): This _must_ be implemented like C's memcpy foreign _ { - when size_of(rawptr) == 8 { - @(link_name="llvm.memcpy.p0i8.p0i8.i64") - llvm_memcpy :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; + when ODIN_USE_LLVM_API { + when size_of(rawptr) == 8 { + @(link_name="llvm.memcpy.p0i8.p0i8.i64") + llvm_memcpy :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; + } else { + @(link_name="llvm.memcpy.p0i8.p0i8.i32") + llvm_memcpy :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; + } } else { - @(link_name="llvm.memcpy.p0i8.p0i8.i32") - llvm_memcpy :: proc(dst, src: rawptr, len: int, is_volatile: bool = false) ---; + when size_of(rawptr) == 8 { + @(link_name="llvm.memcpy.p0i8.p0i8.i64") + llvm_memcpy :: proc(dst, src: rawptr, len: int, align: i32 = 1, is_volatile: bool = false) ---; + } else { + @(link_name="llvm.memcpy.p0i8.p0i8.i32") + llvm_memcpy :: proc(dst, src: rawptr, len: int, align: i32 = 1, is_volatile: bool = false) ---; + } } } llvm_memcpy(dst, src, len); diff --git a/examples/demo/demo.odin b/examples/demo/demo.odin index ed39eba8d..4ef9b2a8c 100644 --- a/examples/demo/demo.odin +++ b/examples/demo/demo.odin @@ -1940,7 +1940,7 @@ main :: proc() { struct_type(); union_type(); using_statement(); - // implicit_context_system(); + implicit_context_system(); parametric_polymorphism(); array_programming(); map_type(); diff --git a/src/checker.cpp b/src/checker.cpp index 23e27af87..0494bde4b 100644 --- a/src/checker.cpp +++ b/src/checker.cpp @@ -711,6 +711,7 @@ void init_universal(void) { add_global_string_constant(str_lit("ODIN_ROOT"), bc->ODIN_ROOT); add_global_constant(str_lit("ODIN_DEBUG"), t_untyped_bool, exact_value_bool(bc->ODIN_DEBUG)); add_global_constant(str_lit("ODIN_DISABLE_ASSERT"), t_untyped_bool, exact_value_bool(bc->ODIN_DISABLE_ASSERT)); + add_global_constant(str_lit("ODIN_USE_LLVM_API"), t_untyped_bool, exact_value_bool(bc->use_llvm_api)); // Builtin Procedures diff --git a/src/ir.cpp b/src/ir.cpp index c5b140991..16999a209 100644 --- a/src/ir.cpp +++ b/src/ir.cpp @@ -11445,7 +11445,7 @@ void ir_setup_type_info_data(irProcedure *proc) { // NOTE(bill): Setup type_info ir_emit_store(proc, results, ir_get_type_info_ptr(proc, t->Proc.results)); } ir_emit_store(proc, variadic, ir_const_bool(t->Proc.variadic)); - ir_emit_store(proc, convention, ir_const_int(t->Proc.calling_convention)); + ir_emit_store(proc, convention, ir_const_u8(t->Proc.calling_convention)); // TODO(bill): TypeInfo for procedures break; diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 8ddd37677..554323b54 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -303,6 +303,8 @@ lbValue lb_addr_load(lbProcedure *p, lbAddr const &addr) { lbValue a = addr.addr; lbValue b = lb_emit_deep_field_gep(p, a, addr.ctx.sel); return lb_emit_load(p, b); + } else { + return lb_emit_load(p, addr.addr); } } else if (addr.kind == lbAddr_SoaVariable) { Type *t = type_deref(addr.addr.type); @@ -2002,30 +2004,15 @@ void lb_close_scope(lbProcedure *p, lbDeferExitKind kind, lbBlock *block, bool p GB_ASSERT(p->scope_index > 0); // NOTE(bill): Remove `context`s made in that scope - - isize end_idx = p->context_stack.count-1; - isize pop_count = 0; - - for (;;) { - if (end_idx < 0) { - break; - } - lbContextData *end = &p->context_stack[end_idx]; - if (end == nullptr) { - break; - } - if (end->scope_index != p->scope_index) { - break; - } - end_idx -= 1; - pop_count += 1; - } - if (pop_stack) { - for (isize i = 0; i < pop_count; i++) { + while (p->context_stack.count > 0) { + lbContextData *ctx = &p->context_stack[p->context_stack.count-1]; + if (ctx->scope_index >= p->scope_index) { array_pop(&p->context_stack); + } else { + break; } - } + } p->scope_index -= 1; } @@ -5292,15 +5279,19 @@ lbValue lb_emit_transmute(lbProcedure *p, lbValue value, Type *t) { } -void lb_emit_init_context(lbProcedure *p, lbValue c) { +void lb_emit_init_context(lbProcedure *p, lbAddr addr) { + GB_ASSERT(addr.kind == lbAddr_Context); + GB_ASSERT(addr.ctx.sel.index.count == 0); + lbModule *m = p->module; gbAllocator a = heap_allocator(); auto args = array_make(a, 1); - args[0] = c.value != nullptr ? c : m->global_default_context.addr; + args[0] = addr.addr; lb_emit_runtime_call(p, "__init_context", args); } void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx) { + ctx.kind = lbAddr_Context; lbContextData cd = {ctx, p->scope_index}; array_add(&p->context_stack, cd); } @@ -5315,7 +5306,7 @@ lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) { c.kind = lbAddr_Context; lb_push_context_onto_stack(p, c); lb_addr_store(p, c, lb_addr_load(p, p->module->global_default_context)); - lb_emit_init_context(p, c.addr); + lb_emit_init_context(p, c); return c; } @@ -8307,7 +8298,7 @@ lbAddr lb_build_addr(lbProcedure *p, Ast *expr) { sel = selection_combine(addr.ctx.sel, sel); } addr.ctx.sel = sel; - + addr.kind = lbAddr_Context; return addr; } else if (addr.kind == lbAddr_SoaVariable) { lbValue index = addr.soa.index; @@ -10042,6 +10033,10 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da void lb_generate_code(lbGenerator *gen) { + #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0) + + TIME_SECTION("LLVM Global Variables"); + lbModule *m = &gen->module; LLVMModuleRef mod = gen->module.mod; CheckerInfo *info = gen->info; @@ -10051,7 +10046,7 @@ void lb_generate_code(lbGenerator *gen) { gbAllocator temp_allocator = arena_allocator(&temp_arena); gen->module.global_default_context = lb_add_global_generated(m, t_context, {}); - + gen->module.global_default_context.kind = lbAddr_Context; auto *min_dep_set = &info->minimum_dependency_set; @@ -10278,6 +10273,7 @@ void lb_generate_code(lbGenerator *gen) { } + TIME_SECTION("LLVM Global Procedures and Types"); for_array(i, info->entities) { // arena_free_all(&temp_arena); // gbAllocator a = temp_allocator; @@ -10335,6 +10331,7 @@ void lb_generate_code(lbGenerator *gen) { } } + TIME_SECTION("LLVM Procedure Generation"); for_array(i, m->procedures_to_generate) { lbProcedure *p = m->procedures_to_generate[i]; if (p->is_done) { @@ -10350,14 +10347,14 @@ void lb_generate_code(lbGenerator *gen) { if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name)); - // LLVMDumpValue(p->value); - // gb_printf_err("\n\n\n\n"); - // LLVMVerifyFunction(p->value, LLVMAbortProcessAction); - exit(1); + LLVMDumpValue(p->value); + gb_printf_err("\n\n\n\n"); + LLVMVerifyFunction(p->value, LLVMAbortProcessAction); } } + TIME_SECTION("LLVM Function Pass"); LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry(); LLVMPassManagerRef function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod); @@ -10432,7 +10429,7 @@ void lb_generate_code(lbGenerator *gen) { } } - lb_emit_init_context(p, {}); + lb_emit_init_context(p, p->module->global_default_context); lb_end_procedure_body(p); @@ -10483,6 +10480,8 @@ void lb_generate_code(lbGenerator *gen) { } + TIME_SECTION("LLVM Module Pass"); + LLVMPassManagerRef module_pass_manager = LLVMCreatePassManager(); defer (LLVMDisposePassManager(module_pass_manager)); LLVMAddAlwaysInlinerPass(module_pass_manager); @@ -10490,8 +10489,8 @@ void lb_generate_code(lbGenerator *gen) { LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate(); defer (LLVMPassManagerBuilderDispose(pass_manager_builder)); - LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, 3); - LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, 3); + LLVMPassManagerBuilderSetOptLevel(pass_manager_builder, build_context.optimization_level); + LLVMPassManagerBuilderSetSizeLevel(pass_manager_builder, build_context.optimization_level); LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false); LLVMRunPassManager(module_pass_manager, mod); @@ -10513,6 +10512,8 @@ void lb_generate_code(lbGenerator *gen) { LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); llvm_error = nullptr; + TIME_SECTION("LLVM Initializtion"); + LLVMInitializeAllTargetInfos(); LLVMInitializeAllTargets(); LLVMInitializeAllTargetMCs(); @@ -10521,6 +10522,8 @@ void lb_generate_code(lbGenerator *gen) { LLVMInitializeAllDisassemblers(); LLVMInitializeNativeTarget(); + timings_start_section(&global_timings, str_lit("LLVM Object Generation")); + char const *target_triple = "x86_64-pc-windows-msvc"; char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; LLVMSetTarget(mod, target_triple); @@ -10539,4 +10542,5 @@ void lb_generate_code(lbGenerator *gen) { return; } +#undef TIME_SECTION } -- cgit v1.2.3 From dae817e5ab786180ebcd284fb27195db5ae5ec00 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 8 Mar 2020 17:44:08 +0000 Subject: Integrate linker code with the new LLVM API backend --- build.bat | 8 +- src/llvm_backend.cpp | 21 +++- src/llvm_backend.hpp | 1 + src/main.cpp | 316 +++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 338 insertions(+), 8 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/build.bat b/build.bat index 436e7852f..5018eb06e 100644 --- a/build.bat +++ b/build.bat @@ -49,14 +49,14 @@ del *.ilk > NUL 2> NUL cl %compiler_settings% "src\main.cpp" ^ /link %linker_settings% -OUT:%exe_name% ^ - && odin build examples/demo/demo.odin -llvm-api -show-more-timings + && odin run examples/demo/demo.odin -llvm-api if %errorlevel% neq 0 ( goto end_of_build ) -link demo.obj kernel32.lib user32.lib /OUT:llvm_demo.exe ^ - /nologo /incremental:no /opt:ref /subsystem:CONSOLE /defaultlib:libcmt -debug - rem && llvm_demo +rem link demo.obj kernel32.lib user32.lib /OUT:llvm_demo.exe ^ +rem /nologo /incremental:no /opt:ref /subsystem:CONSOLE /defaultlib:libcmt -debug +rem rem && llvm_demo del *.obj > NUL 2> NUL diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 554323b54..2b6604f44 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -9384,6 +9384,8 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { } } gbAllocator ha = heap_allocator(); + array_init(&gen->output_object_paths, ha); + gen->output_base = path_to_full_path(ha, gen->output_base); gbString output_file_path = gb_string_make_length(ha, gen->output_base.text, gen->output_base.len); @@ -9394,6 +9396,7 @@ bool lb_init_generator(lbGenerator *gen, Checker *c) { lb_init_module(&gen->module, c); + return true; } @@ -10362,6 +10365,7 @@ void lb_generate_code(lbGenerator *gen) { LLVMAddPromoteMemoryToRegisterPass(function_pass_manager); LLVMAddMergedLoadStoreMotionPass(function_pass_manager); + LLVMAddDeadStoreEliminationPass(function_pass_manager); LLVMAddAggressiveInstCombinerPass(function_pass_manager); LLVMAddConstantPropagationPass(function_pass_manager); LLVMAddAggressiveDCEPass(function_pass_manager); @@ -10376,6 +10380,7 @@ void lb_generate_code(lbGenerator *gen) { } } + TIME_SECTION("LLVM Runtime Creation"); lbProcedure *startup_runtime = nullptr; { // Startup Runtime @@ -10502,12 +10507,15 @@ void lb_generate_code(lbGenerator *gen) { defer (LLVMDisposeMessage(llvm_error)); String filepath_ll = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".ll")); - String filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".obj")); defer (gb_free(heap_allocator(), filepath_ll.text)); - defer (gb_free(heap_allocator(), filepath_obj.text)); + + String filepath_obj = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".obj")); - LLVMBool failure = LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error); + if (build_context.keep_temp_files) { + TIME_SECTION("LLVM Print Module to File"); + LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error); + } LLVMDIBuilderFinalize(m->debug_builder); LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); llvm_error = nullptr; @@ -10522,7 +10530,6 @@ void lb_generate_code(lbGenerator *gen) { LLVMInitializeAllDisassemblers(); LLVMInitializeNativeTarget(); - timings_start_section(&global_timings, str_lit("LLVM Object Generation")); char const *target_triple = "x86_64-pc-windows-msvc"; char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; @@ -10532,9 +10539,13 @@ void lb_generate_code(lbGenerator *gen) { LLVMGetTargetFromTriple(target_triple, &target, &llvm_error); GB_ASSERT(target != nullptr); + TIME_SECTION("LLVM Create Target Machine"); + LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault); defer (LLVMDisposeTargetMachine(target_machine)); + TIME_SECTION("LLVM Object Generation"); + LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, LLVMObjectFile, &llvm_error); if (ok) { gb_printf_err("LLVM Error: %s\n", llvm_error); @@ -10542,5 +10553,7 @@ void lb_generate_code(lbGenerator *gen) { return; } + array_add(&gen->output_object_paths, filepath_obj); + #undef TIME_SECTION } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 3a532f195..d99babce7 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -90,6 +90,7 @@ struct lbGenerator { lbModule module; CheckerInfo *info; + Array output_object_paths; String output_base; String output_name; }; diff --git a/src/main.cpp b/src/main.cpp index 9f79b7912..8113162e5 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -125,6 +125,303 @@ i32 system_exec_command_line_app(char const *name, char const *fmt, ...) { + +i32 linker_stage(lbGenerator *gen) { + i32 exit_code = 0; + + Timings *timings = &global_timings; + + String output_base = gen->output_base; + + if (build_context.cross_compiling && selected_target_metrics->metrics == &target_essence_amd64) { +#ifdef GB_SYSTEM_UNIX + system_exec_command_line_app("linker", "x86_64-essence-gcc \"%.*s.o\" -o \"%.*s\" %.*s", + LIT(output_base), LIT(output_base), LIT(build_context.link_flags)); +#else + gb_printf_err("Don't know how to cross compile to selected target.\n"); +#endif + } else { + #if defined(GB_SYSTEM_WINDOWS) + timings_start_section(timings, str_lit("msvc-link")); + + gbString lib_str = gb_string_make(heap_allocator(), ""); + defer (gb_string_free(lib_str)); + char lib_str_buf[1024] = {0}; + + char const *output_ext = "exe"; + gbString link_settings = gb_string_make_reserve(heap_allocator(), 256); + defer (gb_string_free(link_settings)); + + + // NOTE(ic): It would be nice to extend this so that we could specify the Visual Studio version that we want instead of defaulting to the latest. + Find_Result_Utf8 find_result = find_visual_studio_and_windows_sdk_utf8(); + + if (find_result.windows_sdk_version == 0) { + gb_printf_err("Windows SDK not found.\n"); + return 1; + } + + // Add library search paths. + if (find_result.vs_library_path.len > 0) { + GB_ASSERT(find_result.windows_sdk_um_library_path.len > 0); + GB_ASSERT(find_result.windows_sdk_ucrt_library_path.len > 0); + + String path = {}; + auto add_path = [&](String path) { + if (path[path.len-1] == '\\') { + path.len -= 1; + } + link_settings = gb_string_append_fmt(link_settings, " /LIBPATH:\"%.*s\"", LIT(path)); + }; + add_path(find_result.windows_sdk_um_library_path); + add_path(find_result.windows_sdk_ucrt_library_path); + add_path(find_result.vs_library_path); + } + + for_array(i, gen->module.foreign_library_paths) { + String lib = gen->module.foreign_library_paths[i]; + GB_ASSERT(lib.len < gb_count_of(lib_str_buf)-1); + isize len = gb_snprintf(lib_str_buf, gb_size_of(lib_str_buf), + " \"%.*s\"", LIT(lib)); + lib_str = gb_string_appendc(lib_str, lib_str_buf); + } + + + + if (build_context.is_dll) { + output_ext = "dll"; + link_settings = gb_string_append_fmt(link_settings, "/DLL"); + } else { + link_settings = gb_string_append_fmt(link_settings, "/ENTRY:mainCRTStartup"); + } + + if (build_context.pdb_filepath != "") { + link_settings = gb_string_append_fmt(link_settings, " /PDB:%.*s", LIT(build_context.pdb_filepath)); + } + + if (build_context.no_crt) { + link_settings = gb_string_append_fmt(link_settings, " /nodefaultlib"); + } else { + link_settings = gb_string_append_fmt(link_settings, " /defaultlib:libcmt"); + } + + if (build_context.ODIN_DEBUG) { + link_settings = gb_string_append_fmt(link_settings, " /DEBUG"); + } + + gbString object_files = gb_string_make(heap_allocator(), ""); + defer (gb_string_free(object_files)); + for_array(i, gen->output_object_paths) { + String object_path = gen->output_object_paths[i]; + object_files = gb_string_append_fmt(object_files, "\"%.*s\" ", LIT(object_path)); + } + + char const *subsystem_str = build_context.use_subsystem_windows ? "WINDOWS" : "CONSOLE"; + if (!build_context.use_lld) { // msvc + if (build_context.has_resource) { + exit_code = system_exec_command_line_app("msvc-link", + "\"%.*src.exe\" /nologo /fo \"%.*s.res\" \"%.*s.rc\"", + LIT(find_result.vs_exe_path), + LIT(output_base), + LIT(build_context.resource_filepath) + ); + + if (exit_code != 0) { + return exit_code; + } + + exit_code = system_exec_command_line_app("msvc-link", + "\"%.*slink.exe\" %s \"%.*s.res\" -OUT:\"%.*s.%s\" %s " + "/nologo /incremental:no /opt:ref /subsystem:%s " + " %.*s " + " %s " + "", + LIT(find_result.vs_exe_path), object_files, LIT(output_base), LIT(output_base), output_ext, + link_settings, + subsystem_str, + LIT(build_context.link_flags), + lib_str + ); + } else { + exit_code = system_exec_command_line_app("msvc-link", + "\"%.*slink.exe\" %s -OUT:\"%.*s.%s\" %s " + "/nologo /incremental:no /opt:ref /subsystem:%s " + " %.*s " + " %s " + "", + LIT(find_result.vs_exe_path), object_files, LIT(output_base), output_ext, + link_settings, + subsystem_str, + LIT(build_context.link_flags), + lib_str + ); + } + } else { // lld + exit_code = system_exec_command_line_app("msvc-link", + "\"%.*s\\bin\\lld-link\" %s -OUT:\"%.*s.%s\" %s " + "/nologo /incremental:no /opt:ref /subsystem:%s " + " %.*s " + " %s " + "", + LIT(build_context.ODIN_ROOT), + LIT(output_base), object_files, output_ext, + link_settings, + subsystem_str, + LIT(build_context.link_flags), + lib_str + ); + } + #else + timings_start_section(timings, str_lit("ld-link")); + + // NOTE(vassvik): get cwd, for used for local shared libs linking, since those have to be relative to the exe + char cwd[256]; + getcwd(&cwd[0], 256); + //printf("%s\n", cwd); + + // NOTE(vassvik): needs to add the root to the library search paths, so that the full filenames of the library + // files can be passed with -l: + gbString lib_str = gb_string_make(heap_allocator(), "-L/"); + defer (gb_string_free(lib_str)); + + for_array(i, ir_gen.module.foreign_library_paths) { + String lib = ir_gen.module.foreign_library_paths[i]; + + // NOTE(zangent): Sometimes, you have to use -framework on MacOS. + // This allows you to specify '-f' in a #foreign_system_library, + // without having to implement any new syntax specifically for MacOS. + #if defined(GB_SYSTEM_OSX) + if (string_ends_with(lib, str_lit(".framework"))) { + // framework thingie + String lib_name = lib; + lib_name = remove_extension_from_path(lib_name); + lib_str = gb_string_append_fmt(lib_str, " -framework %.*s ", LIT(lib_name)); + } else if (string_ends_with(lib, str_lit(".a"))) { + // static libs, absolute full path relative to the file in which the lib was imported from + lib_str = gb_string_append_fmt(lib_str, " %.*s ", LIT(lib)); + } else if (string_ends_with(lib, str_lit(".dylib"))) { + // dynamic lib + lib_str = gb_string_append_fmt(lib_str, " %.*s ", LIT(lib)); + } else { + // dynamic or static system lib, just link regularly searching system library paths + lib_str = gb_string_append_fmt(lib_str, " -l%.*s ", LIT(lib)); + } + #else + // NOTE(vassvik): static libraries (.a files) in linux can be linked to directly using the full path, + // since those are statically linked to at link time. shared libraries (.so) has to be + // available at runtime wherever the executable is run, so we make require those to be + // local to the executable (unless the system collection is used, in which case we search + // the system library paths for the library file). + if (string_ends_with(lib, str_lit(".a"))) { + // static libs, absolute full path relative to the file in which the lib was imported from + lib_str = gb_string_append_fmt(lib_str, " -l:\"%.*s\" ", LIT(lib)); + } else if (string_ends_with(lib, str_lit(".so"))) { + // dynamic lib, relative path to executable + // NOTE(vassvik): it is the user's responsibility to make sure the shared library files are visible + // at runtimeto the executable + lib_str = gb_string_append_fmt(lib_str, " -l:\"%s/%.*s\" ", cwd, LIT(lib)); + } else { + // dynamic or static system lib, just link regularly searching system library paths + lib_str = gb_string_append_fmt(lib_str, " -l%.*s ", LIT(lib)); + } + #endif + } + + gbString object_files = gb_string_make(heap_allocator(), ""); + defer (gb_string_free(object_files)); + for_array(i, gen->output_object_paths) { + String object_path = gen->output_object_paths[i]; + object_files = gb_string_append_fmt(object_files, "\"%.*s\" ", LIT(object_path)); + } + + // Unlike the Win32 linker code, the output_ext includes the dot, because + // typically executable files on *NIX systems don't have extensions. + String output_ext = {}; + char const *link_settings = ""; + char const *linker; + if (build_context.is_dll) { + // Shared libraries are .dylib on MacOS and .so on Linux. + #if defined(GB_SYSTEM_OSX) + output_ext = STR_LIT(".dylib"); + link_settings = "-dylib -dynamic"; + #else + output_ext = STR_LIT(".so"); + link_settings = "-shared"; + #endif + } else { + // TODO: Do I need anything here? + link_settings = ""; + } + + if (build_context.out_filepath.len > 0) { + //NOTE(thebirk): We have a custom -out arguments, so we should use the extension from that + isize pos = string_extension_position(build_context.out_filepath); + if (pos > 0) { + output_ext = substring(build_context.out_filepath, pos, build_context.out_filepath.len); + } + } + + #if defined(GB_SYSTEM_OSX) + linker = "ld"; + #else + // TODO(zangent): Figure out how to make ld work on Linux. + // It probably has to do with including the entire CRT, but + // that's quite a complicated issue to solve while remaining distro-agnostic. + // Clang can figure out linker flags for us, and that's good enough _for now_. + linker = "clang -Wno-unused-command-line-argument"; + #endif + + exit_code = system_exec_command_line_app("ld-link", + "%s %s -o \"%.*s%.*s\" %s " + " %s " + " %.*s " + " %s " + #if defined(GB_SYSTEM_OSX) + // This sets a requirement of Mountain Lion and up, but the compiler doesn't work without this limit. + // NOTE: If you change this (although this minimum is as low as you can go with Odin working) + // make sure to also change the 'mtriple' param passed to 'opt' + " -macosx_version_min 10.8.0 " + // This points the linker to where the entry point is + " -e _main " + #endif + , linker, object_files, LIT(output_base), LIT(output_ext), + lib_str, + "-lc -lm", + LIT(build_context.link_flags), + link_settings); + if (exit_code != 0) { + return exit_code; + } + + #if defined(GB_SYSTEM_OSX) + if (build_context.ODIN_DEBUG) { + // NOTE: macOS links DWARF symbols dynamically. Dsymutil will map the stubs in the exe + // to the symbols in the object file + exit_code = system_exec_command_line_app("dsymutil", + "dsymutil %.*s%.*s", LIT(output_base), LIT(output_ext) + ); + + if (exit_code != 0) { + return exit_code; + } + } + #endif + + + if (build_context.show_timings) { + show_timings(&checker, timings); + } + + remove_temp_files(output_base); + + + #endif + } + + return exit_code; +} + + Array setup_args(int argc, char const **argv) { gbAllocator a = heap_allocator(); @@ -1296,9 +1593,28 @@ int main(int arg_count, char const **arg_ptr) { } lb_generate_code(&gen); + i32 linker_stage_exit_count = linker_stage(&gen); + if (linker_stage_exit_count != 0) { + return linker_stage_exit_count; + } + if (build_context.show_timings) { show_timings(&checker, timings); } + + remove_temp_files(gen.output_base); + + if (run_output) { + #if defined(GB_SYSTEM_WINDOWS) + return system_exec_command_line_app("odin run", "%.*s.exe %.*s", LIT(gen.output_base), LIT(run_args_string)); + #else + //NOTE(thebirk): This whole thing is a little leaky + String complete_path = concatenate_strings(heap_allocator(), output_base, output_ext); + complete_path = path_to_full_path(heap_allocator(), complete_path); + return system_exec_command_line_app("odin run", "\"%.*s\" %.*s", LIT(complete_path), LIT(run_args_string)); + #endif + } + return 0; } else { irGen ir_gen = {0}; -- cgit v1.2.3 From 5a02ebe2c8caff530f51df97691554a74c97aba9 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 8 Mar 2020 17:57:46 +0000 Subject: Fix foreign import dependencies; Fix `lbParamPass_Integer` ABI --- src/llvm_backend.cpp | 12 +++++++++--- src/llvm_backend.hpp | 1 + 2 files changed, 10 insertions(+), 3 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 2b6604f44..0aecebf83 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -1137,8 +1137,8 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { p->body = pl->body; p->tags = pt->Proc.tags; p->inlining = ProcInlining_none; - p->is_foreign = false; - p->is_export = false; + p->is_foreign = entity->Procedure.is_foreign; + p->is_export = entity->Procedure.is_export; p->is_entry_point = false; gbAllocator a = heap_allocator(); @@ -1206,6 +1206,12 @@ lbProcedure *lb_create_procedure(lbModule *m, Entity *entity) { lb_add_proc_attribute_at_index(p, offset+parameter_index, "nocapture"); } + + if (entity->Procedure.is_foreign) { + lb_add_foreign_library_path(p->module, entity->Procedure.foreign_library); + } + + { // Debug Information unsigned line = cast(unsigned)entity->token.pos.line; @@ -1379,7 +1385,7 @@ lbValue lb_add_param(lbProcedure *p, Entity *e, Ast *expr, Type *abi_type, i32 i case lbParamPass_Integer: { lbAddr l = lb_add_local(p, e->type, e, false, index); - lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(p->type)); + lbValue iptr = lb_emit_conv(p, l.addr, alloc_type_pointer(abi_type)); lb_emit_store(p, iptr, v); return lb_addr_load(p, l); } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index d99babce7..a58dcdf8b 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -279,6 +279,7 @@ void lb_push_context_onto_stack(lbProcedure *p, lbAddr ctx); lbAddr lb_add_global_generated(lbModule *m, Type *type, lbValue value={}); lbAddr lb_add_local(lbProcedure *p, Type *type, Entity *e=nullptr, bool zero_init=true, i32 param_index=0); +void lb_add_foreign_library_path(lbModule *m, Entity *e); lbValue lb_typeid(lbModule *m, Type *type, Type *typeid_type=t_typeid); -- cgit v1.2.3 From d1e670335f714875a2fe583fd7b04a78fb4812ac Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 8 Mar 2020 18:50:10 +0000 Subject: Fix lb_find_or_add_entity_string_byte_slice --- src/llvm_backend.cpp | 34 ++++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 0aecebf83..a3820fa13 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -3543,8 +3543,9 @@ lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) { res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2); res.type = t_string; return res; + } else { + return lb_const_value(m, t_string, exact_value_string(str)); } - return lb_const_value(m, t_string, exact_value_string(str)); } lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) { @@ -3558,9 +3559,38 @@ lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) lbValue res = {}; res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2); res.type = t_u8_slice; + return res; + } else { + LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)}; + LLVMValueRef data = LLVMConstStringInContext(m->ctx, + cast(char const *)str.text, + cast(unsigned)str.len, + false); + + + isize max_len = 7+8+1; + char *name = gb_alloc_array(heap_allocator(), char, max_len); + isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index); + len -= 1; + m->global_array_index++; + + LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name); + LLVMSetInitializer(global_data, data); + + LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); + + LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true); + LLVMValueRef values[2] = {ptr, str_len}; + + Type *original_type = t_u8_slice; + lbValue res = {}; + res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); + res.type = default_type(original_type); + + map_set(&m->const_strings, key, ptr); + return res; } - return lb_const_value(m, t_u8_slice, exact_value_string(str)); } isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) { -- cgit v1.2.3 From bf0c6f5a30e406a0e0f73014c024ba63dcb47b43 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 8 Mar 2020 19:38:50 +0000 Subject: Fixes for constants and `nil` parameters --- src/llvm_backend.cpp | 94 ++++++++++++++++++++++++++++++++++++++++++++-------- src/llvm_backend.hpp | 3 +- 2 files changed, 83 insertions(+), 14 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index a3820fa13..3b3fe4985 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -40,6 +40,12 @@ LLVMValueRef llvm_one32(lbModule *m) { return LLVMConstInt(lb_type(m, t_i32), 1, false); } +LLVMValueRef llvm_cstring(lbModule *m, String const &str) { + lbValue v = lb_find_or_add_entity_string(m, str); + unsigned indices[1] = {0}; + return LLVMConstExtractValue(v.value, indices, gb_count_of(indices)); +} + lbAddr lb_addr(lbValue addr) { lbAddr v = {lbAddr_Default, addr}; @@ -2135,7 +2141,7 @@ void lb_build_range_indexed(lbProcedure *p, lbValue expr, Type *val_type, lbValu lb_addr_store(p, key, lb_emit_load(p, str)); } else { lbValue hash_ptr = lb_emit_struct_ep(p, hash, 0); - hash_ptr = lb_emit_conv(p, hash_ptr, lb_addr_type(key)); + hash_ptr = lb_emit_conv(p, hash_ptr, key.addr.type); lb_addr_store(p, key, lb_emit_load(p, hash_ptr)); } @@ -3544,7 +3550,34 @@ lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) { res.type = t_string; return res; } else { - return lb_const_value(m, t_string, exact_value_string(str)); + LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)}; + LLVMValueRef data = LLVMConstStringInContext(m->ctx, + cast(char const *)str.text, + cast(unsigned)str.len, + false); + + + isize max_len = 7+8+1; + char *name = gb_alloc_array(heap_allocator(), char, max_len); + isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index); + len -= 1; + m->global_array_index++; + + LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name); + LLVMSetInitializer(global_data, data); + + LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); + + LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true); + LLVMValueRef values[2] = {ptr, str_len}; + + lbValue res = {}; + res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2); + res.type = t_string; + + map_set(&m->const_strings, key, ptr); + + return res; } } @@ -3582,10 +3615,9 @@ lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true); LLVMValueRef values[2] = {ptr, str_len}; - Type *original_type = t_u8_slice; lbValue res = {}; - res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); - res.type = default_type(original_type); + res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2); + res.type = t_u8_slice; map_set(&m->const_strings, key, ptr); @@ -4132,7 +4164,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { ast_node(cl, CompoundLit, value.value_compound); if (cl->elems.count == 0) { - return lb_const_nil(m, type); + return lb_const_nil(m, original_type); } isize offset = 0; @@ -4232,7 +4264,13 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { } break; case ExactValue_Procedure: - GB_PANIC("TODO(bill): ExactValue_Procedure"); + { + Ast *expr = value.value_procedure; + GB_ASSERT(expr != nullptr); + if (expr->kind == Ast_ProcLit) { + return lb_generate_anonymous_proc_lit(m, str_lit("_proclit"), expr); + } + } break; case ExactValue_Typeid: return lb_typeid(m, value.value_typeid, original_type); @@ -4805,7 +4843,7 @@ lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { String str = lb_get_const_string(m, value); lbValue res = {}; res.type = t; - res.value = LLVMConstString(cast(char const *)str.text, cast(unsigned)str.len, false); + res.value = llvm_cstring(m, str); return res; } // if (is_type_float(dst)) { @@ -5354,6 +5392,8 @@ lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) { return res; } + GB_ASSERT(is_type_typed(value.type)); + lbAddr res = lb_add_local_generated(p, value.type, false); lb_addr_store(p, res, value); return res.addr; @@ -5833,6 +5873,7 @@ lbValue lb_emit_call(lbProcedure *p, lbValue value, Array const &args, Type *original_type = e->type; Type *new_type = pt->Proc.abi_compat_params[i]; Type *arg_type = args[i].type; + if (are_types_identical(arg_type, new_type)) { // NOTE(bill): Done array_add(&processed_args, args[i]); @@ -6507,6 +6548,11 @@ lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, // "Intrinsics" + case BuiltinProc_cpu_relax: + // TODO(bill): BuiltinProc_cpu_relax + // ir_write_str_lit(f, "call void asm sideeffect \"pause\", \"\"()"); + return {}; + case BuiltinProc_atomic_fence: LLVMBuildFence(p->builder, LLVMAtomicOrderingSequentiallyConsistent, false, ""); return {}; @@ -6709,8 +6755,6 @@ lbValue lb_build_builtin_proc(lbProcedure *p, Ast *expr, TypeAndValue const &tv, return {}; } - - } GB_PANIC("Unhandled built-in procedure %.*s", LIT(builtin_procs[id].name)); @@ -6832,6 +6876,17 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { } } + for (isize i = 0; i < args.count; i++) { + Entity *e = params->variables[i]; + if (args[i].type == nullptr) { + continue; + } else if (is_type_untyped_nil(args[i].type)) { + args[i] = lb_const_nil(m, e->type); + } else if (is_type_untyped_undef(args[i].type)) { + args[i] = lb_const_undef(m, e->type); + } + } + return lb_emit_call(p, value, args, ce->inlining, p->return_ptr_hint_ast == expr); } @@ -7028,6 +7083,19 @@ lbValue lb_build_call_expr(lbProcedure *p, Ast *expr) { final_count = arg_count; } + if (param_tuple != nullptr) { + for (isize i = 0; i < gb_min(args.count, param_tuple->variables.count); i++) { + Entity *e = param_tuple->variables[i]; + if (args[i].type == nullptr) { + continue; + } else if (is_type_untyped_nil(args[i].type)) { + args[i] = lb_const_nil(m, e->type); + } else if (is_type_untyped_undef(args[i].type)) { + args[i] = lb_const_undef(m, e->type); + } + } + } + auto call_args = array_slice(args, 0, final_count); return lb_emit_call(p, value, call_args, ce->inlining, p->return_ptr_hint_ast == expr); } @@ -7577,7 +7645,7 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri } -lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent = nullptr) { +lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent) { ast_node(pl, ProcLit, expr); // NOTE(bill): Generate a new name @@ -7872,7 +7940,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { lbValue cond = lb_build_cond(p, te->cond, then, else_); lb_start_block(p, then); - Type *type = type_of_expr(expr); + Type *type = default_type(type_of_expr(expr)); lb_open_scope(p); incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value; @@ -7913,7 +7981,7 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { lbValue cond = lb_build_cond(p, te->cond, then, else_); lb_start_block(p, then); - Type *type = type_of_expr(expr); + Type *type = default_type(type_of_expr(expr)); lb_open_scope(p); incoming_values[0] = lb_emit_conv(p, lb_build_expr(p, te->x), type).value; diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index a58dcdf8b..e7e805227 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -312,7 +312,8 @@ void lb_emit_increment(lbProcedure *p, lbValue addr); lbValue lb_type_info(lbModule *m, Type *type); - +lbValue lb_find_or_add_entity_string(lbModule *m, String const &str); +lbValue lb_generate_anonymous_proc_lit(lbModule *m, String const &prefix_name, Ast *expr, lbProcedure *parent = nullptr); bool lb_is_const(lbValue value); bool lb_is_const_nil(lbValue value); -- cgit v1.2.3 From 4468ddf8f8edb5cd51e708ee623598bc6d0716de Mon Sep 17 00:00:00 2001 From: Joshua Huelsman Date: Mon, 9 Mar 2020 03:21:08 -0400 Subject: LLVM: speed improvement changes. --- src/llvm_backend.cpp | 60 +++++++++++++++++++++++++++------------------------- 1 file changed, 31 insertions(+), 29 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 3b3fe4985..36b13d4f2 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -10157,6 +10157,33 @@ void lb_generate_code(lbGenerator *gen) { auto *min_dep_set = &info->minimum_dependency_set; + TIME_SECTION("LLVM Initializtion"); + + LLVMInitializeAllTargetInfos(); + LLVMInitializeAllTargets(); + LLVMInitializeAllTargetMCs(); + LLVMInitializeAllAsmPrinters(); + LLVMInitializeAllAsmParsers(); + LLVMInitializeAllDisassemblers(); + LLVMInitializeNativeTarget(); + + + char const *target_triple = "x86_64-pc-windows-msvc"; + char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; + LLVMSetTarget(mod, target_triple); + + LLVMTargetRef target = {}; + char *llvm_error = nullptr; + LLVMGetTargetFromTriple(target_triple, &target, &llvm_error); + GB_ASSERT(target != nullptr); + + TIME_SECTION("LLVM Create Target Machine"); + + LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault); + defer (LLVMDisposeTargetMachine(target_machine)); + + LLVMSetModuleDataLayout(mod, LLVMCreateTargetDataLayout(target_machine)); + { // Debug Info for_array(i, info->files.entries) { AstFile *f = info->files.entries[i].value; @@ -10467,9 +10494,10 @@ void lb_generate_code(lbGenerator *gen) { LLVMPassManagerRef function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod); defer (LLVMDisposePassManager(function_pass_manager)); + LLVMAddMemCpyOptPass(function_pass_manager); LLVMAddPromoteMemoryToRegisterPass(function_pass_manager); LLVMAddMergedLoadStoreMotionPass(function_pass_manager); - LLVMAddDeadStoreEliminationPass(function_pass_manager); + // LLVMAddDeadStoreEliminationPass(function_pass_manager); LLVMAddAggressiveInstCombinerPass(function_pass_manager); LLVMAddConstantPropagationPass(function_pass_manager); LLVMAddAggressiveDCEPass(function_pass_manager); @@ -10595,6 +10623,7 @@ void lb_generate_code(lbGenerator *gen) { defer (LLVMDisposePassManager(module_pass_manager)); LLVMAddAlwaysInlinerPass(module_pass_manager); LLVMAddStripDeadPrototypesPass(module_pass_manager); + // LLVMAddConstantMergePass(module_pass_manager); LLVMPassManagerBuilderRef pass_manager_builder = LLVMPassManagerBuilderCreate(); defer (LLVMPassManagerBuilderDispose(pass_manager_builder)); @@ -10604,10 +10633,7 @@ void lb_generate_code(lbGenerator *gen) { LLVMPassManagerBuilderPopulateLTOPassManager(pass_manager_builder, module_pass_manager, false, false); LLVMRunPassManager(module_pass_manager, mod); - - - - char *llvm_error = nullptr; + llvm_error = nullptr; defer (LLVMDisposeMessage(llvm_error)); String filepath_ll = concatenate_strings(heap_allocator(), gen->output_base, STR_LIT(".ll")); @@ -10624,30 +10650,6 @@ void lb_generate_code(lbGenerator *gen) { LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); llvm_error = nullptr; - TIME_SECTION("LLVM Initializtion"); - - LLVMInitializeAllTargetInfos(); - LLVMInitializeAllTargets(); - LLVMInitializeAllTargetMCs(); - LLVMInitializeAllAsmPrinters(); - LLVMInitializeAllAsmParsers(); - LLVMInitializeAllDisassemblers(); - LLVMInitializeNativeTarget(); - - - char const *target_triple = "x86_64-pc-windows-msvc"; - char const *target_data_layout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; - LLVMSetTarget(mod, target_triple); - - LLVMTargetRef target = {}; - LLVMGetTargetFromTriple(target_triple, &target, &llvm_error); - GB_ASSERT(target != nullptr); - - TIME_SECTION("LLVM Create Target Machine"); - - LLVMTargetMachineRef target_machine = LLVMCreateTargetMachine(target, target_triple, "generic", "", LLVMCodeGenLevelNone, LLVMRelocDefault, LLVMCodeModelDefault); - defer (LLVMDisposeTargetMachine(target_machine)); - TIME_SECTION("LLVM Object Generation"); LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, LLVMObjectFile, &llvm_error); -- cgit v1.2.3 From 5169dc07c7c2d34e5170279433e6557d40b3afb8 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Sun, 15 Mar 2020 14:37:39 +0000 Subject: Fix `lb_add_proc_attribute_at_index` --- src/llvm_backend.cpp | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 3b3fe4985..7e7080f55 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -1082,10 +1082,21 @@ void lb_add_procedure_value(lbModule *m, lbProcedure *p) { lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) { - lbAddr res = lb_add_local_generated(p, t_string, false); - lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem); - lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len); - return lb_addr_load(p, res); + if (lb_is_const(str_elem) && lb_is_const(str_len)) { + LLVMValueRef values[2] = { + str_elem.value, + str_len.value, + }; + lbValue res = {}; + res.type = t_string; + res.value = LLVMConstNamedStruct(lb_type(p->module, t_string), values, gb_count_of(values)); + return res; + } else { + lbAddr res = lb_add_local_generated(p, t_string, false); + lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 0), str_elem); + lb_emit_store(p, lb_emit_struct_ep(p, res.addr, 1), str_len); + return lb_addr_load(p, res); + } } LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) { @@ -1094,12 +1105,11 @@ LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, } void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) { - LLVMContextRef ctx = LLVMGetModuleContext(p->module->mod); - // LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, lb_create_enum_attribute(ctx, name, value)); + LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, lb_create_enum_attribute(p->module->ctx, name, value)); } void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) { - lb_add_proc_attribute_at_index(p, index, name, true); + lb_add_proc_attribute_at_index(p, index, name, cast(u64)true); } -- cgit v1.2.3 From 04fe23a3c860ea29998c290d2a0dc94ee240a53a Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 19 Mar 2020 10:57:14 +0000 Subject: Have different categories for optimization passes --- build.bat | 2 +- src/llvm_backend.cpp | 659 ++++++++++++++++++++++++++++++++++++--------------- src/llvm_backend.hpp | 5 + src/types.cpp | 8 + 4 files changed, 476 insertions(+), 198 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/build.bat b/build.bat index 5018eb06e..702031eb3 100644 --- a/build.bat +++ b/build.bat @@ -49,7 +49,7 @@ del *.ilk > NUL 2> NUL cl %compiler_settings% "src\main.cpp" ^ /link %linker_settings% -OUT:%exe_name% ^ - && odin run examples/demo/demo.odin -llvm-api + && odin run examples/demo/demo.odin -llvm-api -keep-temp-files if %errorlevel% neq 0 ( goto end_of_build ) diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 040a1f335..b193423a1 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -40,6 +40,13 @@ LLVMValueRef llvm_one32(lbModule *m) { return LLVMConstInt(lb_type(m, t_i32), 1, false); } +lbValue lb_zero(lbModule *m, Type *t) { + lbValue v = {}; + v.value = LLVMConstInt(lb_type(m, t), 0, false); + v.type = t; + return v; +} + LLVMValueRef llvm_cstring(lbModule *m, String const &str) { lbValue v = lb_find_or_add_entity_string(m, str); unsigned indices[1] = {0}; @@ -206,6 +213,13 @@ void lb_addr_store(lbProcedure *p, lbAddr const &addr, lbValue value) { LLVMBuildStore(p->builder, value.value, addr.addr.value); } +void lb_const_store(lbValue ptr, lbValue value) { + GB_ASSERT(lb_is_const(ptr)); + GB_ASSERT(lb_is_const(value)); + GB_ASSERT(is_type_pointer(ptr.type)); + LLVMSetInitializer(ptr.value, value.value); +} + void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) { GB_ASSERT(value.value != nullptr); @@ -221,7 +235,7 @@ void lb_emit_store(lbProcedure *p, lbValue ptr, lbValue value) { GB_ASSERT_MSG(are_types_identical(a, value.type), "%s != %s", type_to_string(a), type_to_string(value.type)); } - LLVMValueRef v = LLVMBuildStore(p->builder, value.value, ptr.value); + LLVMBuildStore(p->builder, value.value, ptr.value); } lbValue lb_emit_load(lbProcedure *p, lbValue value) { @@ -401,12 +415,14 @@ lbValue lb_emit_union_tag_ptr(lbProcedure *p, lbValue u) { return tag_ptr; } -void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) { - gbAllocator a = heap_allocator(); - lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type)); +lbValue lb_emit_union_tag_value(lbProcedure *p, lbValue u) { + lbValue ptr = lb_address_from_load_or_generate_local(p, u); + lbValue tag_ptr = lb_emit_union_tag_ptr(p, ptr); + return lb_emit_load(p, tag_ptr); +} - lb_emit_store(p, underlying, variant); +void lb_emit_store_union_variant_tag(lbProcedure *p, lbValue parent, Type *variant_type) { Type *t = type_deref(parent.type); if (is_type_union_maybe_pointer(t) || type_size_of(t) == 0) { @@ -417,6 +433,14 @@ void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant } } +void lb_emit_store_union_variant(lbProcedure *p, lbValue parent, lbValue variant, Type *variant_type) { + gbAllocator a = heap_allocator(); + lbValue underlying = lb_emit_conv(p, parent, alloc_type_pointer(variant_type)); + + lb_emit_store(p, underlying, variant); + lb_emit_store_union_variant_tag(p, parent, variant_type); +} + void lb_clone_struct_type(LLVMTypeRef dst, LLVMTypeRef src) { unsigned field_count = LLVMCountStructElementTypes(src); @@ -474,7 +498,7 @@ String lb_mangle_name(lbModule *m, Entity *e) { if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) { require_suffix_id = true; } else { - require_suffix_id = true; + // require_suffix_id = true; } if (require_suffix_id) { @@ -779,8 +803,10 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { GB_PANIC("INVALID TYPE"); break; - case Type_Pointer: case Type_Opaque: + return lb_type(m, base->Opaque.elem); + + case Type_Pointer: case Type_Array: case Type_EnumeratedArray: case Type_Slice: @@ -1082,7 +1108,7 @@ void lb_add_procedure_value(lbModule *m, lbProcedure *p) { lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) { - if (lb_is_const(str_elem) && lb_is_const(str_len)) { + if (false && lb_is_const(str_elem) && lb_is_const(str_len)) { LLVMValueRef values[2] = { str_elem.value, str_len.value, @@ -1101,11 +1127,14 @@ lbValue lb_emit_string(lbProcedure *p, lbValue str_elem, lbValue str_len) { LLVMAttributeRef lb_create_enum_attribute(LLVMContextRef ctx, char const *name, u64 value) { unsigned kind = LLVMGetEnumAttributeKindForName(name, gb_strlen(name)); + GB_ASSERT(kind != 0); return LLVMCreateEnumAttribute(ctx, kind, value); } void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name, u64 value) { - LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, lb_create_enum_attribute(p->module->ctx, name, value)); + LLVMAttributeRef attr = lb_create_enum_attribute(p->module->ctx, name, value); + GB_ASSERT(attr != nullptr); + LLVMAddAttributeAtIndex(p->value, cast(unsigned)index, attr); } void lb_add_proc_attribute_at_index(lbProcedure *p, isize index, char const *name) { @@ -1694,6 +1723,10 @@ void lb_emit_if(lbProcedure *p, lbValue cond, lbBlock *true_block, lbBlock *fals } lbValue lb_build_cond(lbProcedure *p, Ast *cond, lbBlock *true_block, lbBlock *false_block) { + GB_ASSERT(cond != nullptr); + GB_ASSERT(true_block != nullptr); + GB_ASSERT(false_block != nullptr); + switch (cond->kind) { case_ast_node(pe, ParenExpr, cond); return lb_build_cond(p, pe->expr, true_block, false_block); @@ -4223,7 +4256,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { for (isize i = 0; i < type->Struct.fields.count; i++) { if (!visited[offset+i]) { GB_ASSERT(values[offset+i] == nullptr); - values[offset+i] = lb_const_nil(m, type->Struct.fields[i]->type).value; + values[offset+i] = lb_const_nil(m, get_struct_field_type(type, i)).value; } } @@ -4814,6 +4847,16 @@ String lookup_subtype_polymorphic_field(CheckerInfo *info, Type *dst, Type *src) return str_lit(""); } +lbValue lb_const_ptr_cast(lbModule *m, lbValue value, Type *t) { + GB_ASSERT(is_type_pointer(value.type)); + GB_ASSERT(is_type_pointer(t)); + GB_ASSERT(lb_is_const(value)); + + lbValue res = {}; + res.value = LLVMConstPointerCast(value.value, lb_type(m, t)); + res.type = t; + return res; +} lbValue lb_emit_conv(lbProcedure *p, lbValue value, Type *t) { lbModule *m = p->module; @@ -5434,7 +5477,7 @@ lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { } if (is_type_struct(t)) { - result_type = t->Struct.fields[index]->type; + result_type = get_struct_field_type(t, index); } else if (is_type_union(t)) { GB_ASSERT(index == -1); return lb_emit_union_tag_ptr(p, s); @@ -5485,8 +5528,8 @@ lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { Type *gst = t->Map.internal_type; GB_ASSERT(gst->kind == Type_Struct); switch (index) { - case 0: result_type = gst->Struct.fields[0]->type; break; - case 1: result_type = gst->Struct.fields[1]->type; break; + case 0: result_type = get_struct_field_type(gst, 0); break; + case 1: result_type = get_struct_field_type(gst, 1); break; } } else if (is_type_array(t)) { return lb_emit_array_epi(p, s, index); @@ -5496,10 +5539,19 @@ lbValue lb_emit_struct_ep(lbProcedure *p, lbValue s, i32 index) { GB_ASSERT_MSG(result_type != nullptr, "%s %d", type_to_string(t), index); - lbValue res = {}; - res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, ""); - res.type = alloc_type_pointer(result_type); - return res; + if (lb_is_const(s)) { + lbModule *m = p->module; + lbValue res = {}; + LLVMValueRef indices[2] = {llvm_zero32(m), LLVMConstInt(lb_type(m, t_i32), index, false)}; + res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices)); + res.type = alloc_type_pointer(result_type); + return res; + } else { + lbValue res = {}; + res.value = LLVMBuildStructGEP(p->builder, s.value, cast(unsigned)index, ""); + res.type = alloc_type_pointer(result_type); + return res; + } } lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) { @@ -5553,7 +5605,7 @@ lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) { } break; case Type_Struct: - result_type = t->Struct.fields[index]->type; + result_type = get_struct_field_type(t, index); break; case Type_Union: GB_ASSERT(index == -1); @@ -5587,8 +5639,8 @@ lbValue lb_emit_struct_ev(lbProcedure *p, lbValue s, i32 index) { init_map_internal_types(t); Type *gst = t->Map.generated_struct_type; switch (index) { - case 0: result_type = gst->Struct.fields[0]->type; break; - case 1: result_type = gst->Struct.fields[1]->type; break; + case 0: result_type = get_struct_field_type(gst, 0); break; + case 1: result_type = get_struct_field_type(gst, 1); break; } } break; @@ -5630,11 +5682,11 @@ lbValue lb_emit_deep_field_gep(lbProcedure *p, lbValue e, Selection sel) { if (is_type_quaternion(type)) { e = lb_emit_struct_ep(p, e, index); } else if (is_type_raw_union(type)) { - type = type->Struct.fields[index]->type; + type = get_struct_field_type(type, index); GB_ASSERT(is_type_pointer(e.type)); e = lb_emit_transmute(p, e, alloc_type_pointer(type)); } else if (is_type_struct(type)) { - type = type->Struct.fields[index]->type; + type = get_struct_field_type(type, index); e = lb_emit_struct_ep(p, e, index); } else if (type->kind == Type_Union) { GB_ASSERT(index == -1); @@ -6005,11 +6057,15 @@ lbValue lb_emit_array_epi(lbProcedure *p, lbValue s, isize index) { LLVMValueRef indices[2] = { LLVMConstInt(lb_type(p->module, t_int), 0, false), - LLVMConstInt(lb_type(p->module, t_int), index, true), + LLVMConstInt(lb_type(p->module, t_int), cast(unsigned)index, false), }; lbValue res = {}; - res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), ""); + if (lb_is_const(s)) { + res.value = LLVMConstGEP(s.value, indices, gb_count_of(indices)); + } else { + res.value = LLVMBuildGEP(p->builder, s.value, indices, gb_count_of(indices), ""); + } res.type = alloc_type_pointer(ptr); return res; } @@ -6018,10 +6074,25 @@ lbValue lb_emit_ptr_offset(lbProcedure *p, lbValue ptr, lbValue index) { LLVMValueRef indices[1] = {index.value}; lbValue res = {}; res.type = ptr.type; - res.value = LLVMBuildGEP2(p->builder, lb_type(p->module, type_deref(ptr.type)), ptr.value, indices, 1, ""); + + if (lb_is_const(ptr) && lb_is_const(index)) { + res.value = LLVMConstGEP(ptr.value, indices, 1); + } else { + res.value = LLVMBuildGEP(p->builder, ptr.value, indices, 1, ""); + } return res; } +LLVMValueRef llvm_const_slice(lbValue data, lbValue len) { + GB_ASSERT(is_type_pointer(data.type)); + GB_ASSERT(are_types_identical(len.type, t_int)); + LLVMValueRef vals[2] = { + data.value, + len.value, + }; + return LLVMConstStruct(vals, gb_count_of(vals), false); +} + void lb_fill_slice(lbProcedure *p, lbAddr const &slice, lbValue base_elem, lbValue len) { Type *t = lb_addr_type(slice); @@ -7283,9 +7354,8 @@ lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) { return res; } } else if (is_type_map(t)) { - GB_PANIC("map nil comparison"); - // lbValue len = lb_map_len(p, x); - // return lb_emit_comp(p, op_kind, len, v_zero); + lbValue cap = lb_map_cap(p, x); + return lb_emit_comp(p, op_kind, cap, lb_zero(p->module, cap.type)); } else if (is_type_union(t)) { if (type_size_of(t) == 0) { if (op_kind == Token_CmpEq) { @@ -7294,9 +7364,8 @@ lbValue lb_emit_comp_against_nil(lbProcedure *p, TokenKind op_kind, lbValue x) { return lb_const_bool(p->module, t_llvm_bool, false); } } else { - GB_PANIC("lb_emit_union_tag_value"); - // lbValue tag = lb_emit_union_tag_value(p, x); - // return lb_emit_comp(p, op_kind, tag, v_zero); + lbValue tag = lb_emit_union_tag_value(p, x); + return lb_emit_comp(p, op_kind, tag, lb_zero(p->module, tag.type)); } } else if (is_type_typeid(t)) { lbValue invalid_typeid = lb_const_value(p->module, t_typeid, exact_value_i64(0)); @@ -7586,6 +7655,20 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri return res; } + + case Token_CmpEq: + case Token_NotEq: + { + LLVMIntPredicate pred = {}; + switch (op_kind) { + case Token_CmpEq: pred = LLVMIntEQ; break; + case Token_NotEq: pred = LLVMIntNE; break; + } + lbValue res = {}; + res.type = t_llvm_bool; + res.value = LLVMBuildICmp(p->builder, pred, left.value, right.value, ""); + return res; + } } } @@ -7603,7 +7686,11 @@ lbValue lb_emit_comp(lbProcedure *p, TokenKind op_kind, lbValue left, lbValue ri lbValue res = {}; res.type = t_llvm_bool; - if (is_type_integer(left.type) || is_type_boolean(left.type) || is_type_pointer(left.type) || is_type_proc(left.type) || is_type_enum(left.type)) { + if (is_type_integer(left.type) || + is_type_boolean(left.type) || + is_type_pointer(left.type) || + is_type_proc(left.type) || + is_type_enum(left.type)) { LLVMIntPredicate pred = {}; if (is_type_unsigned(left.type)) { switch (op_kind) { @@ -9550,11 +9637,20 @@ lbValue lb_find_runtime_value(lbModule *m, String const &name) { return value; } -lbValue lb_get_type_info_ptr(lbProcedure *p, Type *type) { - i32 index = cast(i32)lb_type_info_index(p->module->info, type); +lbValue lb_get_type_info_ptr(lbModule *m, Type *type) { + i32 index = cast(i32)lb_type_info_index(m->info, type); + GB_ASSERT(index >= 0); // gb_printf_err("%d %s\n", index, type_to_string(type)); - lbValue ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, index); - return lb_emit_transmute(p, ptr, t_type_info_ptr); + + LLVMValueRef indices[2] = { + LLVMConstInt(lb_type(m, t_int), 0, false), + LLVMConstInt(lb_type(m, t_int), index, false), + }; + + lbValue res = {}; + res.type = t_type_info_ptr; + res.value = LLVMConstGEP(lb_global_type_info_data.addr.value, indices, cast(unsigned)gb_count_of(indices)); + return res; } @@ -9653,8 +9749,6 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da continue; } - // gb_printf_err("%s @ %td | %.*s\n", type_to_string(t), entry_index, LIT(type_strings[t->kind - lbValue tag = {}; lbValue ti_ptr = lb_emit_array_epi(p, lb_global_type_info_data.addr, cast(i32)entry_index); lbValue variant_ptr = lb_emit_struct_ep(p, ti_ptr, 3); @@ -9666,13 +9760,16 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da switch (t->kind) { case Type_Named: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_named_ptr); - - lbValue name = lb_const_string(p->module, t->Named.type_name->token.string); - lbValue gtip = lb_get_type_info_ptr(p, t->Named.base); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_named_ptr); + LLVMValueRef vals[2] = { + lb_const_string(p->module, t->Named.type_name->token.string).value, + lb_get_type_info_ptr(m, t->Named.base).value, + }; - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), name); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), gtip); + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); break; } @@ -9683,7 +9780,7 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da case Basic_b16: case Basic_b32: case Basic_b64: - tag = lb_emit_conv(p, variant_ptr, t_type_info_boolean_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_boolean_ptr); break; case Basic_i8: @@ -9717,9 +9814,9 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da case Basic_int: case Basic_uint: case Basic_uintptr: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_integer_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_integer_ptr); + lbValue is_signed = lb_const_bool(m, t_bool, (t->Basic.flags & BasicFlag_Unsigned) == 0); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), is_signed); // NOTE(bill): This is matches the runtime layout u8 endianness_value = 0; if (t->Basic.flags & BasicFlag_EndianLittle) { @@ -9728,89 +9825,122 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da endianness_value = 2; } lbValue endianness = lb_const_int(m, t_u8, endianness_value); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), endianness); + + LLVMValueRef vals[2] = { + is_signed.value, + endianness.value, + }; + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); break; } case Basic_rune: - tag = lb_emit_conv(p, variant_ptr, t_type_info_rune_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_rune_ptr); break; // case Basic_f16: case Basic_f32: case Basic_f64: - tag = lb_emit_conv(p, variant_ptr, t_type_info_float_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_float_ptr); break; // case Basic_complex32: case Basic_complex64: case Basic_complex128: - tag = lb_emit_conv(p, variant_ptr, t_type_info_complex_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_complex_ptr); break; case Basic_quaternion128: case Basic_quaternion256: - tag = lb_emit_conv(p, variant_ptr, t_type_info_quaternion_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_quaternion_ptr); break; case Basic_rawptr: - tag = lb_emit_conv(p, variant_ptr, t_type_info_pointer_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr); break; case Basic_string: - tag = lb_emit_conv(p, variant_ptr, t_type_info_string_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr); break; case Basic_cstring: - tag = lb_emit_conv(p, variant_ptr, t_type_info_string_ptr); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_const_bool(m, t_bool, true)); // is_cstring + { + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_string_ptr); + LLVMValueRef vals[1] = { + lb_const_bool(m, t_bool, true).value, + }; + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); + } break; case Basic_any: - tag = lb_emit_conv(p, variant_ptr, t_type_info_any_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_any_ptr); break; case Basic_typeid: - tag = lb_emit_conv(p, variant_ptr, t_type_info_typeid_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_typeid_ptr); break; } break; case Type_Pointer: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_pointer_ptr); - lbValue gep = lb_get_type_info_ptr(p, t->Pointer.elem); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_pointer_ptr); + lbValue gep = lb_get_type_info_ptr(m, t->Pointer.elem); + + LLVMValueRef vals[1] = { + gep.value, + }; + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); break; } case Type_Array: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_array_ptr); - lbValue gep = lb_get_type_info_ptr(p, t->Array.elem); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep); - + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_array_ptr); i64 ez = type_size_of(t->Array.elem); - lbValue elem_size = lb_emit_struct_ep(p, tag, 1); - lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez)); - lbValue count = lb_emit_struct_ep(p, tag, 2); - lb_emit_store(p, count, lb_const_int(m, t_int, t->Array.count)); + LLVMValueRef vals[3] = { + lb_get_type_info_ptr(m, t->Array.elem).value, + lb_const_int(m, t_int, ez).value, + lb_const_int(m, t_int, t->Array.count).value, + }; + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); break; } case Type_EnumeratedArray: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_enumerated_array_ptr); - lbValue elem = lb_get_type_info_ptr(p, t->EnumeratedArray.elem); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), elem); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enumerated_array_ptr); - lbValue index = lb_get_type_info_ptr(p, t->EnumeratedArray.index); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), index); + LLVMValueRef vals[6] = { + lb_get_type_info_ptr(m, t->EnumeratedArray.elem).value, + lb_get_type_info_ptr(m, t->EnumeratedArray.index).value, + lb_const_int(m, t_int, type_size_of(t->EnumeratedArray.elem)).value, + lb_const_int(m, t_int, t->EnumeratedArray.count).value, - i64 ez = type_size_of(t->EnumeratedArray.elem); - lbValue elem_size = lb_emit_struct_ep(p, tag, 2); - lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez)); + // Unions + LLVMConstNull(lb_type(m, t_type_info_enum_value)), + LLVMConstNull(lb_type(m, t_type_info_enum_value)), + }; - lbValue count = lb_emit_struct_ep(p, tag, 3); - lb_emit_store(p, count, lb_const_int(m, t_int, t->EnumeratedArray.count)); + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); + // NOTE(bill): Union assignment lbValue min_value = lb_emit_struct_ep(p, tag, 4); lbValue max_value = lb_emit_struct_ep(p, tag, 5); @@ -9822,51 +9952,66 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da break; } case Type_DynamicArray: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_dynamic_array_ptr); - lbValue gep = lb_get_type_info_ptr(p, t->DynamicArray.elem); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_dynamic_array_ptr); - i64 ez = type_size_of(t->DynamicArray.elem); - lbValue elem_size = lb_emit_struct_ep(p, tag, 1); - lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez)); + LLVMValueRef vals[2] = { + lb_get_type_info_ptr(m, t->DynamicArray.elem).value, + lb_const_int(m, t_int, type_size_of(t->DynamicArray.elem)).value, + }; + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); break; } case Type_Slice: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_slice_ptr); - lbValue gep = lb_get_type_info_ptr(p, t->Slice.elem); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), gep); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_slice_ptr); - i64 ez = type_size_of(t->Slice.elem); - lbValue elem_size = lb_emit_struct_ep(p, tag, 1); - lb_emit_store(p, elem_size, lb_const_int(m, t_int, ez)); + LLVMValueRef vals[2] = { + lb_get_type_info_ptr(m, t->Slice.elem).value, + lb_const_int(m, t_int, type_size_of(t->Slice.elem)).value, + }; + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); break; } case Type_Proc: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_procedure_ptr); - - lbValue params = lb_emit_struct_ep(p, tag, 0); - lbValue results = lb_emit_struct_ep(p, tag, 1); - lbValue variadic = lb_emit_struct_ep(p, tag, 2); - lbValue convention = lb_emit_struct_ep(p, tag, 3); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_procedure_ptr); + LLVMValueRef params = LLVMConstNull(lb_type(m, t_type_info_ptr)); + LLVMValueRef results = LLVMConstNull(lb_type(m, t_type_info_ptr)); if (t->Proc.params != nullptr) { - lb_emit_store(p, params, lb_get_type_info_ptr(p, t->Proc.params)); + params = lb_get_type_info_ptr(m, t->Proc.params).value; } if (t->Proc.results != nullptr) { - lb_emit_store(p, results, lb_get_type_info_ptr(p, t->Proc.results)); + results = lb_get_type_info_ptr(m, t->Proc.results).value; } - lb_emit_store(p, variadic, lb_const_bool(m, t_bool, t->Proc.variadic)); - lb_emit_store(p, convention, lb_const_int(m, t_u8, t->Proc.calling_convention)); - // TODO(bill): TypeInfo for procedures + LLVMValueRef vals[4] = { + params, + results, + lb_const_bool(m, t_bool, t->Proc.variadic).value, + lb_const_int(m, t_u8, t->Proc.calling_convention).value, + }; + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); break; } case Type_Tuple: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_tuple_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_tuple_ptr); + lbValue memory_types = lb_type_info_member_types_offset(p, t->Tuple.variables.count); lbValue memory_names = lb_type_info_member_names_offset(p, t->Tuple.variables.count); + for_array(i, t->Tuple.variables) { // NOTE(bill): offset is not used for tuples Entity *f = t->Tuple.variables[i]; @@ -9874,6 +10019,7 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da lbValue index = lb_const_int(m, t_int, i); lbValue type_info = lb_emit_ptr_offset(p, memory_types, index); + // TODO(bill): Make this constant if possible, 'lb_const_store' does not work lb_emit_store(p, type_info, lb_type_info(m, f->type)); if (f->token.string.len > 0) { lbValue name = lb_emit_ptr_offset(p, memory_names, index); @@ -9882,18 +10028,32 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da } lbValue count = lb_const_int(m, t_int, t->Tuple.variables.count); - lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 0)), memory_types, count); - lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 1)), memory_names, count); + + LLVMValueRef types_slice = llvm_const_slice(memory_types, count); + LLVMValueRef names_slice = llvm_const_slice(memory_names, count); + + LLVMValueRef vals[2] = { + types_slice, + names_slice, + }; + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); + break; } case Type_Enum: - tag = lb_emit_conv(p, variant_ptr, t_type_info_enum_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_enum_ptr); + { GB_ASSERT(t->Enum.base_type != nullptr); - lbValue base = lb_type_info(m, t->Enum.base_type); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), base); + + LLVMValueRef vals[3] = {}; + vals[0] = lb_type_info(m, t->Enum.base_type).value; if (t->Enum.fields.count > 0) { auto fields = t->Enum.fields; lbValue name_array = lb_generate_array(m, t_string, fields.count, @@ -9911,32 +10071,30 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da lbValue v = lb_const_value(m, t->Enum.base_type, value); lb_emit_store_union_variant(p, value_ep, v, v.type); - lb_emit_store(p, name_ep, lb_const_string(m, fields[i]->token.string)); + lb_const_store(name_ep, lb_const_string(m, fields[i]->token.string)); } lbValue v_count = lb_const_int(m, t_int, fields.count); - lbValue names = lb_emit_struct_ep(p, tag, 1); - lbValue name_array_elem = lb_array_elem(p, name_array); - lb_fill_slice(p, lb_addr(names), name_array_elem, v_count); - - lbValue values = lb_emit_struct_ep(p, tag, 2); - lbValue value_array_elem = lb_array_elem(p, value_array); - lb_fill_slice(p, lb_addr(values), value_array_elem, v_count); + vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count); + vals[2] = llvm_const_slice(lb_array_elem(p, value_array), v_count); + } else { + vals[1] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[1]->type)); + vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type)); } + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); } break; case Type_Union: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_union_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_union_ptr); { - lbValue variant_types = lb_emit_struct_ep(p, tag, 0); - lbValue tag_offset_ptr = lb_emit_struct_ep(p, tag, 1); - lbValue tag_type_ptr = lb_emit_struct_ep(p, tag, 2); - lbValue custom_align_ptr = lb_emit_struct_ep(p, tag, 3); - lbValue no_nil_ptr = lb_emit_struct_ep(p, tag, 4); - lbValue maybe_ptr = lb_emit_struct_ep(p, tag, 5); + LLVMValueRef vals[6] = {}; isize variant_count = gb_max(0, t->Union.variants.count); lbValue memory_types = lb_type_info_member_types_offset(p, variant_count); @@ -9944,7 +10102,7 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da // NOTE(bill): Zeroth is nil so ignore it for (isize variant_index = 0; variant_index < variant_count; variant_index++) { Type *vt = t->Union.variants[variant_index]; - lbValue tip = lb_get_type_info_ptr(p, vt); + lbValue tip = lb_get_type_info_ptr(m, vt); lbValue index = lb_const_int(m, t_int, variant_index); lbValue type_info = lb_emit_ptr_offset(p, memory_types, index); @@ -9952,36 +10110,46 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da } lbValue count = lb_const_int(m, t_int, variant_count); - lb_fill_slice(p, lb_addr(variant_types), memory_types, count); + vals[0] = llvm_const_slice(memory_types, count); i64 tag_size = union_tag_size(t); i64 tag_offset = align_formula(t->Union.variant_block_size, tag_size); if (tag_size > 0) { - lb_emit_store(p, tag_offset_ptr, lb_const_int(m, t_uintptr, tag_offset)); - lb_emit_store(p, tag_type_ptr, lb_type_info(m, union_tag_type(t))); + vals[1] = lb_const_int(m, t_uintptr, tag_offset).value; + vals[2] = lb_type_info(m, union_tag_type(t)).value; + } else { + vals[1] = lb_const_int(m, t_uintptr, 0).value; + vals[2] = LLVMConstNull(lb_type(m, t_type_info_ptr)); } - lbValue is_custom_align = lb_const_bool(m, t_bool, t->Union.custom_align != 0); - lb_emit_store(p, custom_align_ptr, is_custom_align); + vals[3] = lb_const_bool(m, t_bool, t->Union.custom_align != 0).value; + vals[4] = lb_const_bool(m, t_bool, t->Union.no_nil).value; + vals[5] = lb_const_bool(m, t_bool, t->Union.maybe).value; + - lb_emit_store(p, no_nil_ptr, lb_const_bool(m, t_bool, t->Union.no_nil)); - lb_emit_store(p, maybe_ptr, lb_const_bool(m, t_bool, t->Union.maybe)); + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); } break; } case Type_Struct: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_struct_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_struct_ptr); + + LLVMValueRef vals[11] = {}; + { lbValue is_packed = lb_const_bool(m, t_bool, t->Struct.is_packed); lbValue is_raw_union = lb_const_bool(m, t_bool, t->Struct.is_raw_union); lbValue is_custom_align = lb_const_bool(m, t_bool, t->Struct.custom_align != 0); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 5), is_packed); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 6), is_raw_union); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 7), is_custom_align); + vals[5] = is_packed.value; + vals[6] = is_raw_union.value; + vals[7] = is_custom_align.value; if (t->Struct.soa_kind != StructSoa_None) { lbValue kind = lb_emit_struct_ep(p, tag, 8); @@ -9991,10 +10159,9 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da lbValue soa_type = lb_type_info(m, t->Struct.soa_elem); lbValue soa_len = lb_const_int(m, t_int, t->Struct.soa_count); - - lb_emit_store(p, kind, soa_kind); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 9), soa_type); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 10), soa_len); + vals[8] = soa_kind.value; + vals[9] = soa_type.value; + vals[10] = soa_len.value; } } @@ -10010,7 +10177,7 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da for (isize source_index = 0; source_index < count; source_index++) { // TODO(bill): Order fields in source order not layout order Entity *f = t->Struct.fields[source_index]; - lbValue tip = lb_get_type_info_ptr(p, f->type); + lbValue tip = lb_get_type_info_ptr(m, f->type); i64 foffset = 0; if (!t->Struct.is_raw_union) { foffset = t->Struct.offsets[f->Variable.field_index]; @@ -10041,31 +10208,46 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da } lbValue cv = lb_const_int(m, t_int, count); - lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 0)), memory_types, cv); - lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 1)), memory_names, cv); - lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 2)), memory_offsets, cv); - lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 3)), memory_usings, cv); - lb_fill_slice(p, lb_addr(lb_emit_struct_ep(p, tag, 4)), memory_tags, cv); + vals[0] = llvm_const_slice(memory_types, cv); + vals[1] = llvm_const_slice(memory_names, cv); + vals[2] = llvm_const_slice(memory_offsets, cv); + vals[3] = llvm_const_slice(memory_usings, cv); + vals[4] = llvm_const_slice(memory_tags, cv); + } + for (isize i = 0; i < gb_count_of(vals); i++) { + if (vals[i] == nullptr) { + vals[i] = LLVMConstNull(lb_type(m, get_struct_field_type(tag.type, i))); + } } + + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); + break; } case Type_Map: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_map_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_map_ptr); init_map_internal_types(t); - lbValue key = lb_emit_struct_ep(p, tag, 0); - lbValue value = lb_emit_struct_ep(p, tag, 1); - lbValue generated_struct = lb_emit_struct_ep(p, tag, 2); + LLVMValueRef vals[3] = { + lb_get_type_info_ptr(m, t->Map.key).value, + lb_get_type_info_ptr(m, t->Map.value).value, + lb_get_type_info_ptr(m, t->Map.generated_struct_type).value, + }; - lb_emit_store(p, key, lb_get_type_info_ptr(p, t->Map.key)); - lb_emit_store(p, value, lb_get_type_info_ptr(p, t->Map.value)); - lb_emit_store(p, generated_struct, lb_get_type_info_ptr(p, t->Map.generated_struct_type)); + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); break; } case Type_BitField: { - tag = lb_emit_conv(p, variant_ptr, t_type_info_bit_field_ptr); + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_field_ptr); // names: []string; // bits: []u32; // offsets: []u32; @@ -10091,46 +10273,80 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da } lbValue v_count = lb_const_int(m, t_int, count); - - lbValue names = lb_emit_struct_ep(p, tag, 0); lbValue name_array_elem = lb_array_elem(p, name_array); - lb_fill_slice(p, lb_addr(names), name_array_elem, v_count); - - lbValue bits = lb_emit_struct_ep(p, tag, 1); lbValue bit_array_elem = lb_array_elem(p, bit_array); - lb_fill_slice(p, lb_addr(bits), bit_array_elem, v_count); - - lbValue offsets = lb_emit_struct_ep(p, tag, 2); lbValue offset_array_elem = lb_array_elem(p, offset_array); - lb_fill_slice(p, lb_addr(offsets), offset_array_elem, v_count); + + + LLVMValueRef vals[3] = { + llvm_const_slice(name_array_elem, v_count), + llvm_const_slice(bit_array_elem, v_count), + llvm_const_slice(offset_array_elem, v_count), + }; + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); } break; } case Type_BitSet: - tag = lb_emit_conv(p, variant_ptr, t_type_info_bit_set_ptr); + { + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_bit_set_ptr); + + GB_ASSERT(is_type_typed(t->BitSet.elem)); + + + LLVMValueRef vals[4] = { + lb_get_type_info_ptr(m, t->BitSet.elem).value, + LLVMConstNull(lb_type(m, t_type_info_ptr)), + lb_const_int(m, t_i64, t->BitSet.lower).value, + lb_const_int(m, t_i64, t->BitSet.upper).value, + }; + if (t->BitSet.underlying != nullptr) { + vals[1] =lb_get_type_info_ptr(m, t->BitSet.underlying).value; + } - GB_ASSERT(is_type_typed(t->BitSet.elem)); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->BitSet.elem)); - if (t->BitSet.underlying != nullptr) { - lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), lb_get_type_info_ptr(p, t->BitSet.underlying)); + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); } - lb_emit_store(p, lb_emit_struct_ep(p, tag, 2), lb_const_int(m, t_i64, t->BitSet.lower)); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 3), lb_const_int(m, t_i64, t->BitSet.upper)); break; case Type_Opaque: - tag = lb_emit_conv(p, variant_ptr, t_type_info_opaque_ptr); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->Opaque.elem)); + { + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_opaque_ptr); + LLVMValueRef vals[1] = { + lb_get_type_info_ptr(m, t->Opaque.elem).value, + }; + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); + } break; case Type_SimdVector: - tag = lb_emit_conv(p, variant_ptr, t_type_info_simd_vector_ptr); - if (t->SimdVector.is_x86_mmx) { - lb_emit_store(p, lb_emit_struct_ep(p, tag, 3), lb_const_bool(m, t_bool, true)); - } else { - lb_emit_store(p, lb_emit_struct_ep(p, tag, 0), lb_get_type_info_ptr(p, t->SimdVector.elem)); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 1), lb_const_int(m, t_int, type_size_of(t->SimdVector.elem))); - lb_emit_store(p, lb_emit_struct_ep(p, tag, 2), lb_const_int(m, t_int, t->SimdVector.count)); + { + tag = lb_const_ptr_cast(m, variant_ptr, t_type_info_simd_vector_ptr); + + LLVMValueRef vals[4] = {}; + + if (t->SimdVector.is_x86_mmx) { + vals[3] = lb_const_bool(m, t_bool, true).value; + } else { + vals[0] = lb_get_type_info_ptr(m, t->SimdVector.elem).value; + vals[1] = lb_const_int(m, t_int, type_size_of(t->SimdVector.elem)).value; + vals[2] = lb_const_int(m, t_int, t->SimdVector.count).value; + } + + lbValue res = {}; + res.type = type_deref(tag.type); + res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); + lb_emit_store(p, tag, res); } break; } @@ -10139,7 +10355,8 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da if (tag.value != nullptr) { Type *tag_type = type_deref(tag.type); GB_ASSERT(is_type_named(tag_type)); - lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type); + // lb_emit_store_union_variant(p, variant_ptr, lb_emit_load(p, tag), tag_type); + lb_emit_store_union_variant_tag(p, variant_ptr, tag_type); } else { if (t != t_llvm_bool) { GB_PANIC("Unhandled Type_Info variant: %s", type_to_string(t)); @@ -10152,7 +10369,7 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da void lb_generate_code(lbGenerator *gen) { #define TIME_SECTION(str) do { if (build_context.show_more_timings) timings_start_section(&global_timings, str_lit(str)); } while (0) - TIME_SECTION("LLVM Global Variables"); + TIME_SECTION("LLVM Initializtion"); lbModule *m = &gen->module; LLVMModuleRef mod = gen->module.mod; @@ -10167,7 +10384,6 @@ void lb_generate_code(lbGenerator *gen) { auto *min_dep_set = &info->minimum_dependency_set; - TIME_SECTION("LLVM Initializtion"); LLVMInitializeAllTargetInfos(); LLVMInitializeAllTargets(); @@ -10217,6 +10433,8 @@ void lb_generate_code(lbGenerator *gen) { ); } + TIME_SECTION("LLVM Global Variables"); + { { // Add type info data isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1; @@ -10489,6 +10707,16 @@ void lb_generate_code(lbGenerator *gen) { } lb_end_procedure(p); + // Add Flags + if (p->body != nullptr) { + if (p->name == "memcpy" || p->name == "memmove" || + p->name == "runtime.mem_copy" || p->name == "mem_copy_non_overlapping" || + string_starts_with(p->name, str_lit("llvm.memcpy")) || + string_starts_with(p->name, str_lit("llvm.memmove"))) { + p->flags |= lbProcedureFlag_WithoutMemcpyPass; + } + } + if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %.*s\n", LIT(p->name)); LLVMDumpValue(p->value); @@ -10501,24 +10729,42 @@ void lb_generate_code(lbGenerator *gen) { TIME_SECTION("LLVM Function Pass"); LLVMPassRegistryRef pass_registry = LLVMGetGlobalPassRegistry(); - LLVMPassManagerRef function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod); - defer (LLVMDisposePassManager(function_pass_manager)); - - LLVMAddMemCpyOptPass(function_pass_manager); - LLVMAddPromoteMemoryToRegisterPass(function_pass_manager); - LLVMAddMergedLoadStoreMotionPass(function_pass_manager); - // LLVMAddDeadStoreEliminationPass(function_pass_manager); - LLVMAddAggressiveInstCombinerPass(function_pass_manager); - LLVMAddConstantPropagationPass(function_pass_manager); - LLVMAddAggressiveDCEPass(function_pass_manager); - LLVMAddMergedLoadStoreMotionPass(function_pass_manager); - LLVMAddPromoteMemoryToRegisterPass(function_pass_manager); - // LLVMAddUnifyFunctionExitNodesPass(function_pass_manager); + + LLVMPassManagerRef default_function_pass_manager = LLVMCreateFunctionPassManagerForModule(mod); + defer (LLVMDisposePassManager(default_function_pass_manager)); + { + LLVMAddMemCpyOptPass(default_function_pass_manager); + LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager); + LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager); + LLVMAddAggressiveInstCombinerPass(default_function_pass_manager); + LLVMAddConstantPropagationPass(default_function_pass_manager); + LLVMAddAggressiveDCEPass(default_function_pass_manager); + LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager); + LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager); + // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager); + } + + LLVMPassManagerRef default_function_pass_manager_without_memcpy = LLVMCreateFunctionPassManagerForModule(mod); + defer (LLVMDisposePassManager(default_function_pass_manager_without_memcpy)); + { + LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy); + LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy); + LLVMAddAggressiveInstCombinerPass(default_function_pass_manager_without_memcpy); + LLVMAddConstantPropagationPass(default_function_pass_manager_without_memcpy); + LLVMAddAggressiveDCEPass(default_function_pass_manager_without_memcpy); + LLVMAddMergedLoadStoreMotionPass(default_function_pass_manager_without_memcpy); + LLVMAddPromoteMemoryToRegisterPass(default_function_pass_manager_without_memcpy); + // LLVMAddUnifyFunctionExitNodesPass(default_function_pass_manager_without_memcpy); + } for_array(i, m->procedures_to_generate) { lbProcedure *p = m->procedures_to_generate[i]; if (p->body != nullptr) { // Build Procedure - LLVMRunFunctionPassManager(function_pass_manager, p->value); + if (p->flags & lbProcedureFlag_WithoutMemcpyPass) { + LLVMRunFunctionPassManager(default_function_pass_manager_without_memcpy, p->value); + } else { + LLVMRunFunctionPassManager(default_function_pass_manager, p->value); + } } } @@ -10587,7 +10833,26 @@ void lb_generate_code(lbGenerator *gen) { LLVMVerifyFunction(p->value, LLVMAbortProcessAction); } - LLVMRunFunctionPassManager(function_pass_manager, p->value); + LLVMRunFunctionPassManager(default_function_pass_manager, p->value); + + /*{ + LLVMValueRef last_instr = LLVMGetLastInstruction(p->decl_block->block); + for (LLVMValueRef instr = LLVMGetFirstInstruction(p->decl_block->block); + instr != last_instr; + instr = LLVMGetNextInstruction(instr)) { + if (LLVMIsAAllocaInst(instr)) { + LLVMTypeRef type = LLVMGetAllocatedType(instr); + LLVMValueRef sz_val = LLVMSizeOf(type); + GB_ASSERT(LLVMIsConstant(sz_val)); + gb_printf_err(">> 0x%p\n", sz_val); + LLVMTypeRef sz_type = LLVMTypeOf(sz_val); + gb_printf_err(">> %s\n", LLVMPrintTypeToString(sz_type)); + unsigned long long sz = LLVMConstIntGetZExtValue(sz_val); + // long long sz = LLVMConstIntGetSExtValue(sz_val); + gb_printf_err(">> %ll\n", sz); + } + } + }*/ } if (!(build_context.is_dll && !has_dll_main)) { @@ -10623,7 +10888,7 @@ void lb_generate_code(lbGenerator *gen) { LLVMVerifyFunction(p->value, LLVMAbortProcessAction); } - LLVMRunFunctionPassManager(function_pass_manager, p->value); + LLVMRunFunctionPassManager(default_function_pass_manager, p->value); } diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index e7e805227..fb09042b5 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -164,8 +164,13 @@ struct lbTargetList { }; +enum lbProcedureFlag : u32 { + lbProcedureFlag_WithoutMemcpyPass = 1<<0, +}; struct lbProcedure { + u32 flags; + lbProcedure *parent; Array children; diff --git a/src/types.cpp b/src/types.cpp index 73023001a..6d880cdec 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -3190,6 +3190,14 @@ i64 type_offset_of_from_selection(Type *type, Selection sel) { return offset; } + +Type *get_struct_field_type(Type *t, isize index) { + t = base_type(type_deref(t)); + GB_ASSERT(t->kind == Type_Struct); + return t->Struct.fields[index]->type; +} + + gbString write_type_to_string(gbString str, Type *type) { if (type == nullptr) { return gb_string_appendc(str, ""); -- cgit v1.2.3 From fc0002ab674969fe3a3c8ea84787c8cd9a2c3606 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 19 Mar 2020 12:28:39 +0000 Subject: Fix enum type info generation --- src/check_expr.cpp | 12 +++++- src/checker.hpp | 2 + src/llvm_backend.cpp | 116 +++++++++++++++++++++++++++++++++++++++++++-------- src/llvm_backend.hpp | 4 +- 4 files changed, 114 insertions(+), 20 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/check_expr.cpp b/src/check_expr.cpp index ad3c27902..4ae7c5019 100644 --- a/src/check_expr.cpp +++ b/src/check_expr.cpp @@ -5667,7 +5667,7 @@ isize add_dependencies_from_unpacking(CheckerContext *c, Entity **lhs, isize lhs c->decl = decl; // will be reset by the 'defer' any way for_array(k, decl->deps.entries) { Entity *dep = decl->deps.entries[k].ptr; - add_declaration_dependency(c, dep); // TODO(bill): Should this be here? + add_declaration_dependency(c, dep); // TODO(bill): Should this be here? } } } @@ -7249,6 +7249,16 @@ ExprKind check_call_expr(CheckerContext *c, Operand *operand, Ast *call, Type *t } Type *pt = base_type(proc_type); + + #if 0 + if (pt->kind == Type_Proc && pt->Proc.calling_convention == ProcCC_Odin) { + init_core_context(c->checker); + GB_ASSERT(t_context != nullptr); + GB_ASSERT(t_context->kind == Type_Named); + add_declaration_dependency(c, t_context->Named.type_name); + } + #endif + if (result_type == nullptr) { operand->mode = Addressing_NoValue; } else { diff --git a/src/checker.hpp b/src/checker.hpp index 39ab94c70..bd36971df 100644 --- a/src/checker.hpp +++ b/src/checker.hpp @@ -382,3 +382,5 @@ void destroy_checker_poly_path(CheckerPolyPath *); void check_poly_path_push(CheckerContext *c, Type *t); Type *check_poly_path_pop (CheckerContext *c); + +void init_core_context(Checker *c); diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index b193423a1..1720b97bb 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -497,8 +497,8 @@ String lb_mangle_name(lbModule *m, Entity *e) { if ((e->scope->flags & (ScopeFlag_File | ScopeFlag_Pkg)) == 0) { require_suffix_id = true; - } else { - // require_suffix_id = true; + } else if (is_blank_ident(e->token)) { + require_suffix_id = true; } if (require_suffix_id) { @@ -958,7 +958,11 @@ LLVMTypeRef lb_type_internal(lbModule *m, Type *type) { fields[1] = lb_type(m, type->Union.variants[0]); } else { field_count += 2; - fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size); + if (block_size == align) { + fields[1] = LLVMIntTypeInContext(m->ctx, 8*block_size); + } else { + fields[1] = LLVMArrayType(lb_type(m, t_u8), block_size); + } fields[2] = lb_type(m, union_tag_type(type)); } @@ -3878,7 +3882,7 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { { HashKey key = hash_string(value.value_string); LLVMValueRef *found = map_get(&m->const_strings, key); - if (found != nullptr) { + if (found != nullptr && false) { LLVMValueRef ptr = *found; lbValue res = {}; res.type = default_type(original_type); @@ -5429,12 +5433,16 @@ lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) { return p->context_stack[p->context_stack.count-1].ctx; } - lbAddr c = lb_add_local_generated(p, t_context, false); - c.kind = lbAddr_Context; - lb_push_context_onto_stack(p, c); - lb_addr_store(p, c, lb_addr_load(p, p->module->global_default_context)); - lb_emit_init_context(p, c); - return c; + if (p->name == LB_STARTUP_RUNTIME_PROC_NAME) { + return p->module->global_default_context; + } else { + lbAddr c = lb_add_local_generated(p, t_context, false); + c.kind = lbAddr_Context; + lb_push_context_onto_stack(p, c); + lb_addr_store(p, c, lb_addr_load(p, p->module->global_default_context)); + lb_emit_init_context(p, c); + return c; + } } lbValue lb_address_from_load_or_generate_local(lbProcedure *p, lbValue value) { @@ -10050,6 +10058,7 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da { GB_ASSERT(t->Enum.base_type != nullptr); + GB_ASSERT(type_size_of(t_type_info_enum_value) == 16); LLVMValueRef vals[3] = {}; @@ -10061,19 +10070,39 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da lbValue value_array = lb_generate_array(m, t_type_info_enum_value, fields.count, str_lit("$enum_values"), cast(i64)entry_index); + + LLVMValueRef *name_values = gb_alloc_array(heap_allocator(), LLVMValueRef, fields.count); + LLVMValueRef *value_values = gb_alloc_array(heap_allocator(), LLVMValueRef, fields.count); + defer (gb_free(heap_allocator(), name_values)); + defer (gb_free(heap_allocator(), value_values)); + GB_ASSERT(is_type_integer(t->Enum.base_type)); - for_array(i, fields) { - lbValue name_ep = lb_emit_array_epi(p, name_array, i); - lbValue value_ep = lb_emit_array_epi(p, value_array, i); + LLVMTypeRef align_type = lb_alignment_prefix_type_hack(m, type_align_of(t)); + LLVMTypeRef array_type = LLVMArrayType(lb_type(m, t_u8), 8); + LLVMTypeRef u64_type = lb_type(m, t_u64); + for_array(i, fields) { ExactValue value = fields[i]->Constant.value; lbValue v = lb_const_value(m, t->Enum.base_type, value); + LLVMValueRef zv = LLVMConstZExt(v.value, u64_type); + lbValue tag = lb_const_union_tag(m, t_type_info_enum_value, v.type); - lb_emit_store_union_variant(p, value_ep, v, v.type); - lb_const_store(name_ep, lb_const_string(m, fields[i]->token.string)); + LLVMValueRef vals[3] = { + LLVMConstNull(align_type), + zv, + tag.value, + }; + + name_values[i] = lb_const_string(m, fields[i]->token.string).value; + value_values[i] = LLVMConstStruct(vals, gb_count_of(vals), false); } + LLVMValueRef name_init = LLVMConstArray(lb_type(m, t_string), name_values, cast(unsigned)fields.count); + LLVMValueRef value_init = LLVMConstArray(lb_type(m, t_type_info_enum_value), value_values, cast(unsigned)fields.count); + LLVMSetInitializer(name_array.value, name_init); + LLVMSetInitializer(value_array.value, value_init); + lbValue v_count = lb_const_int(m, t_int, fields.count); vals[1] = llvm_const_slice(lb_array_elem(p, name_array), v_count); @@ -10083,6 +10112,7 @@ void lb_setup_type_info_data(lbProcedure *p) { // NOTE(bill): Setup type_info da vals[2] = LLVMConstNull(lb_type(m, base_type(t_type_info_enum)->Struct.fields[2]->type)); } + lbValue res = {}; res.type = type_deref(tag.type); res.value = LLVMConstNamedStruct(lb_type(m, res.type), vals, gb_count_of(vals)); @@ -10438,6 +10468,7 @@ void lb_generate_code(lbGenerator *gen) { { { // Add type info data isize max_type_info_count = info->minimum_dependency_type_info_set.entries.count+1; + // 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); LLVMValueRef g = LLVMAddGlobal(mod, lb_type(m, t), LB_TYPE_INFO_DATA_NAME); LLVMSetInitializer(g, LLVMConstNull(lb_type(m, t))); @@ -10770,7 +10801,57 @@ void lb_generate_code(lbGenerator *gen) { TIME_SECTION("LLVM Runtime Creation"); + lbProcedure *startup_type_info = nullptr; + lbProcedure *startup_context = nullptr; lbProcedure *startup_runtime = nullptr; + { // Startup Type Info + Type *params = alloc_type_tuple(); + Type *results = alloc_type_tuple(); + + Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl); + + lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type); + startup_type_info = p; + + lb_begin_procedure_body(p); + + lb_setup_type_info_data(p); + + lb_end_procedure_body(p); + + if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { + gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main"); + LLVMDumpValue(p->value); + gb_printf_err("\n\n\n\n"); + LLVMVerifyFunction(p->value, LLVMAbortProcessAction); + } + + LLVMRunFunctionPassManager(default_function_pass_manager, p->value); + } + { // Startup Context + Type *params = alloc_type_tuple(); + Type *results = alloc_type_tuple(); + + Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl); + + lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_CONTEXT_PROC_NAME), proc_type); + startup_context = p; + + lb_begin_procedure_body(p); + + lb_emit_init_context(p, p->module->global_default_context); + + lb_end_procedure_body(p); + + if (LLVMVerifyFunction(p->value, LLVMReturnStatusAction)) { + gb_printf_err("LLVM CODE GEN FAILED FOR PROCEDURE: %s\n", "main"); + LLVMDumpValue(p->value); + gb_printf_err("\n\n\n\n"); + LLVMVerifyFunction(p->value, LLVMAbortProcessAction); + } + + LLVMRunFunctionPassManager(default_function_pass_manager, p->value); + } { // Startup Runtime Type *params = alloc_type_tuple(); Type *results = alloc_type_tuple(); @@ -10782,8 +10863,6 @@ void lb_generate_code(lbGenerator *gen) { lb_begin_procedure_body(p); - lb_setup_type_info_data(p); - for_array(i, global_variables) { auto *var = &global_variables[i]; if (var->decl->init_expr != nullptr) { @@ -10822,7 +10901,6 @@ void lb_generate_code(lbGenerator *gen) { } } - lb_emit_init_context(p, p->module->global_default_context); lb_end_procedure_body(p); @@ -10875,6 +10953,8 @@ void lb_generate_code(lbGenerator *gen) { lbValue *found = map_get(&m->values, hash_entity(entry_point)); GB_ASSERT(found != nullptr); + LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_type_info->type)), startup_type_info->value, nullptr, 0, ""); + LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_context->type)), startup_context->value, nullptr, 0, ""); LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, startup_runtime->type)), startup_runtime->value, nullptr, 0, ""); LLVMBuildCall2(p->builder, LLVMGetElementType(lb_type(m, found->type)), found->value, nullptr, 0, ""); LLVMBuildRet(p->builder, LLVMConstInt(lb_type(m, t_i32), 0, false)); diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index fb09042b5..d8c4da5fa 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -330,7 +330,9 @@ lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type); void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, lbValue map_key, lbValue map_value); -#define LB_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime" +#define LB_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime" +#define LB_STARTUP_CONTEXT_PROC_NAME "__$startup_context" +#define LB_STARTUP_TYPE_INFO_PROC_NAME "__$startup_type_info" #define LB_TYPE_INFO_DATA_NAME "__$type_info_data" #define LB_TYPE_INFO_TYPES_NAME "__$type_info_types_data" #define LB_TYPE_INFO_NAMES_NAME "__$type_info_names_data" -- cgit v1.2.3 From 93955a0fd8b8387b08a314649b8b705bdfc8c9d2 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 19 Mar 2020 15:03:02 +0000 Subject: Remove `context.std*` parameters; Fix unary boolean not --- core/fmt/fmt.odin | 12 ++-- core/os/os_windows.odin | 2 +- core/runtime/core.odin | 14 ++-- examples/demo/demo.odin | 97 +++++++++++++++++-------- src/llvm_backend.cpp | 186 ++++++++++++++++++------------------------------ 5 files changed, 152 insertions(+), 159 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/core/fmt/fmt.odin b/core/fmt/fmt.odin index b9bb1ee2c..372002e8f 100644 --- a/core/fmt/fmt.odin +++ b/core/fmt/fmt.odin @@ -59,13 +59,13 @@ fprintf :: proc(fd: os.Handle, fmt: string, args: ..any) -> int { // print* procedures return the number of bytes written -print :: proc(args: ..any) -> int { return fprint(context.stdout, ..args); } -println :: proc(args: ..any) -> int { return fprintln(context.stdout, ..args); } -printf :: proc(fmt: string, args: ..any) -> int { return fprintf(context.stdout, fmt, ..args); } +print :: proc(args: ..any) -> int { return fprint(os.stdout, ..args); } +println :: proc(args: ..any) -> int { return fprintln(os.stdout, ..args); } +printf :: proc(fmt: string, args: ..any) -> int { return fprintf(os.stdout, fmt, ..args); } -eprint :: proc(args: ..any) -> int { return fprint(context.stderr, ..args); } -eprintln :: proc(args: ..any) -> int { return fprintln(context.stderr, ..args); } -eprintf :: proc(fmt: string, args: ..any) -> int { return fprintf(context.stderr, fmt, ..args); } +eprint :: proc(args: ..any) -> int { return fprint(os.stderr, ..args); } +eprintln :: proc(args: ..any) -> int { return fprintln(os.stderr, ..args); } +eprintf :: proc(fmt: string, args: ..any) -> int { return fprintf(os.stderr, fmt, ..args); } @(deprecated="prefer eprint") print_err :: proc(args: ..any) -> int { return eprint(..args); } diff --git a/core/os/os_windows.odin b/core/os/os_windows.odin index 0b1a53955..4eb9a3ec8 100644 --- a/core/os/os_windows.odin +++ b/core/os/os_windows.odin @@ -201,7 +201,7 @@ stdout := get_std_handle(win32.STD_OUTPUT_HANDLE); stderr := get_std_handle(win32.STD_ERROR_HANDLE); -get_std_handle :: proc(h: int) -> Handle { +get_std_handle :: proc "contextless" (h: int) -> Handle { fd := win32.get_std_handle(i32(h)); win32.set_handle_information(fd, win32.HANDLE_FLAG_INHERIT, 0); return Handle(fd); diff --git a/core/runtime/core.odin b/core/runtime/core.odin index 87af6b7bb..13b3ef008 100644 --- a/core/runtime/core.odin +++ b/core/runtime/core.odin @@ -288,9 +288,9 @@ Context :: struct { assertion_failure_proc: Assertion_Failure_Proc, logger: Logger, - stdin: os.Handle, - stdout: os.Handle, - stderr: os.Handle, + // stdin: os.Handle, + // stdout: os.Handle, + // stderr: os.Handle, thread_id: int, @@ -463,9 +463,9 @@ __init_context :: proc "contextless" (c: ^Context) { c.logger.procedure = default_logger_proc; c.logger.data = nil; - c.stdin = os.stdin; - c.stdout = os.stdout; - c.stderr = os.stderr; + // c.stdin = os.stdin; + // c.stdout = os.stdout; + // c.stderr = os.stderr; } @builtin @@ -474,7 +474,7 @@ init_global_temporary_allocator :: proc(data: []byte, backup_allocator := contex } default_assertion_failure_proc :: proc(prefix, message: string, loc: Source_Code_Location) { - fd := context.stderr; + fd := os.stderr; print_caller_location(fd, loc); os.write_string(fd, " "); os.write_string(fd, prefix); diff --git a/examples/demo/demo.odin b/examples/demo/demo.odin index 4ef9b2a8c..4438229bf 100644 --- a/examples/demo/demo.odin +++ b/examples/demo/demo.odin @@ -1931,35 +1931,74 @@ union_maybe :: proc() { fmt.println(z, z_ok); } +icons_texture_data_size := [2]int{0 = 512, 1 = 256}; + + main :: proc() { - when true { - the_basics(); - control_flow(); - named_proc_return_parameters(); - explicit_procedure_overloading(); - struct_type(); - union_type(); - using_statement(); - implicit_context_system(); - parametric_polymorphism(); - array_programming(); - map_type(); - implicit_selector_expression(); - partial_switch(); - cstring_example(); - bit_set_type(); - deferred_procedure_associations(); - reflection(); - quaternions(); - inline_for_statement(); - where_clauses(); - foreign_system(); - ranged_fields_for_array_compound_literals(); - deprecated_attribute(); - range_statements_with_multiple_return_values(); - threading_example(); - soa_struct_layout(); - constant_literal_expressions(); - union_maybe(); + // cache size + Nx := 512; + Ny := 128; + Nz := 0; + is_array := false; + + // detect target based on input size + switch { + case Nz > 0 && !is_array: fmt.println("1"); + case Nz > 0 && is_array: fmt.println("2"); + case Ny > 0 && !is_array: fmt.println("3"); + case Ny > 0 && is_array: fmt.println("4"); + case: fmt.println("5"); + } + + // fmt.println("(Nz > 0 && !is_array) ==", Nz > 0 && !is_array); + // fmt.println("(Nz > 0 && is_array) ==", Nz > 0 && is_array); + // fmt.println("(Ny > 0 && !is_array) ==", Ny > 0 && !is_array); + // fmt.println("(Ny > 0 && is_array) ==", Ny > 0 && is_array); + + c0 := (Nz > 0) && !is_array; + c1 := (Nz > 0) && is_array; + c2 := (Ny > 0) && !is_array; + c3 := (Ny > 0) && is_array; + assert(c0 == false); + assert(c1 == false); + assert(c2 == true); + assert(c3 == false); + // switch { + // case c0: fmt.println("1"); + // case c1: fmt.println("2"); + // case c2: fmt.println("3"); + // case c3: fmt.println("4"); + // case: fmt.println("5"); + // } + + when false { + // the_basics(); + // control_flow(); + // named_proc_return_parameters(); + // explicit_procedure_overloading(); + // struct_type(); + // union_type(); + // using_statement(); + // implicit_context_system(); + // parametric_polymorphism(); + // array_programming(); + // map_type(); + // implicit_selector_expression(); + // partial_switch(); + // cstring_example(); + // bit_set_type(); + // deferred_procedure_associations(); + // reflection(); + // quaternions(); + // inline_for_statement(); + // where_clauses(); + // foreign_system(); + // ranged_fields_for_array_compound_literals(); + // deprecated_attribute(); + // range_statements_with_multiple_return_values(); + // threading_example(); + // soa_struct_layout(); + // constant_literal_expressions(); + // union_maybe(); } } diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 1720b97bb..a5c148bfd 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -2735,29 +2735,20 @@ void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) { lbBlock *default_block = nullptr; lbBlock *fall = nullptr; - bool append_fall = false; isize case_count = body->stmts.count; for_array(i, body->stmts) { Ast *clause = body->stmts[i]; - lbBlock *body = fall; - ast_node(cc, CaseClause, clause); + lbBlock *body = fall; + if (body == nullptr) { - if (cc->list.count == 0) { - body = lb_create_block(p, "switch.dflt.body"); - } else { - body = lb_create_block(p, "switch.case.body"); - } - } - if (append_fall && body == fall) { - append_fall = false; + body = lb_create_block(p, "switch.case.body"); } fall = done; if (i+1 < case_count) { - append_fall = true; fall = lb_create_block(p, "switch.fall.body"); } @@ -2773,6 +2764,7 @@ void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) { for_array(j, cc->list) { Ast *expr = unparen_expr(cc->list[j]); next_cond = lb_create_block(p, "switch.case.next"); + lbValue cond = lb_const_bool(p->module, t_llvm_bool, false); if (is_ast_range(expr)) { ast_node(ie, BinaryExpr, expr); @@ -3583,19 +3575,11 @@ lbValue lb_emit_clamp(lbProcedure *p, Type *t, lbValue x, lbValue min, lbValue m - -lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) { +LLVMValueRef lb_find_or_add_entity_string_ptr(lbModule *m, String const &str) { HashKey key = hash_string(str); LLVMValueRef *found = map_get(&m->const_strings, key); if (found != nullptr) { - LLVMValueRef ptr = *found; - LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true); - LLVMValueRef values[2] = {ptr, str_len}; - - lbValue res = {}; - res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2); - res.type = t_string; - return res; + return *found; } else { LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)}; LLVMValueRef data = LLVMConstStringInContext(m->ctx, @@ -3614,62 +3598,49 @@ lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) { LLVMSetInitializer(global_data, data); LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); - - LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true); - LLVMValueRef values[2] = {ptr, str_len}; - - lbValue res = {}; - res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2); - res.type = t_string; - map_set(&m->const_strings, key, ptr); - - return res; + return ptr; } } -lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) { - HashKey key = hash_string(str); - LLVMValueRef *found = map_get(&m->const_strings, key); - if (found != nullptr) { - LLVMValueRef ptr = *found; - LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true); - LLVMValueRef values[2] = {ptr, len}; +lbValue lb_find_or_add_entity_string(lbModule *m, String const &str) { + LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, str); + LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true); + LLVMValueRef values[2] = {ptr, str_len}; - lbValue res = {}; - res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2); - res.type = t_u8_slice; - return res; - } else { - LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)}; - LLVMValueRef data = LLVMConstStringInContext(m->ctx, - cast(char const *)str.text, - cast(unsigned)str.len, - false); + lbValue res = {}; + res.value = LLVMConstNamedStruct(lb_type(m, t_string), values, 2); + res.type = t_string; + return res; +} + +lbValue lb_find_or_add_entity_string_byte_slice(lbModule *m, String const &str) { + LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)}; + LLVMValueRef data = LLVMConstStringInContext(m->ctx, + cast(char const *)str.text, + cast(unsigned)str.len, + false); + char *name = nullptr; + { isize max_len = 7+8+1; - char *name = gb_alloc_array(heap_allocator(), char, max_len); + name = gb_alloc_array(heap_allocator(), char, max_len); isize len = gb_snprintf(name, max_len, "csbs$%x", m->global_array_index); len -= 1; m->global_array_index++; + } + LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name); + LLVMSetInitializer(global_data, data); - LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), name); - LLVMSetInitializer(global_data, data); - - LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); - - LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), str.len, true); - LLVMValueRef values[2] = {ptr, str_len}; - - lbValue res = {}; - res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2); - res.type = t_u8_slice; - - map_set(&m->const_strings, key, ptr); + LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); + LLVMValueRef len = LLVMConstInt(lb_type(m, t_int), str.len, true); + LLVMValueRef values[2] = {ptr, len}; - return res; - } + lbValue res = {}; + res.value = LLVMConstNamedStruct(lb_type(m, t_u8_slice), values, 2); + res.type = t_u8_slice; + return res; } isize lb_type_info_index(CheckerInfo *info, Type *type, bool err_on_not_found=true) { @@ -3880,54 +3851,17 @@ lbValue lb_const_value(lbModule *m, Type *type, ExactValue value) { return res; case ExactValue_String: { - HashKey key = hash_string(value.value_string); - LLVMValueRef *found = map_get(&m->const_strings, key); - if (found != nullptr && false) { - LLVMValueRef ptr = *found; - lbValue res = {}; - res.type = default_type(original_type); - if (is_type_cstring(res.type)) { - res.value = ptr; - } else { - LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true); - LLVMValueRef values[2] = {ptr, str_len}; - - res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); - } - - return res; - } - - LLVMValueRef indices[2] = {llvm_zero32(m), llvm_zero32(m)}; - LLVMValueRef data = LLVMConstStringInContext(ctx, - cast(char const *)value.value_string.text, - cast(unsigned)value.value_string.len, - false); - - - isize max_len = 7+8+1; - char *str = gb_alloc_array(heap_allocator(), char, max_len); - isize len = gb_snprintf(str, max_len, "csbs$%x", m->global_array_index); - len -= 1; - m->global_array_index++; - - LLVMValueRef global_data = LLVMAddGlobal(m->mod, LLVMTypeOf(data), str); - LLVMSetInitializer(global_data, data); - - LLVMValueRef ptr = LLVMConstInBoundsGEP(global_data, indices, 2); - - if (is_type_cstring(type)) { - res.value = ptr; - return res; - } - - LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true); - LLVMValueRef values[2] = {ptr, str_len}; - - res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); + LLVMValueRef ptr = lb_find_or_add_entity_string_ptr(m, value.value_string); + lbValue res = {}; res.type = default_type(original_type); + if (is_type_cstring(res.type)) { + res.value = ptr; + } else { + LLVMValueRef str_len = LLVMConstInt(lb_type(m, t_int), value.value_string.len, true); + LLVMValueRef values[2] = {ptr, str_len}; - map_set(&m->const_strings, key, ptr); + res.value = LLVMConstNamedStruct(lb_type(m, original_type), values, 2); + } return res; } @@ -4413,13 +4347,21 @@ lbValue lb_emit_unary_arith(lbProcedure *p, TokenKind op, lbValue x, Type *type) } - if (op == Token_Not) { + if (op == Token_Xor) { lbValue cmp = {}; cmp.value = LLVMBuildNot(p->builder, x.value, ""); cmp.type = x.type; return lb_emit_conv(p, cmp, type); } + if (op == Token_Not) { + lbValue cmp = {}; + LLVMValueRef zero = LLVMConstInt(lb_type(p->module, x.type), 0, false); + cmp.value = LLVMBuildICmp(p->builder, LLVMIntEQ, x.value, zero, ""); + cmp.type = t_llvm_bool; + return lb_emit_conv(p, cmp, type); + } + if (op == Token_Sub && is_type_integer(type) && is_type_different_to_arch_endianness(type)) { Type *platform_type = integer_endian_type_to_platform_type(type); lbValue v = lb_emit_byte_swap(p, x, platform_type); @@ -5433,7 +5375,9 @@ lbAddr lb_find_or_generate_context_ptr(lbProcedure *p) { return p->context_stack[p->context_stack.count-1].ctx; } - if (p->name == LB_STARTUP_RUNTIME_PROC_NAME) { + Type *pt = base_type(p->type); + GB_ASSERT(pt->kind == Type_Proc); + if (pt->Proc.calling_convention != ProcCC_Odin) { return p->module->global_default_context; } else { lbAddr c = lb_add_local_generated(p, t_context, false); @@ -6041,10 +5985,11 @@ lbValue lb_emit_array_ep(lbProcedure *p, lbValue s, lbValue index) { GB_ASSERT(is_type_pointer(t)); Type *st = base_type(type_deref(t)); GB_ASSERT_MSG(is_type_array(st) || is_type_enumerated_array(st), "%s", type_to_string(st)); + GB_ASSERT_MSG(is_type_integer(index.type), "%s", type_to_string(index.type)); LLVMValueRef indices[2] = {}; indices[0] = llvm_zero32(p->module); - indices[1] = lb_emit_conv(p, index, t_i32).value; + indices[1] = lb_emit_conv(p, index, t_int).value; Type *ptr = base_array_type(st); lbValue res = {}; @@ -7218,13 +7163,21 @@ String lb_get_const_string(lbModule *m, lbValue value) { Type *t = base_type(value.type); GB_ASSERT(are_types_identical(t, t_string)); + + unsigned ptr_indices[1] = {0}; unsigned len_indices[1] = {1}; LLVMValueRef underlying_ptr = LLVMConstExtractValue(value.value, ptr_indices, gb_count_of(ptr_indices)); LLVMValueRef underlying_len = LLVMConstExtractValue(value.value, len_indices, gb_count_of(len_indices)); + GB_ASSERT(LLVMGetConstOpcode(underlying_ptr) == LLVMGetElementPtr); + underlying_ptr = LLVMGetOperand(underlying_ptr, 0); + GB_ASSERT(LLVMIsAGlobalVariable(underlying_ptr)); + underlying_ptr = LLVMGetInitializer(underlying_ptr); + size_t length = 0; char const *text = LLVMGetAsString(underlying_ptr, &length); + isize real_length = cast(isize)LLVMConstIntGetSExtValue(underlying_len); return make_string(cast(u8 const *)text, real_length); @@ -11000,6 +10953,7 @@ void lb_generate_code(lbGenerator *gen) { if (build_context.keep_temp_files) { TIME_SECTION("LLVM Print Module to File"); LLVMPrintModuleToFile(mod, cast(char const *)filepath_ll.text, &llvm_error); + // exit(1); } LLVMDIBuilderFinalize(m->debug_builder); LLVMVerifyModule(mod, LLVMAbortProcessAction, &llvm_error); @@ -11007,8 +10961,8 @@ void lb_generate_code(lbGenerator *gen) { TIME_SECTION("LLVM Object Generation"); - LLVMBool ok = LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, LLVMObjectFile, &llvm_error); - if (ok) { + LLVMBool was_an_error = LLVMTargetMachineEmitToFile(target_machine, mod, cast(char *)filepath_obj.text, LLVMObjectFile, &llvm_error); + if (was_an_error) { gb_printf_err("LLVM Error: %s\n", llvm_error); gb_exit(1); return; -- cgit v1.2.3 From 53c842e9ba1875c25dd04e90079c6ddfe8051b32 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 24 Mar 2020 14:43:28 +0000 Subject: Change to new by-reference semantics for `switch v in &value` --- src/llvm_backend.cpp | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index a5c148bfd..454c51f8c 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -2823,8 +2823,16 @@ void lb_build_switch_stmt(lbProcedure *p, AstSwitchStmt *ss) { void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) { Entity *e = implicit_entity_of_node(clause); GB_ASSERT(e != nullptr); - lbAddr x = lb_add_local(p, e->type, e, false); - lb_addr_store(p, x, value); + if (e->flags & EntityFlag_Value) { + // by value + GB_ASSERT(are_types_identical(e->type, value.type)); + lbAddr x = lb_add_local(p, e->type, e, false); + lb_addr_store(p, x, value); + } else { + // by reference + GB_ASSERT(are_types_identical(e->type, type_deref(value.type))); + lb_add_entity(p->module, e, value); + } } void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) { @@ -2917,15 +2925,9 @@ void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) { lb_start_block(p, body); - // bool any_or_not_ptr = is_type_any(type_deref(parent.type)) || !is_parent_ptr; - bool any_or_not_ptr = !is_parent_ptr; - if (cc->list.count == 1) { + bool by_reference = (case_entity->flags & EntityFlag_Value) == 0; - Type *ct = case_entity->type; - if (any_or_not_ptr) { - ct = alloc_type_pointer(ct); - } - GB_ASSERT_MSG(is_type_pointer(ct), "%s", type_to_string(ct)); + if (cc->list.count == 1) { lbValue data = {}; if (switch_kind == TypeSwitch_Union) { data = union_data; @@ -2933,8 +2935,12 @@ void lb_build_type_switch_stmt(lbProcedure *p, AstTypeSwitchStmt *ss) { lbValue any_data = lb_emit_load(p, lb_emit_struct_ep(p, parent_ptr, 0)); data = any_data; } - value = lb_emit_conv(p, data, ct); - if (any_or_not_ptr) { + + Type *ct = case_entity->type; + Type *ct_ptr = alloc_type_pointer(ct); + + value = lb_emit_conv(p, data, ct_ptr); + if (!by_reference) { value = lb_emit_load(p, value); } } -- cgit v1.2.3 From 796331fea64a795b3764d61c840e8a55befec8fc Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 24 Mar 2020 15:33:34 +0000 Subject: Support by-reference semantics in `for value_ref, i in &some_array` and `for key, value_ref in &some_map` --- src/llvm_backend.cpp | 33 ++++++++++++++++++++++++--------- src/llvm_backend.hpp | 4 ++++ 2 files changed, 28 insertions(+), 9 deletions(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 454c51f8c..2e36a9b99 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -2526,17 +2526,12 @@ void lb_build_range_stmt(lbProcedure *p, AstRangeStmt *rs) { } - lbAddr val0_addr = {}; - lbAddr val1_addr = {}; - if (val0_type) val0_addr = lb_build_addr(p, rs->val0); - if (val1_type) val1_addr = lb_build_addr(p, rs->val1); - if (is_map) { - if (val0_type) lb_addr_store(p, val0_addr, key); - if (val1_type) lb_addr_store(p, val1_addr, val); + if (val0_type) lb_store_range_stmt_val(p, rs->val0, key); + if (val1_type) lb_store_range_stmt_val(p, rs->val1, val); } else { - if (val0_type) lb_addr_store(p, val0_addr, val); - if (val1_type) lb_addr_store(p, val1_addr, key); + if (val0_type) lb_store_range_stmt_val(p, rs->val0, val); + if (val1_type) lb_store_range_stmt_val(p, rs->val1, key); } lb_push_target_list(p, rs->label, done, loop, nullptr); @@ -2835,6 +2830,26 @@ void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value) { } } +lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value) { + Entity *e = entity_of_node(stmt_val); + if (e == nullptr) { + return {}; + } + + if ((e->flags & EntityFlag_Value) == 0) { + if (LLVMIsALoadInst(value.value)) { + lbValue ptr = lb_address_from_load_or_generate_local(p, value); + lb_add_entity(p->module, e, ptr); + return lb_addr(ptr); + } + } + + // by value + lbAddr addr = lb_add_local(p, e->type, e, false); + lb_addr_store(p, addr, value); + return addr; +} + void lb_type_case_body(lbProcedure *p, Ast *label, Ast *clause, lbBlock *body, lbBlock *done) { ast_node(cc, CaseClause, clause); diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index d8c4da5fa..3ff66f665 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -330,6 +330,10 @@ lbValue lb_gen_map_key(lbProcedure *p, lbValue key, Type *key_type); void lb_insert_dynamic_map_key_and_value(lbProcedure *p, lbAddr addr, Type *map_type, lbValue map_key, lbValue map_value); +void lb_store_type_case_implicit(lbProcedure *p, Ast *clause, lbValue value); +lbAddr lb_store_range_stmt_val(lbProcedure *p, Ast *stmt_val, lbValue value); + + #define LB_STARTUP_RUNTIME_PROC_NAME "__$startup_runtime" #define LB_STARTUP_CONTEXT_PROC_NAME "__$startup_context" #define LB_STARTUP_TYPE_INFO_PROC_NAME "__$startup_type_info" -- cgit v1.2.3 From b7893082ce138f5670d52b6c267d0a6599694166 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Tue, 24 Mar 2020 15:51:17 +0000 Subject: Allow map indices to be referenced `&m[key]` and return a valid pointer if it exists otherwise `nil` --- src/llvm_backend.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 2e36a9b99..47c55f769 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -107,7 +107,19 @@ lbValue lb_addr_get_ptr(lbProcedure *p, lbAddr const &addr) { } switch (addr.kind) { - case lbAddr_Map: + case lbAddr_Map: { + Type *map_type = base_type(addr.map.type); + lbValue h = lb_gen_map_header(p, addr.addr, map_type); + lbValue key = lb_gen_map_key(p, addr.map.key, map_type->Map.key); + + auto args = array_make(heap_allocator(), 2); + args[0] = h; + args[1] = key; + + lbValue ptr = lb_emit_runtime_call(p, "__dynamic_map_get", args); + + return lb_emit_conv(p, ptr, alloc_type_pointer(map_type->Map.value)); + } case lbAddr_BitField: { lbValue v = lb_addr_load(p, addr); return lb_address_from_load_or_generate_local(p, v); -- cgit v1.2.3 From b21993a1c470a533a83e5b01274d3b026fb34f9b Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 26 Mar 2020 17:33:54 +0000 Subject: Allow ability to reference compound literals like C99 for -llvm-api --- src/llvm_backend.cpp | 19 ++++++++++++++++++- src/llvm_backend.hpp | 1 + 2 files changed, 19 insertions(+), 1 deletion(-) (limited to 'src/llvm_backend.cpp') diff --git a/src/llvm_backend.cpp b/src/llvm_backend.cpp index 47c55f769..520eff313 100644 --- a/src/llvm_backend.cpp +++ b/src/llvm_backend.cpp @@ -8145,7 +8145,20 @@ lbValue lb_build_expr(lbProcedure *p, Ast *expr) { switch (ue->op.kind) { case Token_And: { Ast *ue_expr = unparen_expr(ue->expr); - if (ue_expr->kind == Ast_TypeAssertion) { + if (ue_expr->kind == Ast_CompoundLit) { + lbValue v = lb_build_expr(p, ue->expr); + + Type *type = v.type; + lbAddr addr = {}; + if (p->is_startup) { + addr = lb_add_global_generated(p->module, type, v); + } else { + addr = lb_add_local_generated(p, type, false); + } + lb_addr_store(p, addr, v); + return addr.addr; + + } else if (ue_expr->kind == Ast_TypeAssertion) { gbAllocator a = heap_allocator(); GB_ASSERT(is_type_pointer(tv.type)); @@ -10797,6 +10810,7 @@ void lb_generate_code(lbGenerator *gen) { Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl); lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_TYPE_INFO_PROC_NAME), proc_type); + p->is_startup = true; startup_type_info = p; lb_begin_procedure_body(p); @@ -10821,6 +10835,7 @@ void lb_generate_code(lbGenerator *gen) { Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl); lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_CONTEXT_PROC_NAME), proc_type); + p->is_startup = true; startup_context = p; lb_begin_procedure_body(p); @@ -10845,6 +10860,7 @@ void lb_generate_code(lbGenerator *gen) { Type *proc_type = alloc_type_proc(nullptr, nullptr, 0, nullptr, 0, false, ProcCC_CDecl); lbProcedure *p = lb_create_dummy_procedure(m, str_lit(LB_STARTUP_RUNTIME_PROC_NAME), proc_type); + p->is_startup = true; startup_runtime = p; lb_begin_procedure_body(p); @@ -10933,6 +10949,7 @@ void lb_generate_code(lbGenerator *gen) { Type *proc_type = alloc_type_proc(nullptr, params, 2, results, 1, false, ProcCC_CDecl); lbProcedure *p = lb_create_dummy_procedure(m, str_lit("main"), proc_type); + p->is_startup = true; lb_begin_procedure_body(p); diff --git a/src/llvm_backend.hpp b/src/llvm_backend.hpp index 3ff66f665..02284b064 100644 --- a/src/llvm_backend.hpp +++ b/src/llvm_backend.hpp @@ -185,6 +185,7 @@ struct lbProcedure { bool is_foreign; bool is_export; bool is_entry_point; + bool is_startup; LLVMValueRef value; -- cgit v1.2.3