Skip to content

Instantly share code, notes, and snippets.

@RealNeGate
Last active March 4, 2024 04:58
Show Gist options
  • Select an option

  • Save RealNeGate/b2009e693739b772a69a40dd1ad50a8a to your computer and use it in GitHub Desktop.

Select an option

Save RealNeGate/b2009e693739b772a69a40dd1ad50a8a to your computer and use it in GitHub Desktop.
// combined SimpleConstProp + Identity + GVN solver.
// returns NULL if it made no progress
Node* peephole_node(Optimizer* opt, Node* n) {
Node* k;
// tries to deduce the value of an op based on the
// types of the inputs, if both inputs were deduced
// constant we'd be constants and if both inputs were
// ranges we might infer extra data if not a constant.
Type* t = value(opt, n);
k = try_as_const(opt, n, t);
if (k) { return k; }
// this is ops which replace the node with a direct
// input (x + 0 => x), because of this we don't need
// to rerun const prop since they don't change nodes
// just referenced existing ones.
//
// identity(opt, n) will always return a node, either n
// or a direct replacement
k = identity(opt, n);
if (k != n) { return k; }
// GVN, we literally just place nodes into a hash table.
// no need to rerun it's ruleset if it's just referencing
// an existing node.
k = hashset_get(opt->gvn_nodes, n);
if (k) {
hashset_put(opt->gvn_nodes, k);
return k;
}
// it's already in it's normal form (no progress)
return NULL;
}
void peephole(Optimizer* opt, Worklist* ws) {
Node* n;
while (n = worklist_pop(ws), n) {
Node* k = peephole_node(ws, n);
if (k != NULL) {
subsume_node(opt, n, k);
worklist_push_users(ws, k);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment