builtin_function_kind.cpp 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/sem_ir/builtin_function_kind.h"
  5. #include <utility>
  6. #include "toolchain/sem_ir/file.h"
  7. #include "toolchain/sem_ir/ids.h"
  8. #include "toolchain/sem_ir/typed_insts.h"
  9. namespace Carbon::SemIR {
  10. // A function that validates that a builtin was declared properly.
  11. using ValidateFn = auto(const File& sem_ir, llvm::ArrayRef<TypeId> arg_types,
  12. TypeId return_type) -> bool;
  13. namespace {
  14. // Information about a builtin function.
  15. struct BuiltinInfo {
  16. llvm::StringLiteral name;
  17. ValidateFn* validate;
  18. };
  19. // The maximum number of type parameters any builtin needs.
  20. constexpr int MaxTypeParams = 1;
  21. // State used when validating a builtin signature that persists between
  22. // individual checks.
  23. struct ValidateState {
  24. // The type values of type parameters in the builtin signature. Invalid if
  25. // either no value has been deduced yet or the parameter is not used.
  26. TypeId type_params[MaxTypeParams] = {TypeId::Invalid};
  27. };
  28. // Constraint that a type is generic type parameter `I` of the builtin,
  29. // satisfying `TypeConstraint`. See ValidateSignature for details.
  30. template <int I, typename TypeConstraint>
  31. struct TypeParam {
  32. static_assert(I >= 0 && I < MaxTypeParams);
  33. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  34. -> bool {
  35. if (state.type_params[I].is_valid() && type_id != state.type_params[I]) {
  36. return false;
  37. }
  38. state.type_params[I] = type_id;
  39. return TypeConstraint::Check(sem_ir, state, type_id);
  40. }
  41. };
  42. // Constraint that a type is a specific builtin. See ValidateSignature for
  43. // details.
  44. template <const InstId& BuiltinId>
  45. struct BuiltinType {
  46. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  47. TypeId type_id) -> bool {
  48. return sem_ir.types().GetInstId(type_id) == BuiltinId;
  49. }
  50. };
  51. // Constraint that a type is `bool`.
  52. using Bool = BuiltinType<InstId::BuiltinBoolType>;
  53. // Constraint that requires the type to be an integer type.
  54. //
  55. // TODO: This only matches i32 for now. Support iN for all N, and the
  56. // Core.BigInt type we use to implement for integer literals.
  57. using AnyInt = BuiltinType<InstId::BuiltinIntType>;
  58. } // namespace
  59. // Validates that this builtin has a signature matching the specified signature.
  60. //
  61. // `SignatureFnType` is a C++ function type that describes the signature that is
  62. // expected for this builtin. For example, `auto (AnyInt, AnyInt) -> AnyInt`
  63. // specifies that the builtin takes values of two integer types and returns a
  64. // value of a third integer type. Types used within the signature should provide
  65. // a `Check` function that validates that the Carbon type is expected:
  66. //
  67. // auto Check(const File&, ValidateState&, TypeId) -> bool;
  68. //
  69. // To constrain that the same type is used in multiple places in the signature,
  70. // `TypeParam<I, T>` can be used. For example:
  71. //
  72. // auto (TypeParam<0, AnyInt>, AnyInt) -> TypeParam<0, AnyInt>
  73. //
  74. // describes a builtin that takes two integers, and whose return type matches
  75. // its first parameter type. For convenience, typedefs for `TypeParam<I, T>`
  76. // are used in the descriptions of the builtins.
  77. template <typename SignatureFnType>
  78. static auto ValidateSignature(const File& sem_ir,
  79. llvm::ArrayRef<TypeId> arg_types,
  80. TypeId return_type) -> bool {
  81. using SignatureTraits = llvm::function_traits<SignatureFnType*>;
  82. ValidateState state;
  83. // Must have expected number of arguments.
  84. if (arg_types.size() != SignatureTraits::num_args) {
  85. return false;
  86. }
  87. // Argument types must match.
  88. if (![&]<std::size_t... Indexes>(std::index_sequence<Indexes...>) {
  89. return ((SignatureTraits::template arg_t<Indexes>::Check(
  90. sem_ir, state, arg_types[Indexes])) &&
  91. ...);
  92. }(std::make_index_sequence<SignatureTraits::num_args>())) {
  93. return false;
  94. }
  95. // Result type must match.
  96. if (!SignatureTraits::result_t::Check(sem_ir, state, return_type)) {
  97. return false;
  98. }
  99. return true;
  100. }
  101. // Descriptions of builtin functions follow. For each builtin, a corresponding
  102. // `BuiltinInfo` constant is declared describing properties of that builtin.
  103. namespace BuiltinFunctionInfo {
  104. // Convenience name used in the builtin type signatures below for a first
  105. // generic type parameter that is constrained to be an integer type.
  106. using IntT = TypeParam<0, AnyInt>;
  107. // Not a builtin function.
  108. constexpr BuiltinInfo None = {"", nullptr};
  109. // "int.negate": integer negation.
  110. constexpr BuiltinInfo IntNegate = {"int.negate",
  111. ValidateSignature<auto(IntT)->IntT>};
  112. // "int.add": integer addition.
  113. constexpr BuiltinInfo IntAdd = {"int.add",
  114. ValidateSignature<auto(IntT, IntT)->IntT>};
  115. // "int.sub": integer subtraction.
  116. constexpr BuiltinInfo IntSub = {"int.sub",
  117. ValidateSignature<auto(IntT, IntT)->IntT>};
  118. // "int.mul": integer multiplication.
  119. constexpr BuiltinInfo IntMul = {"int.mul",
  120. ValidateSignature<auto(IntT, IntT)->IntT>};
  121. // "int.div": integer division.
  122. constexpr BuiltinInfo IntDiv = {"int.div",
  123. ValidateSignature<auto(IntT, IntT)->IntT>};
  124. // "int.mod": integer modulo.
  125. constexpr BuiltinInfo IntMod = {"int.mod",
  126. ValidateSignature<auto(IntT, IntT)->IntT>};
  127. // "int.eq": integer equality comparison.
  128. constexpr BuiltinInfo IntEq = {"int.eq",
  129. ValidateSignature<auto(IntT, IntT)->Bool>};
  130. // "int.neq": integer non-equality comparison.
  131. constexpr BuiltinInfo IntNeq = {"int.neq",
  132. ValidateSignature<auto(IntT, IntT)->Bool>};
  133. } // namespace BuiltinFunctionInfo
  134. CARBON_DEFINE_ENUM_CLASS_NAMES(BuiltinFunctionKind) = {
  135. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  136. BuiltinFunctionInfo::Name.name,
  137. #include "toolchain/sem_ir/builtin_function_kind.def"
  138. };
  139. // Returns the builtin function kind with the given name, or None if the name
  140. // is unknown.
  141. auto BuiltinFunctionKind::ForBuiltinName(llvm::StringRef name)
  142. -> BuiltinFunctionKind {
  143. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  144. if (name == BuiltinFunctionInfo::Name.name) { \
  145. return BuiltinFunctionKind::Name; \
  146. }
  147. #include "toolchain/sem_ir/builtin_function_kind.def"
  148. return BuiltinFunctionKind::None;
  149. }
  150. // Returns the builtin function kind corresponding to the given function
  151. // callee, or None if the callee is not known to be a builtin.
  152. auto BuiltinFunctionKind::ForCallee(const File& sem_ir, InstId callee_id)
  153. -> BuiltinFunctionKind {
  154. if (auto bound_method =
  155. sem_ir.insts().TryGetAs<SemIR::BoundMethod>(callee_id)) {
  156. callee_id = bound_method->function_id;
  157. }
  158. callee_id = sem_ir.constant_values().Get(callee_id).inst_id();
  159. if (!callee_id.is_valid()) {
  160. return SemIR::BuiltinFunctionKind::None;
  161. }
  162. if (auto callee = sem_ir.insts().TryGetAs<SemIR::FunctionDecl>(callee_id)) {
  163. return sem_ir.functions().Get(callee->function_id).builtin_kind;
  164. }
  165. return SemIR::BuiltinFunctionKind::None;
  166. }
  167. auto BuiltinFunctionKind::IsValidType(const File& sem_ir,
  168. llvm::ArrayRef<TypeId> arg_types,
  169. TypeId return_type) const -> bool {
  170. static constexpr ValidateFn* ValidateFns[] = {
  171. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  172. BuiltinFunctionInfo::Name.validate,
  173. #include "toolchain/sem_ir/builtin_function_kind.def"
  174. };
  175. return ValidateFns[AsInt()](sem_ir, arg_types, return_type);
  176. }
  177. } // namespace Carbon::SemIR