builtin_function_kind.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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/type_info.h"
  9. #include "toolchain/sem_ir/typed_insts.h"
  10. namespace Carbon::SemIR {
  11. // A function that validates that a builtin was declared properly.
  12. using ValidateFn = auto(const File& sem_ir, llvm::ArrayRef<TypeId> arg_types,
  13. TypeId return_type) -> bool;
  14. namespace {
  15. // Information about a builtin function.
  16. struct BuiltinInfo {
  17. llvm::StringLiteral name;
  18. ValidateFn* validate;
  19. };
  20. // The maximum number of type parameters any builtin needs.
  21. constexpr int MaxTypeParams = 2;
  22. // State used when validating a builtin signature that persists between
  23. // individual checks.
  24. struct ValidateState {
  25. // The type values of type parameters in the builtin signature. Invalid if
  26. // either no value has been deduced yet or the parameter is not used.
  27. TypeId type_params[MaxTypeParams] = {TypeId::None, TypeId::None};
  28. };
  29. template <typename TypeConstraint>
  30. auto Check(const File& sem_ir, ValidateState& state, TypeId type_id) -> bool;
  31. // Constraint that a type is generic type parameter `I` of the builtin,
  32. // satisfying `TypeConstraint`. See ValidateSignature for details.
  33. template <int I, typename TypeConstraint>
  34. struct TypeParam {
  35. static_assert(I >= 0 && I < MaxTypeParams);
  36. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  37. -> bool {
  38. if (state.type_params[I].has_value() && type_id != state.type_params[I]) {
  39. return false;
  40. }
  41. if (!TypeConstraint::Check(sem_ir, state, type_id)) {
  42. return false;
  43. }
  44. state.type_params[I] = type_id;
  45. return true;
  46. }
  47. };
  48. // Constraint that a type is a specific builtin. See ValidateSignature for
  49. // details.
  50. template <const TypeInstId& BuiltinId>
  51. struct BuiltinType {
  52. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  53. TypeId type_id) -> bool {
  54. return sem_ir.types().GetInstId(type_id) == BuiltinId;
  55. }
  56. };
  57. // Constraint that a type is a pointer to another type. See ValidateSignature
  58. // for details.
  59. template <typename PointeeT>
  60. struct PointerTo {
  61. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  62. -> bool {
  63. if (!sem_ir.types().Is<PointerType>(type_id)) {
  64. return false;
  65. }
  66. return Check<PointeeT>(sem_ir, state, sem_ir.GetPointeeType(type_id));
  67. }
  68. };
  69. // Constraint that a type is `()`, used as the return type of builtin functions
  70. // with no return value.
  71. struct NoReturn {
  72. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  73. TypeId type_id) -> bool {
  74. auto tuple = sem_ir.types().TryGetAs<TupleType>(type_id);
  75. if (!tuple) {
  76. return false;
  77. }
  78. return sem_ir.inst_blocks().Get(tuple->type_elements_id).empty();
  79. }
  80. };
  81. // Constraint that a type is `bool`.
  82. using Bool = BuiltinType<BoolType::TypeInstId>;
  83. // Constraint that a type is `Core.CharLiteral`.
  84. using CharLiteral = BuiltinType<CharLiteralType::TypeInstId>;
  85. // Constraint that a type is `u8` or an adapted type, including `Core.Char`.
  86. struct CharCompatible {
  87. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  88. TypeId type_id) -> bool {
  89. auto int_info = sem_ir.types().TryGetIntTypeInfo(type_id);
  90. if (!int_info) {
  91. // Not an integer.
  92. return false;
  93. }
  94. if (!int_info->bit_width.has_value() || int_info->is_signed) {
  95. // Must be unsigned.
  96. return false;
  97. }
  98. return sem_ir.ints().Get(int_info->bit_width) == 8;
  99. }
  100. };
  101. // Constraint that requires the type to be a sized integer type.
  102. struct AnySizedInt {
  103. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  104. TypeId type_id) -> bool {
  105. return sem_ir.types().Is<IntType>(type_id);
  106. }
  107. };
  108. // Constraint that requires the type to be an integer type: either a sized
  109. // integer type or a literal.
  110. struct AnyInt {
  111. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  112. -> bool {
  113. return AnySizedInt::Check(sem_ir, state, type_id) ||
  114. BuiltinType<IntLiteralType::TypeInstId>::Check(sem_ir, state,
  115. type_id);
  116. }
  117. };
  118. // Constraint that requires the type to be a sized floating-point type.
  119. struct AnySizedFloat {
  120. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  121. TypeId type_id) -> bool {
  122. return sem_ir.types().Is<FloatType>(type_id);
  123. }
  124. };
  125. // Constraint that requires the type to be a float type: either a sized float
  126. // type or a literal.
  127. struct AnyFloat {
  128. static auto Check(const File& sem_ir, ValidateState& state, TypeId type_id)
  129. -> bool {
  130. return AnySizedFloat::Check(sem_ir, state, type_id) ||
  131. BuiltinType<FloatLiteralType::TypeInstId>::Check(sem_ir, state,
  132. type_id);
  133. }
  134. };
  135. // Constraint that allows an arbitrary type.
  136. struct AnyType {
  137. static auto Check(const File& /*sem_ir*/, ValidateState& /*state*/,
  138. TypeId /*type_id*/) -> bool {
  139. return true;
  140. }
  141. };
  142. // Constraint that requires the type to be the type type.
  143. using Type = BuiltinType<TypeType::TypeInstId>;
  144. // Constraint that a type supports a primitive copy. This happens if its
  145. // initializing representation is a copy of its value representation.
  146. struct PrimitiveCopyable {
  147. static auto Check(const File& sem_ir, ValidateState& /*state*/,
  148. TypeId type_id) -> bool {
  149. return InitRepr::ForType(sem_ir, type_id).IsCopyOfObjectRepr() &&
  150. ValueRepr::ForType(sem_ir, type_id)
  151. .IsCopyOfObjectRepr(sem_ir, type_id);
  152. }
  153. };
  154. // Checks that the specified type matches the given type constraint.
  155. template <typename TypeConstraint>
  156. auto Check(const File& sem_ir, ValidateState& state, TypeId type_id) -> bool {
  157. while (type_id.has_value()) {
  158. // Allow a type that satisfies the constraint.
  159. if (TypeConstraint::Check(sem_ir, state, type_id)) {
  160. return true;
  161. }
  162. // Also allow a class type that adapts a matching type.
  163. type_id = sem_ir.types().GetAdaptedType(type_id);
  164. }
  165. return false;
  166. }
  167. } // namespace
  168. // Validates that this builtin has a signature matching the specified signature.
  169. //
  170. // `SignatureFnType` is a C++ function type that describes the signature that is
  171. // expected for this builtin. For example, `auto (AnyInt, AnyInt) -> AnyInt`
  172. // specifies that the builtin takes values of two integer types and returns a
  173. // value of a third integer type. Types used within the signature should provide
  174. // a `Check` function that validates that the Carbon type is expected:
  175. //
  176. // auto Check(const File&, ValidateState&, TypeId) -> bool;
  177. //
  178. // To constrain that the same type is used in multiple places in the signature,
  179. // `TypeParam<I, T>` can be used. For example:
  180. //
  181. // auto (TypeParam<0, AnyInt>, AnyInt) -> TypeParam<0, AnyInt>
  182. //
  183. // describes a builtin that takes two integers, and whose return type matches
  184. // its first parameter type. For convenience, typedefs for `TypeParam<I, T>`
  185. // are used in the descriptions of the builtins.
  186. template <typename SignatureFnType>
  187. static auto ValidateSignature(const File& sem_ir,
  188. llvm::ArrayRef<TypeId> arg_types,
  189. TypeId return_type) -> bool {
  190. using SignatureTraits = llvm::function_traits<SignatureFnType*>;
  191. ValidateState state;
  192. // Must have expected number of arguments.
  193. if (arg_types.size() != SignatureTraits::num_args) {
  194. return false;
  195. }
  196. // Argument types must match.
  197. if (![&]<size_t... Indexes>(std::index_sequence<Indexes...>) {
  198. return ((Check<typename SignatureTraits::template arg_t<Indexes>>(
  199. sem_ir, state, arg_types[Indexes])) &&
  200. ...);
  201. }(std::make_index_sequence<SignatureTraits::num_args>())) {
  202. return false;
  203. }
  204. // Result type must match.
  205. if (!Check<typename SignatureTraits::result_t>(sem_ir, state, return_type)) {
  206. return false;
  207. }
  208. return true;
  209. }
  210. // Validates the signature for NoOp. This ignores all arguments, only validating
  211. // that the return type is compatible.
  212. static auto ValidateNoOpSignature(const File& sem_ir,
  213. llvm::ArrayRef<TypeId> /*arg_types*/,
  214. TypeId return_type) -> bool {
  215. ValidateState state;
  216. return Check<NoReturn>(sem_ir, state, return_type);
  217. }
  218. // Descriptions of builtin functions follow. For each builtin, a corresponding
  219. // `BuiltinInfo` constant is declared describing properties of that builtin.
  220. namespace BuiltinFunctionInfo {
  221. // Convenience name used in the builtin type signatures below for a first
  222. // generic type parameter that is constrained to be an integer type.
  223. using IntT = TypeParam<0, AnyInt>;
  224. // Convenience name used in the builtin type signatures below for a second
  225. // generic type parameter that is constrained to be an integer type.
  226. using IntU = TypeParam<1, AnyInt>;
  227. // Convenience name used in the builtin type signatures below for a first
  228. // generic type parameter that is constrained to be a sized integer type.
  229. using SizedIntT = TypeParam<0, AnySizedInt>;
  230. // Convenience name used in the builtin type signatures below for a second
  231. // generic type parameter that is constrained to be a sized integer type.
  232. using SizedIntU = TypeParam<1, AnySizedInt>;
  233. // Convenience name used in the builtin type signatures below for a first
  234. // generic type parameter that is constrained to be an float type.
  235. using FloatT = TypeParam<0, AnyFloat>;
  236. // Convenience name used in the builtin type signatures below for a second
  237. // generic type parameter that is constrained to be an float type.
  238. using FloatU = TypeParam<1, AnyFloat>;
  239. // Convenience name used in the builtin type signatures below for a first
  240. // generic type parameter that is constrained to be a sized float type.
  241. using SizedFloatT = TypeParam<0, AnySizedFloat>;
  242. // Convenience name used in the builtin type signatures below for a first
  243. // generic type parameter that supports primitive copy.
  244. using PrimitiveCopyParamT = TypeParam<0, PrimitiveCopyable>;
  245. // Not a builtin function.
  246. constexpr BuiltinInfo None = {"", nullptr};
  247. constexpr BuiltinInfo NoOp = {"no_op", ValidateNoOpSignature};
  248. constexpr BuiltinInfo PrimitiveCopy = {
  249. "primitive_copy",
  250. ValidateSignature<auto(PrimitiveCopyParamT)->PrimitiveCopyParamT>};
  251. // Prints a single character.
  252. constexpr BuiltinInfo PrintChar = {
  253. "print.char", ValidateSignature<auto(AnySizedInt)->AnySizedInt>};
  254. // Prints an integer.
  255. constexpr BuiltinInfo PrintInt = {
  256. "print.int", ValidateSignature<auto(AnySizedInt)->NoReturn>};
  257. // Reads a single character from stdin.
  258. constexpr BuiltinInfo ReadChar = {"read.char",
  259. ValidateSignature<auto()->AnySizedInt>};
  260. // Returns the `Core.CharLiteral` type.
  261. constexpr BuiltinInfo CharLiteralMakeType = {"char_literal.make_type",
  262. ValidateSignature<auto()->Type>};
  263. // Returns the `Core.IntLiteral` type.
  264. constexpr BuiltinInfo IntLiteralMakeType = {"int_literal.make_type",
  265. ValidateSignature<auto()->Type>};
  266. // Returns the `Core.FloatLiteral` type.
  267. constexpr BuiltinInfo FloatLiteralMakeType = {"float_literal.make_type",
  268. ValidateSignature<auto()->Type>};
  269. // Returns the `iN` type.
  270. // TODO: Should we use a more specific type as the type of the bit width?
  271. constexpr BuiltinInfo IntMakeTypeSigned = {
  272. "int.make_type_signed", ValidateSignature<auto(AnyInt)->Type>};
  273. // Returns the `uN` type.
  274. constexpr BuiltinInfo IntMakeTypeUnsigned = {
  275. "int.make_type_unsigned", ValidateSignature<auto(AnyInt)->Type>};
  276. // Returns float types, such as `f64`. Currently only supports `f64`.
  277. constexpr BuiltinInfo FloatMakeType = {"float.make_type",
  278. ValidateSignature<auto(AnyInt)->Type>};
  279. // Returns the `bool` type.
  280. constexpr BuiltinInfo BoolMakeType = {"bool.make_type",
  281. ValidateSignature<auto()->Type>};
  282. // Returns the `MaybeUnformed(T)` type.
  283. constexpr BuiltinInfo MaybeUnformedMakeType = {
  284. "maybe_unformed.make_type", ValidateSignature<auto(Type)->Type>};
  285. // Converts between char types, with a diagnostic if the value doesn't fit.
  286. constexpr BuiltinInfo CharConvertChecked = {
  287. "char.convert_checked",
  288. ValidateSignature<auto(CharLiteral)->CharCompatible>};
  289. // Converts between integer types, truncating if necessary.
  290. constexpr BuiltinInfo IntConvert = {"int.convert",
  291. ValidateSignature<auto(AnyInt)->AnyInt>};
  292. // Converts between integer types, with a diagnostic if the value doesn't fit.
  293. constexpr BuiltinInfo IntConvertChecked = {
  294. "int.convert_checked", ValidateSignature<auto(AnyInt)->AnyInt>};
  295. // "int.snegate": integer negation.
  296. constexpr BuiltinInfo IntSNegate = {"int.snegate",
  297. ValidateSignature<auto(IntT)->IntT>};
  298. // "int.sadd": integer addition.
  299. constexpr BuiltinInfo IntSAdd = {"int.sadd",
  300. ValidateSignature<auto(IntT, IntT)->IntT>};
  301. // "int.ssub": integer subtraction.
  302. constexpr BuiltinInfo IntSSub = {"int.ssub",
  303. ValidateSignature<auto(IntT, IntT)->IntT>};
  304. // "int.smul": integer multiplication.
  305. constexpr BuiltinInfo IntSMul = {"int.smul",
  306. ValidateSignature<auto(IntT, IntT)->IntT>};
  307. // "int.sdiv": integer division.
  308. constexpr BuiltinInfo IntSDiv = {"int.sdiv",
  309. ValidateSignature<auto(IntT, IntT)->IntT>};
  310. // "int.smod": integer modulo.
  311. constexpr BuiltinInfo IntSMod = {"int.smod",
  312. ValidateSignature<auto(IntT, IntT)->IntT>};
  313. // "int.unegate": unsigned integer negation.
  314. constexpr BuiltinInfo IntUNegate = {
  315. "int.unegate", ValidateSignature<auto(SizedIntT)->SizedIntT>};
  316. // "int.uadd": unsigned integer addition.
  317. constexpr BuiltinInfo IntUAdd = {
  318. "int.uadd", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  319. // "int.usub": unsigned integer subtraction.
  320. constexpr BuiltinInfo IntUSub = {
  321. "int.usub", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  322. // "int.umul": unsigned integer multiplication.
  323. constexpr BuiltinInfo IntUMul = {
  324. "int.umul", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  325. // "int.udiv": unsigned integer division.
  326. constexpr BuiltinInfo IntUDiv = {
  327. "int.udiv", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  328. // "int.mod": integer modulo.
  329. constexpr BuiltinInfo IntUMod = {
  330. "int.umod", ValidateSignature<auto(SizedIntT, SizedIntT)->SizedIntT>};
  331. // "int.complement": integer bitwise complement.
  332. constexpr BuiltinInfo IntComplement = {"int.complement",
  333. ValidateSignature<auto(IntT)->IntT>};
  334. // "int.and": integer bitwise and.
  335. constexpr BuiltinInfo IntAnd = {"int.and",
  336. ValidateSignature<auto(IntT, IntT)->IntT>};
  337. // "int.or": integer bitwise or.
  338. constexpr BuiltinInfo IntOr = {"int.or",
  339. ValidateSignature<auto(IntT, IntT)->IntT>};
  340. // "int.xor": integer bitwise xor.
  341. constexpr BuiltinInfo IntXor = {"int.xor",
  342. ValidateSignature<auto(IntT, IntT)->IntT>};
  343. // "int.left_shift": integer left shift.
  344. constexpr BuiltinInfo IntLeftShift = {
  345. "int.left_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  346. // "int.right_shift": integer right shift.
  347. constexpr BuiltinInfo IntRightShift = {
  348. "int.right_shift", ValidateSignature<auto(IntT, IntU)->IntT>};
  349. // "int.sadd_assign": integer in-place addition.
  350. constexpr BuiltinInfo IntSAddAssign = {
  351. "int.sadd_assign",
  352. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  353. // "int.ssub_assign": integer in-place subtraction.
  354. constexpr BuiltinInfo IntSSubAssign = {
  355. "int.ssub_assign",
  356. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  357. // "int.smul_assign": integer in-place multiplication.
  358. constexpr BuiltinInfo IntSMulAssign = {
  359. "int.smul_assign",
  360. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  361. // "int.sdiv_assign": integer in-place division.
  362. constexpr BuiltinInfo IntSDivAssign = {
  363. "int.sdiv_assign",
  364. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  365. // "int.smod_assign": integer in-place modulo.
  366. constexpr BuiltinInfo IntSModAssign = {
  367. "int.smod_assign",
  368. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  369. // "int.uadd_assign": unsigned integer in-place addition.
  370. constexpr BuiltinInfo IntUAddAssign = {
  371. "int.uadd_assign",
  372. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  373. // "int.usub_assign": unsigned integer in-place subtraction.
  374. constexpr BuiltinInfo IntUSubAssign = {
  375. "int.usub_assign",
  376. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  377. // "int.umul_assign": unsigned integer in-place multiplication.
  378. constexpr BuiltinInfo IntUMulAssign = {
  379. "int.umul_assign",
  380. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  381. // "int.udiv_assign": unsigned integer in-place division.
  382. constexpr BuiltinInfo IntUDivAssign = {
  383. "int.udiv_assign",
  384. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  385. // "int.mod_assign": integer in-place modulo.
  386. constexpr BuiltinInfo IntUModAssign = {
  387. "int.umod_assign",
  388. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  389. // "int.and_assign": integer in-place bitwise and.
  390. constexpr BuiltinInfo IntAndAssign = {
  391. "int.and_assign",
  392. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  393. // "int.or_assign": integer in-place bitwise or.
  394. constexpr BuiltinInfo IntOrAssign = {
  395. "int.or_assign",
  396. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  397. // "int.xor_assign": integer in-place bitwise xor.
  398. constexpr BuiltinInfo IntXorAssign = {
  399. "int.xor_assign",
  400. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntT)->NoReturn>};
  401. // "int.left_shift_assign": integer in-place left shift.
  402. constexpr BuiltinInfo IntLeftShiftAssign = {
  403. "int.left_shift_assign",
  404. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntU)->NoReturn>};
  405. // "int.right_shift_assign": integer in-place right shift.
  406. constexpr BuiltinInfo IntRightShiftAssign = {
  407. "int.right_shift_assign",
  408. ValidateSignature<auto(PointerTo<SizedIntT>, SizedIntU)->NoReturn>};
  409. // "int.eq": integer equality comparison.
  410. constexpr BuiltinInfo IntEq = {"int.eq",
  411. ValidateSignature<auto(IntT, IntU)->Bool>};
  412. // "int.neq": integer non-equality comparison.
  413. constexpr BuiltinInfo IntNeq = {"int.neq",
  414. ValidateSignature<auto(IntT, IntU)->Bool>};
  415. // "int.less": integer less than comparison.
  416. constexpr BuiltinInfo IntLess = {"int.less",
  417. ValidateSignature<auto(IntT, IntU)->Bool>};
  418. // "int.less_eq": integer less than or equal comparison.
  419. constexpr BuiltinInfo IntLessEq = {"int.less_eq",
  420. ValidateSignature<auto(IntT, IntU)->Bool>};
  421. // "int.greater": integer greater than comparison.
  422. constexpr BuiltinInfo IntGreater = {"int.greater",
  423. ValidateSignature<auto(IntT, IntU)->Bool>};
  424. // "int.greater_eq": integer greater than or equal comparison.
  425. constexpr BuiltinInfo IntGreaterEq = {
  426. "int.greater_eq", ValidateSignature<auto(IntT, IntU)->Bool>};
  427. // "float.negate": float negation.
  428. constexpr BuiltinInfo FloatNegate = {
  429. "float.negate", ValidateSignature<auto(SizedFloatT)->SizedFloatT>};
  430. // "float.add": float addition.
  431. constexpr BuiltinInfo FloatAdd = {
  432. "float.add",
  433. ValidateSignature<auto(SizedFloatT, SizedFloatT)->SizedFloatT>};
  434. // "float.sub": float subtraction.
  435. constexpr BuiltinInfo FloatSub = {
  436. "float.sub",
  437. ValidateSignature<auto(SizedFloatT, SizedFloatT)->SizedFloatT>};
  438. // "float.mul": float multiplication.
  439. constexpr BuiltinInfo FloatMul = {
  440. "float.mul",
  441. ValidateSignature<auto(SizedFloatT, SizedFloatT)->SizedFloatT>};
  442. // "float.div": float division.
  443. constexpr BuiltinInfo FloatDiv = {
  444. "float.div",
  445. ValidateSignature<auto(SizedFloatT, SizedFloatT)->SizedFloatT>};
  446. // "float.add_assign": float in-place addition.
  447. constexpr BuiltinInfo FloatAddAssign = {
  448. "float.add_assign",
  449. ValidateSignature<auto(PointerTo<SizedFloatT>, SizedFloatT)->NoReturn>};
  450. // "float.sub_assign": float in-place subtraction.
  451. constexpr BuiltinInfo FloatSubAssign = {
  452. "float.sub_assign",
  453. ValidateSignature<auto(PointerTo<SizedFloatT>, SizedFloatT)->NoReturn>};
  454. // "float.mul_assign": float in-place multiplication.
  455. constexpr BuiltinInfo FloatMulAssign = {
  456. "float.mul_assign",
  457. ValidateSignature<auto(PointerTo<SizedFloatT>, SizedFloatT)->NoReturn>};
  458. // "float.div_assign": float in-place division.
  459. constexpr BuiltinInfo FloatDivAssign = {
  460. "float.div_assign",
  461. ValidateSignature<auto(PointerTo<SizedFloatT>, SizedFloatT)->NoReturn>};
  462. // Converts between floating-point types, with a diagnostic if the value doesn't
  463. // fit.
  464. constexpr BuiltinInfo FloatConvertChecked = {
  465. "float.convert_checked", ValidateSignature<auto(FloatT)->FloatU>};
  466. // "float.eq": float equality comparison.
  467. constexpr BuiltinInfo FloatEq = {
  468. "float.eq", ValidateSignature<auto(SizedFloatT, SizedFloatT)->Bool>};
  469. // "float.neq": float non-equality comparison.
  470. constexpr BuiltinInfo FloatNeq = {
  471. "float.neq", ValidateSignature<auto(SizedFloatT, SizedFloatT)->Bool>};
  472. // "float.less": float less than comparison.
  473. constexpr BuiltinInfo FloatLess = {
  474. "float.less", ValidateSignature<auto(SizedFloatT, SizedFloatT)->Bool>};
  475. // "float.less_eq": float less than or equal comparison.
  476. constexpr BuiltinInfo FloatLessEq = {
  477. "float.less_eq", ValidateSignature<auto(SizedFloatT, SizedFloatT)->Bool>};
  478. // "float.greater": float greater than comparison.
  479. constexpr BuiltinInfo FloatGreater = {
  480. "float.greater", ValidateSignature<auto(SizedFloatT, SizedFloatT)->Bool>};
  481. // "float.greater_eq": float greater than or equal comparison.
  482. constexpr BuiltinInfo FloatGreaterEq = {
  483. "float.greater_eq",
  484. ValidateSignature<auto(SizedFloatT, SizedFloatT)->Bool>};
  485. // "bool.eq": bool equality comparison.
  486. constexpr BuiltinInfo BoolEq = {"bool.eq",
  487. ValidateSignature<auto(Bool, Bool)->Bool>};
  488. // "bool.neq": bool non-equality comparison.
  489. constexpr BuiltinInfo BoolNeq = {"bool.neq",
  490. ValidateSignature<auto(Bool, Bool)->Bool>};
  491. // "type.and": facet type combination.
  492. constexpr BuiltinInfo TypeAnd = {"type.and",
  493. ValidateSignature<auto(Type, Type)->Type>};
  494. // Destroys a primitive type. The argument must be destructible, which can be
  495. // checked with `type.can_aggregate_destroy`.
  496. // TODO: The argument should be `addr self: Self*`. Consider modifying
  497. // `ValidateSignature` to more fully enforce the structure.
  498. constexpr BuiltinInfo TypeAggregateDestroy = {
  499. "type.aggregate_destroy",
  500. ValidateSignature<auto(PointerTo<AnyType>)->NoReturn>};
  501. // Returns a facet type that's used to determine whether a type can use
  502. // `type.aggregate_destroy`.
  503. constexpr BuiltinInfo TypeCanAggregateDestroy = {
  504. "type.can_aggregate_destroy", ValidateSignature<auto()->Type>};
  505. } // namespace BuiltinFunctionInfo
  506. CARBON_DEFINE_ENUM_CLASS_NAMES(BuiltinFunctionKind) {
  507. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  508. BuiltinFunctionInfo::Name.name,
  509. #include "toolchain/sem_ir/builtin_function_kind.def"
  510. };
  511. // Returns the builtin function kind with the given name, or None if the name
  512. // is unknown.
  513. auto BuiltinFunctionKind::ForBuiltinName(llvm::StringRef name)
  514. -> BuiltinFunctionKind {
  515. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  516. if (name == BuiltinFunctionInfo::Name.name) { \
  517. return BuiltinFunctionKind::Name; \
  518. }
  519. #include "toolchain/sem_ir/builtin_function_kind.def"
  520. return BuiltinFunctionKind::None;
  521. }
  522. auto BuiltinFunctionKind::IsValidType(const File& sem_ir,
  523. llvm::ArrayRef<TypeId> arg_types,
  524. TypeId return_type) const -> bool {
  525. static constexpr ValidateFn* ValidateFns[] = {
  526. #define CARBON_SEM_IR_BUILTIN_FUNCTION_KIND(Name) \
  527. BuiltinFunctionInfo::Name.validate,
  528. #include "toolchain/sem_ir/builtin_function_kind.def"
  529. };
  530. return ValidateFns[AsInt()](sem_ir, arg_types, return_type);
  531. }
  532. static auto IsLiteralType(const File& sem_ir, TypeId type_id) -> bool {
  533. // Unwrap adapters.
  534. type_id = sem_ir.types().GetTransitiveAdaptedType(type_id);
  535. auto type_inst_id = sem_ir.types().GetAsInst(type_id);
  536. return type_inst_id.Is<IntLiteralType>() ||
  537. type_inst_id.Is<FloatLiteralType>();
  538. }
  539. // Determines whether a builtin call involves an integer or floating-point
  540. // literal in its arguments or return type. If so, for many builtins we want to
  541. // treat the call as being compile-time-only. This is because `Core.IntLiteral`
  542. // and `Core.FloatLiteral` have an empty runtime representation, and a value of
  543. // such a type isn't necessarily a compile-time constant, so an arbitrary
  544. // runtime value of such a type may not have a value available for the builtin
  545. // to use. For example, given:
  546. //
  547. // var n: Core.IntLiteral() = 123;
  548. //
  549. // we would be unable to lower a runtime operation such as `(1 as i32) << n`
  550. // because the runtime representation of `n` doesn't track its value at all.
  551. //
  552. // For now, we treat all operations involving `Core.IntLiteral` or
  553. // `Core.FloatLiteral` as being compile-time-only.
  554. //
  555. // TODO: We will need to accept things like `some_i32 << 5` eventually. We could
  556. // allow builtin calls at runtime if all the IntLiteral arguments have constant
  557. // values, or add logic to the prelude to promote the `IntLiteral` operand to a
  558. // different type in such cases.
  559. //
  560. // TODO: For now, we also treat builtins *returning* `Core.IntLiteral` or
  561. // `Core.FloatLiteral` as being compile-time-only. This is mostly done for
  562. // simplicity, but should probably be revisited.
  563. static auto AnyLiteralTypes(const File& sem_ir, llvm::ArrayRef<InstId> arg_ids,
  564. TypeId return_type_id) -> bool {
  565. if (IsLiteralType(sem_ir, return_type_id)) {
  566. return true;
  567. }
  568. for (auto arg_id : arg_ids) {
  569. if (IsLiteralType(sem_ir, sem_ir.insts().Get(arg_id).type_id())) {
  570. return true;
  571. }
  572. }
  573. return false;
  574. }
  575. auto BuiltinFunctionKind::IsCompTimeOnly(const File& sem_ir,
  576. llvm::ArrayRef<InstId> arg_ids,
  577. TypeId return_type_id) const -> bool {
  578. switch (*this) {
  579. case CharConvertChecked:
  580. case FloatConvertChecked:
  581. case IntConvertChecked:
  582. // Checked conversions are compile-time only.
  583. return true;
  584. case IntConvert:
  585. case IntSNegate:
  586. case IntComplement:
  587. case IntSAdd:
  588. case IntSSub:
  589. case IntSMul:
  590. case IntSDiv:
  591. case IntSMod:
  592. case IntAnd:
  593. case IntOr:
  594. case IntXor:
  595. case IntLeftShift:
  596. case IntRightShift:
  597. case IntEq:
  598. case IntNeq:
  599. case IntLess:
  600. case IntLessEq:
  601. case IntGreater:
  602. case IntGreaterEq:
  603. // Integer operations are compile-time-only if they involve literal types.
  604. // See AnyLiteralTypes comment for explanation.
  605. return AnyLiteralTypes(sem_ir, arg_ids, return_type_id);
  606. case TypeAnd:
  607. return true;
  608. case TypeCanAggregateDestroy:
  609. // Type queries must be compile-time.
  610. return true;
  611. default:
  612. // TODO: Should the sized MakeType functions be compile-time only? We
  613. // can't produce diagnostics for bad sizes at runtime.
  614. return false;
  615. }
  616. }
  617. } // namespace Carbon::SemIR