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/parser.hpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'src/parser.hpp') 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, }; -- 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/parser.hpp') 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 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/parser.hpp') 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