constant.cpp 12 KB

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