constant.cpp 10 KB

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