constant.cpp 11 KB

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