wip export rewrite

This commit is contained in:
Andrew Kelley 2017-12-18 09:59:57 -05:00
parent 68f6332343
commit 1fdebc1dc4
46 changed files with 1487 additions and 1194 deletions

View File

@ -5815,13 +5815,13 @@ TopLevelItem = ErrorValueDecl | CompTimeExpression(Block) | TopLevelDecl | TestD
TestDecl = "test" String Block TestDecl = "test" String Block
TopLevelDecl = option(VisibleMod) (FnDef | ExternDecl | GlobalVarDecl | UseDecl) TopLevelDecl = option("pub") (FnDef | ExternDecl | GlobalVarDecl | UseDecl)
ErrorValueDecl = "error" Symbol ";" ErrorValueDecl = "error" Symbol ";"
GlobalVarDecl = VariableDeclaration ";" GlobalVarDecl = VariableDeclaration ";"
VariableDeclaration = option("comptime") ("var" | "const") Symbol option(":" TypeExpr) option("align" "(" Expression ")") "=" Expression VariableDeclaration = option("comptime") ("var" | "const") Symbol option(":" TypeExpr) option("align" "(" Expression ")") option("section" "(" Expression ")") "=" Expression
ContainerMember = (ContainerField | FnDef | GlobalVarDecl) ContainerMember = (ContainerField | FnDef | GlobalVarDecl)
@ -5831,9 +5831,7 @@ UseDecl = "use" Expression ";"
ExternDecl = "extern" option(String) (FnProto | VariableDeclaration) ";" ExternDecl = "extern" option(String) (FnProto | VariableDeclaration) ";"
FnProto = option("coldcc" | "nakedcc" | "stdcallcc") "fn" option(Symbol) ParamDeclList option("align" "(" Expression ")") option("->" TypeExpr) FnProto = option("coldcc" | "nakedcc" | "stdcallcc") "fn" option(Symbol) ParamDeclList option("align" "(" Expression ")") option("section" "(" Expression ")") option("->" TypeExpr)
VisibleMod = "pub" | "export"
FnDef = option("inline" | "extern") FnProto Block FnDef = option("inline" | "extern") FnProto Block

View File

