constant.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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/lower/constant.h"
  5. #include "llvm/ADT/STLExtras.h"
  6. #include "llvm/IR/Constants.h"
  7. #include "llvm/IR/IRBuilder.h"
  8. #include "llvm/IR/Value.h"
  9. #include "toolchain/base/kind_switch.h"
  10. #include "toolchain/lower/file_context.h"
  11. #include "toolchain/sem_ir/expr_info.h"
  12. #include "toolchain/sem_ir/inst.h"
  13. #include "toolchain/sem_ir/typed_insts.h"
  14. namespace Carbon::Lower {
  15. // Context and shared functionality for lowering constant values.
  16. class ConstantContext {
  17. public:
  18. explicit ConstantContext(FileContext& file_context,
  19. const FileContext::LoweredConstantStore* constants)
  20. : file_context_(&file_context), constants_(constants) {}
  21. // Gets the lowered constant value for an instruction, which must have a
  22. // constant value that has already been lowered. Returns nullptr if it
  23. // hasn't been, in which case it should not be needed.
  24. auto GetConstant(SemIR::InstId inst_id) const -> llvm::Constant* {
  25. return GetConstant(file_context_->sem_ir().constant_values().Get(inst_id));
  26. }
  27. // Gets the lowered constant value for a constant that has already been
  28. // lowered. Returns nullptr if it hasn't been, in which case it should not be
  29. // needed.
  30. auto GetConstant(SemIR::ConstantId const_id) const -> llvm::Constant* {
  31. CARBON_CHECK(const_id.is_concrete(), "Unexpected constant ID {0}",
  32. const_id);
  33. auto inst_id = sem_ir().constant_values().GetInstId(const_id);
  34. CARBON_CHECK(sem_ir().insts().GetRawIndex(inst_id) <
  35. sem_ir().insts().GetRawIndex(current_constant_inst_id_),
  36. "Accessed constants out of order: {0} {1} uses {2} {3}",
  37. current_constant_inst_id_,
  38. sem_ir().insts().Get(current_constant_inst_id_), inst_id,
  39. sem_ir().insts().Get(inst_id));
  40. return constants_->Get(inst_id);
  41. }
  42. // Returns a constant for the case of a value that should never be used.
  43. auto GetUnusedConstant(SemIR::TypeId /*type_id*/) const -> llvm::Constant* {
  44. // TODO: Consider using a poison value of the appropriate type.
  45. return nullptr;
  46. }
  47. // Gets the value to use for a literal.
  48. auto GetLiteralAsValue() const -> llvm::Constant* {
  49. return file_context_->GetLiteralAsValue();
  50. }
  51. // Gets a callable's function. Returns nullptr for a builtin.
  52. auto GetFunction(SemIR::FunctionId function_id) -> llvm::Function* {
  53. return file_context_->GetFunction(function_id);
  54. }
  55. auto GetVtable(SemIR::VtableId vtable_id, SemIR::SpecificId specific_id)
  56. -> llvm::GlobalVariable* {
  57. return file_context_->GetVtable(vtable_id, specific_id);
  58. }
  59. // Returns a lowered type for the given type_id.
  60. auto GetType(SemIR::TypeId type_id) const -> llvm::Type* {
  61. return file_context_->GetType(type_id);
  62. }
  63. // Returns a lowered value to use for a value of type `type`.
  64. auto GetTypeAsValue() const -> llvm::Constant* {
  65. return file_context_->GetTypeAsValue();
  66. }
  67. // Returns a lowered global variable declaration.
  68. auto BuildGlobalVariableDecl(SemIR::VarStorage inst) -> llvm::Constant* {
  69. return file_context_->BuildGlobalVariableDecl(inst);
  70. }
  71. // Sets the InstId of the constant we're currently lowering. This is used to
  72. // check we don't look at constants that we've not lowered yet.
  73. auto SetCurrentConstantInstId(SemIR::InstId inst_id) -> void {
  74. CARBON_CHECK(
  75. !current_constant_inst_id_.has_value() ||
  76. sem_ir().insts().GetRawIndex(inst_id) >
  77. sem_ir().insts().GetRawIndex(current_constant_inst_id_),
  78. "Visited constants out of order");
  79. current_constant_inst_id_ = inst_id;
  80. }
  81. auto llvm_context() const -> llvm::LLVMContext& {
  82. return file_context_->llvm_context();
  83. }
  84. auto llvm_module() const -> llvm::Module& {
  85. return file_context_->llvm_module();
  86. }
  87. auto sem_ir() const -> const SemIR::File& { return file_context_->sem_ir(); }
  88. auto inst_namer() const -> const SemIR::InstNamer* {
  89. return file_context_->inst_namer();
  90. }
  91. private:
  92. FileContext* file_context_;
  93. const FileContext::LoweredConstantStore* constants_;
  94. SemIR::InstId current_constant_inst_id_ = SemIR::InstId::None;
  95. };
  96. // Get the element type at a given index from a struct.
  97. static auto GetElementType(llvm::StructType* struct_type, int index)
  98. -> llvm::Type* {
  99. return struct_type->getElementType(index);
  100. }
  101. // Get the element type from an array.
  102. static auto GetElementType(llvm::ArrayType* array_type, int /*index*/)
  103. -> llvm::Type* {
  104. return array_type->getElementType();
  105. }
  106. // Add padding if necessary to convert the given constant to the specified,
  107. // possibly-padded LLVM type. The type of the constant will either already be
  108. // `llvm_type`, or will be a tail-padded type `<{llvm_type, [i8 x N]}>`.
  109. static auto PadToType(llvm::Constant* constant, llvm::Type* llvm_type)
  110. -> llvm::Constant* {
  111. if (constant->getType() == llvm_type) {
  112. return constant;
  113. }
  114. auto* padded = cast<llvm::StructType>(llvm_type);
  115. CARBON_CHECK(padded->getNumElements() == 2 &&
  116. padded->getElementType(0) == constant->getType(),
  117. "Unexpected type {0} for constant {1}", *llvm_type, *constant);
  118. return llvm::ConstantStruct::get(
  119. padded, constant, llvm::PoisonValue::get(padded->getElementType(1)));
  120. }
  121. // Emits an aggregate constant of LLVM type `Type` whose elements are the
  122. // contents of `refs_id`.
  123. template <typename ConstantType, typename Type>
  124. static auto EmitAggregateConstant(ConstantContext& context,
  125. SemIR::InstBlockId refs_id, Type* llvm_type)
  126. -> llvm::Constant* {
  127. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  128. llvm::SmallVector<llvm::Constant*> elements;
  129. elements.reserve(refs.size());
  130. for (auto [i, ref] : llvm::enumerate(refs)) {
  131. if (auto* constant = context.GetConstant(ref)) {
  132. auto* elem_type = GetElementType(llvm_type, i);
  133. elements.push_back(PadToType(constant, elem_type));
  134. } else {
  135. return nullptr;
  136. }
  137. }
  138. return ConstantType::get(llvm_type, elements);
  139. }
  140. // For each instruction InstT that can be emitted as a constant, there is a
  141. // function below to convert it to an `llvm::Constant*`:
  142. //
  143. // auto EmitAsConstant(ConstantContext& context, SemIR::InstT inst)
  144. // -> llvm::Constant*;
  145. // Represent facet values the same as types.
  146. static auto EmitAsConstant(ConstantContext& context, SemIR::FacetValue /*inst*/)
  147. -> llvm::Constant* {
  148. return context.GetTypeAsValue();
  149. }
  150. static auto EmitAsConstant(ConstantContext& context, SemIR::StructValue inst)
  151. -> llvm::Constant* {
  152. return EmitAggregateConstant<llvm::ConstantStruct>(
  153. context, inst.elements_id,
  154. cast<llvm::StructType>(context.GetType(inst.type_id)));
  155. }
  156. static auto EmitAsConstant(ConstantContext& context, SemIR::TupleValue inst)
  157. -> llvm::Constant* {
  158. // TODO: Add an ArrayValue instruction and stop using TupleValues to represent
  159. // array constants.
  160. if (context.sem_ir().types().Is<SemIR::ArrayType>(inst.type_id)) {
  161. return EmitAggregateConstant<llvm::ConstantArray>(
  162. context, inst.elements_id,
  163. cast<llvm::ArrayType>(context.GetType(inst.type_id)));
  164. }
  165. return EmitAggregateConstant<llvm::ConstantStruct>(
  166. context, inst.elements_id,
  167. cast<llvm::StructType>(context.GetType(inst.type_id)));
  168. }
  169. static auto EmitAsConstant(ConstantContext& context, SemIR::AddrOf inst)
  170. -> llvm::Constant* {
  171. // A constant reference expression is lowered as a pointer, so `AddrOf` is a
  172. // no-op.
  173. return context.GetConstant(inst.lvalue_id);
  174. }
  175. static auto EmitAsConstant(ConstantContext& context, SemIR::VtablePtr inst)
  176. -> llvm::Constant* {
  177. return context.GetVtable(inst.vtable_id, inst.specific_id);
  178. }
  179. static auto EmitAsConstant(ConstantContext& context,
  180. SemIR::AnyAggregateAccess inst) -> llvm::Constant* {
  181. auto* aggr_addr = context.GetConstant(inst.aggregate_id);
  182. if (!aggr_addr) {
  183. return nullptr;
  184. }
  185. auto* aggr_type = context.GetType(
  186. context.sem_ir().insts().Get(inst.aggregate_id).type_id());
  187. auto* i32_type = llvm::Type::getInt32Ty(context.llvm_context());
  188. // For now, we rely on the LLVM type's GEP indexes matching the SemIR
  189. // aggregate element indexes.
  190. llvm::Constant* indexes[2] = {
  191. llvm::ConstantInt::get(i32_type, 0),
  192. llvm::ConstantInt::get(i32_type, inst.index.index),
  193. };
  194. auto no_wrap_flags =
  195. llvm::GEPNoWrapFlags::inBounds() | llvm::GEPNoWrapFlags::noUnsignedWrap();
  196. return llvm::ConstantExpr::getGetElementPtr(aggr_type, aggr_addr, indexes,
  197. no_wrap_flags);
  198. }
  199. template <typename InstT>
  200. requires(SemIR::Internal::InstLikeTypeInfo<SemIR::AnyAggregateAccess>::IsKind(
  201. InstT::Kind))
  202. static auto EmitAsConstant(ConstantContext& context, InstT inst)
  203. -> llvm::Constant* {
  204. return EmitAsConstant(context,
  205. SemIR::Inst(inst).As<SemIR::AnyAggregateAccess>());
  206. }
  207. static auto EmitAsConstant(ConstantContext& context,
  208. SemIR::AssociatedEntity inst) -> llvm::Constant* {
  209. return context.GetUnusedConstant(inst.type_id);
  210. }
  211. static auto EmitAsConstant(ConstantContext& context, SemIR::BaseDecl inst)
  212. -> llvm::Constant* {
  213. return context.GetUnusedConstant(inst.type_id);
  214. }
  215. static auto EmitAsConstant(ConstantContext& context, SemIR::BoolLiteral inst)
  216. -> llvm::Constant* {
  217. return llvm::ConstantInt::get(llvm::Type::getInt1Ty(context.llvm_context()),
  218. inst.value.index);
  219. }
  220. static auto EmitAsConstant(ConstantContext& context, SemIR::BoundMethod inst)
  221. -> llvm::Constant* {
  222. // Propagate just the function; the object is separately provided to the
  223. // enclosing call as an implicit argument.
  224. return context.GetConstant(inst.function_decl_id);
  225. }
  226. static auto EmitAsConstant(ConstantContext& context,
  227. SemIR::CharLiteralValue /*inst*/)
  228. -> llvm::Constant* {
  229. return context.GetLiteralAsValue();
  230. }
  231. static auto EmitAsConstant(ConstantContext& context,
  232. SemIR::CompleteTypeWitness inst) -> llvm::Constant* {
  233. return context.GetUnusedConstant(inst.type_id);
  234. }
  235. static auto EmitAsConstant(ConstantContext& context,
  236. SemIR::CppOverloadSetValue /*inst*/)
  237. -> llvm::Constant* {
  238. return context.GetLiteralAsValue();
  239. }
  240. static auto EmitAsConstant(ConstantContext& context, SemIR::FieldDecl inst)
  241. -> llvm::Constant* {
  242. return context.GetUnusedConstant(inst.type_id);
  243. }
  244. static auto EmitAsConstant(ConstantContext& context,
  245. SemIR::FloatLiteralValue /*inst*/)
  246. -> llvm::Constant* {
  247. return context.GetLiteralAsValue();
  248. }
  249. static auto EmitAsConstant(ConstantContext& context, SemIR::FloatValue inst)
  250. -> llvm::Constant* {
  251. const llvm::APFloat& value = context.sem_ir().floats().Get(inst.float_id);
  252. return llvm::ConstantFP::get(context.GetType(inst.type_id), value);
  253. }
  254. static auto EmitAsConstant(ConstantContext& context, SemIR::IntValue inst)
  255. -> llvm::Constant* {
  256. auto* type = context.GetType(inst.type_id);
  257. // IntLiteral is represented as an empty struct. All other integer types are
  258. // represented as an LLVM integer type.
  259. auto* int_type = dyn_cast<llvm::IntegerType>(type);
  260. if (!int_type) {
  261. auto* literal_value = context.GetLiteralAsValue();
  262. CARBON_CHECK(literal_value->getType() == type);
  263. return literal_value;
  264. }
  265. int bit_width = int_type->getBitWidth();
  266. auto val = context.sem_ir().ints().GetAtWidth(inst.int_id, bit_width);
  267. return llvm::ConstantInt::get(type, val);
  268. }
  269. static auto EmitAsConstant(ConstantContext& context, SemIR::Namespace inst)
  270. -> llvm::Constant* {
  271. return context.GetUnusedConstant(inst.type_id);
  272. }
  273. static auto EmitAsConstant(ConstantContext& context,
  274. SemIR::SpecificFunction inst) -> llvm::Constant* {
  275. return context.GetUnusedConstant(inst.type_id);
  276. }
  277. static auto EmitAsConstant(ConstantContext& context, SemIR::StringLiteral inst)
  278. -> llvm::Constant* {
  279. return llvm::IRBuilder<>(context.llvm_context())
  280. .CreateGlobalString(
  281. context.sem_ir().string_literal_values().Get(inst.string_literal_id),
  282. /*Name=*/"", /*AddressSpace=*/0, &context.llvm_module());
  283. }
  284. static auto EmitAsConstant(ConstantContext& context, SemIR::Temporary inst)
  285. -> llvm::Constant* {
  286. auto* const_value = context.GetConstant(inst.init_id);
  287. llvm::StringRef const_name;
  288. if (context.inst_namer()) {
  289. const_name = context.inst_namer()->GetUnscopedNameFor(inst.init_id);
  290. }
  291. if (const_name.empty()) {
  292. const_name = "const";
  293. }
  294. auto* global_variable = new llvm::GlobalVariable(
  295. context.llvm_module(), context.GetType(inst.type_id),
  296. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage, const_value,
  297. const_name);
  298. return global_variable;
  299. }
  300. static auto EmitAsConstant(ConstantContext& context,
  301. SemIR::UninitializedValue inst) -> llvm::Constant* {
  302. return llvm::PoisonValue::get(context.GetType(inst.type_id));
  303. }
  304. static auto EmitAsConstant(ConstantContext& context, SemIR::VarStorage inst)
  305. -> llvm::Constant* {
  306. if (!inst.pattern_id.has_value()) {
  307. // This constant is a placeholder and should not be used by lowering.
  308. return nullptr;
  309. }
  310. // Create the corresponding global variable declaration.
  311. return context.BuildGlobalVariableDecl(inst);
  312. }
  313. // Tries to emit an LLVM constant value for this constant instruction. Centrally
  314. // handles some common cases and then dispatches to the relevant EmitAsConstant
  315. // overload based on the type of the instruction for the remaining cases.
  316. template <typename InstT>
  317. static auto MaybeEmitAsConstant(ConstantContext& context, InstT inst)
  318. -> llvm::Constant* {
  319. if constexpr (InstT::Kind.constant_kind() == SemIR::InstConstantKind::Never ||
  320. InstT::Kind.constant_kind() ==
  321. SemIR::InstConstantKind::Indirect ||
  322. InstT::Kind.constant_kind() ==
  323. SemIR::InstConstantKind::SymbolicOnly) {
  324. CARBON_FATAL("Unexpected constant instruction kind {0}", inst);
  325. } else if constexpr (!InstT::Kind.is_lowered()) {
  326. // This instruction has a constant value, but that constant value will never
  327. // be used by lowering.
  328. return nullptr;
  329. } else if constexpr (InstT::Kind.is_type() == SemIR::InstIsType::Always) {
  330. // All types are lowered to the same value.
  331. return context.GetTypeAsValue();
  332. } else {
  333. return EmitAsConstant(context, inst);
  334. }
  335. }
  336. auto LowerConstants(FileContext& file_context,
  337. FileContext::LoweredConstantStore& constants) -> void {
  338. ConstantContext context(file_context, &constants);
  339. // Lower each constant in InstId order. This guarantees we lower the
  340. // dependencies of a constant before we lower the constant itself.
  341. for (auto [inst_id, const_id] :
  342. file_context.sem_ir().constant_values().enumerate()) {
  343. if (!const_id.has_value() || !const_id.is_concrete()) {
  344. // We are only interested in lowering concrete constants.
  345. continue;
  346. }
  347. auto defining_inst_id =
  348. file_context.sem_ir().constant_values().GetInstId(const_id);
  349. if (defining_inst_id != inst_id) {
  350. // This isn't the instruction that defines the constant.
  351. continue;
  352. }
  353. auto inst = file_context.sem_ir().insts().Get(inst_id);
  354. if (inst.type_id().has_value() &&
  355. !file_context.sem_ir().types().IsComplete(inst.type_id()) &&
  356. !IsRefCategory(SemIR::GetExprCategory(context.sem_ir(), inst_id))) {
  357. // If a non-reference constant doesn't have a complete type, that means we
  358. // imported it but didn't actually use it.
  359. continue;
  360. }
  361. context.SetCurrentConstantInstId(inst_id);
  362. llvm::Constant* value = nullptr;
  363. CARBON_KIND_SWITCH(inst) {
  364. #define CARBON_SEM_IR_INST_KIND(Name) \
  365. case CARBON_KIND(SemIR::Name const_inst): { \
  366. value = MaybeEmitAsConstant(context, const_inst); \
  367. break; \
  368. }
  369. #include "toolchain/sem_ir/inst_kind.def"
  370. }
  371. constants.Set(inst_id, value);
  372. }
  373. }
  374. } // namespace Carbon::Lower