"vscode:/vscode.git/clone" did not exist on "af07367105ee1e811b02acffd18b965b9b0c8ed0"
legalize_safe_memory_access.cc 13.1 KB
Newer Older
1
/*!
2
3
 * \file legalize_safe_memory_access.cc
 * \brief legalize safe memory access
4
5
 */

6
#include <tvm/ffi/reflection/registry.h>
7
8
9
10
11
12
#include <tvm/tir/builtin.h>
#include <tvm/tir/op.h>
#include <tvm/tir/stmt_functor.h>
#include <tvm/tir/transform.h>
#include <tvm/tir/utils.h>

13
14
#include <utility>

15
#include "../op/builtin.h"
16
#include "../op/parallel.h"
17
#include "arith/ir_mutator_with_analyzer.h"
18
19
20
21
22
23
24
25
26
27
28
#include "loop_partition.h"
#include "loop_vectorize.h"

namespace tvm {
namespace tl {

using namespace tir;
using arith::IRMutatorWithAnalyzer;

// Helper class to find leaf For nodes in a given IR
class LeafForFinder : public StmtVisitor {
29
public:
30
31
  std::vector<For> leaf_for_nodes;

32
33
private:
  void VisitStmt_(const ForNode *op) final {
34
35
36
37
38
39
40
41
42
43
44
45
46
47
    has_child_for_ = false;
    bool parent_has_child_for = parent_has_child_for_;
    parent_has_child_for_ = false;

    StmtVisitor::VisitStmt(op->body);

    if (!has_child_for_) {
      leaf_for_nodes.push_back(GetRef<For>(op));
    }

    parent_has_child_for_ = parent_has_child_for;
    parent_has_child_for_ = true;
  }

48
private:
49
50
51
52
  bool has_child_for_ = false;
  bool parent_has_child_for_ = false;
};

53
// GlobalMemChecker for a BufferLoad/BufferStore node:
54
55
56
57
58
59
60
// 1. Identify BufferLoad and BufferStore nodes.
// 2. Check if the buffer is in global scope.
// 3. For each index, compare against the buffer's shape.
//    If the index might exceed the shape (upper bound too large),
//    log a warning or handle accordingly.
struct GlobalMemChecker : public StmtExprVisitor {

61
62
63
  GlobalMemChecker(arith::Analyzer *analyzer, bool recursively_collect_conds)
      : analyzer_(analyzer),
        recursively_collect_conds_(recursively_collect_conds) {}
64
  void VisitExpr_(const BufferLoadNode *op) final {
65
    // Check if the buffer is in global scope
66
67
    // This is because we are writing TilePrograms, where out of bounds
    // accesses only happen in the global buffer.
68
69
70
    if (IsGlobalBuffer(op->buffer)) {
      CheckBufferIndices(op->buffer, op->indices, /*is_load=*/true);
    }
71
72
73
    if (recursively_collect_conds_) {
      StmtExprVisitor::VisitExpr_(op);
    }
74
75
  }

76
  void VisitStmt_(const BufferStoreNode *op) final {
77
78
79
80
    // Check if the buffer is in global scope
    if (IsGlobalBuffer(op->buffer)) {
      CheckBufferIndices(op->buffer, op->indices, /*is_load=*/false);
    }
81
82
83
    if (recursively_collect_conds_) {
      StmtExprVisitor::VisitStmt_(op);
    }
84
85
86
  }

  // Helper function to determine if a buffer is global
87
88
89
90
91
92
  bool IsGlobalBuffer(const Buffer &buffer) {
    // The storage scope is often encoded in the buffer->data var name or
    // associated attributes. In typical TVM IR, global buffers have scope
    // "global". Here we assume a helper function GetPtrStorageScope is
    // available. If not, you might need to parse buffer->data->name_hint or
    // associated attributes.
93
94
95
96
97
    String scope = buffer.scope();
    return scope == "global";
  }

