diff --git a/src/ast/initializers.rs b/src/ast/initializers.rs index 279797d..259c577 100644 --- a/src/ast/initializers.rs +++ b/src/ast/initializers.rs @@ -53,21 +53,7 @@ impl AstBuilderImpl<'_> { node.offset = object.offset; node.cty = object.cty.clone(); } - for child in [ - &mut node.lhs, - &mut node.rhs, - &mut node.cond, - &mut node.then, - &mut node.els, - &mut node.ini, - &mut node.upd, - ] - .into_iter() - .flatten() - { - Self::resolve_deferred_local(child, offset, object); - } - for child in node.children.iter_mut().chain(&mut node.args) { + for child in node.child_nodes_mut() { Self::resolve_deferred_local(child, offset, object); } node.refresh_arithmetic_type(); diff --git a/src/ast/inline_calls.rs b/src/ast/inline_calls.rs index 98e9764..49aea5c 100644 --- a/src/ast/inline_calls.rs +++ b/src/ast/inline_calls.rs @@ -6,21 +6,7 @@ fn visit_direct_calls(node: &mut Node, operation: &mut impl FnMut(&mut String)) if node.nt == NodeType::CallFunc && node.lhs.is_none() { operation(&mut node.global_name); } - for child in [ - &mut node.lhs, - &mut node.rhs, - &mut node.cond, - &mut node.then, - &mut node.els, - &mut node.ini, - &mut node.upd, - ] - .into_iter() - .flatten() - { - visit_direct_calls(child, operation); - } - for child in node.children.iter_mut().chain(&mut node.args) { + for child in node.child_nodes_mut() { visit_direct_calls(child, operation); } } diff --git a/src/ast/lowering.rs b/src/ast/lowering.rs index 1f83ce8..0ff6f4d 100644 --- a/src/ast/lowering.rs +++ b/src/ast/lowering.rs @@ -17,21 +17,7 @@ impl AstBuilderImpl<'_> { for ty in &mut node.parameter_types { ty.lower_parameter_for_codegen(); } - for child in [ - &mut node.lhs, - &mut node.rhs, - &mut node.cond, - &mut node.then, - &mut node.els, - &mut node.ini, - &mut node.upd, - ] - .into_iter() - .flatten() - { - Self::lower_source_types(child); - } - for child in node.children.iter_mut().chain(&mut node.args) { + for child in node.child_nodes_mut() { Self::lower_source_types(child); } } @@ -50,21 +36,7 @@ impl AstBuilderImpl<'_> { } pub(super) fn insert_integer_conversions(node: &mut Node) { - for child in [ - &mut node.lhs, - &mut node.rhs, - &mut node.cond, - &mut node.then, - &mut node.els, - &mut node.ini, - &mut node.upd, - ] - .into_iter() - .flatten() - { - Self::insert_integer_conversions(child); - } - for child in node.children.iter_mut().chain(&mut node.args) { + for child in node.child_nodes_mut() { Self::insert_integer_conversions(child); } if matches!( diff --git a/src/ast/overflow.rs b/src/ast/overflow.rs index fbad28d..03f6cff 100644 --- a/src/ast/overflow.rs +++ b/src/ast/overflow.rs @@ -93,21 +93,7 @@ impl AstBuilderImpl<'_> { } pub(super) fn lower(node: &mut Node, offset: &mut usize) { - for child in [ - &mut node.lhs, - &mut node.rhs, - &mut node.cond, - &mut node.then, - &mut node.els, - &mut node.ini, - &mut node.upd, - ] - .into_iter() - .flatten() - { - lower(child, offset); - } - for child in node.children.iter_mut().chain(&mut node.args) { + for child in node.child_nodes_mut() { lower(child, offset); } if !matches!(node.nt, NodeType::AddOverflow | NodeType::SubOverflow) { diff --git a/src/ast/statement_expression.rs b/src/ast/statement_expression.rs index e7e804b..ac7a4a9 100644 --- a/src/ast/statement_expression.rs +++ b/src/ast/statement_expression.rs @@ -102,15 +102,7 @@ impl AstBuilderImpl<'_> { NodeType::While | NodeType::DoWhile | NodeType::For )); let switches = switches + usize::from(node.nt == NodeType::Switch); - for child in [ - &node.lhs, &node.rhs, &node.cond, &node.then, &node.els, &node.ini, &node.upd, - ] - .into_iter() - .flatten() - { - self.validate_statement_expression_jumps(child, loops, switches); - } - for child in node.children.iter().chain(&node.args) { + for child in node.child_nodes() { self.validate_statement_expression_jumps(child, loops, switches); } } diff --git a/src/ast/validation.rs b/src/ast/validation.rs index 14bb19c..e75e81d 100644 --- a/src/ast/validation.rs +++ b/src/ast/validation.rs @@ -285,15 +285,7 @@ impl AstBuilderImpl<'_> { "external inline definition cannot refer to an internal identifier", ); } - for child in [ - &node.lhs, &node.rhs, &node.cond, &node.then, &node.els, &node.ini, &node.upd, - ] - .into_iter() - .flatten() - { - self.validate_inline_body(child); - } - for child in node.children.iter().chain(&node.args) { + for child in node.child_nodes() { self.validate_inline_body(child); } } @@ -506,15 +498,7 @@ impl AstBuilderImpl<'_> { ); } } - for child in [ - &node.lhs, &node.rhs, &node.cond, &node.then, &node.els, &node.ini, &node.upd, - ] - .into_iter() - .flatten() - { - self.validate_void_expressions(child); - } - for child in node.children.iter().chain(&node.args) { + for child in node.child_nodes() { self.validate_void_expressions(child); } } diff --git a/src/ast/vla.rs b/src/ast/vla.rs index f99872d..ce73c33 100644 --- a/src/ast/vla.rs +++ b/src/ast/vla.rs @@ -34,34 +34,12 @@ fn block(children: Vec) -> Node { } fn walk(node: &Node, visitor: &mut impl FnMut(&Node)) { visitor(node); - for child in [ - &node.lhs, &node.rhs, &node.cond, &node.then, &node.els, &node.ini, &node.upd, - ] - .into_iter() - .flatten() - { - walk(child, visitor); - } - for child in node.children.iter().chain(&node.args) { + for child in node.child_nodes() { walk(child, visitor); } } fn walk_mut(node: &mut Node, visitor: &mut impl FnMut(&mut Node)) { - for child in [ - &mut node.lhs, - &mut node.rhs, - &mut node.cond, - &mut node.then, - &mut node.els, - &mut node.ini, - &mut node.upd, - ] - .into_iter() - .flatten() - { - walk_mut(child, visitor); - } - for child in node.children.iter_mut().chain(&mut node.args) { + for child in node.child_nodes_mut() { walk_mut(child, visitor); } visitor(node); @@ -252,21 +230,7 @@ impl AstBuilderImpl<'_> { // Report type changes so only ancestors of rewritten expressions need refreshing. fn lower_variable_arithmetic_types(node: &mut Node) -> bool { let mut changed = false; - for child in [ - &mut node.lhs, - &mut node.rhs, - &mut node.cond, - &mut node.then, - &mut node.els, - &mut node.ini, - &mut node.upd, - ] - .into_iter() - .flatten() - { - changed |= Self::lower_variable_arithmetic_types(child); - } - for child in node.children.iter_mut().chain(&mut node.args) { + for child in node.child_nodes_mut() { changed |= Self::lower_variable_arithmetic_types(child); } if changed { diff --git a/src/bitfield.rs b/src/bitfield.rs index 972c2a7..0675435 100644 --- a/src/bitfield.rs +++ b/src/bitfield.rs @@ -291,21 +291,7 @@ fn lower_with_type_changes(node: &mut Node, offset: &mut usize) -> bool { return true; } let mut changed = false; - for child in [ - &mut node.lhs, - &mut node.rhs, - &mut node.cond, - &mut node.then, - &mut node.els, - &mut node.ini, - &mut node.upd, - ] - .into_iter() - .flatten() - { - changed |= lower_with_type_changes(child, offset); - } - for child in node.children.iter_mut().chain(&mut node.args) { + for child in node.child_nodes_mut() { changed |= lower_with_type_changes(child, offset); } if node.bit_field.is_some() { diff --git a/src/generator/aarch64/generator/globals.rs b/src/generator/aarch64/generator/globals.rs index 50d70bd..32015c4 100644 --- a/src/generator/aarch64/generator/globals.rs +++ b/src/generator/aarch64/generator/globals.rs @@ -1,270 +1,25 @@ use super::AsmGenerator; -use crate::ctype::Type; -use crate::generator::Os; use crate::generator::aarch64::assembly::Assembly; -use crate::global::{GlobalVariable, GlobalVariableData}; +use crate::generator::globals; +use crate::global::GlobalVariable; use crate::token::Token; impl AsmGenerator<'_> { - pub(super) fn gen_string_literals(&self, string_literals: &[Token]) -> Assembly { - if string_literals.is_empty() { - vec![] - } else { - vec![ - if let Os::MacOS = self.target_os { - ".section __TEXT,__const".into() - } else { - ".section .data".into() - }, - string_literals - .iter() - .enumerate() - .map(|(i, token)| { - let bytes = token.encoded_string(); - vec![ - format!(" .balign {}", token.string_encoding.unit_size()).into(), - format!("L_.str.{}:", i).into(), - format!( - " .byte {}", - bytes - .into_iter() - .map(|byte| byte.to_string()) - .collect::>() - .join(", ") - ) - .into(), - ] - .into() - }) - .collect::>() - .into(), - ] - } - .into() + pub(super) fn gen_string_literals(&self, literals: &[Token]) -> Assembly { + globals::gen_string_literals(self.target_os, literals) } pub(super) fn weak_reference(&self, name: &str) -> Assembly { - let directive = match self.target_os { - Os::Linux => ".weak", - Os::MacOS => ".weak_reference", - }; - format!("{directive} {}", self.with_prefix(name)).into() + globals::weak_reference(self.target_os, name, &|name| self.with_prefix(name)) } - pub(super) fn gen_global_variable(&self, name: &str, gv: &GlobalVariable) -> Assembly { - if gv.declaration_only { - return if gv.weak_import { - self.weak_reference(name) - } else { - vec![].into() - }; - } - if gv.common && !gv.internal && !gv.thread_local && gv.data.is_none() { - let alignment = gv.ty.align_of().max(gv.alignment).max(1); - let alignment = match self.target_os { - Os::Linux => alignment, - Os::MacOS => alignment.trailing_zeros() as usize, - }; - return format!( - ".comm {},{},{}", - self.with_prefix(name), - gv.ty.size_of(), - alignment - ) - .into(); - } - vec![ - if let Os::MacOS = self.target_os { - ".section __DATA,__data".into() - } else { - ".section .data".into() - }, - if gv.internal { - vec![].into() - } else { - format!(".globl {}", self.with_prefix(name)).into() - }, - format!(" .balign {}", gv.ty.align_of().max(gv.alignment)).into(), - format!("{}:", self.with_prefix(name)).into(), - self.gen_initializer_element(&gv.ty, gv.data.as_ref()), - ] - .into() - } - - pub(super) fn gen_initializer_element( - &self, - ty: &Type, - data: Option<&GlobalVariableData>, - ) -> Assembly { - let data = if !matches!(ty, Type::Arr(..) | Type::Struct(_)) { - let mut value = data; - while let Some(GlobalVariableData::Arr(elements)) = value { - value = elements.first(); - } - value - } else { - data - }; - match ty { - Type::Bool | Type::Integer { .. } | Type::LongLong { .. } => format!( - " {} {}", - if ty.size_of() == 1 { - ".byte".to_string() - } else { - format!(".{}byte", ty.size_of()) - }, - if let Some(GlobalVariableData::Address { symbol, offset }) = data { - format!("{}{offset:+}", self.address_symbol(symbol)) - } else if let Some(GlobalVariableData::Elem(value)) = data { - ty.convert_constant(value.parse().unwrap()).to_string() - } else { - "0".into() - } - ) - .into(), - Type::I8 | Type::SignedChar => format!( - " .byte {}", - if let Some(GlobalVariableData::Elem(s)) = data { - s - } else { - "0" - } - ) - .into(), - Type::I32 => format!( - " .4byte {}", - if let Some(GlobalVariableData::Elem(s)) = data { - s - } else { - "0" - } - ) - .into(), - Type::Integer128 { .. } => " .zero 16".into(), - Type::Enum(value) => self.gen_initializer_element(&value.underlying.borrow(), data), - Type::Float16 => " .zero 2".into(), - Type::LongDouble(bits) if *bits != 64 => { - let value = if let Some(GlobalVariableData::Elem(value)) = data { - value.parse::().unwrap() - } else { - 0 - }; - format!( - " .8byte {}\n .8byte {}", - value as u64, - (value >> 64) as u64 - ) - .into() - } - Type::Float(_) | Type::LongDouble(_) => format!( - " .{}byte {}", - ty.size_of(), - if let Some(GlobalVariableData::Elem(value)) = data { - value.as_str() - } else { - "0" - } - ) - .into(), - Type::Arr(children_ty, size) => { - let size = size.unwrap_or(0); - if let Some(GlobalVariableData::Arr(v)) = data { - vec![ - v.iter() - .enumerate() - .filter(|(i, _)| *i < size) - .map(|(_, d)| { - self.gen_initializer_element(children_ty.as_ref(), Some(d)) - }) - .collect::>() - .into(), - format!( - " .zero {}", - children_ty.size_of() - * v.iter() - .enumerate() - .filter(|(i, _)| *i < size) - .fold(size, |_, _| { size.saturating_sub(v.len()) }) - ) - .into(), - ] - .into() - } else { - format!(" .zero {}", children_ty.size_of() * size).into() - } - } - Type::Vector(..) => format!(" .zero {}", ty.size_of()).into(), - Type::Struct(struct_type) - if struct_type.has_bit_fields() || struct_type.definition().borrow().is_union => - { - let mut bytes = vec![0; ty.size_of()]; - let mut addresses = std::collections::HashMap::new(); - crate::global::initializer_bytes(ty, data, 0, &mut bytes, &mut addresses); - let mut lines = vec![]; - let mut index = 0; - while index < bytes.len() { - if let Some((symbol, delta)) = addresses.get(&index) { - let symbol = self.address_symbol(symbol); - lines.push(format!(" .8byte {symbol}{delta:+}").into()); - index += 8; - } else { - lines.push(format!(" .byte {}", bytes[index]).into()); - index += 1; - } - } - lines.into() - } - Type::Struct(struct_type) => { - let elements = if let Some(GlobalVariableData::Arr(elements)) = data { - Some(elements) - } else { - None - }; - let mut lines = vec![]; - let mut end = 0; - for (i, member) in struct_type - .members() - .iter() - .take(if struct_type.definition().borrow().is_union { - 1 - } else { - usize::MAX - }) - .enumerate() - { - if member.offset > end { - lines.push(format!(" .zero {}", member.offset - end).into()); - } - lines.push(self.gen_initializer_element( - &member.ty, - elements.and_then(|elements| elements.get(i)), - )); - end = member.offset + member.ty.size_of(); - } - if ty.size_of() > end { - lines.push(format!(" .zero {}", ty.size_of() - end).into()); - } - lines.into() - } - Type::Aligned(child, _) => self.gen_initializer_element(child, data), - _ => format!( - " .8byte {}", - if let Some(GlobalVariableData::Address { symbol, offset }) = data { - let symbol = self.address_symbol(symbol); - format!("{symbol}{offset:+}") - } else if let Some(GlobalVariableData::Elem(s)) = data { - if s.starts_with("@.str.") { - s.replace('@', "L_") - } else if let Some(name) = s.strip_prefix('@') { - self.address_symbol(name) - } else { - s.clone() - } - } else { - "0".to_string() - } - ) - .into(), - } + pub(super) fn gen_global_variable(&self, name: &str, variable: &GlobalVariable) -> Assembly { + globals::gen_global_variable( + self.target_os, + name, + variable, + &|name| self.with_prefix(name), + &|name| self.address_symbol(name), + ) } } diff --git a/src/generator/globals.rs b/src/generator/globals.rs new file mode 100644 index 0000000..1f2684e --- /dev/null +++ b/src/generator/globals.rs @@ -0,0 +1,293 @@ +//! Data directives shared by the native assembly backends. + +use super::Os; +use crate::ctype::Type; +use crate::global::{GlobalVariable, GlobalVariableData}; +use crate::token::Token; + +pub(super) fn gen_string_literals(target_os: Os, string_literals: &[Token]) -> A +where + A: From + From<&'static str> + From>, +{ + if string_literals.is_empty() { + vec![] + } else { + vec![ + if let Os::MacOS = target_os { + ".section __TEXT,__const".into() + } else { + ".section .data".into() + }, + string_literals + .iter() + .enumerate() + .map(|(i, token)| { + let bytes = token.encoded_string(); + vec![ + format!(" .balign {}", token.string_encoding.unit_size()).into(), + format!("L_.str.{}:", i).into(), + format!( + " .byte {}", + bytes + .into_iter() + .map(|byte| byte.to_string()) + .collect::>() + .join(", ") + ) + .into(), + ] + .into() + }) + .collect::>() + .into(), + ] + } + .into() +} + +pub(super) fn weak_reference( + target_os: Os, + name: &str, + with_prefix: &impl Fn(&str) -> String, +) -> A +where + A: From + From<&'static str> + From>, +{ + let directive = match target_os { + Os::Linux => ".weak", + Os::MacOS => ".weak_reference", + }; + format!("{directive} {}", with_prefix(name)).into() +} + +pub(super) fn gen_global_variable( + target_os: Os, + name: &str, + gv: &GlobalVariable, + with_prefix: &impl Fn(&str) -> String, + address_symbol: &impl Fn(&str) -> String, +) -> A +where + A: From + From<&'static str> + From>, +{ + if gv.declaration_only { + return if gv.weak_import { + weak_reference(target_os, name, with_prefix) + } else { + vec![].into() + }; + } + if gv.common && !gv.internal && !gv.thread_local && gv.data.is_none() { + let alignment = gv.ty.align_of().max(gv.alignment).max(1); + let alignment = match target_os { + Os::Linux => alignment, + Os::MacOS => alignment.trailing_zeros() as usize, + }; + return format!( + ".comm {},{},{}", + with_prefix(name), + gv.ty.size_of(), + alignment + ) + .into(); + } + vec![ + if let Os::MacOS = target_os { + ".section __DATA,__data".into() + } else { + ".section .data".into() + }, + if gv.internal { + vec![].into() + } else { + format!(".globl {}", with_prefix(name)).into() + }, + format!(" .balign {}", gv.ty.align_of().max(gv.alignment)).into(), + format!("{}:", with_prefix(name)).into(), + gen_initializer_element(&gv.ty, gv.data.as_ref(), address_symbol), + ] + .into() +} + +pub(super) fn gen_initializer_element( + ty: &Type, + data: Option<&GlobalVariableData>, + address_symbol: &impl Fn(&str) -> String, +) -> A +where + A: From + From<&'static str> + From>, +{ + let data = if !matches!(ty, Type::Arr(..) | Type::Struct(_)) { + let mut value = data; + while let Some(GlobalVariableData::Arr(elements)) = value { + value = elements.first(); + } + value + } else { + data + }; + match ty { + Type::Bool | Type::Integer { .. } | Type::LongLong { .. } => format!( + " {} {}", + if ty.size_of() == 1 { + ".byte".to_string() + } else { + format!(".{}byte", ty.size_of()) + }, + if let Some(GlobalVariableData::Address { symbol, offset }) = data { + format!("{}{offset:+}", address_symbol(symbol)) + } else if let Some(GlobalVariableData::Elem(value)) = data { + ty.convert_constant(value.parse().unwrap()).to_string() + } else { + "0".into() + } + ) + .into(), + Type::I8 | Type::SignedChar => format!( + " .byte {}", + if let Some(GlobalVariableData::Elem(s)) = data { + s + } else { + "0" + } + ) + .into(), + Type::I32 => format!( + " .4byte {}", + if let Some(GlobalVariableData::Elem(s)) = data { + s + } else { + "0" + } + ) + .into(), + Type::Integer128 { .. } => " .zero 16".into(), + Type::Enum(value) => { + gen_initializer_element(&value.underlying.borrow(), data, address_symbol) + } + Type::Float16 => " .zero 2".into(), + Type::LongDouble(bits) if *bits != 64 => { + let value = if let Some(GlobalVariableData::Elem(value)) = data { + value.parse::().unwrap() + } else { + 0 + }; + format!( + " .8byte {}\n .8byte {}", + value as u64, + (value >> 64) as u64 + ) + .into() + } + Type::Float(_) | Type::LongDouble(_) => format!( + " .{}byte {}", + ty.size_of(), + if let Some(GlobalVariableData::Elem(value)) = data { + value.as_str() + } else { + "0" + } + ) + .into(), + Type::Arr(children_ty, size) => { + let size = size.unwrap_or(0); + if let Some(GlobalVariableData::Arr(v)) = data { + vec![ + v.iter() + .enumerate() + .filter(|(i, _)| *i < size) + .map(|(_, d)| { + gen_initializer_element(children_ty.as_ref(), Some(d), address_symbol) + }) + .collect::>() + .into(), + format!( + " .zero {}", + children_ty.size_of() + * v.iter() + .enumerate() + .filter(|(i, _)| *i < size) + .fold(size, |_, _| { size.saturating_sub(v.len()) }) + ) + .into(), + ] + .into() + } else { + format!(" .zero {}", children_ty.size_of() * size).into() + } + } + Type::Vector(..) => format!(" .zero {}", ty.size_of()).into(), + Type::Struct(struct_type) + if struct_type.has_bit_fields() || struct_type.definition().borrow().is_union => + { + let mut bytes = vec![0; ty.size_of()]; + let mut addresses = std::collections::HashMap::new(); + crate::global::initializer_bytes(ty, data, 0, &mut bytes, &mut addresses); + let mut lines = vec![]; + let mut index = 0; + while index < bytes.len() { + if let Some((symbol, delta)) = addresses.get(&index) { + let symbol = address_symbol(symbol); + lines.push(format!(" .8byte {symbol}{delta:+}").into()); + index += 8; + } else { + lines.push(format!(" .byte {}", bytes[index]).into()); + index += 1; + } + } + lines.into() + } + Type::Struct(struct_type) => { + let elements = if let Some(GlobalVariableData::Arr(elements)) = data { + Some(elements) + } else { + None + }; + let mut lines = vec![]; + let mut end = 0; + for (i, member) in struct_type + .members() + .iter() + .take(if struct_type.definition().borrow().is_union { + 1 + } else { + usize::MAX + }) + .enumerate() + { + if member.offset > end { + lines.push(format!(" .zero {}", member.offset - end).into()); + } + lines.push(gen_initializer_element( + &member.ty, + elements.and_then(|elements| elements.get(i)), + address_symbol, + )); + end = member.offset + member.ty.size_of(); + } + if ty.size_of() > end { + lines.push(format!(" .zero {}", ty.size_of() - end).into()); + } + lines.into() + } + Type::Aligned(child, _) => gen_initializer_element(child, data, address_symbol), + _ => format!( + " .8byte {}", + if let Some(GlobalVariableData::Address { symbol, offset }) = data { + let symbol = address_symbol(symbol); + format!("{symbol}{offset:+}") + } else if let Some(GlobalVariableData::Elem(s)) = data { + if s.starts_with("@.str.") { + s.replace('@', "L_") + } else if let Some(name) = s.strip_prefix('@') { + address_symbol(name) + } else { + s.clone() + } + } else { + "0".to_string() + } + ) + .into(), + } +} diff --git a/src/generator/llvm/generator.rs b/src/generator/llvm/generator.rs index 85671b0..e96f4ae 100644 --- a/src/generator/llvm/generator.rs +++ b/src/generator/llvm/generator.rs @@ -518,15 +518,7 @@ impl<'a> IrGenerator<'a> { )); } } - for child in [ - &node.lhs, &node.rhs, &node.cond, &node.then, &node.els, &node.ini, &node.upd, - ] - .into_iter() - .flatten() - { - Self::allocate_locals(child, options, lines); - } - for child in node.children.iter().chain(&node.args) { + for child in node.child_nodes() { Self::allocate_locals(child, options, lines); } } diff --git a/src/generator/mod.rs b/src/generator/mod.rs index 6f02b41..1a649ed 100644 --- a/src/generator/mod.rs +++ b/src/generator/mod.rs @@ -2,6 +2,7 @@ use crate::{ast::ProgramAst, error::ErrorLogger}; pub mod aarch64; pub mod abi; +mod globals; pub mod llvm; pub mod x86_64; @@ -55,15 +56,7 @@ pub(crate) fn referenced_symbols<'a>( if !node.global_name.is_empty() { add_name(&node.global_name, names, pending); } - for child in [ - &node.lhs, &node.rhs, &node.cond, &node.then, &node.els, &node.ini, &node.upd, - ] - .into_iter() - .flatten() - { - node_names(child, names, pending); - } - for child in node.children.iter().chain(&node.args) { + for child in node.child_nodes() { node_names(child, names, pending); } } diff --git a/src/generator/x86_64/generator/globals.rs b/src/generator/x86_64/generator/globals.rs index 90c7bb0..221b0e0 100644 --- a/src/generator/x86_64/generator/globals.rs +++ b/src/generator/x86_64/generator/globals.rs @@ -1,270 +1,25 @@ use super::AsmGenerator; -use crate::ctype::Type; -use crate::generator::Os; +use crate::generator::globals; use crate::generator::x86_64::assembly::Assembly; -use crate::global::{GlobalVariable, GlobalVariableData}; +use crate::global::GlobalVariable; use crate::token::Token; impl AsmGenerator<'_> { - pub(super) fn gen_string_literals(&self, string_literals: &[Token]) -> Assembly { - if string_literals.is_empty() { - vec![] - } else { - vec![ - if let Os::MacOS = self.target_os { - ".section __TEXT,__const".into() - } else { - ".section .data".into() - }, - string_literals - .iter() - .enumerate() - .map(|(i, token)| { - let bytes = token.encoded_string(); - vec![ - format!(" .balign {}", token.string_encoding.unit_size()).into(), - format!("L_.str.{}:", i).into(), - format!( - " .byte {}", - bytes - .into_iter() - .map(|byte| byte.to_string()) - .collect::>() - .join(", ") - ) - .into(), - ] - .into() - }) - .collect::>() - .into(), - ] - } - .into() + pub(super) fn gen_string_literals(&self, literals: &[Token]) -> Assembly { + globals::gen_string_literals(self.target_os, literals) } pub(super) fn weak_reference(&self, name: &str) -> Assembly { - let directive = match self.target_os { - Os::Linux => ".weak", - Os::MacOS => ".weak_reference", - }; - format!("{directive} {}", self.with_prefix(name)).into() + globals::weak_reference(self.target_os, name, &|name| self.with_prefix(name)) } - pub(super) fn gen_global_variable(&self, name: &str, gv: &GlobalVariable) -> Assembly { - if gv.declaration_only { - return if gv.weak_import { - self.weak_reference(name) - } else { - vec![].into() - }; - } - if gv.common && !gv.internal && !gv.thread_local && gv.data.is_none() { - let alignment = gv.ty.align_of().max(gv.alignment).max(1); - let alignment = match self.target_os { - Os::Linux => alignment, - Os::MacOS => alignment.trailing_zeros() as usize, - }; - return format!( - ".comm {},{},{}", - self.with_prefix(name), - gv.ty.size_of(), - alignment - ) - .into(); - } - vec![ - if let Os::MacOS = self.target_os { - ".section __DATA,__data".into() - } else { - ".section .data".into() - }, - if gv.internal { - vec![].into() - } else { - format!(".globl {}", self.with_prefix(name)).into() - }, - format!(" .balign {}", gv.ty.align_of().max(gv.alignment)).into(), - format!("{}:", self.with_prefix(name)).into(), - self.gen_initializer_element(&gv.ty, gv.data.as_ref()), - ] - .into() - } - - pub(super) fn gen_initializer_element( - &self, - ty: &Type, - data: Option<&GlobalVariableData>, - ) -> Assembly { - let data = if !matches!(ty, Type::Arr(..) | Type::Struct(_)) { - let mut value = data; - while let Some(GlobalVariableData::Arr(elements)) = value { - value = elements.first(); - } - value - } else { - data - }; - match ty { - Type::Bool | Type::Integer { .. } | Type::LongLong { .. } => format!( - " {} {}", - if ty.size_of() == 1 { - ".byte".to_string() - } else { - format!(".{}byte", ty.size_of()) - }, - if let Some(GlobalVariableData::Address { symbol, offset }) = data { - format!("{}{offset:+}", self.address_symbol(symbol)) - } else if let Some(GlobalVariableData::Elem(value)) = data { - ty.convert_constant(value.parse().unwrap()).to_string() - } else { - "0".into() - } - ) - .into(), - Type::I8 | Type::SignedChar => format!( - " .byte {}", - if let Some(GlobalVariableData::Elem(s)) = data { - s - } else { - "0" - } - ) - .into(), - Type::I32 => format!( - " .4byte {}", - if let Some(GlobalVariableData::Elem(s)) = data { - s - } else { - "0" - } - ) - .into(), - Type::Integer128 { .. } => " .zero 16".into(), - Type::Enum(value) => self.gen_initializer_element(&value.underlying.borrow(), data), - Type::Float16 => " .zero 2".into(), - Type::LongDouble(bits) if *bits != 64 => { - let value = if let Some(GlobalVariableData::Elem(value)) = data { - value.parse::().unwrap() - } else { - 0 - }; - format!( - " .8byte {}\n .8byte {}", - value as u64, - (value >> 64) as u64 - ) - .into() - } - Type::Float(_) | Type::LongDouble(_) => format!( - " .{}byte {}", - ty.size_of(), - if let Some(GlobalVariableData::Elem(value)) = data { - value.as_str() - } else { - "0" - } - ) - .into(), - Type::Arr(children_ty, size) => { - let size = size.unwrap_or(0); - if let Some(GlobalVariableData::Arr(v)) = data { - vec![ - v.iter() - .enumerate() - .filter(|(i, _)| *i < size) - .map(|(_, d)| { - self.gen_initializer_element(children_ty.as_ref(), Some(d)) - }) - .collect::>() - .into(), - format!( - " .zero {}", - children_ty.size_of() - * v.iter() - .enumerate() - .filter(|(i, _)| *i < size) - .fold(size, |_, _| { size.saturating_sub(v.len()) }) - ) - .into(), - ] - .into() - } else { - format!(" .zero {}", children_ty.size_of() * size).into() - } - } - Type::Vector(..) => format!(" .zero {}", ty.size_of()).into(), - Type::Struct(struct_type) - if struct_type.has_bit_fields() || struct_type.definition().borrow().is_union => - { - let mut bytes = vec![0; ty.size_of()]; - let mut addresses = std::collections::HashMap::new(); - crate::global::initializer_bytes(ty, data, 0, &mut bytes, &mut addresses); - let mut lines = vec![]; - let mut index = 0; - while index < bytes.len() { - if let Some((symbol, delta)) = addresses.get(&index) { - let symbol = self.address_symbol(symbol); - lines.push(format!(" .8byte {symbol}{delta:+}").into()); - index += 8; - } else { - lines.push(format!(" .byte {}", bytes[index]).into()); - index += 1; - } - } - lines.into() - } - Type::Struct(struct_type) => { - let elements = if let Some(GlobalVariableData::Arr(elements)) = data { - Some(elements) - } else { - None - }; - let mut lines = vec![]; - let mut end = 0; - for (i, member) in struct_type - .members() - .iter() - .take(if struct_type.definition().borrow().is_union { - 1 - } else { - usize::MAX - }) - .enumerate() - { - if member.offset > end { - lines.push(format!(" .zero {}", member.offset - end).into()); - } - lines.push(self.gen_initializer_element( - &member.ty, - elements.and_then(|elements| elements.get(i)), - )); - end = member.offset + member.ty.size_of(); - } - if ty.size_of() > end { - lines.push(format!(" .zero {}", ty.size_of() - end).into()); - } - lines.into() - } - Type::Aligned(child, _) => self.gen_initializer_element(child, data), - _ => format!( - " .8byte {}", - if let Some(GlobalVariableData::Address { symbol, offset }) = data { - let symbol = self.address_symbol(symbol); - format!("{symbol}{offset:+}") - } else if let Some(GlobalVariableData::Elem(s)) = data { - if s.starts_with("@.str.") { - s.replace('@', "L_") - } else if let Some(name) = s.strip_prefix('@') { - self.address_symbol(name) - } else { - s.clone() - } - } else { - "0".to_string() - } - ) - .into(), - } + pub(super) fn gen_global_variable(&self, name: &str, variable: &GlobalVariable) -> Assembly { + globals::gen_global_variable( + self.target_os, + name, + variable, + &|name| self.with_prefix(name), + &|name| self.address_symbol(name), + ) } } diff --git a/src/node.rs b/src/node.rs index 52488ee..e90419b 100644 --- a/src/node.rs +++ b/src/node.rs @@ -161,6 +161,33 @@ pub struct Node { } impl Node { + /// Direct children in structural order, not source-language evaluation order. + pub(crate) fn child_nodes(&self) -> impl Iterator { + [ + &self.lhs, &self.rhs, &self.cond, &self.then, &self.els, &self.ini, &self.upd, + ] + .into_iter() + .filter_map(|child| child.as_deref()) + .chain(&self.children) + .chain(&self.args) + } + + pub(crate) fn child_nodes_mut(&mut self) -> impl Iterator { + [ + &mut self.lhs, + &mut self.rhs, + &mut self.cond, + &mut self.then, + &mut self.els, + &mut self.ini, + &mut self.upd, + ] + .into_iter() + .filter_map(|child| child.as_deref_mut()) + .chain(&mut self.children) + .chain(&mut self.args) + } + /// Whether evaluating this expression can call, write, or read a volatile value. pub(crate) fn has_side_effects(&self) -> bool { Self::has_effects(self, true) @@ -197,17 +224,8 @@ impl Node { .as_deref() .is_some_and(|child| Self::has_effects(child, false)); } - [ - &node.lhs, &node.rhs, &node.cond, &node.then, &node.els, &node.ini, &node.upd, - ] - .into_iter() - .flatten() - .any(|child| Self::has_effects(child, true)) - || node - .children - .iter() - .chain(&node.args) - .any(|child| Self::has_effects(child, true)) + node.child_nodes() + .any(|child| Self::has_effects(child, true)) } pub fn new_with_op(token: Option, nt: NodeType, lhs: Node, rhs: Node) -> Self {