builtin_function_kind.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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 = 2;
  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, 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. if (!TypeConstraint::Check(sem_ir, state, type_id)) {
  39. return false;
  40. }
  41. state.type_params[I] = type_id;
  42. return true;
  43. }
  44. };
  45. // Constraint that a type is a specific builtin. See ValidateSignature for
  46. // details.
  47. template <const InstId& BuiltinId>
  48. struct BuiltinType {
  49. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  50. TypeId type_id) -> bool {
  51. return sem_ir.types().GetInstId(type_id) == BuiltinId;
  52. }
  53. };
  54. // Constraint that the function has no return.
  55. struct NoReturn {
  56. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  57. TypeId type_id) -> bool {
  58. auto tuple = sem_ir.types().TryGetAs<SemIR::TupleType>(type_id);
  59. if (!tuple) {
  60. return false;
  61. }
  62. return sem_ir.type_blocks().Get(tuple->elements_id).empty();
  63. }
  64. };
  65. // Constraint that a type is `bool`.
  66. using Bool = BuiltinType<BoolType::SingletonInstId>;
  67. // Constraint that requires the type to be an integer type.
  68. struct AnyInt {
  69. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  70. -> bool {
  71. if (BuiltinType<IntLiteralType::SingletonInstId>::Check(sem_ir, state,
  72. type_id)) {
  73. return true;
  74. }
  75. return sem_ir.types().Is<IntType>(type_id);
  76. }
  77. };
  78. // Constraint that requires the type to be a float type.
  79. struct AnyFloat {
  80. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  81. -> bool {
  82. if (BuiltinType<LegacyFloatType::SingletonInstId>::Check(sem_ir, state,
  83. type_id)) {
  84. return true;
  85. }
  86. return sem_ir.types().Is<FloatType>(type_id);
  87. }
  88. };
  89. // Checks that the specified type matches the given type constraint.
  90. template <typename TypeConstraint>
  91. auto Check(const File& sem_ir, ValidateState& state, TypeId type_id) -> bool {
  92. while (type_id.is_valid()) {
  93. // Allow a type that satisfies the constraint.
  94. if (TypeConstraint::Check(sem_ir, state, type_id)) {
  95. return true;
  96. }
  97. // Also allow a class type that adapts a matching type.
  98. auto class_type = sem_ir.types().TryGetAs<ClassType>(type_id);
  99. if (!class_type) {
  100. break;
  101. }
  102. type_id = sem_ir.classes()
  103. .Get(class_type->class_id)
  104. .GetAdaptedType(sem_ir, class_type->specific_id);
  105. }
  106. return false;
  107. }
  108. // Constraint that requires the type to be the type type.
  109. using Type = BuiltinType<TypeType::SingletonInstId>;
  110. } // namespace
  111. // Validates that this builtin has a signature matching the specified signature.
  112. //
  113. // `SignatureFnType` is a C++ function type that describes the signature that is
  114. // expected for this builtin. For example, `auto (AnyInt, AnyInt) -> AnyInt`
  115. // specifies that the builtin takes values of two integer types and returns a
  116. // value of a third integer type. Types used within the signature should provide
  117. // a `Check` function that validates that the Carbon type is expected:
  118. //
  119. // auto Check(const File&, ValidateState&, TypeId) -> bool;
  120. //
  121. // To constrain that the same type is used in multiple places in the signature,
  122. // `TypeParam<I, T>` can be used. For example:
  123. //
  124. // auto (TypeParam<0, AnyInt>, AnyInt) -> TypeParam<0, AnyInt>
  125. //
  126. // describes a builtin that takes two integers, and whose return type matches
  127. // its first parameter type. For convenience, typedefs for `TypeParam<I, T>`
  128. // are used in the descriptions of the builtins.
  129. template <typename SignatureFnType>
  130. static auto ValidateSignature(const File& sem_ir,
  131. llvm::ArrayRef<TypeId> arg_types,
  132. TypeId return_type) -> bool {
  133. using SignatureTraits = llvm::function_traits<SignatureFnType*>;
  134. ValidateState state;
  135. // Must have expected number of arguments.
  136. if (arg_types.size() != SignatureTraits::num_args) {
  137. return false;
  138. }
  139. // Argument types must match.
  140. if (![&]<size_t... Indexes>(std::index_sequence<Indexes...>) {
  141. return ((Check<typename SignatureTraits::template arg_t<Indexes>>(
  142. sem_ir, state, arg_types[Indexes])) &&
  143. ...);
  144. }(std::make_index_sequence<SignatureTraits::num_args>())) {
  145. return false;
  146. }
  147. // Result type must match.
  148. if (!Check<typename SignatureTraits::result_t>(sem_ir, state, return_type)) {
  149. return false;
  150. }
  151. return true;
  152. }
  153. // Descriptions of builtin functions follow. For each builtin, a corresponding
  154. // `BuiltinInfo` constant is declared describing properties of that builtin.
  155. namespace BuiltinFunctionInfo {
  156. // Convenience name used in the builtin type signatures below for a first
  157. // generic type parameter that is constrained to be an integer type.
  158. using IntT = TypeParam<0, AnyInt>;
  159. // Convenience name used in the builtin type signatures below for a second
  160. // generic type parameter that is constrained to be an integer type.
  161. using IntU = TypeParam<1, AnyInt>;
  162. // Convenience name used in the builtin type signatures below for a first
  163. // generic type parameter that is constrained to be an float type.
  164. using FloatT = TypeParam<0, AnyFloat>;
  165. // Not a builtin function.
  166. constexpr BuiltinInfo None = {"", nullptr};
  167. // Prints an argument.
  168. constexpr BuiltinInfo PrintInt = {"print.int",
  169. ValidateSignature<auto(AnyInt)->NoReturn>};
  170. // Returns the `Core.IntLiteral` type.
  171. constexpr BuiltinInfo IntLiteralMakeType = {"int_literal.make_type",
  172. ValidateSignature<auto()->Type>};
  173. // Returns the `iN` type.
  174. // TODO: Should we use a more specific type as the type of the bit width?
  175. constexpr BuiltinInfo IntMakeTypeSigned = {
  176. "int.make_type_signed", ValidateSignature<auto(AnyInt)->Type>};
  177. // Returns the `uN` type.
  178. constexpr BuiltinInfo IntMakeTypeUnsigned = {
  179. "int.make_type_unsigned", ValidateSignature<auto(AnyInt)->Type>};
  180. // Returns float types, such as `f64`. Currently only supports `f64`.
  181. constexpr BuiltinInfo FloatMakeType = {"float.make_type",
  182. ValidateSignature<auto(AnyInt)->Type>};
  183. // Returns the `bool` type.
  184. constexpr BuiltinInfo BoolMakeType = {"bool.make_type",
  185. ValidateSignature<auto()->Type>};
  186. // Converts between integer types, with a diagnostic if the value doesn't fit.
  187. constexpr BuiltinInfo IntConvertChecked = {
  188. "int.convert_checked", ValidateSignature<auto(AnyInt)->AnyInt>};
  189. // "int.snegate": integer negation.
  190. constexpr BuiltinInfo IntSNegate = {"int.snegate",
  191. ValidateSignature<auto(IntT)->IntT>};
  192. // "int.sadd": integer addition.
  193. constexpr BuiltinInfo IntSAdd = {"int.sadd",
  194. ValidateSignature<auto(IntT, IntT)->IntT>};
  195. // "int.ssub": integer subtraction.
  196. constexpr BuiltinInfo IntSSub = {"int.ssub",
  197. ValidateSignature<auto(IntT, IntT)->IntT>};
  198. // "int.smul": integer multiplication.
  199. constexpr BuiltinInfo IntSMul = {"int.smul",
  200. ValidateSignature<auto(IntT, IntT)->IntT>};
  201. // "int.sdiv": integer division.
  202. constexpr BuiltinInfo IntSDiv = {"int.sdiv",
  203. ValidateSignature<auto(IntT, IntT)->IntT>};
  204. // "int.smod": integer modulo.
  205. constexpr BuiltinInfo IntSMod = {"int.smod",
  206. ValidateSignature<auto(IntT, IntT)->IntT>};
  207. // "int.unegate": unsigned integer negation.
  208. constexpr BuiltinInfo IntUNegate = {"int.unegate",
  209. ValidateSignature<auto(IntT)->IntT>};
  210. // "int.uadd": unsigned integer addition.
  211. constexpr BuiltinInfo IntUAdd = {"int.uadd",
  212. ValidateSignature<auto(IntT, IntT)->IntT>};
  213. // "int.usub": unsigned integer subtraction.
  214. constexpr BuiltinInfo IntUSub = {"int.usub",
  215. ValidateSignature<auto(IntT, IntT)->IntT>};
  216. // "int.umul": unsigned integer multiplication.
  217. constexpr BuiltinInfo IntUMul = {"int.umul",
  218. ValidateSignature<auto(IntT, IntT)->IntT>};
  219. // "int.udiv": unsigned integer division.
  220. constexpr BuiltinInfo IntUDiv = {"int.udiv",
  221. ValidateSignature<auto(IntT, IntT)->IntT>};
  222. // "int.mod": integer modulo.
  223. constexpr BuiltinInfo IntUMod = {"int.umod",
  224. ValidateSignature<auto(IntT, IntT)->IntT>};
  225. // "int.complement": integer bitwise complement.
  226. constexpr BuiltinInfo IntComplement = {"int.complement",
  227. ValidateSignature<auto(IntT)->IntT>};
  228. // "int.and": integer bitwise and.
  229. constexpr BuiltinInfo IntAnd = {"int.and",
  230. ValidateSignature<auto(IntT, IntT)->IntT>};
  231. // "int.or": integer bitwise or.
  232. constexpr BuiltinInfo IntOr = {"int.or",
  233. ValidateSignature<auto(IntT, IntT)->IntT>};
  234. // "int.xor": integer bitwise xor.
  235. constexpr BuiltinInfo IntXor = {"int.xor",
  236. ValidateSignature<auto(IntT, IntT)->IntT>};
  237. // "int.left_shift": integer left shift.
  238. constexpr BuiltinInfo IntLeftShift = {
  239. "int.left_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  240. // "int.left_shift": integer right shift.
  241. constexpr BuiltinInfo IntRightShift = {
  242. "int.right_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  243. // "int.eq": integer equality comparison.
  244. constexpr BuiltinInfo IntEq = {"int.eq",
  245. ValidateSignature<auto(IntT, IntT)->Bool>};
  246. // "int.neq": integer non-equality comparison.
  247. constexpr BuiltinInfo IntNeq = {"int.neq",
  248. ValidateSignature<auto(IntT, IntT)->Bool>};
  249. // "int.less": integer less than comparison.
  250. constexpr BuiltinInfo IntLess = {"int.less",
  251. ValidateSignature<auto(IntT, IntT)->Bool>};
  252. // "int.less_eq": integer less than or equal comparison.
  253. constexpr BuiltinInfo IntLessEq = {"int.less_eq",
  254. ValidateSignature<auto(IntT, IntT)->Bool>};
  255. // "int.greater": integer greater than comparison.
  256. constexpr BuiltinInfo IntGreater = {"int.greater",
  257. ValidateSignature<auto(IntT, IntT)->Bool>};
  258. // "int.greater_eq": integer greater than or equal comparison.
  259. constexpr BuiltinInfo IntGreaterEq = {
  260. "int.greater_eq", ValidateSignature<auto(IntT, IntT)->Bool>};
  261. // "float.negate": float negation.
  262. constexpr BuiltinInfo FloatNegate = {"float.negate",
  263. ValidateSignature<auto(FloatT)->FloatT>};
  264. // "float.add": float addition.
  265. constexpr BuiltinInfo FloatAdd = {
  266. "float.add", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  267. // "float.sub": float subtraction.
  268. constexpr BuiltinInfo FloatSub = {
  269. "float.sub", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  270. // "float.mul": float multiplication.
  271. constexpr BuiltinInfo FloatMul = {
  272. "float.mul", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  273. // "float.div": float division.
  274. constexpr BuiltinInfo FloatDiv = {
  275. "float.div", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  276. // "float.eq": float equality comparison.
  277. constexpr BuiltinInfo FloatEq = {"float.eq",
  278. ValidateSignature<auto(FloatT, FloatT)->Bool>};
  279. // "float.neq": float non-equality comparison.
  280. constexpr BuiltinInfo FloatNeq = {
  281. "float.neq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  282. // "float.less": float less than comparison.
  283. constexpr BuiltinInfo FloatLess = {
  284. "float.less", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  285. // "float.less_eq": float less than or equal comparison.
  286. constexpr BuiltinInfo FloatLessEq = {
  287. "float.less_eq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  288. // "float.greater": float greater than comparison.
  289. constexpr BuiltinInfo FloatGreater = {
  290. "float.greater", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  291. // "float.greater_eq": float greater than or equal comparison.
  292. constexpr BuiltinInfo FloatGreaterEq = {
  293. "float.greater_eq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  294. } // namespace BuiltinFunctionInfo
  295. CARBON_DEFINE_ENUM_CLASS_NAMES(BuiltinFunctionKind) = {
  296. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  297. BuiltinFunctionInfo::Name.name,
  298. #include "toolchain/sem_ir/builtin_function_kind.def"
  299. };
  300. // Returns the builtin function kind with the given name, or None if the name
  301. // is unknown.
  302. auto BuiltinFunctionKind::ForBuiltinName(llvm::StringRef name)
  303. -> BuiltinFunctionKind {
  304. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  305. if (name == BuiltinFunctionInfo::Name.name) { \
  306. return BuiltinFunctionKind::Name; \
  307. }
  308. #include "toolchain/sem_ir/builtin_function_kind.def"
  309. return BuiltinFunctionKind::None;
  310. }
  311. auto BuiltinFunctionKind::IsValidType(const File& sem_ir,
  312. llvm::ArrayRef<TypeId> arg_types,
  313. TypeId return_type) const -> bool {
  314. static constexpr ValidateFn* ValidateFns[] = {
  315. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  316. BuiltinFunctionInfo::Name.validate,
  317. #include "toolchain/sem_ir/builtin_function_kind.def"
  318. };
  319. return ValidateFns[AsInt()](sem_ir, arg_types, return_type);
  320. }
  321. auto BuiltinFunctionKind::IsCompTimeOnly() const -> bool {
  322. return *this == BuiltinFunctionKind::IntConvertChecked;
  323. }
  324. } // namespace Carbon::SemIR