pattern_match.h 12.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Copyright (c) 2023 PaddlePaddle Authors. 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.

15 16
// The design is mainly from MLIR, very thanks to the greate project.

17 18 19 20 21
#pragma once

#include <functional>
#include <initializer_list>
#include <memory>
22
#include <optional>
23 24 25
#include <string>
#include <type_traits>
#include <vector>
26 27

#include "paddle/ir/core/builder.h"
28
#include "paddle/ir/core/dll_decl.h"
29
#include "paddle/ir/core/ir_context.h"
30
#include "paddle/ir/core/op_info.h"
31 32 33 34 35
#include "paddle/ir/core/operation.h"
#include "paddle/ir/core/type_id.h"
#include "paddle/ir/core/type_name.h"
#include "paddle/ir/core/value.h"

36
namespace ir {
37

38 39
// This class reprensents the benefit of a pattern. The most common
// unit to use is the `numver of operations` in the pattern.
40
class IR_API PatternBenefit {
41
 public:
42 43
  PatternBenefit() = default;
  PatternBenefit(uint32_t val) : val_(val) {}  // NOLINT
44

45
  uint32_t benefit() { return val_; }
46 47 48 49 50 51

  bool operator==(const PatternBenefit& rhs) const { return val_ == rhs.val_; }
  bool operator!=(const PatternBenefit& rhs) const { return !(*this == rhs); }
  bool operator<(const PatternBenefit& rhs) const { return val_ < rhs.val_; }
  bool operator>(const PatternBenefit& rhs) const { return rhs < *this; }
  bool operator<=(const PatternBenefit& rhs) const { return !(*this > rhs); }
52
  bool operator>=(const PatternBenefit& rhs) const { return !(*this < rhs); }
53 54

 private:
55
  uint32_t val_{0};
56 57
};

58 59 60
// This class contains all of the data related to a Pattern, but not contains
// any methods for the matching. This class is used to interface with the
// metadata of a pattern, such as benefit or root operation.
61
class IR_API Pattern {
62 63 64 65 66 67 68 69 70 71
  enum class RootKind {
    // The pattern root matches "any" operation.
    Any,
    // The pattern root is matched using a concrete operation.
    OperationInfo,
    // The pattern root is matched using an interface id.
    InterfaceId,
    // The patter root is matched using a trait id.
    TraitId
  };
72 73

 public:
74 75
  const std::vector<OpInfo>& generated_ops() const { return generated_ops_; }

76
  std::optional<OpInfo> root_kind() const {
77 78
    if (root_kind_ == RootKind::OperationInfo)
      return OpInfo::RecoverFromOpaquePointer(root_val_);
79
    return std::nullopt;
80 81
  }

82
  std::optional<TypeId> GetRootInterfaceID() const {
83 84
    if (root_kind_ == RootKind::InterfaceId)
      return TypeId::RecoverFromOpaquePointer(root_val_);
85
    return std::nullopt;
86 87
  }

88
  std::optional<TypeId> GetRootTraitID() const {
89 90
    if (root_kind_ == RootKind::TraitId)
      return TypeId::RecoverFromOpaquePointer(root_val_);
91
    return std::nullopt;
92 93
  }

94 95
  PatternBenefit benefit() const { return benefit_; }

96
  IrContext* ir_context() const { return context_; }
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

  std::string debug_name() const { return debug_name_; }

  void SetDebugName(const std::string& name) { debug_name_ = name; }

  const std::vector<std::string>& debug_labels() const { return debug_labels_; }

  void AddDebugLabels(const std::vector<std::string>& labels) {
    debug_labels_.insert(debug_labels_.end(), labels.begin(), labels.end());
  }

  void AddDebugLabels(const std::string& label) {
    debug_labels_.push_back(label);
  }

 protected:
  struct MatchAnyOpTypeTag {};
  struct MatchInterfaceOpTypeTag {};
  struct MatchTraitOpTypeTag {};

  Pattern(const std::string& root_name,
          PatternBenefit benefit,
119
          IrContext* context,
120 121 122 123
          const std::vector<std::string>& generated_names = {});

  Pattern(MatchAnyOpTypeTag tag,
          PatternBenefit benefit,
124
          IrContext* context,
125 126 127
          const std::vector<std::string>& generated_names = {});

  Pattern(MatchInterfaceOpTypeTag tag,
128
          TypeId interface_id,
129
          PatternBenefit benefit,
130
          IrContext* context,
131 132 133
          const std::vector<std::string>& generated_names = {});

