• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

daisytuner / docc / 27462544866

13 Jun 2026 09:11AM UTC coverage: 61.274% (-0.06%) from 61.331%
27462544866

push

github

web-flow
simplifies local storage transformations (#758)

275 of 325 new or added lines in 2 files covered. (84.62%)

5 existing lines in 1 file now uncovered.

36247 of 59156 relevant lines covered (61.27%)

1124.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

79.82
/opt/src/transformations/in_local_storage.cpp
1
#include "sdfg/transformations/in_local_storage.h"
2

3
#include <cstddef>
4
#include <functional>
5
#include <string>
6

7
#include "sdfg/analysis/memory_layout_analysis.h"
8
#include "sdfg/analysis/scope_analysis.h"
9
#include "sdfg/analysis/users.h"
10
#include "sdfg/builder/structured_sdfg_builder.h"
11
#include "sdfg/data_flow/access_node.h"
12
#include "sdfg/data_flow/library_nodes/barrier_local_node.h"
13
#include "sdfg/data_flow/memlet.h"
14
#include "sdfg/passes/structured_control_flow/dead_cfg_elimination.h"
15
#include "sdfg/passes/structured_control_flow/sequence_fusion.h"
16
#include "sdfg/structured_control_flow/if_else.h"
17
#include "sdfg/structured_control_flow/sequence.h"
18
#include "sdfg/structured_control_flow/structured_loop.h"
19
#include "sdfg/symbolic/symbolic.h"
20
#include "sdfg/targets/gpu/gpu_schedule_type.h"
21
#include "sdfg/types/array.h"
22
#include "sdfg/types/pointer.h"
23
#include "sdfg/types/scalar.h"
24

25
namespace sdfg {
26
namespace transformations {
27

28
InLocalStorage::InLocalStorage(
29
    structured_control_flow::StructuredLoop& loop,
30
    const data_flow::AccessNode& access_node,
31
    const types::StorageType& storage_type
32
)
33
    : loop_(loop), access_node_(access_node), container_(access_node.data()), storage_type_(storage_type) {}
34✔
34

35
std::string InLocalStorage::name() const { return "InLocalStorage"; }
7✔
36

37
bool InLocalStorage::can_be_applied(builder::StructuredSDFGBuilder& builder, analysis::AnalysisManager& analysis_manager) {
34✔
38
    auto& sdfg = builder.subject();
34✔
39
    auto& body = this->loop_.root();
34✔
40

41
    tile_info_ = TileInfo{};
34✔
42

43
    // Criterion: Container must exist and is pointer
44
    if (!sdfg.exists(this->container_)) {
34✔
45
        return false;
×
46
    }
×
47
    auto& type = sdfg.type(this->container_);
34✔
48
    if (type.type_id() != types::TypeID::Pointer) {
34✔
49
        return false;
1✔
50
    }
1✔
51

52
    // Criterion: Container must be used in the loop body
53
    auto& users = analysis_manager.get<analysis::Users>();
33✔
54
    analysis::UsersView body_users(users, body);
33✔
55
    if (body_users.uses(this->container_).empty()) {
33✔
56
        return false;
2✔
57
    }
2✔
58

59
    // Criterion: Container must be read-only within the loop (no writes)
60
    if (!body_users.writes(this->container_).empty()) {
31✔
61
        return false;
1✔
62
    }
1✔
63

64
    // Use MemoryLayoutAnalysis tile group API
65
    auto& mla = analysis_manager.get<analysis::MemoryLayoutAnalysis>();
30✔
66

67
    // Find a representative memlet from the access node to identify its group.
68
    const analysis::MemoryTileGroup* group = nullptr;
30✔
69
    auto& dfg = access_node_.get_parent();
30✔
70
    for (auto& memlet : dfg.out_edges(access_node_)) {
30✔
71
        auto* candidate = mla.tile_group_for(loop_, memlet);
30✔
72
        if (!candidate) {
30✔
NEW
73
            continue;
×
NEW
74
        }
×
75

76
        auto extents = candidate->tile.extents_approx();
30✔
77
        if (extents.empty()) {
30✔
NEW
78
            continue;
×
NEW
79
        }
×
80

81
        // Reject candidates with any unbounded-dependent extent (returned as null).
82
        bool has_null = false;
30✔
83
        for (auto& ext : extents) {
53✔
84
            if (ext.is_null()) {
53✔
85
                has_null = true;
×
86
                break;
×
87
            }
×
88
        }
53✔
89
        if (has_null) {
30✔
NEW
90
            continue;
×
NEW
91
        }
×
92

93
        // GPU path: accept first valid group (substitution happens later)
94
        if (storage_type_.is_nv_shared()) {
30✔
95
            group = candidate;
5✔
96
            break;
5✔
97
        }
5✔
98

99
        // CPU path: require provably integer extents
100
        bool all_integer = true;
25✔
101
        for (auto& ext : extents) {
44✔
102
            if (!SymEngine::is_a<SymEngine::Integer>(*ext)) {
44✔
103
                all_integer = false;
×
104
                break;
×
105
            }
×
106
        }
44✔
107
        if (all_integer) {
25✔
108
            group = candidate;
25✔
109
            break;
25✔
110
        }
25✔
111
    }
25✔
112
    if (!group) {
30✔
113
        return false;
×
114
    }
×
115

116
    auto& tile = group->tile;
30✔
117
    auto extents = tile.extents_approx();
30✔
118

119
    // Store group memlets for use in apply()
120
    group_memlets_.clear();
30✔
121
    group_memlets_.insert(group->memlets.begin(), group->memlets.end());
30✔
122

123
    // Store tile info (before substitution, bases/strides stay symbolic)
124
    tile_info_.dimensions = extents;
30✔
125
    tile_info_.bases = tile.min_subset;
30✔
126
    tile_info_.strides = std::vector<symbolic::Expression>(tile.layout.strides().begin(), tile.layout.strides().end());
30✔
127
    tile_info_.offset = tile.layout.offset();
30✔
128

129
    // GPU shared memory: resolve symbolic extents using GPU block sizes and
130
    // require at least one cooperative dimension
131
    if (storage_type_.is_nv_shared()) {
30✔
132
        auto ancestors = ControlFlowNode::parent_chain(loop_);
5✔
133

134
        // Build substitution map: symbolic GPU map bounds → integer block sizes
135
        // E.g., Map condition "i < N" with block_size=32 → N=32
136
        for (auto* node : ancestors) {
23✔
137
            if (auto* ancestor_map = dynamic_cast<structured_control_flow::Map*>(node)) {
23✔
138
                if (!gpu::is_gpu_schedule(ancestor_map->schedule_type())) {
9✔
139
                    continue;
×
140
                }
×
141
                auto block_size = gpu::gpu_block_size(ancestor_map->schedule_type());
9✔
142
                // Extract symbolic bound from condition: Lt(indvar, BOUND)
143
                auto condition = ancestor_map->condition();
9✔
144
                if (SymEngine::is_a<SymEngine::StrictLessThan>(*condition)) {
9✔
145
                    auto stl = SymEngine::rcp_static_cast<const SymEngine::StrictLessThan>(condition);
9✔
146
                    auto rhs = stl->get_args()[1];
9✔
147
                    auto iter_count = symbolic::sub(rhs, ancestor_map->init());
9✔
148
                    if (!SymEngine::is_a<SymEngine::Integer>(*iter_count)) {
9✔
149
                        // Symbolic bound — substitute with block size in extents and bases
150
                        for (auto& ext : tile_info_.dimensions) {
16✔
151
                            ext = symbolic::simplify(symbolic::subs(ext, iter_count, block_size));
16✔
152
                        }
16✔
153
                        for (auto& base : tile_info_.bases) {
16✔
154
                            base = symbolic::simplify(symbolic::subs(base, iter_count, block_size));
16✔
155
                        }
16✔
156
                    }
9✔
157
                }
9✔
158
            }
9✔
159
        }
23✔
160

161
        // Also resolve the loop's own bound if symbolic and matches a block size
162
        // E.g., For k = 0..K where K is a parameter — check if K can be resolved
163
        // from any GPU ancestor map
164
        // (Already handled above: if K appears as a GPU map bound, it's substituted)
165

166
        // Criterion: All extents must now be provably integer
167
        for (auto& ext : tile_info_.dimensions) {
9✔
168
            if (!SymEngine::is_a<SymEngine::Integer>(*ext)) {
9✔
169
                return false;
2✔
170
            }
2✔
171
        }
9✔
172

173
        // Criterion: At least one cooperative dimension
174
        bool has_cooperative_dim = false;
3✔
175
        for (auto* node : ancestors) {
6✔
176
            if (auto* ancestor_map = dynamic_cast<structured_control_flow::Map*>(node)) {
6✔
177
                if (!gpu::is_gpu_schedule(ancestor_map->schedule_type())) {
3✔
178
                    continue;
×
179
                }
×
180
                // A GPU dim is cooperative if its indvar does NOT appear in any tile base
181
                bool appears_in_bases = false;
3✔
182
                for (auto& base : tile_info_.bases) {
5✔
183
                    if (symbolic::uses(base, ancestor_map->indvar())) {
5✔
184
                        appears_in_bases = true;
×
185
                        break;
×
186
                    }
×
187
                }
5✔
188
                if (!appears_in_bases) {
3✔
189
                    has_cooperative_dim = true;
3✔
190
                    break;
3✔
191
                }
3✔
192
            }
3✔
193
        }
6✔
194
        if (!has_cooperative_dim) {
3✔
195
            return false;
×
196
        }
×
197
    }
3✔
198

199
    return true;
28✔
200
}
30✔
201

202
void InLocalStorage::apply(builder::StructuredSDFGBuilder& builder, analysis::AnalysisManager& analysis_manager) {
20✔
203
    auto& sdfg = builder.subject();
20✔
204

205
    auto parent_node = loop_.get_parent();
20✔
206
    auto parent = dynamic_cast<structured_control_flow::Sequence*>(parent_node);
20✔
207
    if (!parent) {
20✔
208
        throw InvalidSDFGException("InLocalStorage: Parent of loop must be a Sequence!");
×
209
    }
×
210

211
    // We replace all relevant memlets with flat local indices
212
    // Thus, we now use a flat pointer to index into container
213
    // Remark: sdfg.type may return an opaque pointer, so use
214
    //         memlet instead
215
    auto* memlet = *group_memlets_.begin();
20✔
216
    types::Scalar scalar_type(memlet->base_type().primitive_type());
20✔
217
    types::Pointer pointer_type(scalar_type);
20✔
218

219
    // Create local buffer name
220
    local_name_ = builder.find_new_name("__daisy_in_local_storage_" + this->container_);
20✔
221

222
    // Collect varying dimensions (extent > 1) and compute buffer layout
223
    std::vector<size_t> varying_dims;
20✔
224
    std::vector<symbolic::Expression> dim_sizes;
20✔
225
    for (size_t d = 0; d < tile_info_.dimensions.size(); d++) {
57✔
226
        auto& dim_size = tile_info_.dimensions.at(d);
37✔
227
        if (!symbolic::eq(dim_size, symbolic::integer(1))) {
37✔
228
            varying_dims.push_back(d);
28✔
229
            dim_sizes.push_back(dim_size);
28✔
230
        }
28✔
231
    }
37✔
232

233
    // Compute total buffer size
234
    symbolic::Expression total_size = symbolic::integer(1);
20✔
235
    for (auto& ds : dim_sizes) {
28✔
236
        total_size = symbolic::mul(total_size, ds);
28✔
237
    }
28✔
238

239
    // Helper: build linearized local index from per-dimension symbolic expressions
240
    auto linearize_exprs = [&](const std::vector<symbolic::Expression>& indices) -> symbolic::Expression {
41✔
241
        symbolic::Expression linear_idx = symbolic::integer(0);
41✔
242
        symbolic::Expression stride = symbolic::integer(1);
41✔
243
        for (int i = indices.size() - 1; i >= 0; i--) {
102✔
244
            linear_idx = symbolic::add(linear_idx, symbolic::mul(indices[i], stride));
61✔
245
            stride = symbolic::mul(stride, dim_sizes[i]);
61✔
246
        }
61✔
247
        return linear_idx;
41✔
248
    };
41✔
249

250
    // Helper: build linearized local index from per-dimension indvars (symbols)
251
    auto linearize = [&](const std::vector<symbolic::Symbol>& indvars) -> symbolic::Expression {
20✔
252
        std::vector<symbolic::Expression> exprs(indvars.begin(), indvars.end());
17✔
253
        return linearize_exprs(exprs);
17✔
254
    };
17✔
255

256
    // Helper: build source subset (base[d] + copy_indvar[d]) for original container
257
    auto build_original_subset = [&](const std::vector<symbolic::Expression>& copy_indices) -> data_flow::Subset {
20✔
258
        std::vector<symbolic::Expression> full_indices;
20✔
259
        size_t var_idx = 0;
20✔
260
        for (size_t d = 0; d < tile_info_.dimensions.size(); d++) {
57✔
261
            if (!symbolic::eq(tile_info_.dimensions.at(d), symbolic::integer(1))) {
37✔
262
                full_indices.push_back(symbolic::add(tile_info_.bases.at(d), copy_indices.at(var_idx++)));
28✔
263
            } else {
28✔
264
                full_indices.push_back(tile_info_.bases.at(d));
9✔
265
            }
9✔
266
        }
37✔
267

268
        symbolic::Expression linear = tile_info_.offset;
20✔
269
        for (size_t d = 0; d < full_indices.size(); d++) {
57✔
270
            linear = symbolic::add(linear, symbolic::mul(tile_info_.strides.at(d), full_indices.at(d)));
37✔
271
        }
37✔
272
        return {linear};
20✔
273
    };
20✔
274

275
    // ==================================================================
276
    // Branch: GPU cooperative path vs CPU sequential path
277
    // ==================================================================
278
    if (storage_type_.is_nv_shared()) {
20✔
279
        // ============================================================
280
        // GPU COOPERATIVE PATH
281
        // ============================================================
282
        auto ancestors = ControlFlowNode::parent_chain(loop_);
3✔
283

284
        // Collect cooperative GPU dimensions (indvar not in tile bases)
285
        struct CoopDim {
3✔
286
            symbolic::Symbol indvar;
3✔
287
            symbolic::Integer block_size;
3✔
288
            gpu::GPUDimension dimension;
3✔
289
        };
3✔
290
        std::vector<CoopDim> coop_dims;
3✔
291

292
        for (auto* node : ancestors) {
15✔
293
            if (auto* ancestor_map = dynamic_cast<structured_control_flow::Map*>(node)) {
15✔
294
                if (!gpu::is_gpu_schedule(ancestor_map->schedule_type())) {
6✔
295
                    continue;
×
296
                }
×
297
                bool appears_in_bases = false;
6✔
298
                for (auto& base : tile_info_.bases) {
8✔
299
                    if (symbolic::uses(base, ancestor_map->indvar())) {
8✔
300
                        appears_in_bases = true;
2✔
301
                        break;
2✔
302
                    }
2✔
303
                }
8✔
304
                if (!appears_in_bases) {
6✔
305
                    coop_dims.push_back(
4✔
306
                        {ancestor_map->indvar(),
4✔
307
                         gpu::gpu_block_size(ancestor_map->schedule_type()),
4✔
308
                         gpu::gpu_dimension(ancestor_map->schedule_type())}
4✔
309
                    );
4✔
310
                }
4✔
311
            }
6✔
312
        }
15✔
313

314
        // Compute total cooperative thread count
315
        symbolic::Expression total_coop_threads = symbolic::integer(1);
3✔
316
        for (auto& cd : coop_dims) {
4✔
317
            total_coop_threads = symbolic::mul(total_coop_threads, cd.block_size);
4✔
318
        }
4✔
319

320
        // Create the local buffer with NV_Shared storage
321
        types::Array buffer_type(storage_type_, 0, {}, scalar_type, total_size);
3✔
322
        builder.add_container(local_name_, buffer_type);
3✔
323

324
        // Emit: barrier → guarded cooperative copy → barrier → loop
325
        // 1. Barrier before copy
326
        auto& barrier_block1 = builder.add_block_before(*parent, loop_, {}, loop_.debug_info());
3✔
327
        builder.add_library_node<data_flow::BarrierLocalNode>(barrier_block1, {});
3✔
328

329
        // 2. Cooperative copy with if_else guard
330
        // Flatten cooperative thread index: coop_flat = sum(indvar[i] * product(block_size[j] for j>i))
331
        symbolic::Expression coop_flat = symbolic::integer(0);
3✔
332
        symbolic::Expression coop_stride = symbolic::integer(1);
3✔
333
        for (int i = coop_dims.size() - 1; i >= 0; i--) {
7✔
334
            coop_flat = symbolic::add(coop_flat, symbolic::mul(coop_dims[i].indvar, coop_stride));
4✔
335
            coop_stride = symbolic::mul(coop_stride, coop_dims[i].block_size);
4✔
336
        }
4✔
337

338
        // Each thread loads elements strided by total_coop_threads
339
        // Thread t loads elements: t, t + total_threads, t + 2*total_threads, ...
340
        // We emit a loop: for (idx = coop_flat; idx < total_size; idx += total_coop_threads)
341
        auto idx_name = builder.find_new_name("__daisy_ils_coop_" + this->container_);
3✔
342
        types::Scalar idx_type(types::PrimitiveType::UInt64);
3✔
343
        builder.add_container(idx_name, idx_type);
3✔
344
        auto idx_var = symbolic::symbol(idx_name);
3✔
345

346
        auto copy_init = coop_flat;
3✔
347
        auto copy_condition = symbolic::Lt(idx_var, total_size);
3✔
348
        auto copy_update = symbolic::add(idx_var, total_coop_threads);
3✔
349

350
        auto& copy_loop = builder.add_map_before(
3✔
351
            *parent,
3✔
352
            loop_,
3✔
353
            idx_var,
3✔
354
            copy_condition,
3✔
355
            copy_init,
3✔
356
            copy_update,
3✔
357
            structured_control_flow::ScheduleType_Sequential::create(),
3✔
358
            {},
3✔
359
            loop_.debug_info()
3✔
360
        );
3✔
361

362
        // Decompose flat idx back into per-dimension indices for source subset
363
        // idx maps to varying_dims in row-major order
364
        auto& copy_scope = copy_loop.root();
3✔
365
        auto& copy_block = builder.add_block(copy_scope);
3✔
366
        auto& copy_src = builder.add_access(copy_block, this->container_);
3✔
367
        auto& copy_dst = builder.add_access(copy_block, local_name_);
3✔
368
        auto& copy_tasklet = builder.add_tasklet(copy_block, data_flow::TaskletCode::assign, "_out", {"_in"});
3✔
369

370
        // Decompose idx_var into per-dim indices
371
        std::vector<symbolic::Expression> copy_indices;
3✔
372
        symbolic::Expression remainder = idx_var;
3✔
373
        for (size_t i = 0; i < dim_sizes.size(); i++) {
6✔
374
            if (i < dim_sizes.size() - 1) {
3✔
375
                // integer division: idx / (product of remaining dims)
376
                symbolic::Expression divisor = symbolic::integer(1);
×
377
                for (size_t j = i + 1; j < dim_sizes.size(); j++) {
×
378
                    divisor = symbolic::mul(divisor, dim_sizes[j]);
×
379
                }
×
380
                auto quotient = symbolic::div(remainder, divisor);
×
381
                copy_indices.push_back(quotient);
×
382
                remainder = symbolic::mod(remainder, divisor);
×
383
            } else {
3✔
384
                copy_indices.push_back(remainder);
3✔
385
            }
3✔
386
        }
3✔
387

388
        auto copy_src_subset = build_original_subset(copy_indices);
3✔
389
        data_flow::Subset copy_dst_subset = {idx_var};
3✔
390

391
        builder.add_computational_memlet(copy_block, copy_src, copy_tasklet, "_in", copy_src_subset, pointer_type);
3✔
392
        builder.add_computational_memlet(copy_block, copy_tasklet, "_out", copy_dst, copy_dst_subset, buffer_type);
3✔
393

394
        // 3. Barrier after copy
395
        auto& barrier_block2 = builder.add_block_before(*parent, loop_, {}, loop_.debug_info());
3✔
396
        builder.add_library_node<data_flow::BarrierLocalNode>(barrier_block2, {});
3✔
397
    } else {
17✔
398
        // ============================================================
399
        // CPU SEQUENTIAL PATH
400
        // ============================================================
401
        // Create the local buffer with specified storage type
402
        types::Array buffer_type(storage_type_, 0, {}, scalar_type, total_size);
17✔
403
        builder.add_container(local_name_, buffer_type);
17✔
404

405
        std::vector<symbolic::Symbol> copy_indvars;
17✔
406
        structured_control_flow::Sequence* copy_scope =
17✔
407
            &builder.add_sequence_before(*parent, loop_, {}, loop_.debug_info());
17✔
408
        for (size_t i = 0; i < varying_dims.size(); i++) {
42✔
409
            size_t d = varying_dims[i];
25✔
410
            auto indvar_name = builder.find_new_name("__daisy_ils_" + this->container_ + "_d" + std::to_string(d));
25✔
411
            types::Scalar indvar_type(types::PrimitiveType::UInt64);
25✔
412
            builder.add_container(indvar_name, indvar_type);
25✔
413
            auto indvar = symbolic::symbol(indvar_name);
25✔
414
            copy_indvars.push_back(indvar);
25✔
415

416
            auto init = symbolic::integer(0);
25✔
417
            auto condition = symbolic::Lt(indvar, dim_sizes[i]);
25✔
418
            auto update = symbolic::add(indvar, symbolic::integer(1));
25✔
419

420
            auto& copy_loop = builder.add_map(
25✔
421
                *copy_scope,
25✔
422
                indvar,
25✔
423
                condition,
25✔
424
                init,
25✔
425
                update,
25✔
426
                structured_control_flow::ScheduleType_Sequential::create(),
25✔
427
                {},
25✔
428
                loop_.debug_info()
25✔
429
            );
25✔
430
            copy_scope = &copy_loop.root();
25✔
431
        }
25✔
432

433
        // Create copy block
434
        auto& copy_block = builder.add_block(*copy_scope);
17✔
435
        auto& copy_src = builder.add_access(copy_block, this->container_);
17✔
436
        auto& copy_dst = builder.add_access(copy_block, local_name_);
17✔
437
        auto& copy_tasklet = builder.add_tasklet(copy_block, data_flow::TaskletCode::assign, "_out", {"_in"});
17✔
438

439
        std::vector<symbolic::Expression> copy_exprs(copy_indvars.begin(), copy_indvars.end());
17✔
440
        auto copy_src_subset = build_original_subset(copy_exprs);
17✔
441
        data_flow::Subset copy_dst_subset = {linearize(copy_indvars)};
17✔
442

443
        builder.add_computational_memlet(copy_block, copy_src, copy_tasklet, "_in", copy_src_subset, pointer_type);
17✔
444
        types::Array buffer_type_ref(storage_type_, 0, {}, scalar_type, total_size);
17✔
445
        builder.add_computational_memlet(copy_block, copy_tasklet, "_out", copy_dst, copy_dst_subset, buffer_type_ref);
17✔
446
    }
17✔
447

448
    // ==================================================================
449
    // Update accesses in the main loop to use the local buffer
450
    // ==================================================================
451
    types::Array buffer_type(storage_type_, 0, {}, scalar_type, total_size);
20✔
452
    auto& mla = analysis_manager.get<analysis::MemoryLayoutAnalysis>();
20✔
453

454
    // Recursive helper to traverse all blocks in the loop body
455
    std::function<void(structured_control_flow::ControlFlowNode&)> rewrite_accesses;
20✔
456
    rewrite_accesses = [&](structured_control_flow::ControlFlowNode& node) {
81✔
457
        if (auto* block = dynamic_cast<structured_control_flow::Block*>(&node)) {
81✔
458
            auto& dfg = block->dataflow();
29✔
459

460
            // Collect access nodes to process (avoid iterator invalidation)
461
            std::vector<data_flow::AccessNode*> access_nodes;
29✔
462
            for (auto* access_node : dfg.data_nodes()) {
84✔
463
                if (access_node->data() == this->container_) {
84✔
464
                    access_nodes.push_back(access_node);
26✔
465
                }
26✔
466
            }
84✔
467

468
            for (auto* access : access_nodes) {
29✔
469
                // Classify memlets: group vs non-group
470
                struct MemletRewrite {
26✔
471
                    data_flow::Memlet* memlet;
26✔
472
                    data_flow::Subset local_subset;
26✔
473
                    bool is_outgoing;
26✔
474
                };
26✔
475
                std::vector<MemletRewrite> group_rewrites;
26✔
476
                bool all_in_group = true;
26✔
477

478
                for (auto& memlet : dfg.out_edges(*access)) {
26✔
479
                    if (group_memlets_.count(&memlet) == 0) {
26✔
480
                        all_in_group = false;
2✔
481
                        continue;
2✔
482
                    }
2✔
483
                    auto* acc = mla.access(memlet);
24✔
484
                    if (acc && acc->subset.size() == tile_info_.dimensions.size()) {
24✔
485
                        std::vector<symbolic::Expression> local_indices;
24✔
486
                        for (size_t d = 0; d < tile_info_.dimensions.size(); d++) {
69✔
487
                            if (!symbolic::eq(tile_info_.dimensions.at(d), symbolic::integer(1))) {
45✔
488
                                local_indices.push_back(symbolic::sub(acc->subset.at(d), tile_info_.bases.at(d)));
36✔
489
                            }
36✔
490
                        }
45✔
491
                        symbolic::Expression linear_idx = linearize_exprs(local_indices);
24✔
492
                        group_rewrites.push_back({&memlet, {linear_idx}, true});
24✔
493
                    }
24✔
494
                }
24✔
495
                for (auto& memlet : dfg.in_edges(*access)) {
26✔
496
                    if (group_memlets_.count(&memlet) == 0) {
×
497
                        all_in_group = false;
×
498
                        continue;
×
499
                    }
×
500
                    auto* acc = mla.access(memlet);
×
501
                    if (acc && acc->subset.size() == tile_info_.dimensions.size()) {
×
502
                        std::vector<symbolic::Expression> local_indices;
×
503
                        for (size_t d = 0; d < tile_info_.dimensions.size(); d++) {
×
504
                            if (!symbolic::eq(tile_info_.dimensions.at(d), symbolic::integer(1))) {
×
505
                                local_indices.push_back(symbolic::sub(acc->subset.at(d), tile_info_.bases.at(d)));
×
506
                            }
×
507
                        }
×
508
                        symbolic::Expression linear_idx = linearize_exprs(local_indices);
×
509
                        group_rewrites.push_back({&memlet, {linear_idx}, false});
×
510
                    }
×
511
                }
×
512

513
                if (group_rewrites.empty()) continue;
26✔
514

515
                if (all_in_group) {
24✔
516
                    // Simple case: all memlets in group → rewrite in-place and rename
517
                    for (auto& rw : group_rewrites) {
24✔
518
                        rw.memlet->set_subset(rw.local_subset);
24✔
519
                        rw.memlet->set_base_type(buffer_type);
24✔
520
                    }
24✔
521
                    access->data(local_name_);
24✔
522
                } else {
24✔
523
                    // Mixed case: split — create new local access node, redirect group memlets
524
                    auto& local_access = builder.add_access(*block, local_name_);
×
525
                    for (auto& rw : group_rewrites) {
×
526
                        if (rw.is_outgoing) {
×
527
                            // outgoing: access→tasklet  →  local_access→tasklet
528
                            auto& dst_node = rw.memlet->dst();
×
529
                            auto dst_conn = rw.memlet->dst_conn();
×
530
                            builder.remove_memlet(*block, *rw.memlet);
×
531
                            builder.add_memlet(
×
532
                                *block, local_access, "void", dst_node, dst_conn, rw.local_subset, buffer_type, {}
×
533
                            );
×
534
                        } else {
×
535
                            // incoming: tasklet→access  →  tasklet→local_access
536
                            auto& src_node = rw.memlet->src();
×
537
                            auto src_conn = rw.memlet->src_conn();
×
538
                            builder.remove_memlet(*block, *rw.memlet);
×
539
                            builder.add_memlet(
×
540
                                *block, src_node, src_conn, local_access, "void", rw.local_subset, buffer_type, {}
×
541
                            );
×
542
                        }
×
543
                    }
×
544
                }
×
545
            }
24✔
546
        } else if (auto* seq = dynamic_cast<structured_control_flow::Sequence*>(&node)) {
52✔
547
            for (size_t i = 0; i < seq->size(); i++) {
81✔
548
                rewrite_accesses(seq->at(i).first);
45✔
549
            }
45✔
550
        } else if (auto* loop = dynamic_cast<structured_control_flow::StructuredLoop*>(&node)) {
36✔
551
            rewrite_accesses(loop->root());
16✔
552
        } else if (auto* if_else = dynamic_cast<structured_control_flow::IfElse*>(&node)) {
16✔
553
            for (size_t i = 0; i < if_else->size(); i++) {
×
554
                rewrite_accesses(if_else->at(i).first);
×
555
            }
×
556
        }
×
557
    };
81✔
558
    rewrite_accesses(loop_.root());
20✔
559

560
    // Cleanup
561
    analysis_manager.invalidate_all();
20✔
562

563
    passes::SequenceFusion sf_pass;
20✔
564
    passes::DeadCFGElimination dce_pass;
20✔
565
    bool applies = false;
20✔
566
    do {
37✔
567
        applies = false;
37✔
568
        applies |= dce_pass.run(builder, analysis_manager);
37✔
569
        applies |= sf_pass.run(builder, analysis_manager);
37✔
570
    } while (applies);
37✔
571
}
20✔
572

573
void InLocalStorage::to_json(nlohmann::json& j) const {
6✔
574
    std::string loop_type;
6✔
575
    if (dynamic_cast<structured_control_flow::For*>(&loop_)) {
6✔
576
        loop_type = "for";
6✔
577
    } else if (dynamic_cast<structured_control_flow::Map*>(&loop_)) {
6✔
578
        loop_type = "map";
×
579
    } else {
×
580
        throw std::runtime_error("Unsupported loop type for serialization of loop: " + loop_.indvar()->get_name());
×
581
    }
×
582
    j["subgraph"] = {
6✔
583
        {"0", {{"element_id", this->loop_.element_id()}, {"type", loop_type}}},
6✔
584
        {"1", {{"element_id", this->access_node_.element_id()}, {"type", "access_node"}}}
6✔
585
    };
6✔
586
    j["transformation_type"] = this->name();
6✔
587
    j["container"] = container_;
6✔
588
}
6✔
589

590
InLocalStorage InLocalStorage::from_json(builder::StructuredSDFGBuilder& builder, const nlohmann::json& desc) {
1✔
591
    auto loop_id = desc["subgraph"]["0"]["element_id"].get<size_t>();
1✔
592
    auto element = builder.find_element_by_id(loop_id);
1✔
593
    if (!element) {
1✔
594
        throw InvalidTransformationDescriptionException("Element with ID " + std::to_string(loop_id) + " not found.");
×
595
    }
×
596
    auto loop = dynamic_cast<structured_control_flow::StructuredLoop*>(element);
1✔
597
    if (!loop) {
1✔
598
        throw InvalidTransformationDescriptionException(
×
599
            "Element with ID " + std::to_string(loop_id) + " is not a structured loop."
×
600
        );
×
601
    }
×
602

603
    auto access_node = dynamic_cast<
1✔
604
        data_flow::AccessNode*>(builder.find_element_by_id(desc.at("subgraph").at("1").at("element_id").get<size_t>()));
1✔
605
    if (!access_node) {
1✔
606
        throw InvalidTransformationDescriptionException(
×
607
            "Access node with ID " + std::to_string(desc.at("subgraph").at("1").at("element_id").get<size_t>()) +
×
608
            " not found."
×
609
        );
×
610
    }
×
611

612
    return InLocalStorage(*loop, *access_node);
1✔
613
}
1✔
614

615
} // namespace transformations
616
} // namespace sdfg
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc