MimIR 0.1
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
clos_conv.cpp
Go to the documentation of this file.
2
3#include "mim/check.h"
4
6
7using namespace std::literals;
8
9namespace mim::plug::clos {
10
11namespace {
12
13bool is_memop_res(const Def* fd) {
14 auto proj = fd->isa<Extract>();
15 if (!proj) return false;
16 auto types = proj->tuple()->type()->ops();
17 return std::any_of(types.begin(), types.end(), [](auto d) { return match<mem::M>(d); });
18}
19
20} // namespace
21
22DefSet free_defs(const Nest& nest) {
23 DefSet bound;
24 DefSet free;
25 std::queue<const Def*> queue;
26 queue.emplace(nest.root()->mut());
27
28 while (!queue.empty()) {
29 auto def = pop(queue);
30 for (auto op : def->deps()) {
31 if (op->is_closed()) {
32 // do nothing
33 } else if (nest.contains(op)) {
34 if (auto [_, ins] = bound.emplace(op); ins) queue.emplace(op);
35 } else {
36 free.emplace(op);
37 }
38 }
39 }
40
41 return free;
42}
43
44/*
45 * Free variable analysis
46 */
47
48void FreeDefAna::split_fd(Node* node, const Def* fd, bool& init_node, NodeQueue& worklist) {
49 assert(!match<mem::M>(fd) && "mem tokens must not be free");
50 if (fd->is_closed()) return;
51 if (auto [var, lam] = ca_isa_var<Lam>(fd); var && lam) {
52 if (var != lam->ret_var()) node->add_fvs(fd);
53 } else if (auto q = match(attr::freeBB, fd)) {
54 node->add_fvs(q);
55 } else if (auto pred = fd->isa_mut()) {
56 if (pred != node->mut) {
57 auto [pnode, inserted] = build_node(pred, worklist);
58 node->preds.push_back(pnode);
59 pnode->succs.push_back(node);
60 init_node |= inserted;
61 }
62 } else if (fd->has_dep(Dep::Var) && !fd->isa<Tuple>()) {
63 // Note: Var's can still have Def::Top, if their type is a mut!
64 // So the first case is *not* redundant
65 node->add_fvs(fd);
66 } else if (is_memop_res(fd)) {
67 // Results of memops must not be floated down
68 node->add_fvs(fd);
69 } else {
70 for (auto op : fd->ops()) split_fd(node, op, init_node, worklist);
71 }
72}
73
74std::pair<FreeDefAna::Node*, bool> FreeDefAna::build_node(Def* mut, NodeQueue& worklist) {
75 auto& w = world();
76 auto [p, inserted] = lam2nodes_.emplace(mut, nullptr);
77 if (!inserted) return {p->second.get(), false};
78 w.DLOG("FVA: create node: {}", mut);
79 p->second = std::make_unique<Node>(Node{mut, {}, {}, {}, 0});
80 auto node = p->second.get();
81 auto nest = Nest(mut);
82 bool init_node = false;
83 for (auto v : free_defs(nest)) split_fd(node, v, init_node, worklist);
84 if (!init_node) {
85 worklist.push(node);
86 w.DLOG("FVA: init {}", mut);
87 }
88 return {node, true};
89}
90
91void FreeDefAna::run(NodeQueue& worklist) {
92 while (!worklist.empty()) {
93 auto node = worklist.front();
94 worklist.pop();
95 if (is_done(node)) continue;
96 auto changed = is_bot(node);
97 mark(node);
98 for (auto p : node->preds) {
99 auto& pfvs = p->fvs;
100 for (auto&& pfv : pfvs) changed |= node->add_fvs(pfv).second;
101 }
102 if (changed)
103 for (auto s : node->succs) worklist.push(s);
104 }
105}
106
108 auto worklist = NodeQueue();
109 auto [node, _] = build_node(lam, worklist);
110 if (!is_done(node)) {
111 cur_pass_id++;
112 run(worklist);
113 }
114
115 return node->fvs;
116}
117
118/*
119 * Closure Conversion
120 */
121
123 auto subst = Def2Def();
124 for (auto mut : world().copy_externals()) rewrite(mut, subst);
125 while (!worklist_.empty()) {
126 auto def = worklist_.front();
127 subst = Def2Def();
128 worklist_.pop();
129 if (auto i = closures_.find(def); i != closures_.end()) {
130 rewrite_body(i->second.fn, subst);
131 } else {
132 world().DLOG("RUN: rewrite def {}", def);
133 rewrite(def, subst);
134 }
135 }
136}
137
138void ClosConv::rewrite_body(Lam* new_lam, Def2Def& subst) {
139 auto& w = world();
140 auto it = closures_.find(new_lam);
141 assert(it != closures_.end() && "closure should have a stub if rewrite_body is called!");
142 auto [old_fn, num_fvs, env, new_fn] = it->second;
143
144 if (!old_fn->is_set()) return;
145
146 w.DLOG("rw body: {} [old={}, env={}]\nt", new_fn, old_fn, env);
147 auto env_param = new_fn->var(Clos_Env_Param)->set("closure_env");
148 if (num_fvs == 1) {
149 subst.emplace(env, env_param);
150 } else {
151 for (size_t i = 0; i < num_fvs; i++) {
152 auto fv = env->op(i);
153 auto sym = w.sym("fv_"s + (fv->sym() ? fv->sym().str() : std::to_string(i)));
154 subst.emplace(fv, env_param->proj(i)->set(sym));
155 }
156 }
157
158 auto params = w.tuple(DefVec(old_fn->num_doms(), [&](auto i) { return new_lam->var(skip_env(i)); }));
159 subst.emplace(old_fn->var(), params);
160
161 auto filter = rewrite(new_fn->filter(), subst);
162 auto body = rewrite(new_fn->body(), subst);
163 new_fn->reset({filter, body});
164}
165
166const Def* ClosConv::rewrite(const Def* def, Def2Def& subst) {
167 switch (def->node()) {
168 case Node::Type:
169 case Node::Univ:
170 case Node::Nat:
171 case Node::Bot: // TODO This is used by the AD stuff????
172 case Node::Top: return def;
173 default: break;
174 }
175
176 auto& w = world();
177 auto map = [&](const Def* new_def) {
178 subst[def] = new_def;
179 assert(subst[def] == new_def);
180 return new_def;
181 };
182
183 if (auto i = subst.find(def); i != subst.end()) {
184 return i->second;
185 } else if (auto pi = Pi::isa_cn(def)) {
186 return map(type_clos(pi, subst));
187 } else if (auto lam = def->isa_mut<Lam>(); lam && Lam::isa_cn(lam)) {
188 auto [_, __, fv_env, new_lam] = make_stub(lam, subst);
189 auto clos_ty = rewrite(lam->type(), subst);
190 auto env = rewrite(fv_env, subst);
191 auto closure = clos_pack(env, new_lam, clos_ty);
192 world().DLOG("RW: pack {} ~> {} : {}", lam, closure, clos_ty);
193 return map(closure);
194 } else if (auto a = match<attr>(def)) {
195 switch (a.id()) {
196 case attr::returning:
197 if (auto ret_lam = a->arg()->isa_mut<Lam>()) {
198 // assert(ret_lam && ret_lam->is_basicblock());
199 // Note: This should be cont_lam's only occurance after η-expansion, so its okay to
200 // put into the local subst only
201 auto new_doms
202 = DefVec(ret_lam->num_doms(), [&](auto i) { return rewrite(ret_lam->dom(i), subst); });
203 auto new_lam = ret_lam->stub(w.cn(new_doms));
204 subst[ret_lam] = new_lam;
205 if (ret_lam->is_set()) {
206 new_lam->set_filter(rewrite(ret_lam->filter(), subst));
207 new_lam->set_body(rewrite(ret_lam->body(), subst));
208 }
209 return new_lam;
210 }
211 break;
212 case attr::fstclassBB:
213 case attr::freeBB: {
214 // Note: Same thing about η-conversion applies here
215 auto bb_lam = a->arg()->isa_mut<Lam>();
216 assert(bb_lam && Lam::isa_basicblock(bb_lam));
217 auto [_, __, ___, new_lam] = make_stub({}, bb_lam, subst);
218 subst[bb_lam] = clos_pack(w.tuple(), new_lam, rewrite(bb_lam->type(), subst));
219 rewrite_body(new_lam, subst);
220 return map(subst[bb_lam]);
221 }
222 default: break;
223 }
224 } else if (auto [var, lam] = ca_isa_var<Lam>(def); var && lam && lam->ret_var() == var) {
225 // HACK to rewrite a retvar that is defined in an enclosing lambda
226 // If we put external bb's into the env, this should never happen
227 auto new_lam = make_stub(lam, subst).fn;
228 auto new_idx = skip_env(Lit::as(var->index()));
229 return map(new_lam->var(new_idx));
230 }
231
232 auto new_type = rewrite(def->type(), subst);
233
234 if (auto mut = def->isa_mut()) {
235 if (auto global = def->isa_mut<Global>()) {
236 if (auto i = glob_muts_.find(global); i != glob_muts_.end()) return i->second;
237 auto subst = Def2Def();
238 return glob_muts_[mut] = rewrite_mut(global, new_type, subst);
239 }
240 assert(!isa_clos_type(mut));
241 w.DLOG("RW: mut {}", mut);
242 auto new_mut = rewrite_mut(mut, new_type, subst);
243 // Try to reduce the amount of muts that are created
244 if (!mut->isa_mut<Global>() && Checker::alpha<Checker::Check>(mut, new_mut)) return map(mut);
245 if (auto imm = new_mut->immutabilize()) return map(imm);
246 return map(new_mut);
247 } else {
248 auto new_ops = DefVec(def->num_ops(), [&](auto i) { return rewrite(def->op(i), subst); });
249 if (auto app = def->isa<App>(); app && new_ops[0]->type()->isa<Sigma>())
250 return map(clos_apply(new_ops[0], new_ops[1]));
251 else if (def->isa<Axiom>())
252 return def;
253 else
254 return map(def->rebuild(new_type, new_ops));
255 }
256
257 fe::unreachable();
258}
259
260Def* ClosConv::rewrite_mut(Def* mut, const Def* new_type, Def2Def& subst) {
261 auto new_mut = mut->stub(new_type);
262 subst.emplace(mut, new_mut);
263 for (size_t i = 0; i < mut->num_ops(); i++)
264 if (mut->op(i)) new_mut->set(i, rewrite(mut->op(i), subst));
265 return new_mut;
266}
267
268const Pi* ClosConv::rewrite_type_cn(const Pi* pi, Def2Def& subst) {
269 assert(Pi::isa_basicblock(pi));
270 auto new_ops = DefVec(pi->num_doms(), [&](auto i) { return rewrite(pi->dom(i), subst); });
271 return world().cn(new_ops);
272}
273
274const Def* ClosConv::type_clos(const Pi* pi, Def2Def& subst, const Def* env_type) {
275 if (auto i = glob_muts_.find(pi); i != glob_muts_.end() && !env_type) return i->second;
276 auto& w = world();
277 auto new_doms = DefVec(pi->num_doms(), [&](auto i) {
278 return (i == pi->num_doms() - 1 && Pi::isa_returning(pi)) ? rewrite_type_cn(pi->ret_pi(), subst)
279 : rewrite(pi->dom(i), subst);
280 });
281 auto ct = ctype(w, new_doms, env_type);
282 if (!env_type) {
283 glob_muts_.emplace(pi, ct);
284 w.DLOG("C-TYPE: pct {} ~~> {}", pi, ct);
285 } else {
286 w.DLOG("C-TYPE: ct {}, env = {} ~~> {}", pi, env_type, ct);
287 }
288 return ct;
289}
290
291ClosConv::Stub ClosConv::make_stub(const DefSet& fvs, Lam* old_lam, Def2Def& subst) {
292 auto& w = world();
293 auto env = w.tuple(DefVec(fvs.begin(), fvs.end()));
294 auto num_fvs = fvs.size();
295 auto env_type = rewrite(env->type(), subst);
296 auto new_fn_type = type_clos(old_lam->type(), subst, env_type)->as<Pi>();
297 auto new_lam = old_lam->stub(new_fn_type);
298 // TODO
299 // new_lam->set_debug_name((old_lam->is_external() || !old_lam->is_set()) ? "cc_" + old_lam->name() :
300 // old_lam->name());
301 if (!isa_workable(old_lam)) {
302 auto new_ext_type = w.cn(clos_remove_env(new_fn_type->dom()));
303 auto new_ext_lam = old_lam->stub(new_ext_type);
304 w.DLOG("wrap ext lam: {} -> stub: {}, ext: {}", old_lam, new_lam, new_ext_lam);
305 if (old_lam->is_set()) {
306 old_lam->transfer_external(new_ext_lam);
307 new_ext_lam->app(false, new_lam, clos_insert_env(env, new_ext_lam->var()));
308 new_lam->set(old_lam->filter(), old_lam->body());
309 } else {
310 new_ext_lam->unset();
311 new_lam->app(false, new_ext_lam, clos_remove_env(new_lam->var()));
312 }
313 } else {
314 new_lam->set(old_lam->filter(), old_lam->body());
315 }
316 w.DLOG("STUB {} ~~> ({}, {})", old_lam, env, new_lam);
317 auto closure = Stub{old_lam, num_fvs, env, new_lam};
318 closures_.emplace(old_lam, closure);
319 closures_.emplace(closure.fn, closure);
320 return closure;
321}
322
323ClosConv::Stub ClosConv::make_stub(Lam* old_lam, Def2Def& subst) {
324 if (auto i = closures_.find(old_lam); i != closures_.end()) return i->second;
325 auto fvs = fva_.run(old_lam);
326 auto closure = make_stub(fvs, old_lam, subst);
327 worklist_.emplace(closure.fn);
328 return closure;
329}
330
331} // namespace mim::plug::clos
static bool alpha(const Def *d1, const Def *d2)
Definition check.h:71
Base class for all Defs.
Definition def.h:198
Defs deps() const noexcept
Definition def.cpp:441
constexpr auto ops() const noexcept
Definition def.h:261
T * isa_mut() const
If this is *mut*able, it will cast constness away and perform a dynamic_cast to T.
Definition def.h:430
const Def * var(nat_t a, nat_t i) noexcept
Definition def.h:379
bool has_dep() const
Definition def.h:313
bool is_closed() const
Has no free_vars()?
Definition def.cpp:392
A function.
Definition lam.h:105
static const Lam * isa_cn(const Def *d)
Definition lam.h:136
Lam * set_filter(Filter)
Set filter first.
Definition lam.cpp:28
static const Lam * isa_basicblock(const Def *d)
Definition lam.h:137
Lam * set_body(const Def *body)
Set body second.
Definition lam.h:166
Lam * stub(const Def *type)
Definition lam.h:178
static T as(const Def *def)
Definition def.h:735
Def * mut() const
The mutable capsulated in this Node or nullptr, if it's a virtual root comprising several Nodes.
Definition nest.h:22
Builds a nesting tree of all immutables‍/binders.
Definition nest.h:11
const Node * root() const
Definition nest.h:129
bool contains(const Def *def) const
Definition nest.h:131
World & world()
Definition phase.h:27
static const Pi * isa_cn(const Def *d)
Is this a continuation - i.e. is the Pi::codom mim::Bottom?
Definition lam.h:44
static const Pi * isa_basicblock(const Def *d)
Is this a continuation (Pi::isa_cn) that is not Pi::isa_returning?
Definition lam.h:48
const Pi * cn()
Definition world.h:263
void start() override
Actual entry.
DefSet & run(Lam *lam)
FreeDefAna::run will compute free defs (FD) that appear in lams body.
The clos Plugin
Definition clos.h:7
std::tuple< const Extract *, N * > ca_isa_var(const Def *def)
Checks is def is the variable of a mut of type N.
Definition clos.h:79
DefSet free_defs(const Nest &nest)
Definition clos_conv.cpp:22
const Def * clos_remove_env(size_t i, std::function< const Def *(size_t)> f)
Definition clos.cpp:144
const Def * clos_insert_env(size_t i, const Def *env, std::function< const Def *(size_t)> f)
Definition clos.cpp:140
const Def * ctype(World &w, Defs doms, const Def *env_type=nullptr)
Definition clos.cpp:146
static constexpr size_t Clos_Env_Param
Describes where the environment is placed in the argument list.
Definition clos.h:107
size_t skip_env(size_t i)
Definition clos.h:113
const Def * clos_pack(const Def *env, const Def *fn, const Def *ct=nullptr)
Pack a typed closure. This assumes that fn expects the environment as its Clos_Env_Paramth argument.
Definition clos.cpp:79
const Def * clos_apply(const Def *closure, const Def *args)
Apply a closure to arguments.
Definition clos.cpp:101
const Sigma * isa_clos_type(const Def *def)
Definition clos.cpp:112
DefMap< const Def * > Def2Def
Definition def.h:48
auto pop(S &s) -> decltype(s.top(), typename S::value_type())
Definition util.h:80
Vector< const Def * > DefVec
Definition def.h:50
@ Var
Definition def.h:100
Lam * isa_workable(Lam *lam)
These are Lams that are neither nullptr, nor Lam::is_external, nor Lam::is_unset.
Definition lam.h:249
GIDSet< const Def * > DefSet
Definition def.h:47
auto match(const Def *def)
Definition axiom.h:112
Node
Definition def.h:83
@ Nat
Definition def.h:85
@ Pi
Definition def.h:85
@ Univ
Definition def.h:85
@ Bot
Definition def.h:85
@ Axiom
Definition def.h:85
@ Lam
Definition def.h:85
@ Global
Definition def.h:85
@ Sigma
Definition def.h:85
@ Extract
Definition def.h:85
@ Type
Definition def.h:85
@ Top
Definition def.h:85
@ App
Definition def.h:85
@ Tuple
Definition def.h:85