builtin_function_kind.cpp 30 KB

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