  // Check each index against the buffer shape dimensions
98
99
  void CheckBufferIndices(const Buffer &buffer, const Array<PrimExpr> &indices,
                          bool is_load) {
100
101
    // Ensure indices count matches buffer dimension
    if (indices.size() != buffer->shape.size()) {
102
103
104
      LOG(WARNING) << "Buffer access dimension mismatch: indices size ("
                   << indices.size() << ") vs. shape size ("
                   << buffer->shape.size() << ")";
105
106
107
108
109
110
111
      return;
    }

    for (size_t i = 0; i < indices.size(); i++) {
      PrimExpr index = indices[i];
      PrimExpr shape_dim = buffer->shape[i];

112
113
114
115
116
117
118
      bool has_variable = false;
      PostOrderVisit(index, [&](const ObjectRef &obj) {
        if (const VarNode *v = obj.as<VarNode>()) {
          has_variable = true;
        }
      });
      if (!has_variable) {
119
        // If index is a constant, we can skip the check
120
121
122
        continue;
      }

123
124
125
      // We want to check if index < shape_dim can be proven.
      // If analyzer->CanProve(index < shape_dim) returns false,
      // it means we cannot prove the access is within bounds.
126
      PrimExpr upper_bound_cond = index < shape_dim;
127
128
      if (!analyzer_->CanProve(upper_bound_cond,
                               arith::ProofStrength::kSymbolicBound)) {
129
130
131
132
        _conditions.push_back(upper_bound_cond);
      }
      // Check if index >= 0 can be proven.
      PrimExpr lower_bound_cond = index >= 0;
133
134
      if (!analyzer_->CanProve(lower_bound_cond,
                               arith::ProofStrength::kSymbolicBound)) {
135
        _conditions.push_back(lower_bound_cond);
136
137
138
139
140
141
      }
    }
  }

  Array<PrimExpr> GetConditions() { return _conditions; }

142
private:
143
  Array<PrimExpr> _conditions;
144
  arith::Analyzer *analyzer_;
145
  bool recursively_collect_conds_;
146
147
148
};

class SafeMemorysRewriter : public StmtExprMutator {
149
  arith::Analyzer *analyzer_;
150

151
public:
152
  explicit SafeMemorysRewriter(Map<Buffer, PrimExpr> annotated_safe_value_map,
153
                               arith::Analyzer *analyzer)
154
      : annotated_safe_value_map_(std::move(annotated_safe_value_map)),
155
        analyzer_(analyzer) {}
156

157
private:
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
  PrimExpr VisitExpr_(const BufferLoadNode *op) final {
    auto load = Downcast<BufferLoad>(StmtExprMutator::VisitExpr_(op));

    // For Load/Store, we only check the current node, not its children.
    // Since rewriter will recursively visit children.
    GlobalMemChecker checker(analyzer_, /*recursively_collect_conds=*/false);
    checker(load);
    Array<PrimExpr> conditions = checker.GetConditions();

    if (conditions.empty()) {
      return load;
    }

    // For loading, we can always use safe value if the access is out of
    // bounds
    PrimExpr value = load;
    for (auto cond : conditions) {
      ICHECK(cond.dtype() == DataType::Bool(1))
          << "condition is not a boolean: " << cond;
      value = if_then_else(cond, value, GetSafeValue(load->buffer));
    }
    return value;
  }

182
  Stmt VisitStmt_(const BufferStoreNode *op) final {
183
184
    // Check if the buffer is in global scope
    auto store = Downcast<BufferStore>(StmtExprMutator::VisitStmt_(op));
185

186
    GlobalMemChecker checker(analyzer_, /*recursively_collect_conds=*/false);
187
188
    checker(store);
    Array<PrimExpr> conditions = checker.GetConditions();
189
190
191

    // Skip boundary check if the store value is an IfThenElse
    if (const IfThenElseNode *if_node = store->value.as<IfThenElseNode>()) {
192
      if (!conditions.empty()) {
193
194
195
196
197
198
199
200
201
202
203
        LOG(WARNING)
            << "Skipping boundary check for store with IfThenElse value: "
            << store->value
            << "\nAs manual boundary check detected, potential out-of-bounds "
               "access may occur."
            << "\nAuto detect boundaries are " << conditions;
        return store;
      }
      return store;
    }

204
    if (conditions.empty()) {
205
206
207
      return store;
    }

208
209
210
211
    // If a store is out of bounds, we skip the corresponding stmt directly.
    Stmt store_with_conditions = store;
    for (auto cond : conditions) {
      store_with_conditions = IfThenElse(cond, store_with_conditions);
212
    }
213
    return store_with_conditions;
214
215
  }

216
  // Recursively check Load/Store in the call arguments.
217
  // For example
218
219
  // T.call_extern("handle", "atomicAddx2", T.address_of(C),
  // T.address_of(C_shared))
220
221
222
223
224
225
226
227

