constant.cpp 14 KB

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