  Pattern(MatchTraitOpTypeTag tag,
134
          TypeId trait_id,
135
          PatternBenefit benefit,
136
          IrContext* context,
137 138 139
          const std::vector<std::string>& generated_names = {});

 private:
140 141 142 143 144 145 146
  Pattern(void* root_val,
          RootKind root_kind,
          const std::vector<std::string>& generated_names,
          PatternBenefit benefit,
          IrContext* context);

  void* root_val_;
147 148 149
  RootKind root_kind_;

  const PatternBenefit benefit_;
150 151
  IrContext* context_;
  std::vector<OpInfo> generated_ops_;
152 153 154 155 156 157 158

  std::string debug_name_;
  std::vector<std::string> debug_labels_;
};

class PatternRewriter;

159
class IR_API RewritePattern : public Pattern {
160 161 162
 public:
  virtual ~RewritePattern();

163
  virtual void Rewrite(Operation* op,
164 165 166 167 168 169
                       PatternRewriter& rewriter) const {  // NOLINT
    throw(
        "need to implement either MatchAndRewrite or one of the rewrite "
        "functions.");
  }

170
  virtual bool Match(Operation* op) const {
171 172 173 174
    throw("need to implement either MatchAndRewrite or Match.");
    return false;
  }

175
  virtual bool MatchAndRewrite(Operation* op,
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
                               PatternRewriter& rewriter) const {  // NOLINT
    if (Match(op)) {
      Rewrite(op, rewriter);
      return true;
    }
    return false;
  }

  virtual void Initialize() {}

  template <typename T, typename... Args>
  static std::unique_ptr<T> Create(Args&&... args) {
    std::unique_ptr<T> pattern =
        std::make_unique<T>(std::forward<Args>(args)...);
    pattern->Initialize();

    if (pattern->debug_name().empty())
193
      pattern->SetDebugName(ir::get_type_name<T>());
194 195 196 197 198 199 200 201
    return pattern;
  }

 protected:
  using Pattern::Pattern;
};

namespace detail {
202 203
// A wrapper around PatternWrite that allows for matching and rewriting
// against an instance of a derived operation class or Interface.
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238
template <typename SourceOp>
struct OpOrInterfaceRewritePatternBase : public RewritePattern {
  using RewritePattern::RewritePattern;

  void Rewrite(Operation* op,
               PatternRewriter& rewriter) const final {  // NOLINT
    Rewrite(op->dyn_cast<SourceOp>(), rewriter);
  }

  bool Match(Operation* op) const final {
    return Match(op->dyn_cast<SourceOp>());
  }
  bool MatchAndRewrite(Operation* op,
                       PatternRewriter& rewriter) const final {  // NOLINT
    return MatchAndRewrite(op->dyn_cast<SourceOp>(), rewriter);
  }

  virtual void Rewrite(SourceOp op,
                       PatternRewriter& rewriter) const {  // NOLINT
    throw("must override Rewrite or MatchAndRewrite");
  }
  virtual bool Match(SourceOp op) const {
    throw("must override Match or MatchAndRewrite");
  }
  virtual bool MatchAndRewrite(SourceOp op,
                               PatternRewriter& rewriter) const {  // NOLINT
    if (Match(op)) {
      Rewrite(op, rewriter);
      return true;
    }
    return false;
  }
};
}  // namespace detail

239 240 241
// OpRewritePattern is a wrapper around RewritePattern that allows for
// matching and rewriting against an instance of a derived operation
// class as opposed to a raw Operation.
242 243 244
template <typename SourceOp>
struct OpRewritePattern
    : public detail::OpOrInterfaceRewritePatternBase<SourceOp> {
245
  OpRewritePattern(IrContext* context,
246 247 248
                   PatternBenefit benefit = 1,
                   const std::vector<std::string>& generated_names = {})
      : detail::OpOrInterfaceRewritePatternBase<SourceOp>(
249
            SourceOp::name(), benefit, context, generated_names) {}
250 251 252 253 254
};

// TODO(wilber): Support OpInterfaceRewritePattern and OpTraitRewritePattern.
// ...

255 256 257
// This class provides a series of interfaces for modifying IR and tracking IR
// changes. This class provides a unified API for IR modification.
class RewriterBase : public Builder {
258 259 260
 public:
  // TODO(wilber): Supplementary methods of block and region.

261 262 263 264
  virtual void ReplaceOpWithIf(Operation* op,
                               const std::vector<Value>& new_values,
                               bool* all_uses_replaced,
                               const std::function<bool(OpOperand)>& functor);
265

266 267 268
  void ReplaceOpWithIf(Operation* op,
                       const std::vector<Value>& new_values,
                       const std::function<bool(OpOperand)>& functor);
269

270
  virtual void ReplaceOp(Operation* op, const std::vector<Value>& new_values);
271

272 273
  // template <typename OpTy, typename... Args>
  // OpTy ReplaceOpWithNewOp(Operation *op, Args &&...args);
274

275
  virtual void EraseOp(Operation* op);
276

277
  IR_API void ReplaceAllUsesWith(Value from, Value to);
278 279 280 281 282 283