  // NOTE(chaofan): This is currently not the most rigorous solution.
  // The check here is primarily intended to handle extern functions like
  // atomicAdd, which may involve memory access. Due to their special nature,
  // the BufferLoad in their parameters might be used for boundary checks of the
  // current statement. The current solution adopts a simplified approach:
  // directly applying the boundary constraints of all parameters to the
  // statement. While not entirely precise, it addresses most common scenarios.
228
  Stmt VisitStmt_(const EvaluateNode *op) final {
229
230
    auto evaluate = Downcast<Evaluate>(op);

231
    if (const CallNode *call_op = op->value.as<CallNode>()) {
232
      auto call = Downcast<Call>(op->value);
233
      if (call->op == builtin::call_extern()) {
234
235
236
237
        // For CallExtern, we recursively collect conditions from all children.
        // Since we cannot rewrite any BufferLoad in its children (Rewrite will
        // cause potential Nullptr exception).
        GlobalMemChecker checker(analyzer_, /*recursively_collect_conds=*/true);
238
239
240
        checker(call);
        Array<PrimExpr> conditions = checker.GetConditions();

241
        if (conditions.empty()) {
242
243
244
245
246
247
248
249
          return evaluate;
        }

        Stmt evaluate_with_conditions = evaluate;
        for (auto cond : conditions) {
          evaluate_with_conditions = IfThenElse(cond, evaluate_with_conditions);
        }
        return evaluate_with_conditions;
250
251
252
253
254
255
      }
    }

    return evaluate;
  }

256
257
  bool IsLocalBuffer(const Buffer &buffer) {
    String scope = buffer.scope();
258
259
    return scope == "local" || scope == "local.fragment" ||
           scope == "local.var";
260
261
  }

262
  bool isSharedBuffer(const Buffer &buffer) {
263
264
265
266
    String scope = buffer.scope();
    return scope == "shared" || scope == "shared.dyn";
  }

267
  bool IsGlobalBuffer(const Buffer &buffer) {
268
269
270
    String scope = buffer.scope();
    return scope == "global";
  }
271
272
273
274
  // Get the safe value of the buffer
  PrimExpr GetSafeValue(const Buffer &buffer) {
    if (annotated_safe_value_map_.count(buffer)) {
      return annotated_safe_value_map_[buffer];
275
276
277
278
    }
    return make_zero(buffer->dtype);
  }

279
  Map<Buffer, PrimExpr> annotated_safe_value_map_;
280
281
282
283
};

// Class to legalize safe memory access by transforming them appropriately
class SafeMemoryLegalizer : IRMutatorWithAnalyzer {
284
public:
285
286
287
288
289
290
  // Static method to substitute and transform the given PrimFunc
  static PrimFunc Substitute(PrimFunc f) {
    arith::Analyzer analyzer;
    // Create an instance of the legalizer with the analyzer
    SafeMemoryLegalizer substituter(&analyzer);
    // Get a mutable copy of the function node
291
    PrimFuncNode *fptr = f.CopyOnWrite();
292
293
294
    for (const auto &[_, buffer] : f->buffer_map) {
      substituter.buffer_data_to_buffer_.Set(buffer->data, buffer);
    }
295
296
297
298
299
    // Apply the legalizer to the function body
    fptr->body = substituter.VisitStmt(f->body);
    return f;
  }

300
private:
301
  // Constructor initializing the base class with the analyzer
302
303
  SafeMemoryLegalizer(arith::Analyzer *analyzer)
      : arith::IRMutatorWithAnalyzer(analyzer) {}
304
305

