|
| 1 | +#include "passes.h" |
| 2 | + |
| 3 | +#include "log.h" |
| 4 | +#include "portability.h" |
| 5 | +#include "dict.h" |
| 6 | + |
| 7 | +#include "../ir_private.h" |
| 8 | +#include "../type.h" |
| 9 | +#include "../rewrite.h" |
| 10 | +#include "../transform/ir_gen_helpers.h" |
| 11 | + |
| 12 | +typedef struct { |
| 13 | + Rewriter rewriter; |
| 14 | + struct Dict* map; |
| 15 | +} Context; |
| 16 | + |
| 17 | +static const Node* make_nullptr(Context* ctx, const Type* t) { |
| 18 | + IrArena* a = ctx->rewriter.dst_arena; |
| 19 | + const Node** found = find_value_dict(const Type*, const Node*, ctx->map, t); |
| 20 | + if (found) |
| 21 | + return *found; |
| 22 | + |
| 23 | + BodyBuilder* bb = begin_body(a); |
| 24 | + const Node* nul = gen_reinterpret_cast(bb, t, uint64_literal(a, 0)); |
| 25 | + Node* decl = constant(ctx->rewriter.dst_module, singleton(annotation(a, (Annotation) { |
| 26 | + .name = "Generated", |
| 27 | + })), t, format_string_interned(a, "nullptr_%s", name_type_safe(a, t))); |
| 28 | + decl->payload.constant.instruction = yield_values_and_wrap_in_block(bb, singleton(nul)); |
| 29 | + const Node* ref = ref_decl_helper(a, decl); |
| 30 | + insert_dict(const Type*, const Node*, ctx->map, t, ref); |
| 31 | + return ref; |
| 32 | +} |
| 33 | + |
| 34 | +static const Node* process(Context* ctx, const Node* node) { |
| 35 | + IrArena* a = ctx->rewriter.dst_arena; |
| 36 | + Rewriter* r = &ctx->rewriter; |
| 37 | + switch (node->tag) { |
| 38 | + case NullPtr_TAG: { |
| 39 | + const Type* t = rewrite_node(r, node->payload.null_ptr.ptr_type); |
| 40 | + assert(t->tag == PtrType_TAG); |
| 41 | + return make_nullptr(ctx, t); |
| 42 | + } |
| 43 | + default: break; |
| 44 | + } |
| 45 | + |
| 46 | + return recreate_node_identity(&ctx->rewriter, node); |
| 47 | +} |
| 48 | + |
| 49 | +KeyHash hash_node(Node**); |
| 50 | +bool compare_node(Node**, Node**); |
| 51 | + |
| 52 | +Module* lower_nullptr(SHADY_UNUSED const CompilerConfig* config, Module* src) { |
| 53 | + ArenaConfig aconfig = get_arena_config(get_module_arena(src)); |
| 54 | + IrArena* a = new_ir_arena(aconfig); |
| 55 | + Module* dst = new_module(a, get_module_name(src)); |
| 56 | + Context ctx = { |
| 57 | + .rewriter = create_rewriter(src, dst, (RewriteNodeFn) process), |
| 58 | + .map = new_dict(const Node*, Node*, (HashFn) hash_node, (CmpFn) compare_node), |
| 59 | + }; |
| 60 | + rewrite_module(&ctx.rewriter); |
| 61 | + destroy_rewriter(&ctx.rewriter); |
| 62 | + destroy_dict(ctx.map); |
| 63 | + return dst; |
| 64 | +} |
0 commit comments