builtin_function_kind.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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::None, TypeId::None};
  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].has_value() && 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 a type is `()`, used as the return type of builtin functions
  55. // with no return value.
  56. struct NoReturn {
  57. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  58. TypeId type_id) -> bool {
  59. auto tuple = sem_ir.types().TryGetAs<SemIR::TupleType>(type_id);
  60. if (!tuple) {
  61. return false;
  62. }
  63. return sem_ir.type_blocks().Get(tuple->elements_id).empty();
  64. }
  65. };
  66. // Constraint that a type is `bool`.
  67. using Bool = BuiltinType<BoolType::SingletonInstId>;
  68. // Constraint that requires the type to be a sized integer type.
  69. struct AnySizedInt {
  70. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  71. TypeId type_id) -> bool {
  72. return sem_ir.types().Is<IntType>(type_id);
  73. }
  74. };
  75. // Constraint that requires the type to be an integer type.
  76. struct AnyInt {
  77. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  78. -> bool {
  79. return AnySizedInt::Check(sem_ir, state, type_id) ||
  80. BuiltinType<IntLiteralType::SingletonInstId>::Check(sem_ir, state,
  81. type_id);
  82. }
  83. };
  84. // Constraint that requires the type to be a float type.
  85. struct AnyFloat {
  86. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  87. -> bool {
  88. if (BuiltinType<LegacyFloatType::SingletonInstId>::Check(sem_ir, state,
  89. type_id)) {
  90. return true;
  91. }
  92. return sem_ir.types().Is<FloatType>(type_id);
  93. }
  94. };
  95. // Checks that the specified type matches the given type constraint.
  96. template <typename TypeConstraint>
  97. auto Check(const File& sem_ir, ValidateState& state, TypeId type_id) -> bool {
  98. while (type_id.has_value()) {
  99. // Allow a type that satisfies the constraint.
  100. if (TypeConstraint::Check(sem_ir, state, type_id)) {
  101. return true;
  102. }
  103. // Also allow a class type that adapts a matching type.
  104. auto class_type = sem_ir.types().TryGetAs<ClassType>(type_id);
  105. if (!class_type) {
  106. break;
  107. }
  108. type_id = sem_ir.classes()
  109. .Get(class_type->class_id)
  110. .GetAdaptedType(sem_ir, class_type->specific_id);
  111. }
  112. return false;
  113. }
  114. // Constraint that requires the type to be the type type.
  115. using Type = BuiltinType<TypeType::SingletonInstId>;
  116. } // namespace
  117. // Validates that this builtin has a signature matching the specified signature.
  118. //
  119. // `SignatureFnType` is a C++ function type that describes the signature that is
  120. // expected for this builtin. For example, `auto (AnyInt, AnyInt) -> AnyInt`
  121. // specifies that the builtin takes values of two integer types and returns a
  122. // value of a third integer type. Types used within the signature should provide
  123. // a `Check` function that validates that the Carbon type is expected:
  124. //
  125. // auto Check(const File&, ValidateState&, TypeId) -> bool;
  126. //
  127. // To constrain that the same type is used in multiple places in the signature,
  128. // `TypeParam<I, T>` can be used. For example:
  129. //
  130. // auto (TypeParam<0, AnyInt>, AnyInt) -> TypeParam<0, AnyInt>
  131. //
  132. // describes a builtin that takes two integers, and whose return type matches
  133. // its first parameter type. For convenience, typedefs for `TypeParam<I, T>`
  134. // are used in the descriptions of the builtins.
  135. template <typename SignatureFnType>
  136. static auto ValidateSignature(const File& sem_ir,
  137. llvm::ArrayRef<TypeId> arg_types,
  138. TypeId return_type) -> bool {
  139. using SignatureTraits = llvm::function_traits<SignatureFnType*>;
  140. ValidateState state;
  141. // Must have expected number of arguments.
  142. if (arg_types.size() != SignatureTraits::num_args) {
  143. return false;
  144. }
  145. // Argument types must match.
  146. if (![&]<size_t... Indexes>(std::index_sequence<Indexes...>) {
  147. return ((Check<typename SignatureTraits::template arg_t<Indexes>>(
  148. sem_ir, state, arg_types[Indexes])) &&
  149. ...);
  150. }(std::make_index_sequence<SignatureTraits::num_args>())) {
  151. return false;
  152. }
  153. // Result type must match.
  154. if (!Check<typename SignatureTraits::result_t>(sem_ir, state, return_type)) {
  155. return false;
  156. }
  157. return true;
  158. }
  159. // Descriptions of builtin functions follow. For each builtin, a corresponding
  160. // `BuiltinInfo` constant is declared describing properties of that builtin.
  161. namespace BuiltinFunctionInfo {
  162. // Convenience name used in the builtin type signatures below for a first
  163. // generic type parameter that is constrained to be an integer type.
  164. using IntT = TypeParam<0, AnyInt>;
  165. // Convenience name used in the builtin type signatures below for a second
  166. // generic type parameter that is constrained to be an integer type.
  167. using IntU = TypeParam<1, AnyInt>;
  168. // Convenience name used in the builtin type signatures below for a first
  169. // generic type parameter that is constrained to be a sized integer type.
  170. using SizedIntT = TypeParam<0, AnySizedInt>;
  171. // Convenience name used in the builtin type signatures below for a first
  172. // generic type parameter that is constrained to be an float type.
  173. using FloatT = TypeParam<0, AnyFloat>;
  174. // Not a builtin function.
  175. constexpr BuiltinInfo None = {"", nullptr};
  176. // Prints a single character.
  177. constexpr BuiltinInfo PrintChar = {
  178. "print.char", ValidateSignature<auto(AnySizedInt)->AnySizedInt>};
  179. // Prints an integer.
  180. constexpr BuiltinInfo PrintInt = {
  181. "print.int", ValidateSignature<auto(AnySizedInt)->NoReturn>};
  182. // Reads a single character from stdin.
  183. constexpr BuiltinInfo ReadChar = {"read.char",
  184. ValidateSignature<auto()->AnySizedInt>};
  185. // Returns the `Core.IntLiteral` type.
  186. constexpr BuiltinInfo IntLiteralMakeType = {"int_literal.make_type",
  187. ValidateSignature<auto()->Type>};
  188. // Returns the `iN` type.
  189. // TODO: Should we use a more specific type as the type of the bit width?
  190. constexpr BuiltinInfo IntMakeTypeSigned = {
  191. "int.make_type_signed", ValidateSignature<auto(AnyInt)->Type>};
  192. // Returns the `uN` type.
  193. constexpr BuiltinInfo IntMakeTypeUnsigned = {
  194. "int.make_type_unsigned", ValidateSignature<auto(AnyInt)->Type>};
  195. // Returns float types, such as `f64`. Currently only supports `f64`.
  196. constexpr BuiltinInfo FloatMakeType = {"float.make_type",
  197. ValidateSignature<auto(AnyInt)->Type>};
  198. // Returns the `bool` type.
  199. constexpr BuiltinInfo BoolMakeType = {"bool.make_type",
  200. ValidateSignature<auto()->Type>};
  201. // Converts between integer types, truncating if necessary.
  202. constexpr BuiltinInfo IntConvert = {"int.convert",
  203. ValidateSignature<auto(AnyInt)->AnyInt>};
  204. // Converts between integer types, with a diagnostic if the value doesn't fit.
  205. constexpr BuiltinInfo IntConvertChecked = {
  206. "int.convert_checked", ValidateSignature<auto(AnyInt)->AnyInt>};
  207. // "int.snegate": integer negation.
  208. constexpr BuiltinInfo IntSNegate = {"int.snegate",
  209. ValidateSignature<auto(IntT)->IntT>};
  210. // "int.sadd": integer addition.
  211. constexpr BuiltinInfo IntSAdd = {"int.sadd",
  212. ValidateSignature<auto(IntT, IntT)->IntT>};
  213. // "int.ssub": integer subtraction.
  214. constexpr BuiltinInfo IntSSub = {"int.ssub",
  215. ValidateSignature<auto(IntT, IntT)->IntT>};
  216. // "int.smul": integer multiplication.
  217. constexpr BuiltinInfo IntSMul = {"int.smul",
  218. ValidateSignature<auto(IntT, IntT)->IntT>};
  219. // "int.sdiv": integer division.
  220. constexpr BuiltinInfo IntSDiv = {"int.sdiv",
  221. ValidateSignature<auto(IntT, IntT)->IntT>};
  222. // "int.smod": integer modulo.
  223. constexpr BuiltinInfo IntSMod = {"int.smod",
  224. ValidateSignature<auto(IntT, IntT)->IntT>};
  225. // "int.unegate": unsigned integer negation.
  226. constexpr BuiltinInfo IntUNegate = {
  227. "int.unegate", ValidateSignature<auto(SizedIntT)->SizedIntT>};
  228. // "int.uadd": unsigned integer addition.
  229. constexpr BuiltinInfo IntUAdd = {
  230. "int.uadd", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  231. // "int.usub": unsigned integer subtraction.
  232. constexpr BuiltinInfo IntUSub = {
  233. "int.usub", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  234. // "int.umul": unsigned integer multiplication.
  235. constexpr BuiltinInfo IntUMul = {
  236. "int.umul", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  237. // "int.udiv": unsigned integer division.
  238. constexpr BuiltinInfo IntUDiv = {
  239. "int.udiv", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  240. // "int.mod": integer modulo.
  241. constexpr BuiltinInfo IntUMod = {
  242. "int.umod", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  243. // "int.complement": integer bitwise complement.
  244. constexpr BuiltinInfo IntComplement = {"int.complement",
  245. ValidateSignature<auto(IntT)->IntT>};
  246. // "int.and": integer bitwise and.
  247. constexpr BuiltinInfo IntAnd = {"int.and",
  248. ValidateSignature<auto(IntT, IntT)->IntT>};
  249. // "int.or": integer bitwise or.
  250. constexpr BuiltinInfo IntOr = {"int.or",
  251. ValidateSignature<auto(IntT, IntT)->IntT>};
  252. // "int.xor": integer bitwise xor.
  253. constexpr BuiltinInfo IntXor = {"int.xor",
  254. ValidateSignature<auto(IntT, IntT)->IntT>};
  255. // "int.left_shift": integer left shift.
  256. constexpr BuiltinInfo IntLeftShift = {
  257. "int.left_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  258. // "int.left_shift": integer right shift.
  259. constexpr BuiltinInfo IntRightShift = {
  260. "int.right_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  261. // "int.eq": integer equality comparison.
  262. constexpr BuiltinInfo IntEq = {"int.eq",
  263. ValidateSignature<auto(IntT, IntU)->Bool>};
  264. // "int.neq": integer non-equality comparison.
  265. constexpr BuiltinInfo IntNeq = {"int.neq",
  266. ValidateSignature<auto(IntT, IntU)->Bool>};
  267. // "int.less": integer less than comparison.
  268. constexpr BuiltinInfo IntLess = {"int.less",
  269. ValidateSignature<auto(IntT, IntU)->Bool>};
  270. // "int.less_eq": integer less than or equal comparison.
  271. constexpr BuiltinInfo IntLessEq = {"int.less_eq",
  272. ValidateSignature<auto(IntT, IntU)->Bool>};
  273. // "int.greater": integer greater than comparison.
  274. constexpr BuiltinInfo IntGreater = {"int.greater",
  275. ValidateSignature<auto(IntT, IntU)->Bool>};
  276. // "int.greater_eq": integer greater than or equal comparison.
  277. constexpr BuiltinInfo IntGreaterEq = {
  278. "int.greater_eq", ValidateSignature<auto(IntT, IntU)->Bool>};
  279. // "float.negate": float negation.
  280. constexpr BuiltinInfo FloatNegate = {"float.negate",
  281. ValidateSignature<auto(FloatT)->FloatT>};
  282. // "float.add": float addition.
  283. constexpr BuiltinInfo FloatAdd = {
  284. "float.add", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  285. // "float.sub": float subtraction.
  286. constexpr BuiltinInfo FloatSub = {
  287. "float.sub", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  288. // "float.mul": float multiplication.
  289. constexpr BuiltinInfo FloatMul = {
  290. "float.mul", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  291. // "float.div": float division.
  292. constexpr BuiltinInfo FloatDiv = {
  293. "float.div", ValidateSignature<auto(FloatT, FloatT)->FloatT>};
  294. // "float.eq": float equality comparison.
  295. constexpr BuiltinInfo FloatEq = {"float.eq",
  296. ValidateSignature<auto(FloatT, FloatT)->Bool>};
  297. // "float.neq": float non-equality comparison.
  298. constexpr BuiltinInfo FloatNeq = {
  299. "float.neq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  300. // "float.less": float less than comparison.
  301. constexpr BuiltinInfo FloatLess = {
  302. "float.less", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  303. // "float.less_eq": float less than or equal comparison.
  304. constexpr BuiltinInfo FloatLessEq = {
  305. "float.less_eq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  306. // "float.greater": float greater than comparison.
  307. constexpr BuiltinInfo FloatGreater = {
  308. "float.greater", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  309. // "float.greater_eq": float greater than or equal comparison.
  310. constexpr BuiltinInfo FloatGreaterEq = {
  311. "float.greater_eq", ValidateSignature<auto(FloatT, FloatT)->Bool>};
  312. // "bool.eq": bool equality comparison.
  313. constexpr BuiltinInfo BoolEq = {"bool.eq",
  314. ValidateSignature<auto(Bool, Bool)->Bool>};
  315. // "bool.neq": bool non-equality comparison.
  316. constexpr BuiltinInfo BoolNeq = {"bool.neq",
  317. ValidateSignature<auto(Bool, Bool)->Bool>};
  318. } // namespace BuiltinFunctionInfo
  319. CARBON_DEFINE_ENUM_CLASS_NAMES(BuiltinFunctionKind) = {
  320. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  321. BuiltinFunctionInfo::Name.name,
  322. #include "toolchain/sem_ir/builtin_function_kind.def"
  323. };
  324. // Returns the builtin function kind with the given name, or None if the name
  325. // is unknown.
  326. auto BuiltinFunctionKind::ForBuiltinName(llvm::StringRef name)
  327. -> BuiltinFunctionKind {
  328. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  329. if (name == BuiltinFunctionInfo::Name.name) { \
  330. return BuiltinFunctionKind::Name; \
  331. }
  332. #include "toolchain/sem_ir/builtin_function_kind.def"
  333. return BuiltinFunctionKind::None;
  334. }
  335. auto BuiltinFunctionKind::IsValidType(const File& sem_ir,
  336. llvm::ArrayRef<TypeId> arg_types,
  337. TypeId return_type) const -> bool {
  338. static constexpr ValidateFn* ValidateFns[] = {
  339. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  340. BuiltinFunctionInfo::Name.validate,
  341. #include "toolchain/sem_ir/builtin_function_kind.def"
  342. };
  343. return ValidateFns[AsInt()](sem_ir, arg_types, return_type);
  344. }
  345. // Determines whether a builtin call involves an integer literal in its
  346. // arguments or return type. If so, for many builtins we want to treat the call
  347. // as being compile-time-only. This is because `Core.IntLiteral` has an empty
  348. // runtime representation, and a value of that type isn't necessarily a
  349. // compile-time constant, so an arbitrary runtime value of type
  350. // `Core.IntLiteral` may not have a value available for the builtin to use. For
  351. // example, given:
  352. //
  353. // var n: Core.IntLiteral() = 123;
  354. //
  355. // we would be unable to lower a runtime operation such as `(1 as i32) << n`
  356. // because the runtime representation of `n` doesn't track its value at all.
  357. //
  358. // For now, we treat all operations involving `Core.IntLiteral` as being
  359. // compile-time-only.
  360. //
  361. // TODO: We will need to accept things like `some_i32 << 5` eventually. We could
  362. // allow builtin calls at runtime if all the IntLiteral arguments have constant
  363. // values, or add logic to the prelude to promote the `IntLiteral` operand to a
  364. // different type in such cases.
  365. //
  366. // TODO: For now, we also treat builtins *returning* `Core.IntLiteral` as being
  367. // compile-time-only. This is mostly done for simplicity, but should probably be
  368. // revisited.
  369. static auto AnyIntLiteralTypes(const File& sem_ir,
  370. llvm::ArrayRef<InstId> arg_ids,
  371. TypeId return_type_id) -> bool {
  372. if (sem_ir.types().Is<SemIR::IntLiteralType>(return_type_id)) {
  373. return true;
  374. }
  375. for (auto arg_id : arg_ids) {
  376. if (sem_ir.types().Is<SemIR::IntLiteralType>(
  377. sem_ir.insts().Get(arg_id).type_id())) {
  378. return true;
  379. }
  380. }
  381. return false;
  382. }
  383. auto BuiltinFunctionKind::IsCompTimeOnly(const File& sem_ir,
  384. llvm::ArrayRef<InstId> arg_ids,
  385. TypeId return_type_id) const -> bool {
  386. switch (*this) {
  387. case IntConvertChecked:
  388. // Checked integer conversions are compile-time only.
  389. return true;
  390. case IntConvert:
  391. case IntSNegate:
  392. case IntComplement:
  393. case IntSAdd:
  394. case IntSSub:
  395. case IntSMul:
  396. case IntSDiv:
  397. case IntSMod:
  398. case IntAnd:
  399. case IntOr:
  400. case IntXor:
  401. case IntLeftShift:
  402. case IntRightShift:
  403. case IntEq:
  404. case IntNeq:
  405. case IntLess:
  406. case IntLessEq:
  407. case IntGreater:
  408. case IntGreaterEq:
  409. // Integer operations are compile-time-only if they involve integer
  410. // literal types. See AnyIntLiteralTypes comment for explanation.
  411. return AnyIntLiteralTypes(sem_ir, arg_ids, return_type_id);
  412. default:
  413. // TODO: Should the sized MakeType functions be compile-time only? We
  414. // can't produce diagnostics for bad sizes at runtime.
  415. return false;
  416. }
  417. }
  418. } // namespace Carbon::SemIR