1use crate::zigir::ops::{BinOp, LogicalOp, UnaOp};
13use crate::zigir::passes::{IrPass, PassResult};
14use crate::zigir::types::{IrAssignTarget, IrBlock, IrExpr, IrModule, IrStmt};
15
16use std::cell::RefCell;
17
18use super::walk;
19
20pub struct ConstantFoldPass;
25
26impl ConstantFoldPass {
27 pub fn new() -> Self {
28 Self
29 }
30
31 fn try_fold(expr: &mut IrExpr) -> bool {
38 match expr {
39 IrExpr::Binary {
40 op, left, right, ..
41 } => {
42 let mut changed = false;
44 if Self::try_fold(left) {
45 changed = true;
46 }
47 if Self::try_fold(right) {
48 changed = true;
49 }
50 if let Some(result) = fold_binary(*op, left, right) {
52 *expr = result;
53 true
54 } else {
55 changed
56 }
57 }
58 IrExpr::Unary { op, operand } => {
59 let changed = Self::try_fold(operand);
60 if let Some(result) = fold_unary(*op, operand) {
61 *expr = result;
62 true
63 } else {
64 changed
65 }
66 }
67 IrExpr::Logical {
68 op, left, right, ..
69 } => {
70 let mut changed = false;
71 if Self::try_fold(left) {
72 changed = true;
73 }
74 if Self::try_fold(right) {
75 changed = true;
76 }
77 if let Some(result) = fold_logical(*op, left, right) {
78 *expr = result;
79 true
80 } else {
81 changed
82 }
83 }
84 IrExpr::Conditional { cond, then, else_ } => {
85 let mut changed = false;
86 if Self::try_fold(cond) {
87 changed = true;
88 }
89 let cond_bool = if let IrExpr::BoolLiteral(b) = cond.as_ref() {
91 Some(*b)
92 } else {
93 None
94 };
95 if Self::try_fold(then) {
96 changed = true;
97 }
98 if Self::try_fold(else_) {
99 changed = true;
100 }
101 if let Some(b) = cond_bool {
103 let replacement = if b {
104 (**then).clone()
105 } else {
106 (**else_).clone()
107 };
108 *expr = replacement;
109 return true;
110 }
111 changed
112 }
113 IrExpr::Paren(inner) => {
114 let mut changed = Self::try_fold(inner);
115 if matches!(
117 inner.as_ref(),
118 IrExpr::IntLiteral(_)
119 | IrExpr::FloatLiteral(_)
120 | IrExpr::BoolLiteral(_)
121 | IrExpr::BigIntLiteral(_)
122 ) {
123 *expr = (**inner).clone();
124 changed = true;
125 }
126 changed
127 }
128 IrExpr::Sequence(exprs) => Self::try_fold_iter(exprs),
129 IrExpr::AllocPrint { fmt, args } => {
130 let changed = Self::try_fold_iter(args);
131 if args.is_empty() {
132 let s = fmt.clone();
133 *expr = IrExpr::StringLiteral(s);
134 return true;
135 }
136 changed
137 }
138 IrExpr::Typeof(inner) => {
139 let typeof_result = typeof_literal(inner);
141 let changed = Self::try_fold(inner);
142 if let Some(s) = typeof_result {
143 *expr = IrExpr::StringLiteral(s);
144 return true;
145 }
146 changed
147 }
148 IrExpr::ArrayLiteral(arr) => Self::try_fold_iter(&mut arr.elements),
150 IrExpr::ObjectLiteral(obj) => Self::try_fold_object_items(&mut obj.items),
151 IrExpr::TemplateLiteral { exprs, .. } => Self::try_fold_iter(exprs),
152 IrExpr::Spread(e) | IrExpr::Void(e) => Self::try_fold(e),
153 _ => false,
154 }
155 }
156
157 fn try_fold_iter(exprs: &mut [IrExpr]) -> bool {
158 let mut changed = false;
159 for e in exprs {
160 if Self::try_fold(e) {
161 changed = true;
162 }
163 }
164 changed
165 }
166
167 fn try_fold_object_items(items: &mut [crate::zigir::types::IrObjectItem]) -> bool {
168 use crate::zigir::types::IrObjectItem;
169 let mut changed = false;
170 for item in items {
171 let expr = match item {
172 IrObjectItem::Field(f) => &mut f.value,
173 IrObjectItem::Spread(e) => e,
174 };
175 if Self::try_fold(expr) {
176 changed = true;
177 }
178 }
179 changed
180 }
181
182 fn fold_stmt(stmt: &mut IrStmt) -> bool {
184 let changed = RefCell::new(false);
185 walk::for_each_stmt_child_mut(
186 stmt,
187 &mut |block| {
188 *changed.borrow_mut() |= Self::fold_block(block);
189 },
190 &mut |s| {
191 *changed.borrow_mut() |= Self::fold_stmt(s);
192 },
193 &mut |e| {
194 *changed.borrow_mut() |= Self::try_fold(e);
195 },
196 &mut |t| {
197 *changed.borrow_mut() |= Self::fold_target(t);
198 },
199 );
200 changed.into_inner()
201 }
202
203 fn fold_target(target: &mut IrAssignTarget) -> bool {
205 let mut changed = false;
206 walk::for_each_target_child_mut(target, &mut |e| {
207 changed |= Self::try_fold(e);
208 });
209 changed
210 }
211
212 fn fold_block(block: &mut IrBlock) -> bool {
213 let mut changed = false;
214 for stmt in &mut block.stmts {
215 if Self::fold_stmt(stmt) {
216 changed = true;
217 }
218 }
219 changed
220 }
221}
222
223impl IrPass for ConstantFoldPass {
224 fn name(&self) -> &'static str {
225 "constant-fold"
226 }
227
228 fn description(&self) -> &'static str {
229 "Folds constant arithmetic, string, and boolean expressions"
230 }
231
232 fn run(&mut self, module: &mut IrModule) -> PassResult {
233 let mut changed = false;
234
235 for decl in &mut module.declarations {
237 let ch = RefCell::new(false);
238 walk::for_each_decl_child_mut(
239 decl,
240 &mut |block| {
241 *ch.borrow_mut() |= Self::fold_block(block);
242 },
243 &mut |e| {
244 *ch.borrow_mut() |= Self::try_fold(e);
245 },
246 );
247 if ch.into_inner() {
248 changed = true;
249 }
250 }
251
252 for cs in &mut module.closure_structs {
254 if Self::fold_block(&mut cs.body) {
255 changed = true;
256 }
257 }
258
259 if changed {
260 PassResult::changed()
261 } else {
262 PassResult::unchanged()
263 }
264 }
265}
266
267impl Default for ConstantFoldPass {
268 fn default() -> Self {
269 Self::new()
270 }
271}
272
273fn fold_binary(op: BinOp, left: &IrExpr, right: &IrExpr) -> Option<IrExpr> {
278 match (left, right) {
279 (IrExpr::IntLiteral(a), IrExpr::IntLiteral(b)) => {
281 let result = match op {
282 BinOp::Add => a.checked_add(*b)?,
283 BinOp::Sub => a.checked_sub(*b)?,
284 BinOp::Mul => a.checked_mul(*b)?,
285 BinOp::Div => {
286 if *b == 0 {
287 return None;
288 }
289 a.checked_div(*b)?
290 }
291 BinOp::Mod => {
292 if *b == 0 {
293 return None;
294 }
295 *a % *b
296 }
297 BinOp::BitAnd => a & b,
298 BinOp::BitOr => a | b,
299 BinOp::BitXor => a ^ b,
300 BinOp::Shl => {
301 if *b < 0 || *b >= 64 {
302 return None;
303 }
304 a << *b
305 }
306 BinOp::Shr => {
307 if *b < 0 || *b >= 64 {
308 return None;
309 }
310 a >> *b
311 }
312 BinOp::Eq | BinOp::StrictEq => return Some(IrExpr::BoolLiteral(a == b)),
313 BinOp::Ne | BinOp::StrictNe => return Some(IrExpr::BoolLiteral(a != b)),
314 BinOp::Lt => return Some(IrExpr::BoolLiteral(a < b)),
315 BinOp::Le => return Some(IrExpr::BoolLiteral(a <= b)),
316 BinOp::Gt => return Some(IrExpr::BoolLiteral(a > b)),
317 BinOp::Ge => return Some(IrExpr::BoolLiteral(a >= b)),
318 _ => return None,
319 };
320 Some(IrExpr::IntLiteral(result))
321 }
322 (IrExpr::FloatLiteral(a), IrExpr::FloatLiteral(b)) => {
324 let result = match op {
325 BinOp::Add => a + b,
326 BinOp::Sub => a - b,
327 BinOp::Mul => a * b,
328 BinOp::Div => {
329 if *b == 0.0 {
330 return None;
331 }
332 a / b
333 }
334 BinOp::Mod => a % b,
335 BinOp::Eq | BinOp::StrictEq => return Some(IrExpr::BoolLiteral(a == b)),
336 BinOp::Ne | BinOp::StrictNe => return Some(IrExpr::BoolLiteral(a != b)),
337 BinOp::Lt => return Some(IrExpr::BoolLiteral(a < b)),
338 BinOp::Le => return Some(IrExpr::BoolLiteral(a <= b)),
339 BinOp::Gt => return Some(IrExpr::BoolLiteral(a > b)),
340 BinOp::Ge => return Some(IrExpr::BoolLiteral(a >= b)),
341 _ => return None,
342 };
343 Some(IrExpr::FloatLiteral(result))
344 }
345 (IrExpr::IntLiteral(a), IrExpr::FloatLiteral(b)) => {
347 let a_f = *a as f64;
348 let result = match op {
349 BinOp::Add => a_f + b,
350 BinOp::Sub => a_f - b,
351 BinOp::Mul => a_f * b,
352 BinOp::Div => a_f / b,
353 _ => return None,
354 };
355 Some(IrExpr::FloatLiteral(result))
356 }
357 (IrExpr::FloatLiteral(a), IrExpr::IntLiteral(b)) => {
358 let b_f = *b as f64;
359 let result = match op {
360 BinOp::Add => a + b_f,
361 BinOp::Sub => a - b_f,
362 BinOp::Mul => a * b_f,
363 BinOp::Div => a / b_f,
364 _ => return None,
365 };
366 Some(IrExpr::FloatLiteral(result))
367 }
368 (IrExpr::StringLiteral(a), IrExpr::StringLiteral(b)) => {
370 if op == BinOp::Add {
371 Some(IrExpr::StringLiteral(format!("{}{}", a, b)))
372 } else {
373 None
374 }
375 }
376 (IrExpr::BoolLiteral(a), IrExpr::BoolLiteral(b)) => {
378 let result = match op {
379 BinOp::Eq | BinOp::StrictEq => a == b,
380 BinOp::Ne | BinOp::StrictNe => a != b,
381 _ => return None,
382 };
383 Some(IrExpr::BoolLiteral(result))
384 }
385 (IrExpr::Null, IrExpr::Null) => {
387 if op == BinOp::Eq || op == BinOp::StrictEq {
388 Some(IrExpr::BoolLiteral(true))
389 } else if op == BinOp::Ne || op == BinOp::StrictNe {
390 Some(IrExpr::BoolLiteral(false))
391 } else {
392 None
393 }
394 }
395 _ => None,
396 }
397}
398
399fn fold_unary(op: UnaOp, operand: &IrExpr) -> Option<IrExpr> {
400 match (op, operand) {
401 (UnaOp::Neg, IrExpr::IntLiteral(n)) => Some(IrExpr::IntLiteral(-n)),
402 (UnaOp::Neg, IrExpr::FloatLiteral(n)) => Some(IrExpr::FloatLiteral(-n)),
403 (UnaOp::Not, IrExpr::BoolLiteral(b)) => Some(IrExpr::BoolLiteral(!b)),
404 (UnaOp::BitNot, IrExpr::IntLiteral(n)) => Some(IrExpr::IntLiteral(!n)),
405 (
407 UnaOp::Not,
408 IrExpr::Unary {
409 op: UnaOp::Not,
410 operand: inner,
411 },
412 ) => {
413 if matches!(inner.as_ref(), IrExpr::BoolLiteral(_)) {
414 Some((**inner).clone())
416 } else {
417 None
418 }
419 }
420 _ => None,
421 }
422}
423
424fn fold_logical(op: LogicalOp, left: &IrExpr, right: &IrExpr) -> Option<IrExpr> {
425 match (op, left, right) {
426 (LogicalOp::And, IrExpr::BoolLiteral(false), _) => Some(IrExpr::BoolLiteral(false)),
428 (LogicalOp::And, IrExpr::BoolLiteral(true), _) => {
429 Some(right.clone())
431 }
432 (LogicalOp::Or, IrExpr::BoolLiteral(true), _) => Some(IrExpr::BoolLiteral(true)),
433 (LogicalOp::Or, IrExpr::BoolLiteral(false), _) => {
434 Some(right.clone())
436 }
437 (LogicalOp::Nullish, IrExpr::Null, right) => Some(right.clone()),
438 (LogicalOp::Nullish, IrExpr::Undefined, right) => Some(right.clone()),
439 _ => None,
440 }
441}
442
443fn typeof_literal(expr: &IrExpr) -> Option<String> {
445 match expr {
446 IrExpr::IntLiteral(_) | IrExpr::FloatLiteral(_) => Some("number".to_string()),
447 IrExpr::StringLiteral(_) => Some("string".to_string()),
448 IrExpr::BoolLiteral(_) => Some("boolean".to_string()),
449 IrExpr::Null => Some("object".to_string()), IrExpr::Undefined => Some("undefined".to_string()),
451 IrExpr::ArrowFn(_) | IrExpr::Closure(_) | IrExpr::FnExpr(_) => Some("function".to_string()),
452 _ => None,
453 }
454}
455
456#[cfg(test)]
461mod tests {
462 use super::*;
463 use crate::types::ZigType;
464 use crate::zigir::ident::IrIdent;
465 use crate::zigir::types::{IrBlock, IrDecl, IrFnDecl, IrStmt};
466
467 fn first_return_value(module: &IrModule) -> &IrExpr {
468 let IrDecl::Fn(f) = &module.declarations[0] else {
469 panic!("expected FnDecl at declarations[0]");
470 };
471 let IrStmt::Return { value: Some(expr) } = &f.body.stmts[0] else {
472 panic!("expected Return with value at stmts[0]");
473 };
474 expr
475 }
476
477 #[test]
478 fn test_fold_int_add() {
479 let mut module = make_module_with_body(vec![IrStmt::Return {
480 value: Some(IrExpr::Binary {
481 op: BinOp::Add,
482 left: Box::new(IrExpr::IntLiteral(1)),
483 right: Box::new(IrExpr::IntLiteral(2)),
484 left_type: None,
485 right_type: None,
486 }),
487 }]);
488 let mut pass = ConstantFoldPass::new();
489 let result = pass.run(&mut module);
490 assert!(result.changed);
491 match first_return_value(&module) {
492 IrExpr::IntLiteral(n) => assert_eq!(*n, 3),
493 other => panic!("expected IntLiteral(3), got {:?}", other),
494 }
495 }
496
497 #[test]
498 fn test_fold_float_mul() {
499 let mut module = make_module_with_body(vec![IrStmt::Return {
500 value: Some(IrExpr::Binary {
501 op: BinOp::Mul,
502 left: Box::new(IrExpr::FloatLiteral(1.5)),
503 right: Box::new(IrExpr::FloatLiteral(2.0)),
504 left_type: None,
505 right_type: None,
506 }),
507 }]);
508 let mut pass = ConstantFoldPass::new();
509 let result = pass.run(&mut module);
510 assert!(result.changed);
511 match first_return_value(&module) {
512 IrExpr::FloatLiteral(n) => assert_eq!(*n, 3.0),
513 other => panic!("expected FloatLiteral(3.0), got {:?}", other),
514 }
515 }
516
517 #[test]
518 fn test_fold_string_concat() {
519 let mut module = make_module_with_body(vec![IrStmt::Return {
520 value: Some(IrExpr::Binary {
521 op: BinOp::Add,
522 left: Box::new(IrExpr::StringLiteral("Hello, ".to_string())),
523 right: Box::new(IrExpr::StringLiteral("world!".to_string())),
524 left_type: None,
525 right_type: None,
526 }),
527 }]);
528 let mut pass = ConstantFoldPass::new();
529 let result = pass.run(&mut module);
530 assert!(result.changed);
531 match first_return_value(&module) {
532 IrExpr::StringLiteral(s) => assert_eq!(s, "Hello, world!"),
533 other => panic!("expected StringLiteral, got {:?}", other),
534 }
535 }
536
537 #[test]
538 fn test_fold_unary_negate() {
539 let mut module = make_module_with_body(vec![IrStmt::Return {
540 value: Some(IrExpr::Unary {
541 op: UnaOp::Neg,
542 operand: Box::new(IrExpr::IntLiteral(42)),
543 }),
544 }]);
545 let mut pass = ConstantFoldPass::new();
546 let result = pass.run(&mut module);
547 assert!(result.changed);
548 match first_return_value(&module) {
549 IrExpr::IntLiteral(n) => assert_eq!(*n, -42),
550 other => panic!("expected IntLiteral(-42), got {:?}", other),
551 }
552 }
553
554 #[test]
555 fn test_fold_not_bool() {
556 let mut module = make_module_with_body(vec![IrStmt::Return {
557 value: Some(IrExpr::Unary {
558 op: UnaOp::Not,
559 operand: Box::new(IrExpr::BoolLiteral(true)),
560 }),
561 }]);
562 let mut pass = ConstantFoldPass::new();
563 let result = pass.run(&mut module);
564 assert!(result.changed);
565 match first_return_value(&module) {
566 IrExpr::BoolLiteral(b) => assert!(!b),
567 other => panic!("expected BoolLiteral(false), got {:?}", other),
568 }
569 }
570
571 #[test]
572 fn test_fold_conditional_true() {
573 let mut module = make_module_with_body(vec![IrStmt::Return {
574 value: Some(IrExpr::Conditional {
575 cond: Box::new(IrExpr::BoolLiteral(true)),
576 then: Box::new(IrExpr::IntLiteral(1)),
577 else_: Box::new(IrExpr::IntLiteral(2)),
578 }),
579 }]);
580 let mut pass = ConstantFoldPass::new();
581 let result = pass.run(&mut module);
582 assert!(result.changed);
583 match first_return_value(&module) {
584 IrExpr::IntLiteral(n) => assert_eq!(*n, 1),
585 other => panic!("expected IntLiteral(1), got {:?}", other),
586 }
587 }
588
589 #[test]
590 fn test_fold_and_false() {
591 let mut module = make_module_with_body(vec![IrStmt::Return {
592 value: Some(IrExpr::Logical {
593 op: LogicalOp::And,
594 left: Box::new(IrExpr::BoolLiteral(false)),
595 right: Box::new(IrExpr::Ident(IrIdent::new("x"))),
596 left_type: Some(crate::types::ZigType::Bool),
597 right_type: None,
598 }),
599 }]);
600 let mut pass = ConstantFoldPass::new();
601 let result = pass.run(&mut module);
602 assert!(result.changed);
603 match first_return_value(&module) {
604 IrExpr::BoolLiteral(b) => assert!(!b),
605 other => panic!("expected BoolLiteral(false), got {:?}", other),
606 }
607 }
608
609 #[test]
610 fn test_fold_typeof_int() {
611 let mut module = make_module_with_body(vec![IrStmt::Return {
612 value: Some(IrExpr::Typeof(Box::new(IrExpr::IntLiteral(42)))),
613 }]);
614 let mut pass = ConstantFoldPass::new();
615 let result = pass.run(&mut module);
616 assert!(result.changed);
617 match first_return_value(&module) {
618 IrExpr::StringLiteral(s) => assert_eq!(s, "number"),
619 other => panic!("expected StringLiteral(\"number\"), got {:?}", other),
620 }
621 }
622
623 #[test]
624 fn test_no_fold_dynamic() {
625 let mut module = make_module_with_body(vec![IrStmt::Return {
626 value: Some(IrExpr::Binary {
627 op: BinOp::Add,
628 left: Box::new(IrExpr::Ident(IrIdent::new("x"))),
629 right: Box::new(IrExpr::IntLiteral(1)),
630 left_type: None,
631 right_type: None,
632 }),
633 }]);
634 let mut pass = ConstantFoldPass::new();
635 let result = pass.run(&mut module);
636 assert!(!result.changed); }
638
639 #[test]
640 fn test_fold_nested() {
641 let mut module = make_module_with_body(vec![IrStmt::Return {
643 value: Some(IrExpr::Binary {
644 op: BinOp::Add,
645 left: Box::new(IrExpr::Binary {
646 op: BinOp::Add,
647 left: Box::new(IrExpr::IntLiteral(1)),
648 right: Box::new(IrExpr::IntLiteral(2)),
649 left_type: None,
650 right_type: None,
651 }),
652 right: Box::new(IrExpr::Binary {
653 op: BinOp::Add,
654 left: Box::new(IrExpr::IntLiteral(3)),
655 right: Box::new(IrExpr::IntLiteral(4)),
656 left_type: None,
657 right_type: None,
658 }),
659 left_type: None,
660 right_type: None,
661 }),
662 }]);
663 let mut pass = ConstantFoldPass::new();
664 let result = pass.run(&mut module);
665 assert!(result.changed);
666 match first_return_value(&module) {
667 IrExpr::IntLiteral(n) => assert_eq!(*n, 10),
668 other => panic!("expected IntLiteral(10), got {:?}", other),
669 }
670 }
671
672 #[test]
673 fn test_fold_allocprint_no_args() {
674 let mut module = make_module_with_body(vec![IrStmt::Return {
675 value: Some(IrExpr::AllocPrint {
676 fmt: "hello".to_string(),
677 args: vec![],
678 }),
679 }]);
680 let mut pass = ConstantFoldPass::new();
681 let result = pass.run(&mut module);
682 assert!(result.changed);
683 match first_return_value(&module) {
684 IrExpr::StringLiteral(s) => assert_eq!(s, "hello"),
685 other => panic!("expected StringLiteral(\"hello\"), got {:?}", other),
686 }
687 }
688
689 #[test]
690 fn test_fold_null_equality() {
691 let mut module = make_module_with_body(vec![IrStmt::Return {
692 value: Some(IrExpr::Binary {
693 op: BinOp::Eq,
694 left: Box::new(IrExpr::Null),
695 right: Box::new(IrExpr::Null),
696 left_type: None,
697 right_type: None,
698 }),
699 }]);
700 let mut pass = ConstantFoldPass::new();
701 let result = pass.run(&mut module);
702 assert!(result.changed);
703 match first_return_value(&module) {
704 IrExpr::BoolLiteral(b) => assert!(b),
705 other => panic!("expected BoolLiteral(true), got {:?}", other),
706 }
707 }
708
709 fn make_module_with_body(body: Vec<IrStmt>) -> IrModule {
711 let mut module = IrModule::new("test".to_string());
712 module.declarations.push(IrDecl::Fn(IrFnDecl {
713 name: IrIdent::new("test_fn"),
714 params: vec![],
715 return_type: ZigType::I64,
716 body: IrBlock::new(body),
717 is_export: false,
718 is_async: false,
719 can_throw: false,
720 is_cabi: false,
721 typeof_return_body: None,
722 }));
723 module
724 }
725}