MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
clos2sjlj.cpp
Go to the documentation of this file.
2
4
6
7namespace {
8
9// Exception-handling closures (sjlj branches, throw/landing-pad continuations) are always constructed by this
10// phase itself with an explicit leading `mem.M`, so their env slot is always 1 -- see the callers of split/rebuild.
11constexpr size_t Sjlj_Env_Param = 1_u64;
12
13std::array<const Def*, 3> split(const Def* def) {
14 auto new_ops = DefVec(def->num_projs() - 2, nullptr);
15 auto& w = def->world();
16 const Def* mem = nullptr;
17 const Def* env = nullptr;
18 auto j = 0;
19 for (size_t i = 0; i < def->num_projs(); i++) {
20 auto op = def->proj(i);
21 if (op == w.call<mem::M>(0) || op->type() == w.call<mem::M>(0))
22 mem = op;
23 else if (i == Sjlj_Env_Param)
24 env = op;
25 else
26 new_ops[j++] = op;
27 }
28 assert(mem && env);
29 // Unwrap a single remaining component: we want the bare value here, not a 1-element tuple/sigma wrapper.
30 auto remaining = new_ops.size() == 1 ? new_ops[0] : def->is_intro() ? w.tuple(new_ops) : w.sigma(new_ops);
31 return {mem, env, remaining};
32}
33
34const Def* rebuild(const Def* mem, const Def* env, Defs remaining) {
35 auto& w = mem->world();
36 auto new_ops = DefVec(remaining.size() + 2, [&](auto i) -> const Def* {
37 static_assert(Sjlj_Env_Param == 1);
38 if (i == 0) return mem;
39 if (i == 1) return env;
40 return remaining[i - 2];
41 });
42 return w.tuple(new_ops);
43}
44
45} // namespace
46
47void Clos2SJLJ::get_exn_closures(const Def* def, DefSet& visited) {
48 if (!def->is_term() || def->isa_mut<Lam>() || visited.contains(def)) return;
49 visited.emplace(def);
50 if (auto c = isa_clos_lit(def)) {
51 auto lam = c.fnc_as_lam();
52 if (c.is_basicblock() && !ignore_.contains(lam)) {
53 log().d("exception closure: {}", c.fnc_as_lam());
54 lam2tag_[c.fnc_as_lam()] = {lam2tag_.size() + 1, c.env()};
55 }
56 get_exn_closures(c.env(), visited);
57 } else {
58 for (auto op : def->ops())
59 get_exn_closures(op, visited);
60 }
61}
62
63void Clos2SJLJ::get_exn_closures(Lam* lam) {
64 lam2tag_.clear();
65 if (!lam->is_set() || !Lam::isa_cn(lam)) return;
66 auto app = lam->body()->isa<App>();
67 if (!app) return;
68 if (auto p = app->callee()->isa<Extract>(); p && isa_clos_type(p->tuple()->type())) {
69 auto p2 = p->tuple()->isa<Extract>();
70 if (p2 && p2->tuple()->isa<Tuple>()) {
71 // branch: Check the closure environments, but be careful not to traverse
72 // the closures themselves
73 auto branches = p2->tuple()->ops();
74 for (auto b : branches) {
75 auto c = isa_clos_lit(b);
76 if (c) {
77 ignore_.emplace(c.fnc_as_lam());
78 log().d("ignore: {}", c.fnc_as_lam());
79 }
80 }
81 }
82 }
83 auto visited = DefSet();
84 get_exn_closures(app->arg(), visited);
85}
86
87Lam* Clos2SJLJ::get_throw(const Def* dom) {
88 auto& w = new_world();
89 auto [p, inserted] = dom2throw_.emplace(dom, nullptr);
90 auto& tlam = p->second;
91 if (inserted || !tlam) {
92 tlam = w.mut_con(clos_sub_env(Sjlj_Env_Param, dom, w.sigma({jb_type(), rb_type(), tag_type()})))->set("throw");
93 auto [m0, env, var] = split(tlam->var());
94 auto [jbuf, rbuf, tag] = env->projs<3>();
95 auto [m1, r] = mem::op_alloc(var->type(), m0)->projs<2>();
96 auto m2 = w.call<mem::store>(Defs{m1, r, var});
97 rbuf = w.call<core::bitcast>(w.call<mem::Ptr0>(w.call<mem::Ptr0>(var->type())), rbuf);
98 auto m3 = w.call<mem::store>(Defs{m2, rbuf, r});
99 tlam->set(false, w.call<longjmp>(Defs{m3, jbuf, tag}));
100 ignore_.emplace(tlam);
101 }
102 return tlam;
103}
104
105Lam* Clos2SJLJ::get_lpad(Lam* lam, const Def* rb) {
106 auto& w = new_world();
107 auto [p, inserted] = lam2lpad_.emplace(w.tuple({lam, rb}), nullptr);
108 auto& lpad = p->second;
109 if (inserted || !lpad) {
110 auto [_, env_type, dom] = split(lam->dom());
111 lpad = mem::mut_con(env_type)->set("lpad");
112 auto [m, env, __] = split(lpad->var());
113 auto [m1, arg_ptr] = w.call<mem::load>(Defs{m, rb})->projs<2>();
114 arg_ptr = w.call<core::bitcast>(w.call<mem::Ptr0>(dom), arg_ptr);
115 auto [m2, args] = w.call<mem::load>(Defs{m1, arg_ptr})->projs<2>();
116 auto full_args = (lam->num_doms() == 3) ? rebuild(m2, env, {args}) : rebuild(m2, env, args->ops());
117 lpad->app(false, lam, full_args);
118 ignore_.emplace(lpad);
119 }
120 return lpad;
121}
122
123void Clos2SJLJ::convert(Lam* lam) {
124 auto& w = new_world();
125 get_exn_closures(lam);
126 if (lam2tag_.empty()) return;
127
128 {
129 auto m0 = mem::mem_var(lam);
130 auto [m1, jb] = w.call<clos::alloc_jmpbuf>(m0)->projs<2>();
131 auto [m2, rb] = mem::op_alloc(void_ptr(), m1)->projs<2>();
132 auto new_args = lam->vars();
133 new_args[0] = m2;
134 auto new_defs = lam->reduce(w.tuple(new_args));
135 lam->unset()->set(new_defs);
136
137 cur_jbuf_ = jb;
138 cur_rbuf_ = rb;
139
140 // apparently the reduce can change the id of the closures, so we have to do it again :(
141 get_exn_closures(lam);
142 }
143
144 auto body = lam->body()->as<App>();
145
146 auto branch_type = clos_type(w.cn(w.call<mem::M>(0)));
147 auto branches = DefVec(lam2tag_.size() + 1);
148 {
149 auto env = w.tuple(body->args().view().subspan(1));
150 auto new_callee = mem::mut_con(env->type())->set("sjlj_wrap");
151 auto [m, env_var, _] = split(new_callee->var());
152 auto new_args = DefVec(env->num_projs() + 1, [&](size_t i) { return (i == 0) ? m : env_var->proj(i - 1); });
153 new_callee->app(false, body->callee(), new_args);
154 branches[0] = clos_pack(env, new_callee, branch_type);
155 }
156
157 for (auto [exn_lam, p] : lam2tag_) {
158 auto [i, env] = p;
159 branches[i] = clos_pack(env, get_lpad(exn_lam, cur_rbuf_), branch_type);
160 }
161
162 auto m0 = body->arg(0);
163 assert(m0->type() == w.call<mem::M>(0));
164 auto [m1, tag] = w.call<setjmp>(Defs{m0, cur_jbuf_})->projs<2>();
165 tag = w.call(core::conv::s, branches.size(), tag);
166 auto filter = lam->filter();
167 auto branch = w.extract(w.tuple(branches), tag);
168 lam->unset()->set({filter, clos_apply(branch, m1)});
169
170 // Finally, replace the exception closures (which now live in the branch envs) with throw closures.
171 push(); // cur_jbuf_/cur_rbuf_ are per-Lam, so the substitution must not outlive this convert()
172 auto new_body = subst_exn_closures(lam->body());
173 pop();
174 lam->unset()->set({filter, new_body});
175}
176
177// convert() substitutes within the *already rewritten* body, so a new-world Def means "substitute in place".
178const Def* Clos2SJLJ::rewrite(const Def* def) {
179 return &def->world() == &new_world() ? subst_exn_closures(def) : RWPhase::rewrite(def);
180}
181
182const Def* Clos2SJLJ::subst_exn_closures(const Def* def) {
183 if (auto new_def = lookup(def)) return new_def;
184 if (auto c = isa_clos_lit(def); c && lam2tag_.contains(c.fnc_as_lam())) {
185 auto& w = new_world();
186 auto [i, _] = lam2tag_[c.fnc_as_lam()];
187 auto tlam = get_throw(c.fnc_as_lam()->dom());
188 return map(def, clos_pack(w.tuple({cur_jbuf_, cur_rbuf_, w.lit_idx(i)}), tlam, c.type()));
189 }
190 if (def->isa_mut() || !def->is_term()) return def;
191 if (def->isa<Var>()) return def; // atomic; binder is in binder_ and not descended into here
192 return rewrite_imm(def)->set(def->dbg_key());
193}
194
196 auto new_def = RWPhase::rewrite_mut_Lam(old);
197 if (auto lam = new_def->isa_mut<Lam>(); lam && !is_bootstrapping()) convert(lam);
198 return new_def;
199}
200
201} // namespace mim::plug::clos::phase
Base class for all Defs.
Definition def.h:273
Def * set(size_t i, const Def *)
Successively set from left to right.
Definition def.cpp:196
World & world() const noexcept
Definition def.h:1097
T * isa_mut() const
If this is mutable, it will cast constness away and perform a dynamic_cast to T.
Definition def.h:580
bool is_term() const
Is this Def a term, i.e. is its type() a Type?
Definition def.cpp:486
DbgKey dbg_key() const
Cheap handle for other->set(this->dbg_key()).
Definition def.h:610
auto projs(F f) const
Splits this Def via Def::projections into an Array (if A == std::dynamic_extent) or std::array (other...
Definition def.h:440
A function.
Definition lam.h:113
static const Lam * isa_cn(const Def *d)
Definition lam.h:144
Lam * set(Filter filter, const Def *body)
Definition lam.cpp:27
const fe::Log & log() const
Definition phase.h:79
const fe::Vector< std::string > & args()
Command-line arguments passed to this Phase's plugin via -X <plugin>:<arg>.
Definition phase.cpp:23
bool is_bootstrapping() const
Returns whether we are currently bootstrapping (rewriting annexes).
Definition phase.h:403
World & new_world()
Create new Defs into this.
Definition phase.h:452
virtual void push()
Definition rewrite.h:40
virtual const Def * map(const Def *old_def, const Def *new_def)
Definition rewrite.h:47
virtual void pop()
Definition rewrite.h:41
virtual const Def * rewrite_imm(const Def *)
Definition rewrite.cpp:67
virtual const Def * rewrite(const Def *)
Definition rewrite.cpp:55
virtual const Def * lookup(const Def *old_def)
Lookup old_def by searching in reverse through the stack of maps.
Definition rewrite.h:62
A variable introduced by a binder (mutable).
Definition def.h:825
const Def * rewrite(const Def *) final
const Def * rewrite_mut_Lam(Lam *) final
ClosLit isa_clos_lit(const Def *def, bool fn_isa_lam=true)
Tries to match a closure literal.
Definition clos.cpp:52
const Def * clos_sub_env(size_t ep, const Def *tup_or_sig, const Def *new_env)
Definition clos.h:136
Sigma * clos_type(const Pi *pi)
Creates a typed closure type from pi.
Definition clos.cpp:101
const Def * clos_pack(const Def *env, const Def *fn, const Def *ct=nullptr)
Pack a typed closure.
Definition clos.cpp:61
const Def * clos_apply(const Def *closure, const Def *args)
Apply a closure to arguments.
Definition clos.cpp:78
const Sigma * isa_clos_type(const Def *def)
Definition clos.cpp:90
const Def * mem_var(Lam *lam)
Returns the memory argument of a function if it has one.
Definition mem.h:55
Lam * mut_con(World &w, nat_t a=0)
Yields con[mem.M 0].
Definition mem.h:16
const Def * op_alloc(const Def *type, const Def *as, const Def *mem)
Definition mem.h:129
fe::View< const Def * > Defs
Definition def.h:91
fe::Vector< const Def * > DefVec
Definition def.h:93
GIDSet< const Def * > DefSet
Definition def.h:89
@ Lam
Definition def.h:122
@ Extract
Definition def.h:122
@ App
Definition def.h:122