builtin_function_kind.cpp 31 KB

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