builtin_function_kind.cpp 32 KB

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