@ -5,9 +5,13 @@ const c = @cImport({
@cInclude("string.h"); @cInclude("string.h");
}); });
const msg = c"Hello, world!\n"; comptime {
@export("main", main);
}
extern fn main(argc: c_int, argv: &&u8) -> c_int {
const msg = c"Hello, world!\n";
export fn main(argc: c_int, argv: &&u8) -> c_int {
if (c.printf(msg) != c_int(c.strlen(msg))) if (c.printf(msg) != c_int(c.strlen(msg)))
return -1; return -1;

View File

@ -1,6 +1,9 @@
const base64 = @import("std").base64; const base64 = @import("std").base64;
export fn decode_base_64(dest_ptr: &u8, dest_len: usize, source_ptr: &const u8, source_len: usize) -> usize { comptime {
@export("decode_base_64", decode_base_64);
}
extern fn decode_base_64(dest_ptr: &u8, dest_len: usize, source_ptr: &const u8, source_len: usize) -> usize {
const src = source_ptr[0..source_len]; const src = source_ptr[0..source_len];
const dest = dest_ptr[0..dest_len]; const dest = dest_ptr[0..dest_len];
const base64_decoder = base64.standard_decoder_unsafe; const base64_decoder = base64.standard_decoder_unsafe;

View File

@ -1,3 +1,6 @@
export fn add(a: i32, b: i32) -> i32 { comptime {
@export("add", add);
}
extern fn add(a: i32, b: i32) -> i32 {
a + b a + b
} }

View File

@ -37,6 +37,7 @@ struct IrBasicBlock;
struct ScopeDecls; struct ScopeDecls;
struct ZigWindowsSDK; struct ZigWindowsSDK;
struct Tld; struct Tld;
struct TldExport;
struct IrGotoItem { struct IrGotoItem {
AstNode *source_node; AstNode *source_node;
@ -272,7 +273,6 @@ enum ReturnKnowledge {
enum VisibMod { enum VisibMod {
VisibModPrivate, VisibModPrivate,
VisibModPub, VisibModPub,
VisibModExport,
}; };
enum GlobalLinkageId { enum GlobalLinkageId {
@ -313,11 +313,14 @@ struct TldVar {
Tld base; Tld base;
VariableTableEntry *var; VariableTableEntry *var;
AstNode *set_global_section_node;
Buf *section_name;
AstNode *set_global_linkage_node;
GlobalLinkageId linkage;
Buf *extern_lib_name; Buf *extern_lib_name;
Buf *section_name;
size_t export_count;
union {
TldExport *tld; // if export_count == 1
TldExport **tld_list; // if export_count > 1
} export_data;
}; };
struct TldFn { struct TldFn {
@ -432,6 +435,8 @@ struct AstNodeFnProto {
Buf *lib_name; Buf *lib_name;
// populated if the "align A" is present // populated if the "align A" is present
AstNode *align_expr; AstNode *align_expr;
// populated if the "section(S)" is present
AstNode *section_expr;
}; };
struct AstNodeFnDef { struct AstNodeFnDef {
@ -487,8 +492,10 @@ struct AstNodeVariableDeclaration {
AstNode *expr; AstNode *expr;
// populated if this is an extern declaration // populated if this is an extern declaration
Buf *lib_name; Buf *lib_name;
// populated if the "align A" is present // populated if the "align(A)" is present
AstNode *align_expr; AstNode *align_expr;
// populated if the "section(S)" is present
AstNode *section_expr;
}; };
struct AstNodeErrorValueDecl { struct AstNodeErrorValueDecl {
@ -1177,6 +1184,12 @@ enum FnInline {
FnInlineNever, FnInlineNever,
}; };
struct FnExport {
Buf name;
GlobalLinkageId linkage;
AstNode *source_node;
};
struct FnTableEntry { struct FnTableEntry {
LLVMValueRef llvm_value; LLVMValueRef llvm_value;
const char *llvm_name; const char *llvm_name;
@ -1204,12 +1217,11 @@ struct FnTableEntry {
ZigList<IrInstruction *> alloca_list; ZigList<IrInstruction *> alloca_list;
ZigList<VariableTableEntry *> variable_list; ZigList<VariableTableEntry *> variable_list;
AstNode *set_global_section_node;
Buf *section_name; Buf *section_name;
AstNode *set_global_linkage_node;
GlobalLinkageId linkage;
AstNode *set_alignstack_node; AstNode *set_alignstack_node;
uint32_t alignstack_value; uint32_t alignstack_value;
ZigList<FnExport> export_list;
}; };
uint32_t fn_table_entry_hash(FnTableEntry*); uint32_t fn_table_entry_hash(FnTableEntry*);
@ -1258,8 +1270,6 @@ enum BuiltinFnId {
BuiltinFnIdSetFloatMode, BuiltinFnIdSetFloatMode,
BuiltinFnIdTypeName, BuiltinFnIdTypeName,
BuiltinFnIdCanImplicitCast, BuiltinFnIdCanImplicitCast,
BuiltinFnIdSetGlobalSection,
BuiltinFnIdSetGlobalLinkage,
BuiltinFnIdPanic, BuiltinFnIdPanic,
BuiltinFnIdPtrCast, BuiltinFnIdPtrCast,
BuiltinFnIdBitCast, BuiltinFnIdBitCast,
@ -1279,6 +1289,8 @@ enum BuiltinFnId {
BuiltinFnIdOpaqueType, BuiltinFnIdOpaqueType,
BuiltinFnIdSetAlignStack, BuiltinFnIdSetAlignStack,
BuiltinFnIdArgType, BuiltinFnIdArgType,
BuiltinFnIdExport,
BuiltinFnIdExportWithLinkage,
}; };
struct BuiltinFnEntry { struct BuiltinFnEntry {
@ -1425,7 +1437,7 @@ struct CodeGen {
HashMap<GenericFnTypeId *, FnTableEntry *, generic_fn_type_id_hash, generic_fn_type_id_eql> generic_table; HashMap<GenericFnTypeId *, FnTableEntry *, generic_fn_type_id_hash, generic_fn_type_id_eql> generic_table;
HashMap<Scope *, IrInstruction *, fn_eval_hash, fn_eval_eql> memoized_fn_eval_table; HashMap<Scope *, IrInstruction *, fn_eval_hash, fn_eval_eql> memoized_fn_eval_table;
HashMap<ZigLLVMFnKey, LLVMValueRef, zig_llvm_fn_key_hash, zig_llvm_fn_key_eql> llvm_fn_table; HashMap<ZigLLVMFnKey, LLVMValueRef, zig_llvm_fn_key_hash, zig_llvm_fn_key_eql> llvm_fn_table;
HashMap<Buf *, Tld *, buf_hash, buf_eql_buf> exported_symbol_names; HashMap<Buf *, AstNode *, buf_hash, buf_eql_buf> exported_symbol_names;
HashMap<Buf *, Tld *, buf_hash, buf_eql_buf> external_prototypes; HashMap<Buf *, Tld *, buf_hash, buf_eql_buf> external_prototypes;
@ -1886,8 +1898,6 @@ enum IrInstructionId {
IrInstructionIdCheckStatementIsVoid, IrInstructionIdCheckStatementIsVoid,
IrInstructionIdTypeName, IrInstructionIdTypeName,
IrInstructionIdCanImplicitCast, IrInstructionIdCanImplicitCast,
IrInstructionIdSetGlobalSection,
IrInstructionIdSetGlobalLinkage,
IrInstructionIdDeclRef, IrInstructionIdDeclRef,
IrInstructionIdPanic, IrInstructionIdPanic,
IrInstructionIdTagName, IrInstructionIdTagName,
@ -1901,6 +1911,7 @@ enum IrInstructionId {
IrInstructionIdOpaqueType, IrInstructionIdOpaqueType,
IrInstructionIdSetAlignStack, IrInstructionIdSetAlignStack,
IrInstructionIdArgType, IrInstructionIdArgType,
IrInstructionIdExport,
}; };
struct IrInstruction { struct IrInstruction {
@ -2626,20 +2637,6 @@ struct IrInstructionCanImplicitCast {
IrInstruction *target_value; IrInstruction *target_value;
}; };
struct IrInstructionSetGlobalSection {
IrInstruction base;
Tld *tld;
IrInstruction *value;
};
struct IrInstructionSetGlobalLinkage {
IrInstruction base;
Tld *tld;
IrInstruction *value;
};
struct IrInstructionDeclRef { struct IrInstructionDeclRef {
IrInstruction base; IrInstruction base;
@ -2728,6 +2725,14 @@ struct IrInstructionArgType {
IrInstruction *arg_index; IrInstruction *arg_index;
}; };
struct IrInstructionExport {
IrInstruction base;
IrInstruction *name;
IrInstruction *linkage;
IrInstruction *target;
};
static const size_t slice_ptr_index = 0; static const size_t slice_ptr_index = 0;
static const size_t slice_len_index = 1; static const size_t slice_len_index = 1;

View File

@ -1062,7 +1062,7 @@ void init_fn_type_id(FnTypeId *fn_type_id, AstNode *proto_node, size_t param_cou
AstNodeFnProto *fn_proto = &proto_node->data.fn_proto; AstNodeFnProto *fn_proto = &proto_node->data.fn_proto;
if (fn_proto->cc == CallingConventionUnspecified) { if (fn_proto->cc == CallingConventionUnspecified) {
bool extern_abi = fn_proto->is_extern || (fn_proto->visib_mod == VisibModExport); bool extern_abi = fn_proto->is_extern;
fn_type_id->cc = extern_abi ? CallingConventionC : CallingConventionUnspecified; fn_type_id->cc = extern_abi ? CallingConventionC : CallingConventionUnspecified;
} else { } else {
fn_type_id->cc = fn_proto->cc; fn_type_id->cc = fn_proto->cc;
@ -1093,6 +1093,38 @@ static bool analyze_const_align(CodeGen *g, Scope *scope, AstNode *node, uint32_
return true; return true;
} }
static bool analyze_const_string(CodeGen *g, Scope *scope, AstNode *node, Buf **out_buffer) {
TypeTableEntry *ptr_type = get_pointer_to_type(g, g->builtin_types.entry_u8, true);
TypeTableEntry *str_type = get_slice_type(g, ptr_type);
IrInstruction *instr = analyze_const_value(g, scope, node, str_type, nullptr);
if (type_is_invalid(instr->value.type))
return false;
ConstExprValue *ptr_field = &instr->value.data.x_struct.fields[slice_ptr_index];
ConstExprValue *len_field = &instr->value.data.x_struct.fields[slice_len_index];
assert(ptr_field->data.x_ptr.special == ConstPtrSpecialBaseArray);
ConstExprValue *array_val = ptr_field->data.x_ptr.data.base_array.array_val;
expand_undef_array(g, array_val);
size_t len = bigint_as_unsigned(&len_field->data.x_bigint);
Buf *result = buf_alloc();
buf_resize(result, len);
for (size_t i = 0; i < len; i += 1) {
size_t new_index = ptr_field->data.x_ptr.data.base_array.elem_index + i;
ConstExprValue *char_val = &array_val->data.x_array.s_none.elements[new_index];
if (char_val->special == ConstValSpecialUndef) {
add_node_error(g, node, buf_sprintf("use of undefined value"));
return false;
}
uint64_t big_c = bigint_as_unsigned(&char_val->data.x_bigint);
assert(big_c <= UINT8_MAX);
uint8_t c = (uint8_t)big_c;
buf_ptr(result)[i] = c;
}
*out_buffer = result;
return true;
}
static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *child_scope) { static TypeTableEntry *analyze_fn_type(CodeGen *g, AstNode *proto_node, Scope *child_scope) {
assert(proto_node->type == NodeTypeFnProto); assert(proto_node->type == NodeTypeFnProto);
AstNodeFnProto *fn_proto = &proto_node->data.fn_proto; AstNodeFnProto *fn_proto = &proto_node->data.fn_proto;
@ -2472,7 +2504,7 @@ static void get_fully_qualified_decl_name(Buf *buf, Tld *tld, uint8_t sep) {
buf_append_buf(buf, tld->name); buf_append_buf(buf, tld->name);
} }
FnTableEntry *create_fn_raw(FnInline inline_value, GlobalLinkageId linkage) { FnTableEntry *create_fn_raw(FnInline inline_value) {
FnTableEntry *fn_entry = allocate<FnTableEntry>(1); FnTableEntry *fn_entry = allocate<FnTableEntry>(1);
fn_entry->analyzed_executable.backward_branch_count = &fn_entry->prealloc_bbc; fn_entry->analyzed_executable.backward_branch_count = &fn_entry->prealloc_bbc;
@ -2480,7 +2512,6 @@ FnTableEntry *create_fn_raw(FnInline inline_value, GlobalLinkageId linkage) {
fn_entry->analyzed_executable.fn_entry = fn_entry; fn_entry->analyzed_executable.fn_entry = fn_entry;
fn_entry->ir_executable.fn_entry = fn_entry; fn_entry->ir_executable.fn_entry = fn_entry;
fn_entry->fn_inline = inline_value; fn_entry->fn_inline = inline_value;
fn_entry->linkage = linkage;
return fn_entry; return fn_entry;
} }
@ -2490,9 +2521,7 @@ FnTableEntry *create_fn(AstNode *proto_node) {
AstNodeFnProto *fn_proto = &proto_node->data.fn_proto; AstNodeFnProto *fn_proto = &proto_node->data.fn_proto;
FnInline inline_value = fn_proto->is_inline ? FnInlineAlways : FnInlineAuto; FnInline inline_value = fn_proto->is_inline ? FnInlineAlways : FnInlineAuto;
GlobalLinkageId linkage = (fn_proto->visib_mod == VisibModExport || proto_node->data.fn_proto.is_extern) ? FnTableEntry *fn_entry = create_fn_raw(inline_value);
GlobalLinkageIdStrong : GlobalLinkageIdInternal;
FnTableEntry *fn_entry = create_fn_raw(inline_value, linkage);
fn_entry->proto_node = proto_node; fn_entry->proto_node = proto_node;
fn_entry->body_node = (proto_node->data.fn_proto.fn_def_node == nullptr) ? nullptr : fn_entry->body_node = (proto_node->data.fn_proto.fn_def_node == nullptr) ? nullptr :
@ -2572,7 +2601,7 @@ static void resolve_decl_fn(CodeGen *g, TldFn *tld_fn) {
add_node_error(g, param_node, buf_sprintf("missing parameter name")); add_node_error(g, param_node, buf_sprintf("missing parameter name"));
} }
} }
} else if (fn_table_entry->linkage != GlobalLinkageIdInternal) { } else {
g->external_prototypes.put_unique(tld_fn->base.name, &tld_fn->base); g->external_prototypes.put_unique(tld_fn->base.name, &tld_fn->base);
} }
@ -2580,6 +2609,15 @@ static void resolve_decl_fn(CodeGen *g, TldFn *tld_fn) {
fn_table_entry->type_entry = analyze_fn_type(g, source_node, child_scope); fn_table_entry->type_entry = analyze_fn_type(g, source_node, child_scope);
if (fn_proto->section_expr != nullptr) {
if (fn_table_entry->body_node == nullptr) {
add_node_error(g, fn_proto->section_expr,
buf_sprintf("cannot set section of external function '%s'", buf_ptr(&fn_table_entry->symbol_name)));
} else {
analyze_const_string(g, child_scope, fn_proto->section_expr, &fn_table_entry->section_name);
}
}
if (fn_table_entry->type_entry->id == TypeTableEntryIdInvalid) { if (fn_table_entry->type_entry->id == TypeTableEntryIdInvalid) {
tld_fn->base.resolution = TldResolutionInvalid; tld_fn->base.resolution = TldResolutionInvalid;
return; return;
@ -2594,15 +2632,12 @@ static void resolve_decl_fn(CodeGen *g, TldFn *tld_fn) {
{ {
if (g->have_pub_main && buf_eql_str(&fn_table_entry->symbol_name, "main")) { if (g->have_pub_main && buf_eql_str(&fn_table_entry->symbol_name, "main")) {
g->main_fn = fn_table_entry; g->main_fn = fn_table_entry;
TypeTableEntry *err_void = get_error_type(g, g->builtin_types.entry_void);
if (tld_fn->base.visib_mod != VisibModExport) { TypeTableEntry *actual_return_type = fn_table_entry->type_entry->data.fn.fn_type_id.return_type;
TypeTableEntry *err_void = get_error_type(g, g->builtin_types.entry_void); if (actual_return_type != err_void) {
TypeTableEntry *actual_return_type = fn_table_entry->type_entry->data.fn.fn_type_id.return_type; add_node_error(g, fn_proto->return_type,
if (actual_return_type != err_void) { buf_sprintf("expected return type of main to be '%%void', instead is '%s'",
add_node_error(g, fn_proto->return_type, buf_ptr(&actual_return_type->name)));
buf_sprintf("expected return type of main to be '%%void', instead is '%s'",
buf_ptr(&actual_return_type->name)));
}
} }
} else if ((import->package == g->panic_package || g->have_pub_panic) && } else if ((import->package == g->panic_package || g->have_pub_panic) &&
buf_eql_str(&fn_table_entry->symbol_name, "panic")) buf_eql_str(&fn_table_entry->symbol_name, "panic"))
@ -2613,7 +2648,7 @@ static void resolve_decl_fn(CodeGen *g, TldFn *tld_fn) {
} }
} }
} else if (source_node->type == NodeTypeTestDecl) { } else if (source_node->type == NodeTypeTestDecl) {
FnTableEntry *fn_table_entry = create_fn_raw(FnInlineAuto, GlobalLinkageIdStrong); FnTableEntry *fn_table_entry = create_fn_raw(FnInlineAuto);
get_fully_qualified_decl_name(&fn_table_entry->symbol_name, &tld_fn->base, '_'); get_fully_qualified_decl_name(&fn_table_entry->symbol_name, &tld_fn->base, '_');
@ -2640,20 +2675,6 @@ static void resolve_decl_comptime(CodeGen *g, TldCompTime *tld_comptime) {
} }
static void add_top_level_decl(CodeGen *g, ScopeDecls *decls_scope, Tld *tld) { static void add_top_level_decl(CodeGen *g, ScopeDecls *decls_scope, Tld *tld) {
if (tld->visib_mod == VisibModExport) {
g->resolve_queue.append(tld);
}
if (tld->visib_mod == VisibModExport) {
auto entry = g->exported_symbol_names.put_unique(tld->name, tld);
if (entry) {
Tld *other_tld = entry->value;
ErrorMsg *msg = add_node_error(g, tld->source_node,
buf_sprintf("exported symbol collision: '%s'", buf_ptr(tld->name)));
add_error_note(g, msg, other_tld->source_node, buf_sprintf("other symbol is here"));
}
}
{ {
auto entry = decls_scope->decl_table.put_unique(tld->name, tld); auto entry = decls_scope->decl_table.put_unique(tld->name, tld);
if (entry) { if (entry) {
@ -2729,7 +2750,6 @@ static void preview_comptime_decl(CodeGen *g, AstNode *node, ScopeDecls *decls_s
g->resolve_queue.append(&tld_comptime->base); g->resolve_queue.append(&tld_comptime->base);
} }
void init_tld(Tld *tld, TldId id, Buf *name, VisibMod visib_mod, AstNode *source_node, void init_tld(Tld *tld, TldId id, Buf *name, VisibMod visib_mod, AstNode *source_node,
Scope *parent_scope) Scope *parent_scope)
{ {
@ -2985,7 +3005,6 @@ static void resolve_decl_var(CodeGen *g, TldVar *tld_var) {
AstNodeVariableDeclaration *var_decl = &source_node->data.variable_declaration; AstNodeVariableDeclaration *var_decl = &source_node->data.variable_declaration;
bool is_const = var_decl->is_const; bool is_const = var_decl->is_const;
bool is_export = (tld_var->base.visib_mod == VisibModExport);
bool is_extern = var_decl->is_extern; bool is_extern = var_decl->is_extern;
TypeTableEntry *explicit_type = nullptr; TypeTableEntry *explicit_type = nullptr;
@ -2994,20 +3013,13 @@ static void resolve_decl_var(CodeGen *g, TldVar *tld_var) {
explicit_type = validate_var_type(g, var_decl->type, proposed_type); explicit_type = validate_var_type(g, var_decl->type, proposed_type);
} }
if (is_export && is_extern) {
add_node_error(g, source_node, buf_sprintf("variable is both export and extern"));
}
VarLinkage linkage; VarLinkage linkage;
if (is_export) { if (is_extern) {
linkage = VarLinkageExport;
} else if (is_extern) {
linkage = VarLinkageExternal; linkage = VarLinkageExternal;
} else { } else {
linkage = VarLinkageInternal; linkage = VarLinkageInternal;
} }
IrInstruction *init_value = nullptr; IrInstruction *init_value = nullptr;
// TODO more validation for types that can't be used for export/extern variables // TODO more validation for types that can't be used for export/extern variables
@ -3056,6 +3068,15 @@ static void resolve_decl_var(CodeGen *g, TldVar *tld_var) {
} }
} }
if (var_decl->section_expr != nullptr) {
if (var_decl->is_extern) {
add_node_error(g, var_decl->section_expr,
buf_sprintf("cannot set section of external variable '%s'", buf_ptr(var_decl->symbol)));
} else if (!analyze_const_string(g, tld_var->base.parent_scope, var_decl->section_expr, &tld_var->section_name)) {
tld_var->section_name = nullptr;
}
}
g->global_vars.append(tld_var); g->global_vars.append(tld_var);
} }
@ -3724,8 +3745,10 @@ ImportTableEntry *add_source_file(CodeGen *g, PackageTableEntry *package, Buf *a
Buf *proto_name = proto_node->data.fn_proto.name; Buf *proto_name = proto_node->data.fn_proto.name;
bool is_pub = (proto_node->data.fn_proto.visib_mod == VisibModPub); bool is_pub = (proto_node->data.fn_proto.visib_mod == VisibModPub);
bool ok_cc = (proto_node->data.fn_proto.cc == CallingConventionUnspecified ||
proto_node->data.fn_proto.cc == CallingConventionCold);
if (is_pub) { if (is_pub && ok_cc) {
if (buf_eql_str(proto_name, "main")) { if (buf_eql_str(proto_name, "main")) {
g->have_pub_main = true; g->have_pub_main = true;
g->windows_subsystem_windows = false; g->windows_subsystem_windows = false;
@ -3733,28 +3756,7 @@ ImportTableEntry *add_source_file(CodeGen *g, PackageTableEntry *package, Buf *a
} else if (buf_eql_str(proto_name, "panic")) { } else if (buf_eql_str(proto_name, "panic")) {
g->have_pub_panic = true; g->have_pub_panic = true;
} }
} else if (proto_node->data.fn_proto.visib_mod == VisibModExport && buf_eql_str(proto_name, "main") &&
g->libc_link_lib != nullptr)
{
g->have_c_main = true;
g->windows_subsystem_windows = false;
g->windows_subsystem_console = true;
} else if (proto_node->data.fn_proto.visib_mod == VisibModExport && buf_eql_str(proto_name, "WinMain") &&
g->zig_target.os == ZigLLVM_Win32)
{
g->have_winmain = true;
g->windows_subsystem_windows = true;
g->windows_subsystem_console = false;
} else if (proto_node->data.fn_proto.visib_mod == VisibModExport &&
buf_eql_str(proto_name, "WinMainCRTStartup") && g->zig_target.os == ZigLLVM_Win32)
{
g->have_winmain_crt_startup = true;
} else if (proto_node->data.fn_proto.visib_mod == VisibModExport &&
buf_eql_str(proto_name, "DllMainCRTStartup") && g->zig_target.os == ZigLLVM_Win32)
{
g->have_dllmain_crt_startup = true;
} }
} }
} }
@ -5445,3 +5447,4 @@ uint32_t type_ptr_hash(const TypeTableEntry *ptr) {
bool type_ptr_eql(const TypeTableEntry *a, const TypeTableEntry *b) { bool type_ptr_eql(const TypeTableEntry *a, const TypeTableEntry *b) {
return a == b; return a == b;
} }

View File

@ -182,4 +182,6 @@ uint32_t get_abi_alignment(CodeGen *g, TypeTableEntry *type_entry);
TypeTableEntry *get_align_amt_type(CodeGen *g); TypeTableEntry *get_align_amt_type(CodeGen *g);
PackageTableEntry *new_anonymous_package(void); PackageTableEntry *new_anonymous_package(void);
Buf *const_value_to_buffer(ConstExprValue *const_val);
#endif #endif

View File

@ -78,7 +78,6 @@ static const char *visib_mod_string(VisibMod mod) {
switch (mod) { switch (mod) {
case VisibModPub: return "pub "; case VisibModPub: return "pub ";
case VisibModPrivate: return ""; case VisibModPrivate: return "";
case VisibModExport: return "export ";
} }
zig_unreachable(); zig_unreachable();
} }
@ -440,6 +439,16 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
} }
} }
fprintf(ar->f, ")"); fprintf(ar->f, ")");
if (node->data.fn_proto.align_expr) {
fprintf(ar->f, " align(");
render_node_grouped(ar, node->data.fn_proto.align_expr);
fprintf(ar->f, ")");
}
if (node->data.fn_proto.section_expr) {
fprintf(ar->f, " section(");
render_node_grouped(ar, node->data.fn_proto.section_expr);
fprintf(ar->f, ")");
}
AstNode *return_type_node = node->data.fn_proto.return_type; AstNode *return_type_node = node->data.fn_proto.return_type;
if (return_type_node != nullptr) { if (return_type_node != nullptr) {
@ -526,6 +535,16 @@ static void render_node_extra(AstRender *ar, AstNode *node, bool grouped) {
fprintf(ar->f, ": "); fprintf(ar->f, ": ");
render_node_grouped(ar, node->data.variable_declaration.type); render_node_grouped(ar, node->data.variable_declaration.type);
} }
if (node->data.variable_declaration.align_expr) {
fprintf(ar->f, "align(");
render_node_grouped(ar, node->data.variable_declaration.align_expr);
fprintf(ar->f, ") ");
}
if (node->data.variable_declaration.section_expr) {
fprintf(ar->f, "section(");
render_node_grouped(ar, node->data.variable_declaration.section_expr);
fprintf(ar->f, ") ");
}
if (node->data.variable_declaration.expr) { if (node->data.variable_declaration.expr) {
fprintf(ar->f, " = "); fprintf(ar->f, " = ");
render_node_grouped(ar, node->data.variable_declaration.expr); render_node_grouped(ar, node->data.variable_declaration.expr);

View File

@ -391,24 +391,51 @@ static void add_uwtable_attr(CodeGen *g, LLVMValueRef fn_val) {
} }
} }
static LLVMLinkage to_llvm_linkage(GlobalLinkageId id) {
switch (id) {
case GlobalLinkageIdInternal:
return LLVMInternalLinkage;
case GlobalLinkageIdStrong:
return LLVMExternalLinkage;
case GlobalLinkageIdWeak:
return LLVMWeakODRLinkage;
case GlobalLinkageIdLinkOnce:
return LLVMLinkOnceODRLinkage;
}
zig_unreachable();
}
static LLVMValueRef fn_llvm_value(CodeGen *g, FnTableEntry *fn_table_entry) { static LLVMValueRef fn_llvm_value(CodeGen *g, FnTableEntry *fn_table_entry) {
if (fn_table_entry->llvm_value) if (fn_table_entry->llvm_value)
return fn_table_entry->llvm_value; return fn_table_entry->llvm_value;
bool external_linkage = (fn_table_entry->linkage != GlobalLinkageIdInternal); Buf *unmangled_name = &fn_table_entry->symbol_name;
Buf *symbol_name = get_mangled_name(g, &fn_table_entry->symbol_name, external_linkage); Buf *symbol_name;
GlobalLinkageId linkage;
if (fn_table_entry->body_node == nullptr) {
symbol_name = unmangled_name;
linkage = GlobalLinkageIdStrong;
} else if (fn_table_entry->export_list.length == 0) {
symbol_name = get_mangled_name(g, unmangled_name, false);
linkage = GlobalLinkageIdInternal;
} else {
FnExport *fn_export = &fn_table_entry->export_list.items[0];
symbol_name = &fn_export->name;
linkage = fn_export->linkage;
}
bool external_linkage = linkage != GlobalLinkageIdInternal;
if (fn_table_entry->type_entry->data.fn.fn_type_id.cc == CallingConventionStdcall && external_linkage && if (fn_table_entry->type_entry->data.fn.fn_type_id.cc == CallingConventionStdcall && external_linkage &&
g->zig_target.arch.arch == ZigLLVM_x86) g->zig_target.arch.arch == ZigLLVM_x86)
{ {
// prevent name mangling // prevent llvm name mangling
symbol_name = buf_sprintf("\x01_%s", buf_ptr(symbol_name)); symbol_name = buf_sprintf("\x01_%s", buf_ptr(symbol_name));
} }
TypeTableEntry *fn_type = fn_table_entry->type_entry; TypeTableEntry *fn_type = fn_table_entry->type_entry;
LLVMTypeRef fn_llvm_type = fn_type->data.fn.raw_type_ref; LLVMTypeRef fn_llvm_type = fn_type->data.fn.raw_type_ref;
if (external_linkage && fn_table_entry->body_node == nullptr) { if (fn_table_entry->body_node == nullptr) {
LLVMValueRef existing_llvm_fn = LLVMGetNamedFunction(g->module, buf_ptr(symbol_name)); LLVMValueRef existing_llvm_fn = LLVMGetNamedFunction(g->module, buf_ptr(symbol_name));
if (existing_llvm_fn) { if (existing_llvm_fn) {
fn_table_entry->llvm_value = LLVMConstBitCast(existing_llvm_fn, LLVMPointerType(fn_llvm_type, 0)); fn_table_entry->llvm_value = LLVMConstBitCast(existing_llvm_fn, LLVMPointerType(fn_llvm_type, 0));
@ -418,6 +445,12 @@ static LLVMValueRef fn_llvm_value(CodeGen *g, FnTableEntry *fn_table_entry) {
} }
} else { } else {
fn_table_entry->llvm_value = LLVMAddFunction(g->module, buf_ptr(symbol_name), fn_llvm_type); fn_table_entry->llvm_value = LLVMAddFunction(g->module, buf_ptr(symbol_name), fn_llvm_type);
for (size_t i = 1; i < fn_table_entry->export_list.length; i += 1) {
FnExport *fn_export = &fn_table_entry->export_list.items[i];
LLVMAddAlias(g->module, LLVMTypeOf(fn_table_entry->llvm_value),
fn_table_entry->llvm_value, buf_ptr(&fn_export->name));
}
} }
fn_table_entry->llvm_name = LLVMGetValueName(fn_table_entry->llvm_value); fn_table_entry->llvm_name = LLVMGetValueName(fn_table_entry->llvm_value);
@ -445,20 +478,10 @@ static LLVMValueRef fn_llvm_value(CodeGen *g, FnTableEntry *fn_table_entry) {
} }
} }
switch (fn_table_entry->linkage) { LLVMSetLinkage(fn_table_entry->llvm_value, to_llvm_linkage(linkage));
case GlobalLinkageIdInternal:
LLVMSetLinkage(fn_table_entry->llvm_value, LLVMInternalLinkage); if (linkage == GlobalLinkageIdInternal) {
LLVMSetUnnamedAddr(fn_table_entry->llvm_value, true); LLVMSetUnnamedAddr(fn_table_entry->llvm_value, true);
break;
case GlobalLinkageIdStrong:
LLVMSetLinkage(fn_table_entry->llvm_value, LLVMExternalLinkage);
break;
case GlobalLinkageIdWeak:
LLVMSetLinkage(fn_table_entry->llvm_value, LLVMWeakODRLinkage);
break;
case GlobalLinkageIdLinkOnce:
LLVMSetLinkage(fn_table_entry->llvm_value, LLVMLinkOnceODRLinkage);
break;
} }
if (fn_type->data.fn.fn_type_id.return_type->id == TypeTableEntryIdUnreachable) { if (fn_type->data.fn.fn_type_id.return_type->id == TypeTableEntryIdUnreachable) {
@ -565,7 +588,8 @@ static ZigLLVMDIScope *get_di_scope(CodeGen *g, Scope *scope) {
bool is_definition = fn_table_entry->body_node != nullptr; bool is_definition = fn_table_entry->body_node != nullptr;
unsigned flags = 0; unsigned flags = 0;
bool is_optimized = g->build_mode != BuildModeDebug; bool is_optimized = g->build_mode != BuildModeDebug;
bool is_internal_linkage = (fn_table_entry->linkage == GlobalLinkageIdInternal); bool is_internal_linkage = (fn_table_entry->body_node != nullptr &&
fn_table_entry->export_list.length == 0);
ZigLLVMDISubprogram *subprogram = ZigLLVMCreateFunction(g->dbuilder, ZigLLVMDISubprogram *subprogram = ZigLLVMCreateFunction(g->dbuilder,
get_di_scope(g, scope->parent), buf_ptr(&fn_table_entry->symbol_name), "", get_di_scope(g, scope->parent), buf_ptr(&fn_table_entry->symbol_name), "",
import->di_file, line_number, import->di_file, line_number,
@ -3487,8 +3511,6 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable,
case IrInstructionIdCheckStatementIsVoid: case IrInstructionIdCheckStatementIsVoid:
case IrInstructionIdTypeName: case IrInstructionIdTypeName:
case IrInstructionIdCanImplicitCast: case IrInstructionIdCanImplicitCast:
case IrInstructionIdSetGlobalSection:
case IrInstructionIdSetGlobalLinkage:
case IrInstructionIdDeclRef: case IrInstructionIdDeclRef:
case IrInstructionIdSwitchVar: case IrInstructionIdSwitchVar:
case IrInstructionIdOffsetOf: case IrInstructionIdOffsetOf:
@ -3499,6 +3521,7 @@ static LLVMValueRef ir_render_instruction(CodeGen *g, IrExecutable *executable,
case IrInstructionIdSetAlignStack: case IrInstructionIdSetAlignStack:
case IrInstructionIdArgType: case IrInstructionIdArgType:
case IrInstructionIdTagType: case IrInstructionIdTagType:
case IrInstructionIdExport:
zig_unreachable(); zig_unreachable();
case IrInstructionIdReturn: case IrInstructionIdReturn:
return ir_render_return(g, executable, (IrInstructionReturn *)instruction); return ir_render_return(g, executable, (IrInstructionReturn *)instruction);
@ -4969,8 +4992,6 @@ static void define_builtin_fns(CodeGen *g) {
create_builtin_fn(g, BuiltinFnIdIntType, "IntType", 2); // TODO rename to Int create_builtin_fn(g, BuiltinFnIdIntType, "IntType", 2); // TODO rename to Int
create_builtin_fn(g, BuiltinFnIdSetDebugSafety, "setDebugSafety", 2); create_builtin_fn(g, BuiltinFnIdSetDebugSafety, "setDebugSafety", 2);
create_builtin_fn(g, BuiltinFnIdSetFloatMode, "setFloatMode", 2); create_builtin_fn(g, BuiltinFnIdSetFloatMode, "setFloatMode", 2);
create_builtin_fn(g, BuiltinFnIdSetGlobalSection, "setGlobalSection", 2);
create_builtin_fn(g, BuiltinFnIdSetGlobalLinkage, "setGlobalLinkage", 2);
create_builtin_fn(g, BuiltinFnIdPanic, "panic", 1); create_builtin_fn(g, BuiltinFnIdPanic, "panic", 1);
create_builtin_fn(g, BuiltinFnIdPtrCast, "ptrCast", 2); create_builtin_fn(g, BuiltinFnIdPtrCast, "ptrCast", 2);
create_builtin_fn(g, BuiltinFnIdBitCast, "bitCast", 2); create_builtin_fn(g, BuiltinFnIdBitCast, "bitCast", 2);
@ -4995,6 +5016,8 @@ static void define_builtin_fns(CodeGen *g) {
create_builtin_fn(g, BuiltinFnIdOpaqueType, "OpaqueType", 0); create_builtin_fn(g, BuiltinFnIdOpaqueType, "OpaqueType", 0);
create_builtin_fn(g, BuiltinFnIdSetAlignStack, "setAlignStack", 1); create_builtin_fn(g, BuiltinFnIdSetAlignStack, "setAlignStack", 1);
create_builtin_fn(g, BuiltinFnIdArgType, "ArgType", 2); create_builtin_fn(g, BuiltinFnIdArgType, "ArgType", 2);
create_builtin_fn(g, BuiltinFnIdExport, "export", 2);
create_builtin_fn(g, BuiltinFnIdExportWithLinkage, "exportWithLinkage", 3);
} }
static const char *bool_to_str(bool b) { static const char *bool_to_str(bool b) {
@ -5433,6 +5456,27 @@ static void gen_root_source(CodeGen *g) {
assert(g->root_out_name); assert(g->root_out_name);
assert(g->out_type != OutTypeUnknown); assert(g->out_type != OutTypeUnknown);
{
// Zig has lazy top level definitions. Here we semantically analyze the panic function.
ImportTableEntry *import_with_panic;
if (g->have_pub_panic) {
import_with_panic = g->root_import;
} else {
g->panic_package = create_panic_pkg(g);
import_with_panic = add_special_code(g, g->panic_package, "panic.zig");
}
scan_import(g, import_with_panic);
Tld *panic_tld = find_decl(g, &import_with_panic->decls_scope->base, buf_create_from_str("panic"));
assert(panic_tld != nullptr);
resolve_top_level_decl(g, panic_tld, false, nullptr);
}
if (!g->error_during_imports) {
semantic_analyze(g);
}
report_errors_and_maybe_exit(g);
if (!g->is_test_build && g->zig_target.os != ZigLLVM_UnknownOS && if (!g->is_test_build && g->zig_target.os != ZigLLVM_UnknownOS &&
!g->have_c_main && !g->have_winmain && !g->have_winmain_crt_startup && !g->have_c_main && !g->have_winmain && !g->have_winmain_crt_startup &&
((g->have_pub_main && g->out_type == OutTypeObj) || g->out_type == OutTypeExe)) ((g->have_pub_main && g->out_type == OutTypeObj) || g->out_type == OutTypeExe))
@ -5442,20 +5486,6 @@ static void gen_root_source(CodeGen *g) {
if (g->zig_target.os == ZigLLVM_Win32 && !g->have_dllmain_crt_startup && g->out_type == OutTypeLib) { if (g->zig_target.os == ZigLLVM_Win32 && !g->have_dllmain_crt_startup && g->out_type == OutTypeLib) {
g->bootstrap_import = add_special_code(g, create_bootstrap_pkg(g, g->root_package), "bootstrap_lib.zig"); g->bootstrap_import = add_special_code(g, create_bootstrap_pkg(g, g->root_package), "bootstrap_lib.zig");
} }
ImportTableEntry *import_with_panic;
if (g->have_pub_panic) {
import_with_panic = g->root_import;
} else {
g->panic_package = create_panic_pkg(g);
import_with_panic = add_special_code(g, g->panic_package, "panic.zig");
}
// Zig has lazy top level definitions. Here we semantically analyze the panic function.
{
scan_import(g, import_with_panic);
Tld *panic_tld = find_decl(g, &import_with_panic->decls_scope->base, buf_create_from_str("panic"));
assert(panic_tld != nullptr);
resolve_top_level_decl(g, panic_tld, false, nullptr);
}
if (!g->error_during_imports) { if (!g->error_during_imports) {
semantic_analyze(g); semantic_analyze(g);
@ -5682,7 +5712,7 @@ static void gen_h_file(CodeGen *g) {
for (size_t fn_def_i = 0; fn_def_i < g->fn_defs.length; fn_def_i += 1) { for (size_t fn_def_i = 0; fn_def_i < g->fn_defs.length; fn_def_i += 1) {
FnTableEntry *fn_table_entry = g->fn_defs.at(fn_def_i); FnTableEntry *fn_table_entry = g->fn_defs.at(fn_def_i);
if (fn_table_entry->linkage == GlobalLinkageIdInternal) if (fn_table_entry->export_list.length == 0)
continue; continue;
FnTypeId *fn_type_id = &fn_table_entry->type_entry->data.fn.fn_type_id; FnTypeId *fn_type_id = &fn_table_entry->type_entry->data.fn.fn_type_id;

View File

@ -207,6 +207,10 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionDeclVar *) {
return IrInstructionIdDeclVar; return IrInstructionIdDeclVar;
} }
static constexpr IrInstructionId ir_instruction_id(IrInstructionExport *) {
return IrInstructionIdExport;
}
static constexpr IrInstructionId ir_instruction_id(IrInstructionLoadPtr *) { static constexpr IrInstructionId ir_instruction_id(IrInstructionLoadPtr *) {
return IrInstructionIdLoadPtr; return IrInstructionIdLoadPtr;
} }
@ -523,14 +527,6 @@ static constexpr IrInstructionId ir_instruction_id(IrInstructionCanImplicitCast
return IrInstructionIdCanImplicitCast; return IrInstructionIdCanImplicitCast;
} }
static constexpr IrInstructionId ir_instruction_id(IrInstructionSetGlobalSection *) {
return IrInstructionIdSetGlobalSection;
}
static constexpr IrInstructionId ir_instruction_id(IrInstructionSetGlobalLinkage *) {
return IrInstructionIdSetGlobalLinkage;
}
static constexpr IrInstructionId ir_instruction_id(IrInstructionDeclRef *) { static constexpr IrInstructionId ir_instruction_id(IrInstructionDeclRef *) {
return IrInstructionIdDeclRef; return IrInstructionIdDeclRef;
} }
@ -1205,6 +1201,24 @@ static IrInstruction *ir_build_var_decl_from(IrBuilder *irb, IrInstruction *old_
return new_instruction; return new_instruction;
} }
static IrInstruction *ir_build_export(IrBuilder *irb, Scope *scope, AstNode *source_node,
IrInstruction *name, IrInstruction *target, IrInstruction *linkage)
{
IrInstructionExport *export_instruction = ir_build_instruction<IrInstructionExport>(
irb, scope, source_node);
export_instruction->base.value.special = ConstValSpecialStatic;
export_instruction->base.value.type = irb->codegen->builtin_types.entry_void;
export_instruction->name = name;
export_instruction->target = target;
export_instruction->linkage = linkage;
ir_ref_instruction(name, irb->current_basic_block);
ir_ref_instruction(target, irb->current_basic_block);
if (linkage) ir_ref_instruction(linkage, irb->current_basic_block);
return &export_instruction->base;
}
static IrInstruction *ir_build_load_ptr(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *ptr) { static IrInstruction *ir_build_load_ptr(IrBuilder *irb, Scope *scope, AstNode *source_node, IrInstruction *ptr) {
IrInstructionLoadPtr *instruction = ir_build_instruction<IrInstructionLoadPtr>(irb, scope, source_node); IrInstructionLoadPtr *instruction = ir_build_instruction<IrInstructionLoadPtr>(irb, scope, source_node);
instruction->ptr = ptr; instruction->ptr = ptr;
@ -2159,32 +2173,6 @@ static IrInstruction *ir_build_can_implicit_cast(IrBuilder *irb, Scope *scope, A
return &instruction->base; return &instruction->base;
} }
static IrInstruction *ir_build_set_global_section(IrBuilder *irb, Scope *scope, AstNode *source_node,
Tld *tld, IrInstruction *value)
{
IrInstructionSetGlobalSection *instruction = ir_build_instruction<IrInstructionSetGlobalSection>(
irb, scope, source_node);
instruction->tld = tld;
instruction->value = value;
ir_ref_instruction(value, irb->current_basic_block);
return &instruction->base;
}
static IrInstruction *ir_build_set_global_linkage(IrBuilder *irb, Scope *scope, AstNode *source_node,
Tld *tld, IrInstruction *value)
{
IrInstructionSetGlobalLinkage *instruction = ir_build_instruction<IrInstructionSetGlobalLinkage>(
irb, scope, source_node);
instruction->tld = tld;
instruction->value = value;
ir_ref_instruction(value, irb->current_basic_block);
return &instruction->base;
}
static IrInstruction *ir_build_decl_ref(IrBuilder *irb, Scope *scope, AstNode *source_node, static IrInstruction *ir_build_decl_ref(IrBuilder *irb, Scope *scope, AstNode *source_node,
Tld *tld, LVal lval) Tld *tld, LVal lval)
{ {
@ -2396,6 +2384,21 @@ static IrInstruction *ir_instruction_declvar_get_dep(IrInstructionDeclVar *instr
return nullptr; return nullptr;
} }
static IrInstruction *ir_instruction_export_get_dep(IrInstructionExport *instruction, size_t index) {
if (index < 1) return instruction->name;
index -= 1;
if (index < 1) return instruction->target;
index -= 1;
if (instruction->linkage != nullptr) {
if (index < 1) return instruction->linkage;
index -= 1;
}
return nullptr;
}
static IrInstruction *ir_instruction_loadptr_get_dep(IrInstructionLoadPtr *instruction, size_t index) { static IrInstruction *ir_instruction_loadptr_get_dep(IrInstructionLoadPtr *instruction, size_t index) {
switch (index) { switch (index) {
case 0: return instruction->ptr; case 0: return instruction->ptr;
@ -2979,20 +2982,6 @@ static IrInstruction *ir_instruction_canimplicitcast_get_dep(IrInstructionCanImp
} }
} }
static IrInstruction *ir_instruction_setglobalsection_get_dep(IrInstructionSetGlobalSection *instruction, size_t index) {
switch (index) {
case 0: return instruction->value;
default: return nullptr;
}
}
static IrInstruction *ir_instruction_setgloballinkage_get_dep(IrInstructionSetGlobalLinkage *instruction, size_t index) {
switch (index) {
case 0: return instruction->value;
default: return nullptr;
}
}
static IrInstruction *ir_instruction_declref_get_dep(IrInstructionDeclRef *instruction, size_t index) { static IrInstruction *ir_instruction_declref_get_dep(IrInstructionDeclRef *instruction, size_t index) {
return nullptr; return nullptr;
} }
@ -3106,6 +3095,8 @@ static IrInstruction *ir_instruction_get_dep(IrInstruction *instruction, size_t
return ir_instruction_binop_get_dep((IrInstructionBinOp *) instruction, index); return ir_instruction_binop_get_dep((IrInstructionBinOp *) instruction, index);
case IrInstructionIdDeclVar: case IrInstructionIdDeclVar:
return ir_instruction_declvar_get_dep((IrInstructionDeclVar *) instruction, index); return ir_instruction_declvar_get_dep((IrInstructionDeclVar *) instruction, index);
case IrInstructionIdExport:
return ir_instruction_export_get_dep((IrInstructionExport *) instruction, index);
case IrInstructionIdLoadPtr: case IrInstructionIdLoadPtr:
return ir_instruction_loadptr_get_dep((IrInstructionLoadPtr *) instruction, index); return ir_instruction_loadptr_get_dep((IrInstructionLoadPtr *) instruction, index);
case IrInstructionIdStorePtr: case IrInstructionIdStorePtr:
@ -3264,10 +3255,6 @@ static IrInstruction *ir_instruction_get_dep(IrInstruction *instruction, size_t
return ir_instruction_typename_get_dep((IrInstructionTypeName *) instruction, index); return ir_instruction_typename_get_dep((IrInstructionTypeName *) instruction, index);
case IrInstructionIdCanImplicitCast: case IrInstructionIdCanImplicitCast:
return ir_instruction_canimplicitcast_get_dep((IrInstructionCanImplicitCast *) instruction, index); return ir_instruction_canimplicitcast_get_dep((IrInstructionCanImplicitCast *) instruction, index);
case IrInstructionIdSetGlobalSection:
return ir_instruction_setglobalsection_get_dep((IrInstructionSetGlobalSection *) instruction, index);
case IrInstructionIdSetGlobalLinkage:
return ir_instruction_setgloballinkage_get_dep((IrInstructionSetGlobalLinkage *) instruction, index);
case IrInstructionIdDeclRef: case IrInstructionIdDeclRef:
return ir_instruction_declref_get_dep((IrInstructionDeclRef *) instruction, index); return ir_instruction_declref_get_dep((IrInstructionDeclRef *) instruction, index);
case IrInstructionIdPanic: case IrInstructionIdPanic:
@ -4528,39 +4515,6 @@ static IrInstruction *ir_gen_builtin_fn_call(IrBuilder *irb, Scope *scope, AstNo
return ir_build_can_implicit_cast(irb, scope, node, arg0_value, arg1_value); return ir_build_can_implicit_cast(irb, scope, node, arg0_value, arg1_value);
} }
case BuiltinFnIdSetGlobalSection:
case BuiltinFnIdSetGlobalLinkage:
{
AstNode *arg0_node = node->data.fn_call_expr.params.at(0);
if (arg0_node->type != NodeTypeSymbol) {
add_node_error(irb->codegen, arg0_node, buf_sprintf("expected identifier"));
return irb->codegen->invalid_instruction;
}
Buf *variable_name = arg0_node->data.symbol_expr.symbol;
Tld *tld = find_decl(irb->codegen, scope, variable_name);
if (!tld) {
add_node_error(irb->codegen, node, buf_sprintf("use of undeclared identifier '%s'",
buf_ptr(variable_name)));
return irb->codegen->invalid_instruction;
}
if (tld->id != TldIdVar && tld->id != TldIdFn) {
add_node_error(irb->codegen, node, buf_sprintf("'%s' must be global variable or function",
buf_ptr(variable_name)));
return irb->codegen->invalid_instruction;
}
AstNode *arg1_node = node->data.fn_call_expr.params.at(1);
IrInstruction *arg1_value = ir_gen_node(irb, arg1_node, scope);
if (arg1_value == irb->codegen->invalid_instruction)
return arg1_value;
if (builtin_fn->id == BuiltinFnIdSetGlobalSection) {
return ir_build_set_global_section(irb, scope, node, tld, arg1_value);
} else if (builtin_fn->id == BuiltinFnIdSetGlobalLinkage) {
return ir_build_set_global_linkage(irb, scope, node, tld, arg1_value);
} else {
zig_unreachable();
}
}
case BuiltinFnIdPanic: case BuiltinFnIdPanic:
{ {
AstNode *arg0_node = node->data.fn_call_expr.params.at(0); AstNode *arg0_node = node->data.fn_call_expr.params.at(0);
@ -4784,6 +4738,31 @@ static IrInstruction *ir_gen_builtin_fn_call(IrBuilder *irb, Scope *scope, AstNo
return ir_build_arg_type(irb, scope, node, arg0_value, arg1_value); return ir_build_arg_type(irb, scope, node, arg0_value, arg1_value);
} }
case BuiltinFnIdExport:
case BuiltinFnIdExportWithLinkage:
{
AstNode *arg0_node = node->data.fn_call_expr.params.at(0);
IrInstruction *arg0_value = ir_gen_node(irb, arg0_node, scope);
if (arg0_value == irb->codegen->invalid_instruction)
return arg0_value;
AstNode *arg1_node = node->data.fn_call_expr.params.at(1);
IrInstruction *arg1_value = ir_gen_node(irb, arg1_node, scope);
if (arg1_value == irb->codegen->invalid_instruction)
return arg1_value;
IrInstruction *arg2_value;
if (builtin_fn->id == BuiltinFnIdExportWithLinkage) {
AstNode *arg2_node = node->data.fn_call_expr.params.at(2);
arg2_value = ir_gen_node(irb, arg2_node, scope);
if (arg2_value == irb->codegen->invalid_instruction)
return arg2_value;
} else {
arg2_value = nullptr;
}
return ir_build_export(irb, scope, node, arg0_value, arg1_value, arg2_value);
}
} }
zig_unreachable(); zig_unreachable();
} }
@ -5106,6 +5085,11 @@ static IrInstruction *ir_gen_var_decl(IrBuilder *irb, Scope *scope, AstNode *nod
return align_value; return align_value;
} }
if (variable_declaration->section_expr != nullptr) {
add_node_error(irb->codegen, variable_declaration->section_expr,
buf_sprintf("cannot set section of local variable '%s'", buf_ptr(variable_declaration->symbol)));
}
IrInstruction *init_value = ir_gen_node(irb, variable_declaration->expr, scope); IrInstruction *init_value = ir_gen_node(irb, variable_declaration->expr, scope);
if (init_value == irb->codegen->invalid_instruction) if (init_value == irb->codegen->invalid_instruction)
return init_value; return init_value;
@ -6355,6 +6339,10 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop
case NodeTypeSwitchRange: case NodeTypeSwitchRange:
case NodeTypeStructField: case NodeTypeStructField:
case NodeTypeLabel: case NodeTypeLabel:
case NodeTypeFnDef:
case NodeTypeFnDecl:
case NodeTypeErrorValueDecl:
case NodeTypeTestDecl:
zig_unreachable(); zig_unreachable();
case NodeTypeBlock: case NodeTypeBlock:
return ir_lval_wrap(irb, scope, ir_gen_block(irb, scope, node), lval); return ir_lval_wrap(irb, scope, ir_gen_block(irb, scope, node), lval);
@ -6436,14 +6424,6 @@ static IrInstruction *ir_gen_node_raw(IrBuilder *irb, AstNode *node, Scope *scop
return ir_lval_wrap(irb, scope, ir_gen_container_decl(irb, scope, node), lval); return ir_lval_wrap(irb, scope, ir_gen_container_decl(irb, scope, node), lval);
case NodeTypeFnProto: case NodeTypeFnProto:
return ir_lval_wrap(irb, scope, ir_gen_fn_proto(irb, scope, node), lval); return ir_lval_wrap(irb, scope, ir_gen_fn_proto(irb, scope, node), lval);
case NodeTypeFnDef:
zig_panic("TODO IR gen NodeTypeFnDef");
case NodeTypeFnDecl:
zig_panic("TODO IR gen NodeTypeFnDecl");
case NodeTypeErrorValueDecl:
zig_panic("TODO IR gen NodeTypeErrorValueDecl");
case NodeTypeTestDecl:
zig_panic("TODO IR gen NodeTypeTestDecl");
} }
zig_unreachable(); zig_unreachable();
} }
@ -10481,6 +10461,194 @@ static TypeTableEntry *ir_analyze_instruction_decl_var(IrAnalyze *ira, IrInstruc
return ira->codegen->builtin_types.entry_void; return ira->codegen->builtin_types.entry_void;
} }
static TypeTableEntry *ir_analyze_instruction_export(IrAnalyze *ira, IrInstructionExport *instruction) {
IrInstruction *name = instruction->name->other;
Buf *symbol_name = ir_resolve_str(ira, name);
if (symbol_name == nullptr) {
return ira->codegen->builtin_types.entry_invalid;
}
IrInstruction *target = instruction->target->other;
if (type_is_invalid(target->value.type)) {
return ira->codegen->builtin_types.entry_invalid;
}
GlobalLinkageId global_linkage_id = GlobalLinkageIdStrong;
if (instruction->linkage != nullptr) {
IrInstruction *linkage_value = instruction->linkage->other;
if (!ir_resolve_global_linkage(ira, linkage_value, &global_linkage_id)) {
return ira->codegen->builtin_types.entry_invalid;
}
}
auto entry = ira->codegen->exported_symbol_names.put_unique(symbol_name, instruction->base.source_node);
if (entry) {
AstNode *other_export_node = entry->value;
ErrorMsg *msg = ir_add_error(ira, &instruction->base,
buf_sprintf("exported symbol collision: '%s'", buf_ptr(symbol_name)));
add_error_note(ira->codegen, msg, other_export_node, buf_sprintf("other symbol is here"));
}
switch (target->value.type->id) {
case TypeTableEntryIdInvalid:
case TypeTableEntryIdVar:
case TypeTableEntryIdUnreachable:
zig_unreachable();
case TypeTableEntryIdFn: {
FnTableEntry *fn_entry = target->value.data.x_fn.fn_entry;
CallingConvention cc = fn_entry->type_entry->data.fn.fn_type_id.cc;
switch (cc) {
case CallingConventionUnspecified: {
ErrorMsg *msg = ir_add_error(ira, target,
buf_sprintf("exported function must specify calling convention"));
add_error_note(ira->codegen, msg, fn_entry->proto_node, buf_sprintf("declared here"));
} break;
case CallingConventionC:
if (buf_eql_str(symbol_name, "main") && ira->codegen->libc_link_lib != nullptr) {
ira->codegen->have_c_main = true;
ira->codegen->windows_subsystem_windows = false;
ira->codegen->windows_subsystem_console = true;
} else if (buf_eql_str(symbol_name, "WinMain") &&
ira->codegen->zig_target.os == ZigLLVM_Win32)
{
ira->codegen->have_winmain = true;
ira->codegen->windows_subsystem_windows = true;
ira->codegen->windows_subsystem_console = false;
} else if (buf_eql_str(symbol_name, "WinMainCRTStartup") &&
ira->codegen->zig_target.os == ZigLLVM_Win32)
{
ira->codegen->have_winmain_crt_startup = true;
} else if (buf_eql_str(symbol_name, "DllMainCRTStartup") &&
ira->codegen->zig_target.os == ZigLLVM_Win32)
{
ira->codegen->have_dllmain_crt_startup = true;
}
// fallthrough
case CallingConventionNaked:
case CallingConventionCold:
case CallingConventionStdcall: {
FnExport *fn_export = fn_entry->export_list.add_one();
memset(fn_export, 0, sizeof(FnExport));
buf_init_from_buf(&fn_export->name, symbol_name);
fn_export->linkage = global_linkage_id;
fn_export->source_node = instruction->base.source_node;
} break;
}
} break;
case TypeTableEntryIdStruct:
if (is_slice(target->value.type)) {
ir_add_error(ira, target,
buf_sprintf("unable to export value of type '%s'", buf_ptr(&target->value.type->name)));
} else if (target->value.type->data.structure.layout != ContainerLayoutExtern) {
ErrorMsg *msg = ir_add_error(ira, target,
buf_sprintf("exported struct value must be declared extern"));
add_error_note(ira->codegen, msg, target->value.type->data.structure.decl_node, buf_sprintf("declared here"));
}
break;
case TypeTableEntryIdUnion:
if (target->value.type->data.unionation.layout != ContainerLayoutExtern) {
ErrorMsg *msg = ir_add_error(ira, target,
buf_sprintf("exported union value must be declared extern"));
add_error_note(ira->codegen, msg, target->value.type->data.unionation.decl_node, buf_sprintf("declared here"));
}
break;
case TypeTableEntryIdEnum:
if (target->value.type->data.enumeration.layout != ContainerLayoutExtern) {
ErrorMsg *msg = ir_add_error(ira, target,
buf_sprintf("exported enum value must be declared extern"));
add_error_note(ira->codegen, msg, target->value.type->data.enumeration.decl_node, buf_sprintf("declared here"));
}
break;
case TypeTableEntryIdMetaType: {
TypeTableEntry *type_value = target->value.data.x_type;
switch (type_value->id) {
case TypeTableEntryIdInvalid:
case TypeTableEntryIdVar:
zig_unreachable();
case TypeTableEntryIdStruct:
if (is_slice(type_value)) {
ir_add_error(ira, target,
buf_sprintf("unable to export type '%s'", buf_ptr(&type_value->name)));
} else if (type_value->data.structure.layout != ContainerLayoutExtern) {
ErrorMsg *msg = ir_add_error(ira, target,
buf_sprintf("exported struct must be declared extern"));
add_error_note(ira->codegen, msg, type_value->data.structure.decl_node, buf_sprintf("declared here"));
}
break;
case TypeTableEntryIdUnion:
if (type_value->data.unionation.layout != ContainerLayoutExtern) {
ErrorMsg *msg = ir_add_error(ira, target,
buf_sprintf("exported union must be declared extern"));
add_error_note(ira->codegen, msg, type_value->data.unionation.decl_node, buf_sprintf("declared here"));
}
break;
case TypeTableEntryIdEnum:
if (type_value->data.enumeration.layout != ContainerLayoutExtern) {
ErrorMsg *msg = ir_add_error(ira, target,
buf_sprintf("exported enum must be declared extern"));
add_error_note(ira->codegen, msg, type_value->data.enumeration.decl_node, buf_sprintf("declared here"));
}
break;
case TypeTableEntryIdFn: {
if (type_value->data.fn.fn_type_id.cc == CallingConventionUnspecified) {
ir_add_error(ira, target,
buf_sprintf("exported function type must specify calling convention"));
}
} break;
case TypeTableEntryIdInt:
case TypeTableEntryIdFloat:
case TypeTableEntryIdPointer:
case TypeTableEntryIdArray:
case TypeTableEntryIdBool:
break;
case TypeTableEntryIdMetaType:
case TypeTableEntryIdVoid:
case TypeTableEntryIdUnreachable:
case TypeTableEntryIdNumLitFloat:
case TypeTableEntryIdNumLitInt:
case TypeTableEntryIdUndefLit:
case TypeTableEntryIdNullLit:
case TypeTableEntryIdMaybe:
case TypeTableEntryIdErrorUnion:
case TypeTableEntryIdPureError:
case TypeTableEntryIdNamespace:
case TypeTableEntryIdBlock:
case TypeTableEntryIdBoundFn:
case TypeTableEntryIdArgTuple:
case TypeTableEntryIdOpaque:
ir_add_error(ira, target,
buf_sprintf("invalid export target '%s'", buf_ptr(&type_value->name)));
break;
}
} break;
case TypeTableEntryIdVoid:
case TypeTableEntryIdBool:
case TypeTableEntryIdInt:
case TypeTableEntryIdFloat:
case TypeTableEntryIdPointer:
case TypeTableEntryIdArray:
case TypeTableEntryIdNumLitFloat:
case TypeTableEntryIdNumLitInt:
case TypeTableEntryIdUndefLit:
case TypeTableEntryIdNullLit:
case TypeTableEntryIdMaybe:
case TypeTableEntryIdErrorUnion:
case TypeTableEntryIdPureError:
zig_panic("TODO export const value of type %s", buf_ptr(&target->value.type->name));
case TypeTableEntryIdNamespace:
case TypeTableEntryIdBlock:
case TypeTableEntryIdBoundFn:
case TypeTableEntryIdArgTuple:
case TypeTableEntryIdOpaque:
ir_add_error(ira, target,
buf_sprintf("invalid export target type '%s'", buf_ptr(&target->value.type->name)));
break;
}
ir_build_const_from(ira, &instruction->base);
return ira->codegen->builtin_types.entry_void;
}
static bool ir_analyze_fn_call_inline_arg(IrAnalyze *ira, AstNode *fn_proto_node, static bool ir_analyze_fn_call_inline_arg(IrAnalyze *ira, AstNode *fn_proto_node,
IrInstruction *arg, Scope **exec_scope, size_t *next_proto_i) IrInstruction *arg, Scope **exec_scope, size_t *next_proto_i)
{ {
@ -12399,102 +12567,6 @@ static TypeTableEntry *ir_analyze_instruction_ptr_type_child(IrAnalyze *ira,
return ira->codegen->builtin_types.entry_type; return ira->codegen->builtin_types.entry_type;
} }
static TypeTableEntry *ir_analyze_instruction_set_global_section(IrAnalyze *ira,
IrInstructionSetGlobalSection *instruction)
{
Tld *tld = instruction->tld;
IrInstruction *section_value = instruction->value->other;
resolve_top_level_decl(ira->codegen, tld, true, instruction->base.source_node);
if (tld->resolution == TldResolutionInvalid)
return ira->codegen->builtin_types.entry_invalid;
Buf *section_name = ir_resolve_str(ira, section_value);
if (!section_name)
return ira->codegen->builtin_types.entry_invalid;
AstNode **set_global_section_node;
Buf **section_name_ptr;
if (tld->id == TldIdVar) {
TldVar *tld_var = (TldVar *)tld;
set_global_section_node = &tld_var->set_global_section_node;
section_name_ptr = &tld_var->section_name;
if (tld_var->var->linkage == VarLinkageExternal) {
ErrorMsg *msg = ir_add_error(ira, &instruction->base,
buf_sprintf("cannot set section of external variable '%s'", buf_ptr(&tld_var->var->name)));
add_error_note(ira->codegen, msg, tld->source_node, buf_sprintf("declared here"));
return ira->codegen->builtin_types.entry_invalid;
}
} else if (tld->id == TldIdFn) {
TldFn *tld_fn = (TldFn *)tld;
FnTableEntry *fn_entry = tld_fn->fn_entry;
set_global_section_node = &fn_entry->set_global_section_node;
section_name_ptr = &fn_entry->section_name;
if (fn_entry->def_scope == nullptr) {
ErrorMsg *msg = ir_add_error(ira, &instruction->base,
buf_sprintf("cannot set section of external function '%s'", buf_ptr(&fn_entry->symbol_name)));
add_error_note(ira->codegen, msg, tld->source_node, buf_sprintf("declared here"));
return ira->codegen->builtin_types.entry_invalid;
}
} else {
// error is caught in pass1 IR gen
zig_unreachable();
}
AstNode *source_node = instruction->base.source_node;
if (*set_global_section_node) {
ErrorMsg *msg = ir_add_error_node(ira, source_node, buf_sprintf("section set twice"));
add_error_note(ira->codegen, msg, *set_global_section_node, buf_sprintf("first set here"));
return ira->codegen->builtin_types.entry_invalid;
}
*set_global_section_node = source_node;
*section_name_ptr = section_name;
ir_build_const_from(ira, &instruction->base);
return ira->codegen->builtin_types.entry_void;
}
static TypeTableEntry *ir_analyze_instruction_set_global_linkage(IrAnalyze *ira,
IrInstructionSetGlobalLinkage *instruction)
{
Tld *tld = instruction->tld;
IrInstruction *linkage_value = instruction->value->other;
GlobalLinkageId linkage_scalar;
if (!ir_resolve_global_linkage(ira, linkage_value, &linkage_scalar))
return ira->codegen->builtin_types.entry_invalid;
AstNode **set_global_linkage_node;
GlobalLinkageId *dest_linkage_ptr;
if (tld->id == TldIdVar) {
TldVar *tld_var = (TldVar *)tld;
set_global_linkage_node = &tld_var->set_global_linkage_node;
dest_linkage_ptr = &tld_var->linkage;
} else if (tld->id == TldIdFn) {
TldFn *tld_fn = (TldFn *)tld;
FnTableEntry *fn_entry = tld_fn->fn_entry;
set_global_linkage_node = &fn_entry->set_global_linkage_node;
dest_linkage_ptr = &fn_entry->linkage;
} else {
// error is caught in pass1 IR gen
zig_unreachable();
}
AstNode *source_node = instruction->base.source_node;
if (*set_global_linkage_node) {
ErrorMsg *msg = ir_add_error_node(ira, source_node, buf_sprintf("linkage set twice"));
add_error_note(ira->codegen, msg, *set_global_linkage_node, buf_sprintf("first set here"));
return ira->codegen->builtin_types.entry_invalid;
}
*set_global_linkage_node = source_node;
*dest_linkage_ptr = linkage_scalar;
ir_build_const_from(ira, &instruction->base);
return ira->codegen->builtin_types.entry_void;
}
static TypeTableEntry *ir_analyze_instruction_set_debug_safety(IrAnalyze *ira, static TypeTableEntry *ir_analyze_instruction_set_debug_safety(IrAnalyze *ira,
IrInstructionSetDebugSafety *set_debug_safety_instruction) IrInstructionSetDebugSafety *set_debug_safety_instruction)
{ {
@ -16165,10 +16237,6 @@ static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstructi
return ir_analyze_instruction_to_ptr_type(ira, (IrInstructionToPtrType *)instruction); return ir_analyze_instruction_to_ptr_type(ira, (IrInstructionToPtrType *)instruction);
case IrInstructionIdPtrTypeChild: case IrInstructionIdPtrTypeChild:
return ir_analyze_instruction_ptr_type_child(ira, (IrInstructionPtrTypeChild *)instruction); return ir_analyze_instruction_ptr_type_child(ira, (IrInstructionPtrTypeChild *)instruction);
case IrInstructionIdSetGlobalSection:
return ir_analyze_instruction_set_global_section(ira, (IrInstructionSetGlobalSection *)instruction);
case IrInstructionIdSetGlobalLinkage:
return ir_analyze_instruction_set_global_linkage(ira, (IrInstructionSetGlobalLinkage *)instruction);
case IrInstructionIdSetDebugSafety: case IrInstructionIdSetDebugSafety:
return ir_analyze_instruction_set_debug_safety(ira, (IrInstructionSetDebugSafety *)instruction); return ir_analyze_instruction_set_debug_safety(ira, (IrInstructionSetDebugSafety *)instruction);
case IrInstructionIdSetFloatMode: case IrInstructionIdSetFloatMode:
@ -16311,6 +16379,8 @@ static TypeTableEntry *ir_analyze_instruction_nocast(IrAnalyze *ira, IrInstructi
return ir_analyze_instruction_arg_type(ira, (IrInstructionArgType *)instruction); return ir_analyze_instruction_arg_type(ira, (IrInstructionArgType *)instruction);
case IrInstructionIdTagType: case IrInstructionIdTagType:
return ir_analyze_instruction_tag_type(ira, (IrInstructionTagType *)instruction); return ir_analyze_instruction_tag_type(ira, (IrInstructionTagType *)instruction);
case IrInstructionIdExport:
return ir_analyze_instruction_export(ira, (IrInstructionExport *)instruction);
} }
zig_unreachable(); zig_unreachable();
} }
@ -16418,12 +16488,11 @@ bool ir_has_side_effects(IrInstruction *instruction) {
case IrInstructionIdOverflowOp: // TODO when we support multiple returns this can be side effect free case IrInstructionIdOverflowOp: // TODO when we support multiple returns this can be side effect free
case IrInstructionIdCheckSwitchProngs: case IrInstructionIdCheckSwitchProngs:
case IrInstructionIdCheckStatementIsVoid: case IrInstructionIdCheckStatementIsVoid:
case IrInstructionIdSetGlobalSection:
case IrInstructionIdSetGlobalLinkage:
case IrInstructionIdPanic: case IrInstructionIdPanic:
case IrInstructionIdSetEvalBranchQuota: case IrInstructionIdSetEvalBranchQuota:
case IrInstructionIdPtrTypeOf: case IrInstructionIdPtrTypeOf:
case IrInstructionIdSetAlignStack: case IrInstructionIdSetAlignStack:
case IrInstructionIdExport:
return true; return true;
case IrInstructionIdPhi: case IrInstructionIdPhi:
case IrInstructionIdUnOp: case IrInstructionIdUnOp:

View File

@ -899,19 +899,6 @@ static void ir_print_ptr_type_of(IrPrint *irp, IrInstructionPtrTypeOf *instructi
ir_print_other_instruction(irp, instruction->child_type); ir_print_other_instruction(irp, instruction->child_type);
} }
static void ir_print_set_global_section(IrPrint *irp, IrInstructionSetGlobalSection *instruction) {
fprintf(irp->f, "@setGlobalSection(%s,", buf_ptr(instruction->tld->name));
ir_print_other_instruction(irp, instruction->value);
fprintf(irp->f, ")");
}
static void ir_print_set_global_linkage(IrPrint *irp, IrInstructionSetGlobalLinkage *instruction) {
fprintf(irp->f, "@setGlobalLinkage(%s,", buf_ptr(instruction->tld->name));
ir_print_other_instruction(irp, instruction->value);
fprintf(irp->f, ")");
}
static void ir_print_decl_ref(IrPrint *irp, IrInstructionDeclRef *instruction) { static void ir_print_decl_ref(IrPrint *irp, IrInstructionDeclRef *instruction) {
const char *ptr_str = instruction->lval.is_ptr ? "ptr " : ""; const char *ptr_str = instruction->lval.is_ptr ? "ptr " : "";
const char *const_str = instruction->lval.is_const ? "const " : ""; const char *const_str = instruction->lval.is_const ? "const " : "";
@ -991,6 +978,24 @@ static void ir_print_enum_tag_type(IrPrint *irp, IrInstructionTagType *instructi
fprintf(irp->f, ")"); fprintf(irp->f, ")");
} }
static void ir_print_export(IrPrint *irp, IrInstructionExport *instruction) {
if (instruction->linkage == nullptr) {
fprintf(irp->f, "@export(");
ir_print_other_instruction(irp, instruction->name);
fprintf(irp->f, ",");
ir_print_other_instruction(irp, instruction->target);
fprintf(irp->f, ")");
} else {
fprintf(irp->f, "@exportWithLinkage(");
ir_print_other_instruction(irp, instruction->name);
fprintf(irp->f, ",");
ir_print_other_instruction(irp, instruction->target);
fprintf(irp->f, ",");
ir_print_other_instruction(irp, instruction->linkage);
fprintf(irp->f, ")");
}
}
static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) { static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) {
ir_print_prefix(irp, instruction); ir_print_prefix(irp, instruction);
@ -1267,12 +1272,6 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) {
case IrInstructionIdPtrTypeOf: case IrInstructionIdPtrTypeOf:
ir_print_ptr_type_of(irp, (IrInstructionPtrTypeOf *)instruction); ir_print_ptr_type_of(irp, (IrInstructionPtrTypeOf *)instruction);
break; break;
case IrInstructionIdSetGlobalSection:
ir_print_set_global_section(irp, (IrInstructionSetGlobalSection *)instruction);
break;
case IrInstructionIdSetGlobalLinkage:
ir_print_set_global_linkage(irp, (IrInstructionSetGlobalLinkage *)instruction);
break;
case IrInstructionIdDeclRef: case IrInstructionIdDeclRef:
ir_print_decl_ref(irp, (IrInstructionDeclRef *)instruction); ir_print_decl_ref(irp, (IrInstructionDeclRef *)instruction);
break; break;
@ -1306,6 +1305,9 @@ static void ir_print_instruction(IrPrint *irp, IrInstruction *instruction) {
case IrInstructionIdTagType: case IrInstructionIdTagType:
ir_print_enum_tag_type(irp, (IrInstructionTagType *)instruction); ir_print_enum_tag_type(irp, (IrInstructionTagType *)instruction);
break; break;
case IrInstructionIdExport:
ir_print_export(irp, (IrInstructionExport *)instruction);
break;
} }
fprintf(irp->f, "\n"); fprintf(irp->f, "\n");
} }

View File

@ -1600,6 +1600,14 @@ static AstNode *ast_parse_variable_declaration_expr(ParseContext *pc, size_t *to
next_token = &pc->tokens->at(*token_index); next_token = &pc->tokens->at(*token_index);
} }
if (next_token->id == TokenIdKeywordSection) {
*token_index += 1;
ast_eat_token(pc, token_index, TokenIdLParen);
node->data.variable_declaration.section_expr = ast_parse_expression(pc, token_index, true);
ast_eat_token(pc, token_index, TokenIdRParen);
next_token = &pc->tokens->at(*token_index);
}
if (next_token->id == TokenIdEq) { if (next_token->id == TokenIdEq) {
*token_index += 1; *token_index += 1;
node->data.variable_declaration.expr = ast_parse_expression(pc, token_index, true); node->data.variable_declaration.expr = ast_parse_expression(pc, token_index, true);
@ -2144,7 +2152,7 @@ static bool statement_terminates_without_semicolon(AstNode *node) {
/* /*
Block = "{" many(Statement) option(Expression) "}" Block = "{" many(Statement) option(Expression) "}"
Statement = Label | VariableDeclaration ";" | Defer(Block) | Defer(Expression) ";" | BlockExpression(Block) | Expression ";" | ";" Statement = Label | VariableDeclaration ";" | Defer(Block) | Defer(Expression) ";" | BlockExpression(Block) | Expression ";" | ";" | ExportDecl
*/ */
static AstNode *ast_parse_block(ParseContext *pc, size_t *token_index, bool mandatory) { static AstNode *ast_parse_block(ParseContext *pc, size_t *token_index, bool mandatory) {
Token *last_token = &pc->tokens->at(*token_index); Token *last_token = &pc->tokens->at(*token_index);
@ -2205,7 +2213,7 @@ static AstNode *ast_parse_block(ParseContext *pc, size_t *token_index, bool mand
} }
/* /*
FnProto = option("coldcc" | "nakedcc" | "stdcallcc") "fn" option(Symbol) ParamDeclList option("align" "(" Expression ")") option("->" TypeExpr) FnProto = option("coldcc" | "nakedcc" | "stdcallcc") "fn" option(Symbol) ParamDeclList option("align" "(" Expression ")") option("section" "(" Expression ")") option("-&gt;" TypeExpr)
*/ */
static AstNode *ast_parse_fn_proto(ParseContext *pc, size_t *token_index, bool mandatory, VisibMod visib_mod) { static AstNode *ast_parse_fn_proto(ParseContext *pc, size_t *token_index, bool mandatory, VisibMod visib_mod) {
Token *first_token = &pc->tokens->at(*token_index); Token *first_token = &pc->tokens->at(*token_index);
@ -2259,6 +2267,14 @@ static AstNode *ast_parse_fn_proto(ParseContext *pc, size_t *token_index, bool m
ast_eat_token(pc, token_index, TokenIdRParen); ast_eat_token(pc, token_index, TokenIdRParen);
next_token = &pc->tokens->at(*token_index); next_token = &pc->tokens->at(*token_index);
} }
if (next_token->id == TokenIdKeywordSection) {
*token_index += 1;
ast_eat_token(pc, token_index, TokenIdLParen);
node->data.fn_proto.section_expr = ast_parse_expression(pc, token_index, true);
ast_eat_token(pc, token_index, TokenIdRParen);
next_token = &pc->tokens->at(*token_index);
}
if (next_token->id == TokenIdArrow) { if (next_token->id == TokenIdArrow) {
*token_index += 1; *token_index += 1;
node->data.fn_proto.return_type = ast_parse_type_expr(pc, token_index, false); node->data.fn_proto.return_type = ast_parse_type_expr(pc, token_index, false);
@ -2447,9 +2463,6 @@ static AstNode *ast_parse_container_decl(ParseContext *pc, size_t *token_index,
if (visib_tok->id == TokenIdKeywordPub) { if (visib_tok->id == TokenIdKeywordPub) {
*token_index += 1; *token_index += 1;
visib_mod = VisibModPub; visib_mod = VisibModPub;
} else if (visib_tok->id == TokenIdKeywordExport) {
*token_index += 1;
visib_mod = VisibModExport;
} else { } else {
visib_mod = VisibModPrivate; visib_mod = VisibModPrivate;
} }
@ -2580,9 +2593,6 @@ static void ast_parse_top_level_decls(ParseContext *pc, size_t *token_index, Zig
if (visib_tok->id == TokenIdKeywordPub) { if (visib_tok->id == TokenIdKeywordPub) {
*token_index += 1; *token_index += 1;
visib_mod = VisibModPub; visib_mod = VisibModPub;
} else if (visib_tok->id == TokenIdKeywordExport) {
*token_index += 1;
visib_mod = VisibModExport;
} else { } else {
visib_mod = VisibModPrivate; visib_mod = VisibModPrivate;
} }
@ -2669,6 +2679,7 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont
visit_field(&node->data.fn_proto.return_type, visit, context); visit_field(&node->data.fn_proto.return_type, visit, context);
visit_node_list(&node->data.fn_proto.params, visit, context); visit_node_list(&node->data.fn_proto.params, visit, context);
visit_field(&node->data.fn_proto.align_expr, visit, context); visit_field(&node->data.fn_proto.align_expr, visit, context);
visit_field(&node->data.fn_proto.section_expr, visit, context);
break; break;
case NodeTypeFnDef: case NodeTypeFnDef:
visit_field(&node->data.fn_def.fn_proto, visit, context); visit_field(&node->data.fn_def.fn_proto, visit, context);
@ -2696,6 +2707,7 @@ void ast_visit_node_children(AstNode *node, void (*visit)(AstNode **, void *cont
visit_field(&node->data.variable_declaration.type, visit, context); visit_field(&node->data.variable_declaration.type, visit, context);
visit_field(&node->data.variable_declaration.expr, visit, context); visit_field(&node->data.variable_declaration.expr, visit, context);
visit_field(&node->data.variable_declaration.align_expr, visit, context); visit_field(&node->data.variable_declaration.align_expr, visit, context);
visit_field(&node->data.variable_declaration.section_expr, visit, context);
break; break;
case NodeTypeErrorValueDecl: case NodeTypeErrorValueDecl:
// none // none

View File

@ -119,7 +119,6 @@ static const struct ZigKeyword zig_keywords[] = {
{"else", TokenIdKeywordElse}, {"else", TokenIdKeywordElse},
{"enum", TokenIdKeywordEnum}, {"enum", TokenIdKeywordEnum},
{"error", TokenIdKeywordError}, {"error", TokenIdKeywordError},
{"export", TokenIdKeywordExport},
{"extern", TokenIdKeywordExtern}, {"extern", TokenIdKeywordExtern},
{"false", TokenIdKeywordFalse}, {"false", TokenIdKeywordFalse},
{"fn", TokenIdKeywordFn}, {"fn", TokenIdKeywordFn},
@ -134,6 +133,7 @@ static const struct ZigKeyword zig_keywords[] = {
{"packed", TokenIdKeywordPacked}, {"packed", TokenIdKeywordPacked},
{"pub", TokenIdKeywordPub}, {"pub", TokenIdKeywordPub},
{"return", TokenIdKeywordReturn}, {"return", TokenIdKeywordReturn},
{"section", TokenIdKeywordSection},
{"stdcallcc", TokenIdKeywordStdcallCC}, {"stdcallcc", TokenIdKeywordStdcallCC},
{"struct", TokenIdKeywordStruct}, {"struct", TokenIdKeywordStruct},
{"switch", TokenIdKeywordSwitch}, {"switch", TokenIdKeywordSwitch},
@ -1518,7 +1518,6 @@ const char * token_name(TokenId id) {
case TokenIdKeywordElse: return "else"; case TokenIdKeywordElse: return "else";
case TokenIdKeywordEnum: return "enum"; case TokenIdKeywordEnum: return "enum";
case TokenIdKeywordError: return "error"; case TokenIdKeywordError: return "error";
case TokenIdKeywordExport: return "export";
case TokenIdKeywordExtern: return "extern"; case TokenIdKeywordExtern: return "extern";
case TokenIdKeywordFalse: return "false"; case TokenIdKeywordFalse: return "false";
case TokenIdKeywordFn: return "fn"; case TokenIdKeywordFn: return "fn";
@ -1533,6 +1532,7 @@ const char * token_name(TokenId id) {
case TokenIdKeywordPacked: return "packed"; case TokenIdKeywordPacked: return "packed";
case TokenIdKeywordPub: return "pub"; case TokenIdKeywordPub: return "pub";
case TokenIdKeywordReturn: return "return"; case TokenIdKeywordReturn: return "return";
case TokenIdKeywordSection: return "section";
case TokenIdKeywordStdcallCC: return "stdcallcc"; case TokenIdKeywordStdcallCC: return "stdcallcc";
case TokenIdKeywordStruct: return "struct"; case TokenIdKeywordStruct: return "struct";
case TokenIdKeywordSwitch: return "switch"; case TokenIdKeywordSwitch: return "switch";

View File

@ -47,6 +47,7 @@ enum TokenId {
TokenIdFloatLiteral, TokenIdFloatLiteral,
TokenIdIntLiteral, TokenIdIntLiteral,
TokenIdKeywordAlign, TokenIdKeywordAlign,
TokenIdKeywordSection,
TokenIdKeywordAnd, TokenIdKeywordAnd,
TokenIdKeywordAsm, TokenIdKeywordAsm,
TokenIdKeywordBreak, TokenIdKeywordBreak,
@ -58,7 +59,6 @@ enum TokenId {
TokenIdKeywordElse, TokenIdKeywordElse,
TokenIdKeywordEnum, TokenIdKeywordEnum,
TokenIdKeywordError, TokenIdKeywordError,
TokenIdKeywordExport,
TokenIdKeywordExtern, TokenIdKeywordExtern,
TokenIdKeywordFalse, TokenIdKeywordFalse,
TokenIdKeywordFn, TokenIdKeywordFn,

View File

@ -73,7 +73,6 @@ struct Context {
ImportTableEntry *import; ImportTableEntry *import;
ZigList<ErrorMsg *> *errors; ZigList<ErrorMsg *> *errors;
VisibMod visib_mod; VisibMod visib_mod;
VisibMod export_visib_mod;
AstNode *root; AstNode *root;
HashMap<const void *, AstNode *, ptr_hash, ptr_eq> decl_table; HashMap<const void *, AstNode *, ptr_hash, ptr_eq> decl_table;
HashMap<Buf *, AstNode *, buf_hash, buf_eql_buf> macro_table; HashMap<Buf *, AstNode *, buf_hash, buf_eql_buf> macro_table;
@ -3251,7 +3250,8 @@ static void visit_fn_decl(Context *c, const FunctionDecl *fn_decl) {
StorageClass sc = fn_decl->getStorageClass(); StorageClass sc = fn_decl->getStorageClass();
if (sc == SC_None) { if (sc == SC_None) {
proto_node->data.fn_proto.visib_mod = fn_decl->hasBody() ? c->export_visib_mod : c->visib_mod; // TODO add export decl
proto_node->data.fn_proto.visib_mod = c->visib_mod;
} else if (sc == SC_Extern || sc == SC_Static) { } else if (sc == SC_Extern || sc == SC_Static) {
proto_node->data.fn_proto.visib_mod = c->visib_mod; proto_node->data.fn_proto.visib_mod = c->visib_mod;
} else if (sc == SC_PrivateExtern) { } else if (sc == SC_PrivateExtern) {
@ -4274,10 +4274,8 @@ int parse_h_file(ImportTableEntry *import, ZigList<ErrorMsg *> *errors, const ch
c->errors = errors; c->errors = errors;
if (buf_ends_with_str(buf_create_from_str(target_file), ".h")) { if (buf_ends_with_str(buf_create_from_str(target_file), ".h")) {
c->visib_mod = VisibModPub; c->visib_mod = VisibModPub;
c->export_visib_mod = VisibModPub;
} else { } else {
c->visib_mod = VisibModPub; c->visib_mod = VisibModPub;
c->export_visib_mod = VisibModExport;
} }
c->decl_table.init(8); c->decl_table.init(8);
c->macro_table.init(8); c->macro_table.init(8);

View File

@ -96,8 +96,6 @@ const WHITE = "\x1b[37;1m";
const DIM = "\x1b[2m"; const DIM = "\x1b[2m";
const RESET = "\x1b[0m"; const RESET = "\x1b[0m";
pub var user_main_fn: ?fn() -> %void = null;
error PathNotFound; error PathNotFound;
error InvalidDebugInfo; error InvalidDebugInfo;

View File

@ -188,39 +188,39 @@ pub const Elf = struct {
if (elf.is_64) { if (elf.is_64) {
if (sh_entry_size != 64) return error.InvalidFormat; if (sh_entry_size != 64) return error.InvalidFormat;
for (elf.section_headers) |*section| { for (elf.section_headers) |*elf_section| {
section.name = %return in.readInt(elf.endian, u32); elf_section.name = %return in.readInt(elf.endian, u32);
section.sh_type = %return in.readInt(elf.endian, u32); elf_section.sh_type = %return in.readInt(elf.endian, u32);
section.flags = %return in.readInt(elf.endian, u64); elf_section.flags = %return in.readInt(elf.endian, u64);
section.addr = %return in.readInt(elf.endian, u64); elf_section.addr = %return in.readInt(elf.endian, u64);
section.offset = %return in.readInt(elf.endian, u64); elf_section.offset = %return in.readInt(elf.endian, u64);
section.size = %return in.readInt(elf.endian, u64); elf_section.size = %return in.readInt(elf.endian, u64);
section.link = %return in.readInt(elf.endian, u32); elf_section.link = %return in.readInt(elf.endian, u32);
section.info = %return in.readInt(elf.endian, u32); elf_section.info = %return in.readInt(elf.endian, u32);
section.addr_align = %return in.readInt(elf.endian, u64); elf_section.addr_align = %return in.readInt(elf.endian, u64);
section.ent_size = %return in.readInt(elf.endian, u64); elf_section.ent_size = %return in.readInt(elf.endian, u64);
} }
} else { } else {
if (sh_entry_size != 40) return error.InvalidFormat; if (sh_entry_size != 40) return error.InvalidFormat;
for (elf.section_headers) |*section| { for (elf.section_headers) |*elf_section| {
// TODO (multiple occurences) allow implicit cast from %u32 -> %u64 ? // TODO (multiple occurences) allow implicit cast from %u32 -> %u64 ?
section.name = %return in.readInt(elf.endian, u32); elf_section.name = %return in.readInt(elf.endian, u32);
section.sh_type = %return in.readInt(elf.endian, u32); elf_section.sh_type = %return in.readInt(elf.endian, u32);
section.flags = u64(%return in.readInt(elf.endian, u32)); elf_section.flags = u64(%return in.readInt(elf.endian, u32));
section.addr = u64(%return in.readInt(elf.endian, u32)); elf_section.addr = u64(%return in.readInt(elf.endian, u32));
section.offset = u64(%return in.readInt(elf.endian, u32)); elf_section.offset = u64(%return in.readInt(elf.endian, u32));
section.size = u64(%return in.readInt(elf.endian, u32)); elf_section.size = u64(%return in.readInt(elf.endian, u32));
section.link = %return in.readInt(elf.endian, u32); elf_section.link = %return in.readInt(elf.endian, u32);
section.info = %return in.readInt(elf.endian, u32); elf_section.info = %return in.readInt(elf.endian, u32);
section.addr_align = u64(%return in.readInt(elf.endian, u32)); elf_section.addr_align = u64(%return in.readInt(elf.endian, u32));
section.ent_size = u64(%return in.readInt(elf.endian, u32)); elf_section.ent_size = u64(%return in.readInt(elf.endian, u32));
} }
} }
for (elf.section_headers) |*section| { for (elf.section_headers) |*elf_section| {
if (section.sh_type != SHT_NOBITS) { if (elf_section.sh_type != SHT_NOBITS) {
const file_end_offset = %return math.add(u64, section.offset, section.size); const file_end_offset = %return math.add(u64, elf_section.offset, elf_section.size);
if (stream_end < file_end_offset) return error.InvalidFormat; if (stream_end < file_end_offset) return error.InvalidFormat;
} }
} }
@ -243,10 +243,10 @@ pub const Elf = struct {
var file_stream = io.FileInStream.init(elf.in_file); var file_stream = io.FileInStream.init(elf.in_file);
const in = &file_stream.stream; const in = &file_stream.stream;
for (elf.section_headers) |*section| { for (elf.section_headers) |*elf_section| {
if (section.sh_type == SHT_NULL) continue; if (elf_section.sh_type == SHT_NULL) continue;
const name_offset = elf.string_section.offset + section.name; const name_offset = elf.string_section.offset + elf_section.name;
%return elf.in_file.seekTo(name_offset); %return elf.in_file.seekTo(name_offset);
for (name) |expected_c| { for (name) |expected_c| {
@ -256,7 +256,7 @@ pub const Elf = struct {
{ {
const null_byte = %return in.readByte(); const null_byte = %return in.readByte();
if (null_byte == 0) return section; if (null_byte == 0) return elf_section;
} }
next_section: next_section:
@ -265,7 +265,7 @@ pub const Elf = struct {
return null; return null;
} }
pub fn seekToSection(elf: &Elf, section: &SectionHeader) -> %void { pub fn seekToSection(elf: &Elf, elf_section: &SectionHeader) -> %void {
%return elf.in_file.seekTo(section.offset); %return elf.in_file.seekTo(elf_section.offset);
} }
}; };

View File

@ -4,6 +4,7 @@ const math = @import("math/index.zig");
const builtin = @import("builtin"); const builtin = @import("builtin");
pub const Cmp = math.Cmp; pub const Cmp = math.Cmp;
error OutOfMemory;
pub const Allocator = struct { pub const Allocator = struct {
/// Allocate byte_count bytes and return them in a slice, with the /// Allocate byte_count bytes and return them in a slice, with the

View File

@ -651,28 +651,6 @@ pub const iovec = extern struct {
iov_len: usize, iov_len: usize,
}; };
//
//const IF_NAMESIZE = 16;
//
//export struct ifreq {
// ifrn_name: [IF_NAMESIZE]u8,
// union {
// ifru_addr: sockaddr,
// ifru_dstaddr: sockaddr,
// ifru_broadaddr: sockaddr,
// ifru_netmask: sockaddr,
// ifru_hwaddr: sockaddr,
// ifru_flags: i16,
// ifru_ivalue: i32,
// ifru_mtu: i32,
// ifru_map: ifmap,
// ifru_slave: [IF_NAMESIZE]u8,
// ifru_newname: [IF_NAMESIZE]u8,
// ifru_data: &u8,
// } ifr_ifru;
//}
//
pub fn getsockname(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) -> usize { pub fn getsockname(fd: i32, noalias addr: &sockaddr, noalias len: &socklen_t) -> usize {
arch.syscall3(arch.SYS_getsockname, usize(fd), @ptrToInt(addr), @ptrToInt(len)) arch.syscall3(arch.SYS_getsockname, usize(fd), @ptrToInt(addr), @ptrToInt(len))
} }

View File

@ -502,13 +502,3 @@ pub nakedcc fn restore_rt() {
: [number] "{eax}" (usize(SYS_rt_sigreturn)) : [number] "{eax}" (usize(SYS_rt_sigreturn))
: "rcx", "r11") : "rcx", "r11")
} }
export struct msghdr {
msg_name: &u8,
msg_namelen: socklen_t,
msg_iov: &iovec,
msg_iovlen: i32,
msg_control: &u8,
msg_controllen: socklen_t,
msg_flags: i32,
}

View File

@ -5,20 +5,19 @@ const root = @import("@root");
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin"); const builtin = @import("builtin");
const is_windows = builtin.os == builtin.Os.windows;
const want_main_symbol = builtin.link_libc;
const want_start_symbol = !want_main_symbol and !is_windows;
const want_WinMainCRTStartup = is_windows and !builtin.link_libc;
var argc_ptr: &usize = undefined; var argc_ptr: &usize = undefined;
comptime {
export nakedcc fn _start() -> noreturn { if (builtin.link_libc) {
if (!want_start_symbol) { @export("main", main);
@setGlobalLinkage(_start, builtin.GlobalLinkage.Internal); } else if (builtin.os == builtin.Os.windows) {
unreachable; @export("WinMainCRTStartup", WinMainCRTStartup);
} else {
@export("_start", _start);
} }
}
nakedcc fn _start() -> noreturn {
switch (builtin.arch) { switch (builtin.arch) {
builtin.Arch.x86_64 => { builtin.Arch.x86_64 => {
argc_ptr = asm("lea (%%rsp), %[argc]": [argc] "=r" (-> &usize)); argc_ptr = asm("lea (%%rsp), %[argc]": [argc] "=r" (-> &usize));
@ -33,14 +32,9 @@ export nakedcc fn _start() -> noreturn {
@noInlineCall(posixCallMainAndExit); @noInlineCall(posixCallMainAndExit);
} }
export fn WinMainCRTStartup() -> noreturn { extern fn WinMainCRTStartup() -> noreturn {
if (!want_WinMainCRTStartup) {
@setGlobalLinkage(WinMainCRTStartup, builtin.GlobalLinkage.Internal);
unreachable;
}
@setAlignStack(16); @setAlignStack(16);
std.debug.user_main_fn = root.main;
root.main() %% std.os.windows.ExitProcess(1); root.main() %% std.os.windows.ExitProcess(1);
std.os.windows.ExitProcess(0); std.os.windows.ExitProcess(0);
} }
@ -60,17 +54,10 @@ fn callMain(argc: usize, argv: &&u8, envp: &?&u8) -> %void {
while (envp[env_count] != null) : (env_count += 1) {} while (envp[env_count] != null) : (env_count += 1) {}
std.os.posix_environ_raw = @ptrCast(&&u8, envp)[0..env_count]; std.os.posix_environ_raw = @ptrCast(&&u8, envp)[0..env_count];
std.debug.user_main_fn = root.main;
return root.main(); return root.main();
} }
export fn main(c_argc: i32, c_argv: &&u8, c_envp: &?&u8) -> i32 { extern fn main(c_argc: i32, c_argv: &&u8, c_envp: &?&u8) -> i32 {
if (!want_main_symbol) {
@setGlobalLinkage(main, builtin.GlobalLinkage.Internal);
unreachable;
}
callMain(usize(c_argc), c_argv, c_envp) %% return 1; callMain(usize(c_argc), c_argv, c_envp) %% return 1;
return 0; return 0;
} }

View File

@ -2,7 +2,11 @@
const std = @import("std"); const std = @import("std");
export stdcallcc fn _DllMainCRTStartup(hinstDLL: std.os.windows.HINSTANCE, fdwReason: std.os.windows.DWORD, comptime {
@export("_DllMainCRTStartup", _DllMainCRTStartup);
}
stdcallcc fn _DllMainCRTStartup(hinstDLL: std.os.windows.HINSTANCE, fdwReason: std.os.windows.DWORD,
lpReserved: std.os.windows.LPVOID) -> std.os.windows.BOOL lpReserved: std.os.windows.LPVOID) -> std.os.windows.BOOL
{ {
return std.os.windows.TRUE; return std.os.windows.TRUE;

View File

@ -13,10 +13,24 @@ pub coldcc fn panic(msg: []const u8) -> noreturn {
} }
} }
comptime {
@export("memset", memset);
@export("memcpy", memcpy);
@export("fmodf", fmodf);
@export("fmod", fmod);
@export("floorf", floorf);
@export("ceilf", ceilf);
@export("floor", floor);
@export("ceil", ceil);
if (builtin.mode != builtin.Mode.ReleaseFast and builtin.os != builtin.Os.windows) {
@export("__stack_chk_fail", __stack_chk_fail);
}
}
// Note that memset does not return `dest`, like the libc API. // Note that memset does not return `dest`, like the libc API.
// The semantics of memset is dictated by the corresponding // The semantics of memset is dictated by the corresponding
// LLVM intrinsics, not by the libc API. // LLVM intrinsics, not by the libc API.
export fn memset(dest: ?&u8, c: u8, n: usize) { extern fn memset(dest: ?&u8, c: u8, n: usize) {
@setDebugSafety(this, false); @setDebugSafety(this, false);
var index: usize = 0; var index: usize = 0;
@ -27,7 +41,7 @@ export fn memset(dest: ?&u8, c: u8, n: usize) {
// Note that memcpy does not return `dest`, like the libc API. // Note that memcpy does not return `dest`, like the libc API.
// The semantics of memcpy is dictated by the corresponding // The semantics of memcpy is dictated by the corresponding
// LLVM intrinsics, not by the libc API. // LLVM intrinsics, not by the libc API.
export fn memcpy(noalias dest: ?&u8, noalias src: ?&const u8, n: usize) { extern fn memcpy(noalias dest: ?&u8, noalias src: ?&const u8, n: usize) {
@setDebugSafety(this, false); @setDebugSafety(this, false);
var index: usize = 0; var index: usize = 0;
@ -35,25 +49,21 @@ export fn memcpy(noalias dest: ?&u8, noalias src: ?&const u8, n: usize) {
(??dest)[index] = (??src)[index]; (??dest)[index] = (??src)[index];
} }
export fn __stack_chk_fail() -> noreturn { extern fn __stack_chk_fail() -> noreturn {
if (builtin.mode == builtin.Mode.ReleaseFast or builtin.os == builtin.Os.windows) {
@setGlobalLinkage(__stack_chk_fail, builtin.GlobalLinkage.Internal);
unreachable;
}
@panic("stack smashing detected"); @panic("stack smashing detected");
} }
const math = @import("../math/index.zig"); const math = @import("../math/index.zig");
export fn fmodf(x: f32, y: f32) -> f32 { generic_fmod(f32, x, y) } extern fn fmodf(x: f32, y: f32) -> f32 { generic_fmod(f32, x, y) }
export fn fmod(x: f64, y: f64) -> f64 { generic_fmod(f64, x, y) } extern fn fmod(x: f64, y: f64) -> f64 { generic_fmod(f64, x, y) }
// TODO add intrinsics for these (and probably the double version too) // TODO add intrinsics for these (and probably the double version too)
// and have the math stuff use the intrinsic. same as @mod and @rem // and have the math stuff use the intrinsic. same as @mod and @rem
export fn floorf(x: f32) -> f32 { math.floor(x) } extern fn floorf(x: f32) -> f32 { math.floor(x) }
export fn ceilf(x: f32) -> f32 { math.ceil(x) } extern fn ceilf(x: f32) -> f32 { math.ceil(x) }
export fn floor(x: f64) -> f64 { math.floor(x) } extern fn floor(x: f64) -> f64 { math.floor(x) }
export fn ceil(x: f64) -> f64 { math.ceil(x) } extern fn ceil(x: f64) -> f64 { math.ceil(x) }
fn generic_fmod(comptime T: type, x: T, y: T) -> T { fn generic_fmod(comptime T: type, x: T, y: T) -> T {
@setDebugSafety(this, false); @setDebugSafety(this, false);

View File

@ -1,66 +1,55 @@
const builtin = @import("builtin"); pub nakedcc fn _aulldiv() {
const linkage = if (builtin.is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Strong; @setDebugSafety(this, false);
const is_win32 = builtin.os == builtin.Os.windows and builtin.arch == builtin.Arch.i386; asm volatile (
\\.intel_syntax noprefix
export nakedcc fn _aulldiv() { \\
if (is_win32) { \\ push ebx
@setDebugSafety(this, false); \\ push esi
@setGlobalLinkage(_aulldiv, linkage); \\ mov eax,dword ptr [esp+18h]
asm volatile ( \\ or eax,eax
\\.intel_syntax noprefix \\ jne L1
\\ \\ mov ecx,dword ptr [esp+14h]
\\ push ebx \\ mov eax,dword ptr [esp+10h]
\\ push esi \\ xor edx,edx
\\ mov eax,dword ptr [esp+18h] \\ div ecx
\\ or eax,eax \\ mov ebx,eax
\\ jne L1 \\ mov eax,dword ptr [esp+0Ch]
\\ mov ecx,dword ptr [esp+14h] \\ div ecx
\\ mov eax,dword ptr [esp+10h] \\ mov edx,ebx
\\ xor edx,edx \\ jmp L2
\\ div ecx \\ L1:
\\ mov ebx,eax \\ mov ecx,eax
\\ mov eax,dword ptr [esp+0Ch] \\ mov ebx,dword ptr [esp+14h]
\\ div ecx \\ mov edx,dword ptr [esp+10h]
\\ mov edx,ebx \\ mov eax,dword ptr [esp+0Ch]
\\ jmp L2 \\ L3:
\\ L1: \\ shr ecx,1
\\ mov ecx,eax \\ rcr ebx,1
\\ mov ebx,dword ptr [esp+14h] \\ shr edx,1
\\ mov edx,dword ptr [esp+10h] \\ rcr eax,1
\\ mov eax,dword ptr [esp+0Ch] \\ or ecx,ecx
\\ L3: \\ jne L3
\\ shr ecx,1 \\ div ebx
\\ rcr ebx,1 \\ mov esi,eax
\\ shr edx,1 \\ mul dword ptr [esp+18h]
\\ rcr eax,1 \\ mov ecx,eax
\\ or ecx,ecx \\ mov eax,dword ptr [esp+14h]
\\ jne L3 \\ mul esi
\\ div ebx \\ add edx,ecx
\\ mov esi,eax \\ jb L4
\\ mul dword ptr [esp+18h] \\ cmp edx,dword ptr [esp+10h]
\\ mov ecx,eax \\ ja L4
\\ mov eax,dword ptr [esp+14h] \\ jb L5
\\ mul esi \\ cmp eax,dword ptr [esp+0Ch]
\\ add edx,ecx \\ jbe L5
\\ jb L4 \\ L4:
\\ cmp edx,dword ptr [esp+10h] \\ dec esi
\\ ja L4 \\ L5:
\\ jb L5 \\ xor edx,edx
\\ cmp eax,dword ptr [esp+0Ch] \\ mov eax,esi
\\ jbe L5 \\ L2:
\\ L4: \\ pop esi
\\ dec esi \\ pop ebx
\\ L5: \\ ret 10h
\\ xor edx,edx );
\\ mov eax,esi
\\ L2:
\\ pop esi
\\ pop ebx
\\ ret 10h
);
unreachable;
}
@setGlobalLinkage(_aulldiv, builtin.GlobalLinkage.Internal);
unreachable;
} }

View File

@ -1,67 +1,56 @@
const builtin = @import("builtin"); pub nakedcc fn _aullrem() {
const linkage = if (builtin.is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Strong; @setDebugSafety(this, false);
const is_win32 = builtin.os == builtin.Os.windows and builtin.arch == builtin.Arch.i386; asm volatile (
\\.intel_syntax noprefix
export nakedcc fn _aullrem() { \\
if (is_win32) { \\ push ebx
@setDebugSafety(this, false); \\ mov eax,dword ptr [esp+14h]
@setGlobalLinkage(_aullrem, linkage); \\ or eax,eax
asm volatile ( \\ jne L1a
\\.intel_syntax noprefix \\ mov ecx,dword ptr [esp+10h]
\\ \\ mov eax,dword ptr [esp+0Ch]
\\ push ebx \\ xor edx,edx
\\ mov eax,dword ptr [esp+14h] \\ div ecx
\\ or eax,eax \\ mov eax,dword ptr [esp+8]
\\ jne L1a \\ div ecx
\\ mov ecx,dword ptr [esp+10h] \\ mov eax,edx
\\ mov eax,dword ptr [esp+0Ch] \\ xor edx,edx
\\ xor edx,edx \\ jmp L2a
\\ div ecx \\ L1a:
\\ mov eax,dword ptr [esp+8] \\ mov ecx,eax
\\ div ecx \\ mov ebx,dword ptr [esp+10h]
\\ mov eax,edx \\ mov edx,dword ptr [esp+0Ch]
\\ xor edx,edx \\ mov eax,dword ptr [esp+8]
\\ jmp L2a \\ L3a:
\\ L1a: \\ shr ecx,1
\\ mov ecx,eax \\ rcr ebx,1
\\ mov ebx,dword ptr [esp+10h] \\ shr edx,1
\\ mov edx,dword ptr [esp+0Ch] \\ rcr eax,1
\\ mov eax,dword ptr [esp+8] \\ or ecx,ecx
\\ L3a: \\ jne L3a
\\ shr ecx,1 \\ div ebx
\\ rcr ebx,1 \\ mov ecx,eax
\\ shr edx,1 \\ mul dword ptr [esp+14h]
\\ rcr eax,1 \\ xchg eax,ecx
\\ or ecx,ecx \\ mul dword ptr [esp+10h]
\\ jne L3a \\ add edx,ecx
\\ div ebx \\ jb L4a
\\ mov ecx,eax \\ cmp edx,dword ptr [esp+0Ch]
\\ mul dword ptr [esp+14h] \\ ja L4a
\\ xchg eax,ecx \\ jb L5a
\\ mul dword ptr [esp+10h] \\ cmp eax,dword ptr [esp+8]
\\ add edx,ecx \\ jbe L5a
\\ jb L4a \\ L4a:
\\ cmp edx,dword ptr [esp+0Ch] \\ sub eax,dword ptr [esp+10h]
\\ ja L4a \\ sbb edx,dword ptr [esp+14h]
\\ jb L5a \\ L5a:
\\ cmp eax,dword ptr [esp+8] \\ sub eax,dword ptr [esp+8]
\\ jbe L5a \\ sbb edx,dword ptr [esp+0Ch]
\\ L4a: \\ neg edx
\\ sub eax,dword ptr [esp+10h] \\ neg eax
\\ sbb edx,dword ptr [esp+14h] \\ sbb edx,0
\\ L5a: \\ L2a:
\\ sub eax,dword ptr [esp+8] \\ pop ebx
\\ sbb edx,dword ptr [esp+0Ch] \\ ret 10h
\\ neg edx );
\\ neg eax
\\ sbb edx,0
\\ L2a:
\\ pop ebx
\\ ret 10h
);
unreachable;
}
@setGlobalLinkage(_aullrem, builtin.GlobalLinkage.Internal);
unreachable;
} }

View File

@ -20,11 +20,9 @@ const infRep = exponentMask;
const builtin = @import("builtin"); const builtin = @import("builtin");
const is_test = builtin.is_test; const is_test = builtin.is_test;
const linkage = @import("index.zig").linkage;
export fn __letf2(a: f128, b: f128) -> c_int { pub extern fn __letf2(a: f128, b: f128) -> c_int {
@setDebugSafety(this, is_test); @setDebugSafety(this, is_test);
@setGlobalLinkage(__letf2, linkage);
const aInt = @bitCast(rep_t, a); const aInt = @bitCast(rep_t, a);
const bInt = @bitCast(rep_t, b); const bInt = @bitCast(rep_t, b);
@ -63,14 +61,6 @@ export fn __letf2(a: f128, b: f128) -> c_int {
}; };
} }
// Alias for libgcc compatibility
// TODO https://github.com/zig-lang/zig/issues/420
export fn __cmptf2(a: f128, b: f128) -> c_int {
@setGlobalLinkage(__cmptf2, linkage);
@setDebugSafety(this, is_test);
return __letf2(a, b);
}
// TODO https://github.com/zig-lang/zig/issues/305 // TODO https://github.com/zig-lang/zig/issues/305
// and then make the return types of some of these functions the enum instead of c_int // and then make the return types of some of these functions the enum instead of c_int
const GE_LESS = c_int(-1); const GE_LESS = c_int(-1);
@ -78,8 +68,7 @@ const GE_EQUAL = c_int(0);
const GE_GREATER = c_int(1); const GE_GREATER = c_int(1);
const GE_UNORDERED = c_int(-1); // Note: different from LE_UNORDERED const GE_UNORDERED = c_int(-1); // Note: different from LE_UNORDERED
export fn __getf2(a: f128, b: f128) -> c_int { pub extern fn __getf2(a: f128, b: f128) -> c_int {
@setGlobalLinkage(__getf2, linkage);
@setDebugSafety(this, is_test); @setDebugSafety(this, is_test);
const aInt = @bitCast(srep_t, a); const aInt = @bitCast(srep_t, a);
@ -108,38 +97,10 @@ export fn __getf2(a: f128, b: f128) -> c_int {
}; };
} }
export fn __unordtf2(a: f128, b: f128) -> c_int { pub extern fn __unordtf2(a: f128, b: f128) -> c_int {
@setGlobalLinkage(__unordtf2, linkage);
@setDebugSafety(this, is_test); @setDebugSafety(this, is_test);
const aAbs = @bitCast(rep_t, a) & absMask; const aAbs = @bitCast(rep_t, a) & absMask;
const bAbs = @bitCast(rep_t, b) & absMask; const bAbs = @bitCast(rep_t, b) & absMask;
return c_int(aAbs > infRep or bAbs > infRep); return c_int(aAbs > infRep or bAbs > infRep);
} }
// The following are alternative names for the preceding routines.
// TODO use aliases https://github.com/zig-lang/zig/issues/462
export fn __eqtf2(a: f128, b: f128) -> c_int {
@setGlobalLinkage(__eqtf2, linkage);
@setDebugSafety(this, is_test);
return __letf2(a, b);
}
export fn __lttf2(a: f128, b: f128) -> c_int {
@setGlobalLinkage(__lttf2, linkage);
@setDebugSafety(this, is_test);
return __letf2(a, b);
}
export fn __netf2(a: f128, b: f128) -> c_int {
@setGlobalLinkage(__netf2, linkage);
@setDebugSafety(this, is_test);
return __letf2(a, b);
}
export fn __gttf2(a: f128, b: f128) -> c_int {
@setGlobalLinkage(__gttf2, linkage);
@setDebugSafety(this, is_test);
return __getf2(a, b);
}

View File

@ -1,10 +1,8 @@
const fixuint = @import("fixuint.zig").fixuint; const fixuint = @import("fixuint.zig").fixuint;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __fixunsdfdi(a: f64) -> u64 { pub extern fn __fixunsdfdi(a: f64) -> u64 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__fixunsdfdi, linkage);
return fixuint(f64, u64, a); return fixuint(f64, u64, a);
} }

View File

@ -1,10 +1,8 @@
const fixuint = @import("fixuint.zig").fixuint; const fixuint = @import("fixuint.zig").fixuint;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __fixunsdfsi(a: f64) -> u32 { pub extern fn __fixunsdfsi(a: f64) -> u32 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__fixunsdfsi, linkage);
return fixuint(f64, u32, a); return fixuint(f64, u32, a);
} }

View File

@ -1,10 +1,8 @@
const fixuint = @import("fixuint.zig").fixuint; const fixuint = @import("fixuint.zig").fixuint;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __fixunsdfti(a: f64) -> u128 { pub extern fn __fixunsdfti(a: f64) -> u128 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__fixunsdfti, linkage);
return fixuint(f64, u128, a); return fixuint(f64, u128, a);
} }

View File

@ -1,10 +1,8 @@
const fixuint = @import("fixuint.zig").fixuint; const fixuint = @import("fixuint.zig").fixuint;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __fixunssfdi(a: f32) -> u64 { pub extern fn __fixunssfdi(a: f32) -> u64 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__fixunssfdi, linkage);
return fixuint(f32, u64, a); return fixuint(f32, u64, a);
} }

View File

@ -1,10 +1,8 @@
const fixuint = @import("fixuint.zig").fixuint; const fixuint = @import("fixuint.zig").fixuint;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __fixunssfsi(a: f32) -> u32 { pub extern fn __fixunssfsi(a: f32) -> u32 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__fixunssfsi, linkage);
return fixuint(f32, u32, a); return fixuint(f32, u32, a);
} }

View File

@ -1,10 +1,8 @@
const fixuint = @import("fixuint.zig").fixuint; const fixuint = @import("fixuint.zig").fixuint;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __fixunssfti(a: f32) -> u128 { pub extern fn __fixunssfti(a: f32) -> u128 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__fixunssfti, linkage);
return fixuint(f32, u128, a); return fixuint(f32, u128, a);
} }

View File

@ -1,10 +1,8 @@
const fixuint = @import("fixuint.zig").fixuint; const fixuint = @import("fixuint.zig").fixuint;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __fixunstfdi(a: f128) -> u64 { pub extern fn __fixunstfdi(a: f128) -> u64 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__fixunstfdi, linkage);
return fixuint(f128, u64, a); return fixuint(f128, u64, a);
} }

View File

@ -1,10 +1,8 @@
const fixuint = @import("fixuint.zig").fixuint; const fixuint = @import("fixuint.zig").fixuint;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __fixunstfsi(a: f128) -> u32 { pub extern fn __fixunstfsi(a: f128) -> u32 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__fixunstfsi, linkage);
return fixuint(f128, u32, a); return fixuint(f128, u32, a);
} }

View File

@ -1,10 +1,8 @@
const fixuint = @import("fixuint.zig").fixuint; const fixuint = @import("fixuint.zig").fixuint;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __fixunstfti(a: f128) -> u128 { pub extern fn __fixunstfti(a: f128) -> u128 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__fixunstfti, linkage);
return fixuint(f128, u128, a); return fixuint(f128, u128, a);
} }

View File

@ -1,34 +1,75 @@
comptime {
_ = @import("comparetf2.zig");
_ = @import("fixunsdfdi.zig");
_ = @import("fixunsdfsi.zig");
_ = @import("fixunsdfti.zig");
_ = @import("fixunssfdi.zig");
_ = @import("fixunssfsi.zig");
_ = @import("fixunssfti.zig");
_ = @import("fixunstfdi.zig");
_ = @import("fixunstfsi.zig");
_ = @import("fixunstfti.zig");
_ = @import("udivmoddi4.zig");
_ = @import("udivmodti4.zig");
_ = @import("udivti3.zig");
_ = @import("umodti3.zig");
_ = @import("aulldiv.zig");
_ = @import("aullrem.zig");
}
const builtin = @import("builtin"); const builtin = @import("builtin");
const is_test = builtin.is_test; const is_test = builtin.is_test;
comptime {
const linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Weak;
const strong_linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Strong;
@exportWithLinkage("__letf2", @import("comparetf2.zig").__letf2, linkage);
@exportWithLinkage("__getf2", @import("comparetf2.zig").__getf2, linkage);
if (!is_test) {
// only create these aliases when not testing
@exportWithLinkage("__cmptf2", @import("comparetf2.zig").__letf2, linkage);
@exportWithLinkage("__eqtf2", @import("comparetf2.zig").__letf2, linkage);
@exportWithLinkage("__lttf2", @import("comparetf2.zig").__letf2, linkage);
@exportWithLinkage("__netf2", @import("comparetf2.zig").__letf2, linkage);
@exportWithLinkage("__gttf2", @import("comparetf2.zig").__getf2, linkage);
}
@exportWithLinkage("__unordtf2", @import("comparetf2.zig").__unordtf2, linkage);
@exportWithLinkage("__fixunssfsi", @import("fixunssfsi.zig").__fixunssfsi, linkage);
@exportWithLinkage("__fixunssfdi", @import("fixunssfdi.zig").__fixunssfdi, linkage);
@exportWithLinkage("__fixunssfti", @import("fixunssfti.zig").__fixunssfti, linkage);
@exportWithLinkage("__fixunsdfsi", @import("fixunsdfsi.zig").__fixunsdfsi, linkage);
@exportWithLinkage("__fixunsdfdi", @import("fixunsdfdi.zig").__fixunsdfdi, linkage);
@exportWithLinkage("__fixunsdfti", @import("fixunsdfti.zig").__fixunsdfti, linkage);
@exportWithLinkage("__fixunstfsi", @import("fixunstfsi.zig").__fixunstfsi, linkage);
@exportWithLinkage("__fixunstfdi", @import("fixunstfdi.zig").__fixunstfdi, linkage);
@exportWithLinkage("__fixunstfti", @import("fixunstfti.zig").__fixunstfti, linkage);
@exportWithLinkage("__udivmoddi4", @import("udivmoddi4.zig").__udivmoddi4, linkage);
@exportWithLinkage("__udivmodti4", @import("udivmodti4.zig").__udivmodti4, linkage);
@exportWithLinkage("__udivti3", @import("udivti3.zig").__udivti3, linkage);
@exportWithLinkage("__umodti3", @import("umodti3.zig").__umodti3, linkage);
@exportWithLinkage("__udivsi3", __udivsi3, linkage);
@exportWithLinkage("__udivdi3", __udivdi3, linkage);
@exportWithLinkage("__umoddi3", __umoddi3, linkage);
@exportWithLinkage("__udivmodsi4", __udivmodsi4, linkage);
if (isArmArch()) {
@exportWithLinkage("__aeabi_uldivmod", __aeabi_uldivmod, linkage);
@exportWithLinkage("__aeabi_uidivmod", __aeabi_uidivmod, linkage);
@exportWithLinkage("__aeabi_uidiv", __udivsi3, linkage);
}
if (builtin.os == builtin.Os.windows) {
switch (builtin.arch) {
builtin.Arch.i386 => {
if (!builtin.link_libc) {
@exportWithLinkage("_chkstk", _chkstk, strong_linkage);
@exportWithLinkage("__chkstk_ms", __chkstk_ms, linkage);
}
@exportWithLinkage("_aulldiv", @import("aulldiv.zig")._aulldiv, strong_linkage);
@exportWithLinkage("_aullrem", @import("aullrem.zig")._aullrem, strong_linkage);
},
builtin.Arch.x86_64 => {
if (!builtin.link_libc) {
@exportWithLinkage("__chkstk", __chkstk, strong_linkage);
@exportWithLinkage("___chkstk_ms", ___chkstk_ms, linkage);
}
},
else => {},
}
}
}
const assert = @import("../../debug.zig").assert; const assert = @import("../../debug.zig").assert;
const win32 = builtin.os == builtin.Os.windows and builtin.arch == builtin.Arch.i386;
const win64 = builtin.os == builtin.Os.windows and builtin.arch == builtin.Arch.x86_64;
const win32_nocrt = win32 and !builtin.link_libc;
const win64_nocrt = win64 and !builtin.link_libc;
pub const linkage = if (builtin.is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Weak;
const strong_linkage = if (builtin.is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Strong;
const __udivmoddi4 = @import("udivmoddi4.zig").__udivmoddi4; const __udivmoddi4 = @import("udivmoddi4.zig").__udivmoddi4;
// Avoid dragging in the debug safety mechanisms into this .o file, // Avoid dragging in the debug safety mechanisms into this .o file,
@ -41,15 +82,13 @@ pub coldcc fn panic(msg: []const u8) -> noreturn {
} }
} }
export fn __udivdi3(a: u64, b: u64) -> u64 { extern fn __udivdi3(a: u64, b: u64) -> u64 {
@setDebugSafety(this, is_test); @setDebugSafety(this, is_test);
@setGlobalLinkage(__udivdi3, linkage);
return __udivmoddi4(a, b, null); return __udivmoddi4(a, b, null);
} }
export fn __umoddi3(a: u64, b: u64) -> u64 { extern fn __umoddi3(a: u64, b: u64) -> u64 {
@setDebugSafety(this, is_test); @setDebugSafety(this, is_test);
@setGlobalLinkage(__umoddi3, linkage);
var r: u64 = undefined; var r: u64 = undefined;
_ = __udivmoddi4(a, b, &r); _ = __udivmoddi4(a, b, &r);
@ -60,17 +99,11 @@ const AeabiUlDivModResult = extern struct {
quot: u64, quot: u64,
rem: u64, rem: u64,
}; };
export fn __aeabi_uldivmod(numerator: u64, denominator: u64) -> AeabiUlDivModResult { extern fn __aeabi_uldivmod(numerator: u64, denominator: u64) -> AeabiUlDivModResult {
@setDebugSafety(this, is_test); @setDebugSafety(this, is_test);
if (comptime isArmArch()) { var result: AeabiUlDivModResult = undefined;
@setGlobalLinkage(__aeabi_uldivmod, linkage); result.quot = __udivmoddi4(numerator, denominator, &result.rem);
var result: AeabiUlDivModResult = undefined; return result;
result.quot = __udivmoddi4(numerator, denominator, &result.rem);
return result;
}
@setGlobalLinkage(__aeabi_uldivmod, builtin.GlobalLinkage.Internal);
unreachable;
} }
fn isArmArch() -> bool { fn isArmArch() -> bool {
@ -98,156 +131,124 @@ fn isArmArch() -> bool {
}; };
} }
export nakedcc fn __aeabi_uidivmod() { nakedcc fn __aeabi_uidivmod() {
@setDebugSafety(this, false); @setDebugSafety(this, false);
asm volatile (
if (comptime isArmArch()) { \\ push { lr }
@setGlobalLinkage(__aeabi_uidivmod, linkage); \\ sub sp, sp, #4
asm volatile ( \\ mov r2, sp
\\ push { lr } \\ bl __udivmodsi4
\\ sub sp, sp, #4 \\ ldr r1, [sp]
\\ mov r2, sp \\ add sp, sp, #4
\\ bl __udivmodsi4 \\ pop { pc }
\\ ldr r1, [sp] ::: "r2", "r1");
\\ add sp, sp, #4
\\ pop { pc }
::: "r2", "r1");
unreachable;
}
@setGlobalLinkage(__aeabi_uidivmod, builtin.GlobalLinkage.Internal);
} }
// _chkstk (_alloca) routine - probe stack between %esp and (%esp-%eax) in 4k increments, // _chkstk (_alloca) routine - probe stack between %esp and (%esp-%eax) in 4k increments,
// then decrement %esp by %eax. Preserves all registers except %esp and flags. // then decrement %esp by %eax. Preserves all registers except %esp and flags.
// This routine is windows specific // This routine is windows specific
// http://msdn.microsoft.com/en-us/library/ms648426.aspx // http://msdn.microsoft.com/en-us/library/ms648426.aspx
export nakedcc fn _chkstk() align(4) { nakedcc fn _chkstk() align(4) {
@setDebugSafety(this, false); @setDebugSafety(this, false);
if (win32_nocrt) { asm volatile (
@setGlobalLinkage(_chkstk, strong_linkage); \\ push %%ecx
asm volatile ( \\ push %%eax
\\ push %%ecx \\ cmp $0x1000,%%eax
\\ push %%eax \\ lea 12(%%esp),%%ecx
\\ cmp $0x1000,%%eax \\ jb 1f
\\ lea 12(%%esp),%%ecx \\ 2:
\\ jb 1f \\ sub $0x1000,%%ecx
\\ 2: \\ test %%ecx,(%%ecx)
\\ sub $0x1000,%%ecx \\ sub $0x1000,%%eax
\\ test %%ecx,(%%ecx) \\ cmp $0x1000,%%eax
\\ sub $0x1000,%%eax \\ ja 2b
\\ cmp $0x1000,%%eax \\ 1:
\\ ja 2b \\ sub %%eax,%%ecx
\\ 1: \\ test %%ecx,(%%ecx)
\\ sub %%eax,%%ecx \\ pop %%eax
\\ test %%ecx,(%%ecx) \\ pop %%ecx
\\ pop %%eax \\ ret
\\ pop %%ecx );
\\ ret
);
unreachable;
}
@setGlobalLinkage(_chkstk, builtin.GlobalLinkage.Internal);
} }
export nakedcc fn __chkstk() align(4) { nakedcc fn __chkstk() align(4) {
@setDebugSafety(this, false); @setDebugSafety(this, false);
if (win64_nocrt) { asm volatile (
@setGlobalLinkage(__chkstk, strong_linkage); \\ push %%rcx
asm volatile ( \\ push %%rax
\\ push %%rcx \\ cmp $0x1000,%%rax
\\ push %%rax \\ lea 24(%%rsp),%%rcx
\\ cmp $0x1000,%%rax \\ jb 1f
\\ lea 24(%%rsp),%%rcx \\2:
\\ jb 1f \\ sub $0x1000,%%rcx
\\2: \\ test %%rcx,(%%rcx)
\\ sub $0x1000,%%rcx \\ sub $0x1000,%%rax
\\ test %%rcx,(%%rcx) \\ cmp $0x1000,%%rax
\\ sub $0x1000,%%rax \\ ja 2b
\\ cmp $0x1000,%%rax \\1:
\\ ja 2b \\ sub %%rax,%%rcx
\\1: \\ test %%rcx,(%%rcx)
\\ sub %%rax,%%rcx \\ pop %%rax
\\ test %%rcx,(%%rcx) \\ pop %%rcx
\\ pop %%rax \\ ret
\\ pop %%rcx );
\\ ret
);
unreachable;
}
@setGlobalLinkage(__chkstk, builtin.GlobalLinkage.Internal);
} }
// _chkstk routine // _chkstk routine
// This routine is windows specific // This routine is windows specific
// http://msdn.microsoft.com/en-us/library/ms648426.aspx // http://msdn.microsoft.com/en-us/library/ms648426.aspx
export nakedcc fn __chkstk_ms() align(4) { nakedcc fn __chkstk_ms() align(4) {
@setDebugSafety(this, false); @setDebugSafety(this, false);
if (win32_nocrt) { asm volatile (
@setGlobalLinkage(__chkstk_ms, linkage); \\ push %%ecx
asm volatile ( \\ push %%eax
\\ push %%ecx \\ cmp $0x1000,%%eax
\\ push %%eax \\ lea 12(%%esp),%%ecx
\\ cmp $0x1000,%%eax \\ jb 1f
\\ lea 12(%%esp),%%ecx \\ 2:
\\ jb 1f \\ sub $0x1000,%%ecx
\\ 2: \\ test %%ecx,(%%ecx)
\\ sub $0x1000,%%ecx \\ sub $0x1000,%%eax
\\ test %%ecx,(%%ecx) \\ cmp $0x1000,%%eax
\\ sub $0x1000,%%eax \\ ja 2b
\\ cmp $0x1000,%%eax \\ 1:
\\ ja 2b \\ sub %%eax,%%ecx
\\ 1: \\ test %%ecx,(%%ecx)
\\ sub %%eax,%%ecx \\ pop %%eax
\\ test %%ecx,(%%ecx) \\ pop %%ecx
\\ pop %%eax \\ ret
\\ pop %%ecx );
\\ ret
);
unreachable;
}
@setGlobalLinkage(__chkstk_ms, builtin.GlobalLinkage.Internal);
} }
export nakedcc fn ___chkstk_ms() align(4) { nakedcc fn ___chkstk_ms() align(4) {
@setDebugSafety(this, false); @setDebugSafety(this, false);
if (win64_nocrt) { asm volatile (
@setGlobalLinkage(___chkstk_ms, linkage); \\ push %%rcx
asm volatile ( \\ push %%rax
\\ push %%rcx \\ cmp $0x1000,%%rax
\\ push %%rax \\ lea 24(%%rsp),%%rcx
\\ cmp $0x1000,%%rax \\ jb 1f
\\ lea 24(%%rsp),%%rcx \\2:
\\ jb 1f \\ sub $0x1000,%%rcx
\\2: \\ test %%rcx,(%%rcx)
\\ sub $0x1000,%%rcx \\ sub $0x1000,%%rax
\\ test %%rcx,(%%rcx) \\ cmp $0x1000,%%rax
\\ sub $0x1000,%%rax \\ ja 2b
\\ cmp $0x1000,%%rax \\1:
\\ ja 2b \\ sub %%rax,%%rcx
\\1: \\ test %%rcx,(%%rcx)
\\ sub %%rax,%%rcx \\ pop %%rax
\\ test %%rcx,(%%rcx) \\ pop %%rcx
\\ pop %%rax \\ ret
\\ pop %%rcx );
\\ ret
);
unreachable;
}
@setGlobalLinkage(___chkstk_ms, builtin.GlobalLinkage.Internal);
} }
export fn __udivmodsi4(a: u32, b: u32, rem: &u32) -> u32 { extern fn __udivmodsi4(a: u32, b: u32, rem: &u32) -> u32 {
@setDebugSafety(this, is_test); @setDebugSafety(this, is_test);
@setGlobalLinkage(__udivmodsi4, linkage);
const d = __udivsi3(a, b); const d = __udivsi3(a, b);
*rem = u32(i32(a) -% (i32(d) * i32(b))); *rem = u32(i32(a) -% (i32(d) * i32(b)));
@ -255,19 +256,8 @@ export fn __udivmodsi4(a: u32, b: u32, rem: &u32) -> u32 {
} }
// TODO make this an alias instead of an extra function call extern fn __udivsi3(n: u32, d: u32) -> u32 {
// https://github.com/andrewrk/zig/issues/256
export fn __aeabi_uidiv(n: u32, d: u32) -> u32 {
@setDebugSafety(this, is_test); @setDebugSafety(this, is_test);
@setGlobalLinkage(__aeabi_uidiv, linkage);
return __udivsi3(n, d);
}
export fn __udivsi3(n: u32, d: u32) -> u32 {
@setDebugSafety(this, is_test);
@setGlobalLinkage(__udivsi3, linkage);
const n_uword_bits: c_uint = u32.bit_count; const n_uword_bits: c_uint = u32.bit_count;
// special cases // special cases
@ -463,4 +453,3 @@ fn test_one_udivsi3(a: u32, b: u32, expected_q: u32) {
const q: u32 = __udivsi3(a, b); const q: u32 = __udivsi3(a, b);
assert(q == expected_q); assert(q == expected_q);
} }

View File

@ -1,10 +1,8 @@
const udivmod = @import("udivmod.zig").udivmod; const udivmod = @import("udivmod.zig").udivmod;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __udivmoddi4(a: u64, b: u64, maybe_rem: ?&u64) -> u64 { pub extern fn __udivmoddi4(a: u64, b: u64, maybe_rem: ?&u64) -> u64 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__udivmoddi4, linkage);
return udivmod(u64, a, b, maybe_rem); return udivmod(u64, a, b, maybe_rem);
} }

View File

@ -1,10 +1,8 @@
const udivmod = @import("udivmod.zig").udivmod; const udivmod = @import("udivmod.zig").udivmod;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __udivmodti4(a: u128, b: u128, maybe_rem: ?&u128) -> u128 { pub extern fn __udivmodti4(a: u128, b: u128, maybe_rem: ?&u128) -> u128 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__udivmodti4, linkage);
return udivmod(u128, a, b, maybe_rem); return udivmod(u128, a, b, maybe_rem);
} }

View File

@ -1,9 +1,7 @@
const __udivmodti4 = @import("udivmodti4.zig").__udivmodti4; const __udivmodti4 = @import("udivmodti4.zig").__udivmodti4;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __udivti3(a: u128, b: u128) -> u128 { pub extern fn __udivti3(a: u128, b: u128) -> u128 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__udivti3, linkage);
return __udivmodti4(a, b, null); return __udivmodti4(a, b, null);
} }

View File

@ -1,10 +1,8 @@
const __udivmodti4 = @import("udivmodti4.zig").__udivmodti4; const __udivmodti4 = @import("udivmodti4.zig").__udivmodti4;
const builtin = @import("builtin"); const builtin = @import("builtin");
const linkage = @import("index.zig").linkage;
export fn __umodti3(a: u128, b: u128) -> u128 { pub extern fn __umodti3(a: u128, b: u128) -> u128 {
@setDebugSafety(this, builtin.is_test); @setDebugSafety(this, builtin.is_test);
@setGlobalLinkage(__umodti3, linkage);
var r: u128 = undefined; var r: u128 = undefined;
_ = __udivmodti4(a, b, &r); _ = __udivmodti4(a, b, &r);
return r; return r;

View File

@ -2,23 +2,24 @@ const config = @import("builtin");
const assert = @import("std").debug.assert; const assert = @import("std").debug.assert;
comptime { comptime {
@export("derp", derp);
if (config.arch == config.Arch.x86_64 and config.os == config.Os.linux) { if (config.arch == config.Arch.x86_64 and config.os == config.Os.linux) {
asm volatile ( asm volatile (
\\.globl aoeu; \\.globl my_aoeu_symbol_asdf;
\\.type aoeu, @function; \\.type my_aoeu_symbol_asdf, @function;
\\.set aoeu, derp; \\.set my_aoeu_symbol_asdf, derp;
); );
} }
} }
test "module level assembly" { test "module level assembly" {
if (config.arch == config.Arch.x86_64 and config.os == config.Os.linux) { if (config.arch == config.Arch.x86_64 and config.os == config.Os.linux) {
assert(aoeu() == 1234); assert(my_aoeu_symbol_asdf() == 1234);
} }
} }
extern fn aoeu() -> i32; extern fn my_aoeu_symbol_asdf() -> i32;
export fn derp() -> i32 { extern fn derp() -> i32 {
return 1234; return 1234;
} }

View File

@ -12,8 +12,10 @@ test "empty function with comments" {
emptyFunctionWithComments(); emptyFunctionWithComments();
} }
export fn disabledExternFn() { comptime {
@setGlobalLinkage(disabledExternFn, builtin.GlobalLinkage.Internal); @exportWithLinkage("disabledExternFn", disabledExternFn, builtin.GlobalLinkage.Internal)
}
extern fn disabledExternFn() {
} }
test "call disabled extern fn" { test "call disabled extern fn" {
@ -533,7 +535,10 @@ var global_ptr = &gdt[0];
// can't really run this test but we can make sure it has no compile error // can't really run this test but we can make sure it has no compile error
// and generates code // and generates code
const vram = @intToPtr(&volatile u8, 0x20000000)[0..0x8000]; const vram = @intToPtr(&volatile u8, 0x20000000)[0..0x8000];
export fn writeToVRam() { comptime {
@export("writeToVRam", writeToVRam);
}
extern fn writeToVRam() {
vram[0] = 'X'; vram[0] = 'X';
} }
@ -557,3 +562,15 @@ fn hereIsAnOpaqueType(ptr: &OpaqueA) -> &OpaqueA {
var a = ptr; var a = ptr;
return a; return a;
} }
test "function and variable in weird section" {
if (builtin.os == builtin.Os.linux or builtin.os == builtin.Os.windows) {
// macos can't handle this
assert(fnInWeirdSection() == 1234);
}
}
var varInWeirdSection: i32 section(".data2") = 1234;
fn fnInWeirdSection() section(".text2") -> i32 {
return varInWeirdSection;
}

View File

@ -4,7 +4,8 @@ const tests = @import("tests.zig");
pub fn addCases(cases: &tests.CompareOutputContext) { pub fn addCases(cases: &tests.CompareOutputContext) {
cases.addC("hello world with libc", cases.addC("hello world with libc",
\\const c = @cImport(@cInclude("stdio.h")); \\const c = @cImport(@cInclude("stdio.h"));
\\export fn main(argc: c_int, argv: &&u8) -> c_int { \\comptime { @export("main", main); }
\\extern fn main(argc: c_int, argv: &&u8) -> c_int {
\\ _ = c.puts(c"Hello, world!"); \\ _ = c.puts(c"Hello, world!");
\\ return 0; \\ return 0;
\\} \\}
@ -137,7 +138,8 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
\\ @cInclude("stdio.h"); \\ @cInclude("stdio.h");
\\}); \\});
\\ \\
\\export fn main(argc: c_int, argv: &&u8) -> c_int { \\comptime { @export("main", main); }
\\extern fn main(argc: c_int, argv: &&u8) -> c_int {
\\ if (is_windows) { \\ if (is_windows) {
\\ // we want actual \n, not \r\n \\ // we want actual \n, not \r\n
\\ _ = c._setmode(1, c._O_BINARY); \\ _ = c._setmode(1, c._O_BINARY);
@ -282,7 +284,10 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
cases.addC("expose function pointer to C land", cases.addC("expose function pointer to C land",
\\const c = @cImport(@cInclude("stdlib.h")); \\const c = @cImport(@cInclude("stdlib.h"));
\\ \\
\\export fn compare_fn(a: ?&const c_void, b: ?&const c_void) -> c_int { \\comptime {
\\ @export("main", main);
\\}
\\extern fn compare_fn(a: ?&const c_void, b: ?&const c_void) -> c_int {
\\ const a_int = @ptrCast(&align(1) i32, a ?? unreachable); \\ const a_int = @ptrCast(&align(1) i32, a ?? unreachable);
\\ const b_int = @ptrCast(&align(1) i32, b ?? unreachable); \\ const b_int = @ptrCast(&align(1) i32, b ?? unreachable);
\\ if (*a_int < *b_int) { \\ if (*a_int < *b_int) {
@ -294,7 +299,7 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
\\ } \\ }
\\} \\}
\\ \\
\\export fn main() -> c_int { \\extern fn main() -> c_int {
\\ var array = []u32 { 1, 7, 3, 2, 0, 9, 4, 8, 6, 5 }; \\ var array = []u32 { 1, 7, 3, 2, 0, 9, 4, 8, 6, 5 };
\\ \\
\\ c.qsort(@ptrCast(&c_void, &array[0]), c_ulong(array.len), @sizeOf(i32), compare_fn); \\ c.qsort(@ptrCast(&c_void, &array[0]), c_ulong(array.len), @sizeOf(i32), compare_fn);
@ -322,7 +327,8 @@ pub fn addCases(cases: &tests.CompareOutputContext) {
\\ @cInclude("stdio.h"); \\ @cInclude("stdio.h");
\\}); \\});
\\ \\
\\export fn main(argc: c_int, argv: &&u8) -> c_int { \\comptime { @export("main", main); }
\\extern fn main(argc: c_int, argv: &&u8) -> c_int {
\\ if (is_windows) { \\ if (is_windows) {
\\ // we want actual \n, not \r\n \\ // we want actual \n, not \r\n
\\ _ = c._setmode(1, c._O_BINARY); \\ _ = c._setmode(1, c._O_BINARY);

File diff suppressed because it is too large Load Diff

View File

@ -2,6 +2,9 @@ pub fn panic(msg: []const u8) -> noreturn { @breakpoint(); while (true) {} }
fn bar() -> %void {} fn bar() -> %void {}
export fn foo() { comptime {
@export("foo", foo);
}
extern fn foo() {
%%bar(); %%bar();
} }

View File

@ -26,7 +26,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return a < 0 ? -a : a; \\ return a < 0 ? -a : a;
\\} \\}
, ,
\\export fn abs(a: c_int) -> c_int { \\pub fn abs(a: c_int) -> c_int {
\\ return if (a < 0) -a else a; \\ return if (a < 0) -a else a;
\\} \\}
); );
@ -325,12 +325,12 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return a; \\ return a;
\\} \\}
, ,
\\export fn foo1(_arg_a: c_uint) -> c_uint { \\pub fn foo1(_arg_a: c_uint) -> c_uint {
\\ var a = _arg_a; \\ var a = _arg_a;
\\ a +%= 1; \\ a +%= 1;
\\ return a; \\ return a;
\\} \\}
\\export fn foo2(_arg_a: c_int) -> c_int { \\pub fn foo2(_arg_a: c_int) -> c_int {
\\ var a = _arg_a; \\ var a = _arg_a;
\\ a += 1; \\ a += 1;
\\ return a; \\ return a;
@ -346,7 +346,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return i; \\ return i;
\\} \\}
, ,
\\export fn log2(_arg_a: c_uint) -> c_int { \\pub fn log2(_arg_a: c_uint) -> c_int {
\\ var a = _arg_a; \\ var a = _arg_a;
\\ var i: c_int = 0; \\ var i: c_int = 0;
\\ while (a > c_uint(0)) { \\ while (a > c_uint(0)) {
@ -367,7 +367,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return a; \\ return a;
\\} \\}
, ,
\\export fn max(a: c_int, b: c_int) -> c_int { \\pub fn max(a: c_int, b: c_int) -> c_int {
\\ if (a < b) return b; \\ if (a < b) return b;
\\ if (a < b) return b else return a; \\ if (a < b) return b else return a;
\\} \\}
@ -382,7 +382,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return a; \\ return a;
\\} \\}
, ,
\\export fn max(a: c_int, b: c_int) -> c_int { \\pub fn max(a: c_int, b: c_int) -> c_int {
\\ if (a == b) return a; \\ if (a == b) return a;
\\ if (a != b) return b; \\ if (a != b) return b;
\\ return a; \\ return a;
@ -407,7 +407,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ c = a % b; \\ c = a % b;
\\} \\}
, ,
\\export fn s(a: c_int, b: c_int) -> c_int { \\pub fn s(a: c_int, b: c_int) -> c_int {
\\ var c: c_int; \\ var c: c_int;
\\ c = (a + b); \\ c = (a + b);
\\ c = (a - b); \\ c = (a - b);
@ -415,7 +415,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ c = @divTrunc(a, b); \\ c = @divTrunc(a, b);
\\ c = @rem(a, b); \\ c = @rem(a, b);
\\} \\}
\\export fn u(a: c_uint, b: c_uint) -> c_uint { \\pub fn u(a: c_uint, b: c_uint) -> c_uint {
\\ var c: c_uint; \\ var c: c_uint;
\\ c = (a +% b); \\ c = (a +% b);
\\ c = (a -% b); \\ c = (a -% b);
@ -430,7 +430,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return (a & b) ^ (a | b); \\ return (a & b) ^ (a | b);
\\} \\}
, ,
\\export fn max(a: c_int, b: c_int) -> c_int { \\pub fn max(a: c_int, b: c_int) -> c_int {
\\ return (a & b) ^ (a | b); \\ return (a & b) ^ (a | b);
\\} \\}
); );
@ -444,7 +444,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return a; \\ return a;
\\} \\}
, ,
\\export fn max(a: c_int, b: c_int) -> c_int { \\pub fn max(a: c_int, b: c_int) -> c_int {
\\ if ((a < b) or (a == b)) return b; \\ if ((a < b) or (a == b)) return b;
\\ if ((a >= b) and (a == b)) return a; \\ if ((a >= b) and (a == b)) return a;
\\ return a; \\ return a;
@ -458,7 +458,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ a = tmp; \\ a = tmp;
\\} \\}
, ,
\\export fn max(_arg_a: c_int) -> c_int { \\pub fn max(_arg_a: c_int) -> c_int {
\\ var a = _arg_a; \\ var a = _arg_a;
\\ var tmp: c_int; \\ var tmp: c_int;
\\ tmp = a; \\ tmp = a;
@ -472,7 +472,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ c = b = a; \\ c = b = a;
\\} \\}
, ,
\\export fn max(a: c_int) { \\pub fn max(a: c_int) {
\\ var b: c_int; \\ var b: c_int;
\\ var c: c_int; \\ var c: c_int;
\\ c = { \\ c = {
@ -493,7 +493,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return i; \\ return i;
\\} \\}
, ,
\\export fn log2(_arg_a: u32) -> c_int { \\pub fn log2(_arg_a: u32) -> c_int {
\\ var a = _arg_a; \\ var a = _arg_a;
\\ var i: c_int = 0; \\ var i: c_int = 0;
\\ while (a > c_uint(0)) { \\ while (a > c_uint(0)) {
@ -518,7 +518,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\void foo(void) { bar(); } \\void foo(void) { bar(); }
, ,
\\pub fn bar() {} \\pub fn bar() {}
\\export fn foo() { \\pub fn foo() {
\\ bar(); \\ bar();
\\} \\}
); );
@ -534,7 +534,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\pub const struct_Foo = extern struct { \\pub const struct_Foo = extern struct {
\\ field: c_int, \\ field: c_int,
\\}; \\};
\\export fn read_field(foo: ?&struct_Foo) -> c_int { \\pub fn read_field(foo: ?&struct_Foo) -> c_int {
\\ return (??foo).field; \\ return (??foo).field;
\\} \\}
); );
@ -544,7 +544,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ ;;;;; \\ ;;;;;
\\} \\}
, ,
\\export fn foo() {} \\pub fn foo() {}
); );
cases.add("undefined array global", cases.add("undefined array global",
@ -560,7 +560,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\} \\}
, ,
\\pub var array: [100]c_int = undefined; \\pub var array: [100]c_int = undefined;
\\export fn foo(index: c_int) -> c_int { \\pub fn foo(index: c_int) -> c_int {
\\ return array[index]; \\ return array[index];
\\} \\}
); );
@ -571,7 +571,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return (int)a; \\ return (int)a;
\\} \\}
, ,
\\export fn float_to_int(a: f32) -> c_int { \\pub fn float_to_int(a: f32) -> c_int {
\\ return c_int(a); \\ return c_int(a);
\\} \\}
); );
@ -581,7 +581,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return x; \\ return x;
\\} \\}
, ,
\\export fn foo(x: ?&c_ushort) -> ?&c_void { \\pub fn foo(x: ?&c_ushort) -> ?&c_void {
\\ return @ptrCast(?&c_void, x); \\ return @ptrCast(?&c_void, x);
\\} \\}
); );
@ -592,7 +592,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return sizeof(int); \\ return sizeof(int);
\\} \\}
, ,
\\export fn size_of() -> usize { \\pub fn size_of() -> usize {
\\ return @sizeOf(c_int); \\ return @sizeOf(c_int);
\\} \\}
); );
@ -602,7 +602,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return 0; \\ return 0;
\\} \\}
, ,
\\export fn foo() -> ?&c_int { \\pub fn foo() -> ?&c_int {
\\ return null; \\ return null;
\\} \\}
); );
@ -612,7 +612,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return 1, 2; \\ return 1, 2;
\\} \\}
, ,
\\export fn foo() -> c_int { \\pub fn foo() -> c_int {
\\ return { \\ return {
\\ _ = 1; \\ _ = 1;
\\ 2 \\ 2
@ -625,7 +625,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ return (1 << 2) >> 1; \\ return (1 << 2) >> 1;
\\} \\}
, ,
\\export fn foo() -> c_int { \\pub fn foo() -> c_int {
\\ return (1 << @import("std").math.Log2Int(c_int)(2)) >> @import("std").math.Log2Int(c_int)(1); \\ return (1 << @import("std").math.Log2Int(c_int)(2)) >> @import("std").math.Log2Int(c_int)(1);
\\} \\}
); );
@ -643,7 +643,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ a <<= (a <<= 1); \\ a <<= (a <<= 1);
\\} \\}
, ,
\\export fn foo() { \\pub fn foo() {
\\ var a: c_int = 0; \\ var a: c_int = 0;
\\ a += { \\ a += {
\\ const _ref = &a; \\ const _ref = &a;
@ -701,7 +701,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ a <<= (a <<= 1); \\ a <<= (a <<= 1);
\\} \\}
, ,
\\export fn foo() { \\pub fn foo() {
\\ var a: c_uint = c_uint(0); \\ var a: c_uint = c_uint(0);
\\ a +%= { \\ a +%= {
\\ const _ref = &a; \\ const _ref = &a;
@ -771,7 +771,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ u = u--; \\ u = u--;
\\} \\}
, ,
\\export fn foo() { \\pub fn foo() {
\\ var i: c_int = 0; \\ var i: c_int = 0;
\\ var u: c_uint = c_uint(0); \\ var u: c_uint = c_uint(0);
\\ i += 1; \\ i += 1;
@ -819,7 +819,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ u = --u; \\ u = --u;
\\} \\}
, ,
\\export fn foo() { \\pub fn foo() {
\\ var i: c_int = 0; \\ var i: c_int = 0;
\\ var u: c_uint = c_uint(0); \\ var u: c_uint = c_uint(0);
\\ i += 1; \\ i += 1;
@ -862,7 +862,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ while (b != 0); \\ while (b != 0);
\\} \\}
, ,
\\export fn foo() { \\pub fn foo() {
\\ var a: c_int = 2; \\ var a: c_int = 2;
\\ while (true) { \\ while (true) {
\\ a -= 1; \\ a -= 1;
@ -886,9 +886,9 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ baz(); \\ baz();
\\} \\}
, ,
\\export fn foo() {} \\pub fn foo() {}
\\export fn baz() {} \\pub fn baz() {}
\\export fn bar() { \\pub fn bar() {
\\ var f: ?extern fn() = foo; \\ var f: ?extern fn() = foo;
\\ (??f)(); \\ (??f)();
\\ (??f)(); \\ (??f)();
@ -901,7 +901,7 @@ pub fn addCases(cases: &tests.TranslateCContext) {
\\ *x = 1; \\ *x = 1;
\\} \\}
, ,
\\export fn foo(x: ?&c_int) { \\pub fn foo(x: ?&c_int) {
\\ (*??x) = 1; \\ (*??x) = 1;
\\} \\}
); );