constant.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  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. llvm::MutableArrayRef<llvm::Constant*> 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.
  21. auto GetConstant(SemIR::InstId inst_id) const -> llvm::Constant* {
  22. return GetConstant(file_context_->sem_ir().constant_values().Get(inst_id));
  23. }
  24. // Gets the lowered constant value for a constant that has already been
  25. // lowered.
  26. auto GetConstant(SemIR::ConstantId const_id) const -> llvm::Constant* {
  27. CARBON_CHECK(const_id.is_template(), "Unexpected constant ID {0}",
  28. const_id);
  29. auto inst_id =
  30. file_context_->sem_ir().constant_values().GetInstId(const_id);
  31. CARBON_CHECK(
  32. inst_id.index >= 0 && inst_id.index <= last_lowered_constant_index_,
  33. "Queried constant {0} with instruction {1} that has not been lowered "
  34. "yet",
  35. const_id, inst_id);
  36. return constants_[inst_id.index];
  37. }
  38. // Returns a constant for the case of a value that should never be used.
  39. auto GetUnusedConstant(SemIR::TypeId /*type_id*/) const -> llvm::Constant* {
  40. // TODO: Consider using a poison value of the appropriate type.
  41. return nullptr;
  42. }
  43. // Gets a callable's function. Returns nullptr for a builtin.
  44. auto GetFunction(SemIR::FunctionId function_id) -> llvm::Function* {
  45. return file_context_->GetFunction(function_id);
  46. }
  47. // Returns a lowered type for the given type_id.
  48. auto GetType(SemIR::TypeId type_id) const -> llvm::Type* {
  49. return file_context_->GetType(type_id);
  50. }
  51. // Returns a lowered value to use for a value of type `type`.
  52. auto GetTypeAsValue() const -> llvm::Constant* {
  53. return file_context_->GetTypeAsValue();
  54. }
  55. // Sets the index of the constant we most recently lowered. This is used to
  56. // check we don't look at constants that we've not lowered yet.
  57. auto SetLastLoweredConstantIndex(int32_t index) {
  58. last_lowered_constant_index_ = index;
  59. }
  60. auto llvm_context() const -> llvm::LLVMContext& {
  61. return file_context_->llvm_context();
  62. }
  63. auto llvm_module() const -> llvm::Module& {
  64. return file_context_->llvm_module();
  65. }
  66. auto sem_ir() const -> const SemIR::File& { return file_context_->sem_ir(); }
  67. private:
  68. FileContext* file_context_;
  69. llvm::MutableArrayRef<llvm::Constant*> constants_;
  70. int32_t last_lowered_constant_index_ = -1;
  71. };
  72. // Emits an aggregate constant of LLVM type `Type` whose elements are the
  73. // contents of `refs_id`.
  74. template <typename ConstantType, typename Type>
  75. static auto EmitAggregateConstant(ConstantContext& context,
  76. SemIR::InstBlockId refs_id, Type* llvm_type)
  77. -> llvm::Constant* {
  78. auto refs = context.sem_ir().inst_blocks().Get(refs_id);
  79. llvm::SmallVector<llvm::Constant*> elements;
  80. elements.reserve(refs.size());
  81. for (auto ref : refs) {
  82. elements.push_back(context.GetConstant(ref));
  83. }
  84. return ConstantType::get(llvm_type, elements);
  85. }
  86. // For each instruction InstT that can be emitted as a constant, there is a
  87. // function below to convert it to an `llvm::Constant*`:
  88. //
  89. // auto EmitAsConstant(ConstantContext& context, SemIR::InstT inst)
  90. // -> llvm::Constant*;
  91. // Represent facet values the same as types.
  92. static auto EmitAsConstant(ConstantContext& context, SemIR::FacetValue /*inst*/)
  93. -> llvm::Constant* {
  94. return context.GetTypeAsValue();
  95. }
  96. static auto EmitAsConstant(ConstantContext& context, SemIR::StructValue inst)
  97. -> llvm::Constant* {
  98. return EmitAggregateConstant<llvm::ConstantStruct>(
  99. context, inst.elements_id,
  100. cast<llvm::StructType>(context.GetType(inst.type_id)));
  101. }
  102. static auto EmitAsConstant(ConstantContext& context, SemIR::TupleValue inst)
  103. -> llvm::Constant* {
  104. // TODO: Add an ArrayValue instruction and stop using TupleValues to represent
  105. // array constants.
  106. if (context.sem_ir().types().Is<SemIR::ArrayType>(inst.type_id)) {
  107. return EmitAggregateConstant<llvm::ConstantArray>(
  108. context, inst.elements_id,
  109. cast<llvm::ArrayType>(context.GetType(inst.type_id)));
  110. }
  111. return EmitAggregateConstant<llvm::ConstantStruct>(
  112. context, inst.elements_id,
  113. cast<llvm::StructType>(context.GetType(inst.type_id)));
  114. }
  115. static auto EmitAsConstant(ConstantContext& /*context*/, SemIR::AddrOf /*inst*/)
  116. -> llvm::Constant* {
  117. // TODO: Constant lvalue support. For now we have no constant lvalues, so we
  118. // should never form a constant AddrOf.
  119. CARBON_FATAL("AddrOf constants not supported yet");
  120. }
  121. static auto EmitAsConstant(ConstantContext& context,
  122. SemIR::AssociatedEntity inst) -> llvm::Constant* {
  123. return context.GetUnusedConstant(inst.type_id);
  124. }
  125. static auto EmitAsConstant(ConstantContext& context, SemIR::BaseDecl inst)
  126. -> llvm::Constant* {
  127. return context.GetUnusedConstant(inst.type_id);
  128. }
  129. static auto EmitAsConstant(ConstantContext& context, SemIR::BoolLiteral inst)
  130. -> llvm::Constant* {
  131. return llvm::ConstantInt::get(llvm::Type::getInt1Ty(context.llvm_context()),
  132. inst.value.index);
  133. }
  134. static auto EmitAsConstant(ConstantContext& context, SemIR::BoundMethod inst)
  135. -> llvm::Constant* {
  136. // Propagate just the function; the object is separately provided to the
  137. // enclosing call as an implicit argument.
  138. return context.GetConstant(inst.function_id);
  139. }
  140. static auto EmitAsConstant(ConstantContext& context,
  141. SemIR::CompleteTypeWitness inst) -> llvm::Constant* {
  142. return context.GetUnusedConstant(inst.type_id);
  143. }
  144. static auto EmitAsConstant(ConstantContext& context, SemIR::FieldDecl inst)
  145. -> llvm::Constant* {
  146. return context.GetUnusedConstant(inst.type_id);
  147. }
  148. static auto EmitAsConstant(ConstantContext& context, SemIR::FloatLiteral inst)
  149. -> llvm::Constant* {
  150. const llvm::APFloat& value = context.sem_ir().floats().Get(inst.float_id);
  151. return llvm::ConstantFP::get(context.GetType(inst.type_id), value);
  152. }
  153. static auto EmitAsConstant(ConstantContext& context, SemIR::IntValue inst)
  154. -> llvm::Constant* {
  155. auto* type = context.GetType(inst.type_id);
  156. // IntLiteral is represented as an empty struct. All other integer types are
  157. // represented as an LLVM integer type.
  158. auto* int_type = llvm::dyn_cast<llvm::IntegerType>(type);
  159. if (!int_type) {
  160. auto* struct_type = llvm::dyn_cast<llvm::StructType>(type);
  161. CARBON_CHECK(struct_type && struct_type->getNumElements() == 0);
  162. return llvm::ConstantStruct::get(struct_type);
  163. }
  164. auto val = context.sem_ir().ints().Get(inst.int_id);
  165. int bit_width = int_type->getBitWidth();
  166. bool is_signed =
  167. context.sem_ir().types().GetIntTypeInfo(inst.type_id).is_signed;
  168. return llvm::ConstantInt::get(type, is_signed ? val.sextOrTrunc(bit_width)
  169. : val.zextOrTrunc(bit_width));
  170. }
  171. static auto EmitAsConstant(ConstantContext& context, SemIR::Namespace inst)
  172. -> llvm::Constant* {
  173. return context.GetUnusedConstant(inst.type_id);
  174. }
  175. static auto EmitAsConstant(ConstantContext& context,
  176. SemIR::SpecificFunction inst) -> llvm::Constant* {
  177. return context.GetUnusedConstant(inst.type_id);
  178. }
  179. static auto EmitAsConstant(ConstantContext& /*context*/,
  180. SemIR::StringLiteral inst) -> llvm::Constant* {
  181. CARBON_FATAL("TODO: Add support: {0}", inst);
  182. }
  183. // Tries to emit an LLVM constant value for this constant instruction. Centrally
  184. // handles some common cases and then dispatches to the relevant EmitAsConstant
  185. // overload based on the type of the instruction for the remaining cases.
  186. template <typename InstT>
  187. static auto MaybeEmitAsConstant(ConstantContext& context, InstT inst)
  188. -> llvm::Constant* {
  189. if constexpr (InstT::Kind.constant_kind() == SemIR::InstConstantKind::Never ||
  190. InstT::Kind.constant_kind() ==
  191. SemIR::InstConstantKind::SymbolicOnly) {
  192. CARBON_FATAL("Unexpected constant instruction kind {0}", inst);
  193. } else if constexpr (!InstT::Kind.is_lowered()) {
  194. // This instruction has a constant value, but that constant value will never
  195. // be used by lowering.
  196. return nullptr;
  197. } else if constexpr (InstT::Kind.is_type() == SemIR::InstIsType::Always) {
  198. // All types are lowered to the same value.
  199. return context.GetTypeAsValue();
  200. } else {
  201. return EmitAsConstant(context, inst);
  202. }
  203. }
  204. auto LowerConstants(FileContext& file_context,
  205. llvm::MutableArrayRef<llvm::Constant*> constants) -> void {
  206. ConstantContext context(file_context, constants);
  207. // Lower each constant in InstId order. This guarantees we lower the
  208. // dependencies of a constant before we lower the constant itself.
  209. for (auto [inst_id_val, const_id] :
  210. llvm::enumerate(file_context.sem_ir().constant_values().array_ref())) {
  211. if (!const_id.is_valid() || !const_id.is_template()) {
  212. // We are only interested in lowering template constants.
  213. continue;
  214. }
  215. auto inst_id = file_context.sem_ir().constant_values().GetInstId(const_id);
  216. if (inst_id.index != static_cast<int32_t>(inst_id_val)) {
  217. // This isn't the instruction that defines the constant.
  218. continue;
  219. }
  220. auto inst = file_context.sem_ir().insts().Get(inst_id);
  221. if (inst.type_id().is_valid() &&
  222. !file_context.sem_ir().types().IsComplete(inst.type_id())) {
  223. // If a constant doesn't have a complete type, that means we imported it
  224. // but didn't actually use it.
  225. continue;
  226. }
  227. llvm::Constant* value = nullptr;
  228. CARBON_KIND_SWITCH(inst) {
  229. #define CARBON_SEM_IR_INST_KIND(Name) \
  230. case CARBON_KIND(SemIR::Name const_inst): { \
  231. value = MaybeEmitAsConstant(context, const_inst); \
  232. break; \
  233. }
  234. #include "toolchain/sem_ir/inst_kind.def"
  235. }
  236. constants[inst_id.index] = value;
  237. context.SetLastLoweredConstantIndex(inst_id.index);
  238. }
  239. } // namespace Carbon::Lower
  240. } // namespace Carbon::Lower