Skip to content

Commit a7c2aaf

Browse files
authored
cgen: initialize globals directly for simple cases (#11002)
1 parent f679227 commit a7c2aaf

File tree

3 files changed

+38
-3
lines changed

3 files changed

+38
-3
lines changed

vlib/v/ast/ast.v

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1989,3 +1989,32 @@ fn gen_all_registers(mut t Table, without_numbers []string, with_numbers map[str
19891989
}
19901990
return res
19911991
}
1992+
1993+
// is `expr` a literal, i.e. it does not depend on any other declarations (C compile time constant)
1994+
pub fn (expr Expr) is_literal() bool {
1995+
match expr {
1996+
BoolLiteral, CharLiteral, FloatLiteral, IntegerLiteral {
1997+
return true
1998+
}
1999+
PrefixExpr {
2000+
return expr.right.is_literal()
2001+
}
2002+
InfixExpr {
2003+
return expr.left.is_literal() && expr.right.is_literal()
2004+
}
2005+
ParExpr {
2006+
return expr.expr.is_literal()
2007+
}
2008+
CastExpr {
2009+
return !expr.has_arg && expr.expr.is_literal()
2010+
&& (expr.typ.is_ptr() || expr.typ.is_pointer()
2011+
|| expr.typ in [i8_type, i16_type, int_type, i64_type, byte_type, u8_type, u16_type, u32_type, u64_type, f32_type, f64_type, char_type, bool_type, rune_type])
2012+
}
2013+
SizeOf, IsRefType {
2014+
return expr.is_type || expr.expr.is_literal()
2015+
}
2016+
else {
2017+
return false
2018+
}
2019+
}
2020+
}

vlib/v/gen/c/cgen.v

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5156,8 +5156,13 @@ fn (mut g Gen) global_decl(node ast.GlobalDecl) {
51565156
}
51575157
styp := g.typ(field.typ)
51585158
if field.has_expr {
5159-
g.definitions.writeln('$mod$styp $field.name;')
5160-
g.global_inits[key].writeln('\t$field.name = ${g.expr_string(field.expr)}; // global')
5159+
g.definitions.write_string('$mod$styp $field.name')
5160+
if field.expr.is_literal() {
5161+
g.definitions.writeln(' = ${g.expr_string(field.expr)}; // global')
5162+
} else {
5163+
g.definitions.writeln(';')
5164+
g.global_inits[key].writeln('\t$field.name = ${g.expr_string(field.expr)}; // global')
5165+
}
51615166
} else {
51625167
default_initializer := g.type_default(field.typ)
51635168
if default_initializer == '{0}' {

vlib/v/tests/init_global_test.v

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ __global (
3636
sem sync.Semaphore
3737
shmap shared map[string]f64
3838
mtx sync.RwMutex
39-
f1 = f64(34.0625)
39+
f1 = f64(545 / (sizeof(f64) + f32(8))) // directly initialized
4040
f2 f64
4141
)
4242

@@ -116,6 +116,7 @@ fn switch2() u64 {
116116
}
117117

118118
fn test_global_mutex() {
119+
assert f1 == 34.0625
119120
t := go switch2()
120121
for _ in 0 .. 2500000 {
121122
mtx.@lock()

0 commit comments

Comments
 (0)