summaryrefslogtreecommitdiff
path: root/compiler/kuma/src/kuma.cpp
blob: 6fad96b26f241c15af9cc9b7541423374f18e777 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
 * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "kuma.h"

//
// Greedy Allocation Algorithm
//
namespace kuma
{

void solve(Context<Algorithm::Greedy> *ctx)
{
  uint32_t next = 0;

  for (uint32_t n = 0; n < ctx->item_count(); ++n)
  {
    ctx->mem_offset(n, next);
    next += ctx->item_size(n);
  }

  ctx->mem_total(next);
};

} // namespace kuma

//
// Linear Scan First Fit Algorithm
//
#include "IntervalSet.h"

namespace kuma
{

void solve(Context<Algorithm::LinearScanFirstFit> *ctx)
{
  using namespace kuma::details;

  uint32_t upper_bound = 0;
  std::map<ItemID, std::pair<uint32_t /* BEGIN */, uint32_t /* END */>> committed_items;

  // Allocate items in linear order (from item 0, item 1, ...)
  //
  // The implementor of Context is responsible for item ordering.
  for (uint32_t n = 0; n < ctx->item_count(); ++n)
  {
    IntervalSet intervals;

    for (auto item_in_conflict : ctx->conflict_with(n))
    {
      auto it = committed_items.find(item_in_conflict);

      // Skip if item_in_conflict is not committed yet
      if (it == committed_items.end())
      {
        continue;
      }

      auto const alloc_s = it->second.first;
      auto const alloc_e = it->second.second;
      intervals.insert(mask(alloc_s, alloc_e));
    }

    uint32_t const item_size = ctx->item_size(n);
    uint32_t const item_alloc_s = intervals.firstfit(item_size);
    uint32_t const item_alloc_e = item_alloc_s + item_size;

    // Notify "mem_offset"
    ctx->mem_offset(n, item_alloc_s);

    // Update "upper bound" and commit allocation
    upper_bound = std::max(upper_bound, item_alloc_e);
    committed_items[n] = std::make_pair(item_alloc_s, item_alloc_e);
  }

  // Notify "mem_total"
  ctx->mem_total(upper_bound);
}

} // namespace kuma