builtin_function_kind.cpp 28 KB

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