MimIR
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
close.cpp
Go to the documentation of this file.
2
3#include <ranges>
4
5#include <mim/rewrite.h>
6#include <mim/world.h>
7
9
10namespace mim::plug::mach {
11
12namespace {
13
14/// The values that @p x consists of, down to projections that do not split any further.
15void flatten(const Def* x, DefVec& res) {
16 if (auto n = x->num_projs(); n > 1)
17 for (size_t i = 0; i != n; ++i)
18 flatten(x->proj(n, i), res);
19 else
20 res.emplace_back(x);
21}
22
23/// The part of @p arg that a jump passes for @p e, if @p e is @p var or a projection of it.
24const Def* part(const Def* var, const Def* arg, const Def* e) {
25 if (e == var) return arg;
26 if (auto ex = e->isa<Extract>())
27 if (auto a = part(var, arg, ex->tuple())) return e->world().extract(a, ex->index());
28 return nullptr;
29}
30
31/// Rewrites a block and the blocks nested in it, in place or into its closed version.
32class Closer : public Rewriter {
33public:
34 Closer(const Liveness& live, Lam* fun, const LamMap<DefVec>& sigs, const LamMap<Lam*>& lams)
35 : Rewriter(fun->world())
36 , target_(live.target())
37 , live_(live)
38 , fun_(fun)
39 , sigs_(sigs)
40 , lams_(lams) {}
41
42 void run(Lam* lam);
43
44private:
45 const Def* rewrite(const Def*) final;
46
47 void tree(Lam* old_lam, Lam* new_lam);
48 /// Maps a parameter that the closed version splits to the tuple of its parts.
49 const Def* join(const Def* x);
50 /// Turns the return continuation @p k into a jump to its closed version.
51 void forward(Lam* k);
52 /// The rewritten @p term; the blocks nested in its block go to @p nested.
53 const Def* jump(const App* term, fe::Vector<Lam*>& nested);
54 /// The arguments of @p term for the closed @p bb; a value that @p bb does not use is dead.
55 DefVec args(Lam* bb, const App* term);
56 Lam* closed(Lam* lam) const {
57 auto new_lam = fe::lookup(lams_, lam);
58 return new_lam ? new_lam : lam;
59 }
60
61 const Target& target_;
62 const Liveness& live_;
63 Lam* fun_;
64 const LamMap<DefVec>& sigs_;
65 const LamMap<Lam*>& lams_;
66 DefSet owned_;
67};
68
69void Closer::run(Lam* lam) {
70 auto new_lam = closed(lam);
71 if (new_lam != lam) {
72 const auto& sig = sigs_.find(lam)->second;
73 auto m = sig.size();
74 for (size_t i = 0; i != m; ++i)
75 map(sig[i], new_lam->var(m, i));
76 join(lam->var());
77 }
78 tree(lam, new_lam);
79}
80
81const Def* Closer::join(const Def* x) {
82 if (auto y = lookup(x)) return y;
83 auto n = x->num_projs();
84 return map(x, world().tuple(DefVec(n, [&](size_t i) { return join(x->proj(n, i)); })));
85}
86
87void Closer::tree(Lam* old_lam, Lam* new_lam) {
88 auto b = live_.block(old_lam);
89 owned_.insert(b->insns.begin(), b->insns.end());
90 auto nested = fe::Vector<Lam*>();
91 auto body = jump(old_lam->body()->as<App>(), nested);
92 if (new_lam != old_lam) {
93 new_lam->set(world().lit_ff(), body);
94 } else {
95 auto filter = rewrite(old_lam->filter());
96 old_lam->unset()->set(filter, body);
97 }
98 if (auto k = call_cont(live_, fun_, *b)) nested.emplace_back(k->lam);
99 for (auto bb : nested)
100 if (lams_.contains(bb))
101 forward(bb);
102 else
103 tree(bb, bb);
104}
105
106void Closer::forward(Lam* k) {
107 auto args = DefVec();
108 for (auto e : sigs_.find(k)->second)
109 args.emplace_back(part(k->var(), k->var(), e) ? e : rewrite(e));
110 k->unset()->set(world().lit_ff(), world().app(closed(k), world().tuple(args)));
111}
112
113const Def* Closer::rewrite(const Def* def) {
114 if (auto new_def = lookup(def)) return new_def;
115 if (def->isa_mut() || def->is_closed() || def->isa<Var>()) return def;
116 if (auto app = def->isa<App>(); app && target_.prev_mem(app) && !owned_.contains(app))
117 def->blame("{} backend: instruction `{}` is not available here", target_.name(), def).bail();
118 return Rewriter::rewrite(def);
119}
120
121const Def* Closer::jump(const App* term, fe::Vector<Lam*>& nested) {
122 if (auto bb = Lam::isa_mut_basicblock(term->callee()); bb && sigs_.contains(bb))
123 return world().app(closed(bb), world().tuple(args(bb, term)));
124 if (auto dispatch = Dispatch(term))
125 for (size_t i = 0, n = dispatch.num_targets(); i != n; ++i)
126 nested.emplace_back(dispatch.target(i)->as_mut<Lam>());
127 return rewrite(term);
128}
129
130DefVec Closer::args(Lam* bb, const App* term) {
131 auto res = DefVec();
132 const auto& used = live_.block(bb)->live_in;
133 for (auto e : sigs_.find(bb)->second)
134 if (auto a = part(bb->var(), term->arg(), e))
135 res.emplace_back(rewrite(a));
136 else if (used.contains(e))
137 res.emplace_back(rewrite(e));
138 else
139 res.emplace_back(world().lit(e->type(), 0));
140 return res;
141}
142
143} // namespace
144
145void Close::visit(Lam* fun) {
146 const auto& t = target();
147 auto& w = world();
148 auto live = Liveness(*this, fun, true);
149 const auto& blocks = live.blocks();
150
151 auto jumps = LamMap<size_t>();
152 for (const auto& b : blocks)
153 for (auto s : b.targets)
154 ++jumps[blocks[s].lam];
155
156 auto nested = LamSet();
157 for (const auto& b : blocks) {
158 if (auto k = call_cont(live, fun, b); k && !nested.emplace(k->lam).second)
159 k->lam->blame("{} backend: return continuation `{}` of several calls", t.name(), k->lam).bail();
160 if (auto dispatch = Dispatch(b.lam->body())) {
161 // mem.sink_args and mem.add_mem leave nothing but the memory.
162 if (dispatch.num_args() != 1 || !t.is_mem(dispatch.arg()))
163 b.lam->blame("{} backend: `{}` passes more than its memory to a branch", t.name(), b.lam).bail();
164 for (size_t i = 0, e = dispatch.num_targets(); i != e; ++i) {
165 auto bb = Lam::isa_mut_basicblock(dispatch.target(i));
166 if (!bb || !live.block(bb))
167 b.lam->blame("{} backend: `{}` branches to something other than blocks", t.name(), b.lam).bail();
168 if (jumps[bb] != 1 || !nested.emplace(bb).second)
169 bb->blame("{} backend: branch target `{}` has several predecessors", t.name(), bb).bail();
170 }
171 }
172 }
173
174 auto lifted = LamMap<const DefSet*>();
175 for (const auto& b : blocks | std::views::drop(1))
176 if (!nested.contains(b.lam)) lifted[b.lam] = &b.live_in;
177 // A value lives across a call only up to the return continuation, which forwards it to a closed block.
178 auto forwards = fe::Vector<Lam*>();
179 for (const auto& b : blocks)
180 if (auto k = call_cont(live, fun, b); k && !k->live_in.empty()) {
181 lifted[k->lam] = &k->live_in;
182 forwards.emplace_back(k->lam);
183 }
184
185 auto rank = [&](const Def* x) -> size_t {
186 if (t.is_mem(x)) return 0;
187 if (x->type()->isa<Pi>()) return Target::Num_Classes + 1;
188 return 1 + t.cls(x);
189 };
190
191 auto sigs = LamMap<DefVec>();
192 auto lams = LamMap<Lam*>();
193 for (const auto& b : blocks) {
194 auto vs = fe::lookup(lifted, b.lam);
195 if (!vs) continue;
196 auto lam = b.lam;
197 auto n = lam->num_vars();
198 auto params = DefVec(n, [&](size_t i) { return lam->var(n, i); });
199 auto parts = DefVec();
200 for (auto x : params)
201 flatten(x, parts);
202 auto extra = DefVec(vs->begin(), vs->end());
203 std::ranges::sort(extra, {}, &Def::gid);
204 for (auto v : extra)
205 if (auto c = t.cls(v); c != Target::Gpr && c != Target::Fpr)
206 lam->blame("{} backend: `{}` of class {} would become a parameter of `{}`", t.name(), v, size_t(c), lam)
207 .bail();
208
209 auto sig = parts;
210 sig.insert(sig.end(), extra.begin(), extra.end());
211 std::ranges::stable_sort(sig, {}, rank);
212 auto same = extra.empty() && std::ranges::equal(sig, params);
213 sigs[lam] = sig;
214 if (same) continue;
215
216 auto m = sig.size();
217 auto new_lam = w.mut_con(DefVec(m, [&](size_t i) { return sig[i]->type(); }))->set(lam->dbg());
218 for (size_t i = 0; i != m; ++i)
219 new_lam->var(m, i)->set(sig[i]->sym());
220 lams[lam] = new_lam;
221 }
222
223 // The block a forwarding return continuation is nested in rewrites it, so its closed version reads it first.
224 for (auto k : forwards | std::views::reverse)
225 Closer(live, fun, sigs, lams).run(k);
226 for (const auto& b : blocks)
227 if (!nested.contains(b.lam)) Closer(live, fun, sigs, lams).run(b.lam);
228}
229
230} // namespace mim::plug::mach
Base class for all Defs.
Definition def.h:285
constexpr u32 gid() const noexcept
Global id - unique number for this Def.
Definition def.h:308
Dispatch(const Def *)
Definition tuple.cpp:105
A function.
Definition lam.h:91
static Lam * isa_mut_basicblock(const Def *d)
Definition lam.h:130
World & world()
Definition phase.h:60
A dependent function type.
Definition lam.h:14
std::string_view name() const
The plugin name, used as the prefix of diagnostics.
Definition target.h:18
void visit(Lam *) final
Definition close.cpp:145
const Target & target() const
Definition phase.h:61
const Block * block(Lam *lam) const
Definition liveness.h:64
Liveness(const FunPhase &phase, Lam *fun, bool solve=false)
Bails unless the blocks of the function fun are closed; with solve, it iterates to the fixed point in...
Definition liveness.cpp:11
const Def * prev_mem(const App *app) const
The memory app continues, if app is an instruction on a mem.M 0 chain.
Definition target.h:210
The mach Plugin
Definition asm.h:15
const Liveness::Block * call_cont(const Liveness &live, Lam *fun, const Liveness::Block &block)
The block that a call at the end of block returns to, if any.
Definition liveness.h:178
GIDSet< Lam * > LamSet
Definition lam.h:211
GIDMap< Lam *, To > LamMap
Definition lam.h:210
fe::Vector< const Def * > DefVec
Definition def.h:96
GIDSet< const Def * > DefSet
Definition def.h:92
@ Lam
Definition def.h:123