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/main.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index 317e8f577..95bc52d63 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -17,11 +17,15 @@ gb_global Timings global_timings = {0}; #include "parser.cpp" #include "docs.cpp" #include "checker.cpp" + +#include "llvm_backend.cpp" + #include "ir.cpp" #include "ir_opt.cpp" #include "ir_print.cpp" #include "query_data.cpp" + #if defined(GB_SYSTEM_WINDOWS) // NOTE(IC): In order to find Visual C++ paths without relying on environment variables. #include "microsoft_craziness.h" @@ -234,6 +238,7 @@ enum BuildFlagKind { BuildFlag_NoCRT, BuildFlag_UseLLD, BuildFlag_Vet, + BuildFlag_UseLLVMApi, BuildFlag_IgnoreUnknownAttributes, BuildFlag_Compact, @@ -324,6 +329,7 @@ bool parse_build_flags(Array args) { add_flag(&build_flags, BuildFlag_NoCRT, str_lit("no-crt"), BuildFlagParam_None); add_flag(&build_flags, BuildFlag_UseLLD, str_lit("lld"), BuildFlagParam_None); add_flag(&build_flags, BuildFlag_Vet, str_lit("vet"), BuildFlagParam_None); + add_flag(&build_flags, BuildFlag_UseLLVMApi, str_lit("llvm-api"), BuildFlagParam_None); add_flag(&build_flags, BuildFlag_IgnoreUnknownAttributes, str_lit("ignore-unknown-attributes"), BuildFlagParam_None); add_flag(&build_flags, BuildFlag_Compact, str_lit("compact"), BuildFlagParam_None); @@ -347,6 +353,7 @@ bool parse_build_flags(Array args) { gb_printf_err("Invalid flag: %.*s\n", LIT(flag)); continue; } + String name = substring(flag, 1, flag.len); isize end = 0; for (; end < name.len; end++) { @@ -692,6 +699,10 @@ bool parse_build_flags(Array args) { build_context.vet = true; break; + case BuildFlag_UseLLVMApi: + build_context.use_llvm_api = true; + break; + case BuildFlag_IgnoreUnknownAttributes: build_context.ignore_unknown_attributes = true; break; @@ -1263,6 +1274,15 @@ int main(int arg_count, char const **arg_ptr) { return 1; } + if (build_context.use_llvm_api) { + lbGenerator gen = {}; + if (!lb_init_generator(&gen, &checker)) { + return 1; + } + lb_generate_module(&gen); + return 0; + } + irGen ir_gen = {0}; if (!ir_gen_init(&ir_gen, &checker)) { return 1; -- 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/main.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 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/main.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 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/main.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 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/main.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 ed4d21045b563e2066fa5599cc626b489523fcad Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 19 Mar 2020 15:14:31 +0000 Subject: Add `LLVM_BACKEND_SUPPORT` macro to make the backend optional --- build.bat | 4 +++- src/main.cpp | 12 +++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) (limited to 'src/main.cpp') diff --git a/build.bat b/build.bat index 702031eb3..c7c5e6d26 100644 --- a/build.bat +++ b/build.bat @@ -13,6 +13,8 @@ if "%1" == "1" ( ) set compiler_flags= -nologo -Oi -TP -fp:precise -Gm- -MP -FC -EHsc- -GR- -GF +set compiler_defines= -DLLVM_BACKEND_SUPPORT + if %release_mode% EQU 0 ( rem Debug set compiler_flags=%compiler_flags% -Od -MDd -Z7 @@ -41,7 +43,7 @@ if %release_mode% EQU 0 ( rem Debug set linker_flags=%linker_flags% -debug ) -set compiler_settings=%compiler_includes% %compiler_flags% %compiler_warnings% +set compiler_settings=%compiler_includes% %compiler_flags% %compiler_warnings% %compiler_defines% set linker_settings=%libs% %linker_flags% del *.pdb > NUL 2> NUL diff --git a/src/main.cpp b/src/main.cpp index 8113162e5..caad1c901 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -18,7 +18,10 @@ gb_global Timings global_timings = {0}; #include "docs.cpp" #include "checker.cpp" + +#if defined(LLVM_BACKEND_SUPPORT) #include "llvm_backend.cpp" +#endif #include "ir.cpp" #include "ir_opt.cpp" @@ -126,6 +129,7 @@ i32 system_exec_command_line_app(char const *name, char const *fmt, ...) { +#if defined(LLVM_BACKEND_SUPPORT) i32 linker_stage(lbGenerator *gen) { i32 exit_code = 0; @@ -420,7 +424,7 @@ i32 linker_stage(lbGenerator *gen) { return exit_code; } - +#endif Array setup_args(int argc, char const **argv) { gbAllocator a = heap_allocator(); @@ -1586,6 +1590,8 @@ int main(int arg_count, char const **arg_ptr) { } if (build_context.use_llvm_api) { +#if defined(LLVM_BACKEND_SUPPORT) + timings_start_section(timings, str_lit("LLVM API Code Gen")); lbGenerator gen = {}; if (!lb_init_generator(&gen, &checker)) { @@ -1616,6 +1622,10 @@ int main(int arg_count, char const **arg_ptr) { } return 0; +#else + gb_printf_err("LLVM C API backend is not supported on this platform yet\n"); + return 1; +#endif } else { irGen ir_gen = {0}; if (!ir_gen_init(&ir_gen, &checker)) { -- cgit v1.2.3 From 8093062e3b58af6124f75161be110a4eccef7b54 Mon Sep 17 00:00:00 2001 From: gingerBill Date: Thu, 19 Mar 2020 15:36:13 +0000 Subject: Wrap all LLVM C includes --- src/main.cpp | 4 ++++ src/types.cpp | 2 -- 2 files changed, 4 insertions(+), 2 deletions(-) (limited to 'src/main.cpp') diff --git a/src/main.cpp b/src/main.cpp index caad1c901..46364d8d6 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -10,6 +10,10 @@ gb_global Timings global_timings = {0}; +#if defined(LLVM_BACKEND_SUPPORT) +#include "llvm-c/Types.h" +#endif + #include "parser.hpp" #include "checker.hpp" diff --git a/src/types.cpp b/src/types.cpp index 6d880cdec..4c7f07cc7 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -1,5 +1,3 @@ -#include "llvm-c/Types.h" - struct Scope; struct Ast; -- cgit v1.2.3