  void ReplaceUseIf(Value from,
                    Value to,
                    std::function<bool(OpOperand&)> functor);

 protected:
284
  explicit RewriterBase(IrContext* ctx) : Builder(ctx) {}
285 286 287

  virtual ~RewriterBase();

288 289
  virtual void NotifyRootReplaced(Operation* op,
                                  const std::vector<Value>& replacement) {}
290 291 292

  virtual void NotifyOperationRemoved(Operation* op) {}

293 294 295 296 297 298 299 300 301 302 303 304 305 306
  virtual void NotifyOperationInserted(Operation* op) {}

  virtual void StartRootUpdate(Operation* op) {}

  virtual void FinalizeRootUpdate(Operation* op) {}

  virtual void CancleRootUpdate(Operation* op) {}

  template <typename CallableT>
  void UpdateRootInplace(Operation* root, CallableT&& callable) {
    StartRootUpdate(root);
    callable();
    FinalizeRootUpdate(root);
  }
307 308 309 310 311 312 313 314 315 316 317 318 319

 private:
  void operator=(const RewriterBase&) = delete;
  RewriterBase(const RewriterBase&) = delete;

  void ReplaceOpWithResultsOfAnotherOp(Operation* op, Operation* new_op);
};

class PatternRewriter : public RewriterBase {
 public:
  using RewriterBase::RewriterBase;
};

320
// A pattern collection, easy to add patterns.
321 322 323 324 325 326 327 328 329 330 331
class RewritePatternSet {
  using NativePatternListT = std::vector<std::unique_ptr<RewritePattern>>;

 public:
  explicit RewritePatternSet(IrContext* context) : context_(context) {}

  RewritePatternSet(IrContext* context, std::unique_ptr<RewritePattern> pattern)
      : context_(context) {
    native_patterns_.emplace_back(std::move(pattern));
  }

332
  IrContext* ir_context() const { return context_; }
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383

  NativePatternListT& native_patterns() { return native_patterns_; }

  void Clear() { native_patterns_.clear(); }

  // 'add' methods for adding patterns to the set.
  template <typename... Ts,
            typename ConstructorArg,
            typename... ConstructorArgs,
            typename = std::enable_if_t<sizeof...(Ts) != 0>>
  RewritePatternSet& Add(ConstructorArg&& arg, ConstructorArgs&&... args) {
    std::initializer_list<int>{
        (AddImpl<Ts>({},
                     std::forward<ConstructorArg>(arg),
                     std::forward<ConstructorArgs>(args)...),
         0)...};
    return *this;
  }

  template <typename... Ts,
            typename ConstructorArg,
            typename... ConstructorArgs,
            typename = std::enable_if_t<sizeof...(Ts) != 0>>
  RewritePatternSet& AddWithLabel(const std::vector<std::string>& debug_labels,
                                  ConstructorArg&& arg,
                                  ConstructorArgs&&... args) {
    std::initializer_list<int>{
        (AddImpl<Ts>(debug_labels,
                     std::forward<ConstructorArg>(arg),
                     std::forward<ConstructorArgs>(args)...),
         0)...};
    return *this;
  }

  RewritePatternSet& Add(std::unique_ptr<RewritePattern> pattern) {
    native_patterns_.emplace_back(std::move(pattern));
    return *this;
  }

 private:
  template <typename T, typename... Args>
  std::enable_if_t<std::is_base_of<RewritePattern, T>::value> AddImpl(
      const std::vector<std::string>& debug_labels, Args&&... args) {
    std::unique_ptr<T> pattern =
        RewritePattern::Create<T>(std::forward<Args>(args)...);
    pattern->AddDebugLabels(debug_labels);
    native_patterns_.emplace_back(std::move(pattern));
  }

 private:
  IrContext* const context_;
384

385 386
  NativePatternListT native_patterns_;
};
387

388
}  // namespace ir