// Copyright (c) 2024 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. #pragma once #include #include "paddle/common/enforce.h" #include "paddle/pir/include/core/value.h" namespace pir { class Block; class Operation; namespace detail { template struct ExactlyOneIrType { using type = void; }; template struct ExactlyOneIrType { using type = std::conditional_t::value, FirstT, typename ExactlyOneIrType::type>; }; } // namespace detail class IrMapping { public: template using remove_lowlevel_const_t = std::conditional_t< std::is_pointer::value, std::add_pointer_t>>, T>; template using IrType = typename detail::ExactlyOneIrType, Value, Block*, Operation*>::type; template auto& GetMutableMap() { if constexpr (std::is_same::value) { return value_map_; } else if constexpr (std::is_same::value) { return block_map_; } else if constexpr (std::is_same::value) { return operation_map_; } else { IR_THROW("Not support type in IRMapping."); } } template const auto& GetMap() const { if constexpr (std::is_same::value) { return value_map_; } else if constexpr (std::is_same::value) { return block_map_; } else if constexpr (std::is_same::value) { return operation_map_; } else { IR_THROW("Not support type in IRMapping."); } } template void Add(T from, S to) { if (!from) return; GetMutableMap>()[from] = to; } template bool Has(T from) const { if (!from) return false; bool has_value = GetMap>().count(from) > 0UL; return has_value; } template IrType Lookup(T from) const { if (!from) return static_cast>(nullptr); PADDLE_ENFORCE_GT( GetMap>().count(from), 0UL, common::errors::InvalidArgument("Not found key in IRMapping.")); return GetMap>().at(from); } template void Erase(T from) { GetMutableMap>().erase(from); } void Clear() { value_map_.clear(); block_map_.clear(); operation_map_.clear(); } private: std::unordered_map value_map_; std::unordered_map block_map_; std::unordered_map operation_map_; }; } // namespace pir