  // Override the VisitStmt_ method to handle ForNode (loop statements)
306
  Stmt VisitStmt_(const ForNode *op) final {
307
308
309
310
    // Visit and potentially modify the loop node
    For for_node = Downcast<For>(IRMutatorWithAnalyzer::VisitStmt_(op));
    auto has_inner_loop = HasInnerLoop(for_node->body);
    if (!has_inner_loop) {
311
      SafeMemorysRewriter rewriter(annotated_safe_value_map_, analyzer_);
312
      for_node.CopyOnWrite()->body = rewriter(for_node->body);
313
314
      // // Detect Buffer Load Node in the loop body, collect the indices and
      // buffer size
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334

      // // Run the checker on the loop body
      // GlobalMemChecker checker(analyzer_);
      // checker(for_node->body);
      // Array<PrimExpr> conditions = checker.GetConditions();
      // auto body = for_node->body;
      // // Note that we might have duplicate conditions
      // // Which will be optimized by simplify pass
      // // Replace the loop body with the new body
      // for (auto cond : conditions) {
      //   body = IfThenElse(cond, body);
      // }
      // for_node.CopyOnWrite()->body = body;
      return std::move(for_node);
    }

    // Visit a For Node
    return IRMutatorWithAnalyzer::VisitStmt_(op);
  }

335
336
337
338
  Stmt VisitStmt_(const BlockNode *op) final {
    for (auto buffer : op->alloc_buffers) {
      buffer_data_to_buffer_.Set(buffer->data, buffer);
    }
339
340
    if (op->annotations.count(attr::kSafeValueMap)) {
      auto map = op->annotations.Get(attr::kSafeValueMap)
341
                     ->as<Map<Var, PrimExpr>>()
342
                     .value();
343
      for (const auto &[var, safe_value] : map) {
344
        ICHECK(buffer_data_to_buffer_.count(var))
345
346
            << "buffer " << var << " is not found in the block "
            << buffer_data_to_buffer_;
347
        auto buffer = buffer_data_to_buffer_[var];
348
        annotated_safe_value_map_.Set(buffer, safe_value);
349
350
351
352
353
      }
    }
    return IRMutatorWithAnalyzer::VisitStmt_(op);
  }

354
  static bool HasInnerLoop(const Stmt &stmt) {
355
356
    LeafForFinder finder;
    finder(stmt);
357
    return !finder.leaf_for_nodes.empty();
358
  }
359
360

  Map<Var, Buffer> buffer_data_to_buffer_;
361
  Map<Buffer, PrimExpr> annotated_safe_value_map_;
362
363
364
365
366
367
};

// Create a pass that legalizes vectorized loops in the IRModule
tvm::transform::Pass LegalizeSafeMemoryAccess() {
  using namespace tir::transform;
  // Define the transformation function to be applied
368
  auto pass_func = [=](PrimFunc f, const IRModule &m, PassContext ctx) {
369
370
371
372
373
    bool disable_safe_memory_legalize =
        ctx->GetConfig<Bool>(kDisableSafeMemoryLegalize, Bool(false)).value();
    if (disable_safe_memory_legalize) {
      return f;
    }
374
375
376
377
378
379
380
    return SafeMemoryLegalizer::Substitute(std::move(f));
  };
  // Create and return a PrimFunc pass with the transformation function
  return CreatePrimFuncPass(pass_func, 0, "tl.LegalizeSafeMemoryAccess", {});
}

// Register the pass globally so it can be used in the compilation pipeline
381
382
383
384
385
TVM_FFI_STATIC_INIT_BLOCK({
  namespace refl = tvm::ffi::reflection;
  refl::GlobalDef().def("tl.transform.LegalizeSafeMemoryAccess",
                        LegalizeSafeMemoryAccess);
});
386

387
388
} // namespace tl
} // namespace tvm