@@ -5,7 +5,7 @@ using StaticArrays, SparseArrays, LinearAlgebra, NaNMath, SpecialFunctions,
55
66export toexpr, Assignment, (← ), Let, Func, DestructuredArgs, LiteralExpr,
77 SetArray, MakeArray, MakeSparseArray, MakeTuple, AtIndex,
8- SpawnFetch, Multithreaded, cse
8+ SpawnFetch, Multithreaded, ForLoop, cse
99
1010import .. SymbolicUtils
1111import .. SymbolicUtils. Rewriters
@@ -705,6 +705,27 @@ function toexpr(exp::LiteralExpr, st)
705705 recurse_expr (exp. ex, st)
706706end
707707
708+ """
709+ ForLoop(itervar, range, body)
710+
711+ Generate a `for` loop of the form
712+ ```julia
713+ for itervar in range
714+ body
715+ end
716+ ```
717+ """
718+ struct ForLoop <: CodegenPrimitive
719+ itervar
720+ range
721+ body
722+ end
723+
724+ function toexpr (f:: ForLoop , st)
725+ :(for $ (toexpr (f. itervar, st)) in $ (toexpr (f. range, st))
726+ $ (toexpr (f. body, st))
727+ end )
728+ end
708729
709730# ## Code-related utilities
710731
@@ -935,4 +956,10 @@ function cse!(x::SpawnFetch{T}, state::CSEState) where {T}
935956 return SpawnFetch {T} (map (cse, x. exprs), cse! (x. args, state), x. combine)
936957end
937958
959+ function cse! (x:: ForLoop , state:: CSEState )
960+ # cse the range with current scope, CSE the body with a new scope
961+ new_state = new_scope (state)
962+ return ForLoop (x. itervar, cse! (x. range, state), apply_cse (cse! (x. body, new_state), new_state))
963+ end
964+
938965end
0 commit comments