file_context.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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/file_context.h"
  5. #include "common/check.h"
  6. #include "common/vlog.h"
  7. #include "llvm/ADT/STLExtras.h"
  8. #include "llvm/ADT/Sequence.h"
  9. #include "llvm/Transforms/Utils/ModuleUtils.h"
  10. #include "toolchain/base/kind_switch.h"
  11. #include "toolchain/lower/constant.h"
  12. #include "toolchain/lower/function_context.h"
  13. #include "toolchain/lower/mangler.h"
  14. #include "toolchain/sem_ir/absolute_node_id.h"
  15. #include "toolchain/sem_ir/entry_point.h"
  16. #include "toolchain/sem_ir/file.h"
  17. #include "toolchain/sem_ir/function.h"
  18. #include "toolchain/sem_ir/generic.h"
  19. #include "toolchain/sem_ir/ids.h"
  20. #include "toolchain/sem_ir/inst.h"
  21. #include "toolchain/sem_ir/inst_kind.h"
  22. #include "toolchain/sem_ir/typed_insts.h"
  23. namespace Carbon::Lower {
  24. FileContext::FileContext(
  25. llvm::LLVMContext& llvm_context,
  26. std::optional<llvm::ArrayRef<Parse::GetTreeAndSubtreesFn>>
  27. tree_and_subtrees_getters_for_debug_info,
  28. llvm::StringRef module_name, const SemIR::File& sem_ir,
  29. const SemIR::InstNamer* inst_namer, llvm::raw_ostream* vlog_stream)
  30. : llvm_context_(&llvm_context),
  31. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  32. di_builder_(*llvm_module_),
  33. di_compile_unit_(
  34. tree_and_subtrees_getters_for_debug_info
  35. ? BuildDICompileUnit(module_name, *llvm_module_, di_builder_)
  36. : nullptr),
  37. tree_and_subtrees_getters_for_debug_info_(
  38. tree_and_subtrees_getters_for_debug_info),
  39. sem_ir_(&sem_ir),
  40. inst_namer_(inst_namer),
  41. vlog_stream_(vlog_stream) {
  42. CARBON_CHECK(!sem_ir.has_errors(),
  43. "Generating LLVM IR from invalid SemIR::File is unsupported.");
  44. }
  45. // TODO: Move this to lower.cpp.
  46. auto FileContext::Run() -> std::unique_ptr<llvm::Module> {
  47. CARBON_CHECK(llvm_module_, "Run can only be called once.");
  48. // Lower all types that were required to be complete.
  49. types_.resize(sem_ir_->insts().size());
  50. for (auto type_id : sem_ir_->types().complete_types()) {
  51. if (type_id.index >= 0) {
  52. types_[type_id.index] = BuildType(sem_ir_->types().GetInstId(type_id));
  53. }
  54. }
  55. // Lower function declarations.
  56. functions_.resize_for_overwrite(sem_ir_->functions().size());
  57. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  58. functions_[id.index] = BuildFunctionDecl(id);
  59. }
  60. // Specific functions are lowered when we emit a reference to them.
  61. specific_functions_.resize(sem_ir_->specifics().size());
  62. // Lower global variable declarations.
  63. for (auto inst_id :
  64. sem_ir().inst_blocks().Get(sem_ir().top_inst_block_id())) {
  65. // Only `VarStorage` indicates a global variable declaration in the
  66. // top instruction block.
  67. if (auto var = sem_ir().insts().TryGetAs<SemIR::VarStorage>(inst_id)) {
  68. global_variables_.Insert(inst_id, BuildGlobalVariableDecl(*var));
  69. }
  70. }
  71. // Lower constants.
  72. constants_.resize(sem_ir_->insts().size());
  73. LowerConstants(*this, constants_);
  74. // Lower function definitions.
  75. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  76. BuildFunctionDefinition(id);
  77. }
  78. // Lower function definitions for generics.
  79. // This cannot be a range-based loop, as new definitions can be added
  80. // while building other definitions.
  81. // NOLINTNEXTLINE
  82. for (size_t i = 0; i != specific_function_definitions_.size(); ++i) {
  83. auto [function_id, specific_id] = specific_function_definitions_[i];
  84. BuildFunctionDefinition(function_id, specific_id);
  85. }
  86. // Append `__global_init` to `llvm::global_ctors` to initialize global
  87. // variables.
  88. if (sem_ir().global_ctor_id().has_value()) {
  89. llvm::appendToGlobalCtors(llvm_module(),
  90. GetFunction(sem_ir().global_ctor_id()),
  91. /*Priority=*/0);
  92. }
  93. return std::move(llvm_module_);
  94. }
  95. auto FileContext::BuildDICompileUnit(llvm::StringRef module_name,
  96. llvm::Module& llvm_module,
  97. llvm::DIBuilder& di_builder)
  98. -> llvm::DICompileUnit* {
  99. llvm_module.addModuleFlag(llvm::Module::Max, "Dwarf Version", 5);
  100. llvm_module.addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  101. llvm::DEBUG_METADATA_VERSION);
  102. // TODO: Include directory path in the compile_unit_file.
  103. llvm::DIFile* compile_unit_file = di_builder.createFile(module_name, "");
  104. // TODO: Introduce a new language code for Carbon. C works well for now since
  105. // it's something debuggers will already know/have support for at least.
  106. // Probably have to bump to C++ at some point for virtual functions,
  107. // templates, etc.
  108. return di_builder.createCompileUnit(llvm::dwarf::DW_LANG_C, compile_unit_file,
  109. "carbon",
  110. /*isOptimized=*/false, /*Flags=*/"",
  111. /*RV=*/0);
  112. }
  113. auto FileContext::GetGlobal(SemIR::InstId inst_id) -> llvm::Value* {
  114. auto inst = sem_ir().insts().Get(inst_id);
  115. auto const_id = sem_ir().constant_values().Get(inst_id);
  116. if (const_id.is_concrete()) {
  117. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  118. // For value expressions and initializing expressions, the value produced by
  119. // a constant instruction is a value representation of the constant. For
  120. // initializing expressions, `FinishInit` will perform a copy if needed.
  121. // TODO: Handle reference expression constants.
  122. auto* const_value = constants_[const_inst_id.index];
  123. // If we want a pointer to the constant, materialize a global to hold it.
  124. // TODO: We could reuse the same global if the constant is used more than
  125. // once.
  126. auto value_rep = SemIR::ValueRepr::ForType(sem_ir(), inst.type_id());
  127. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  128. // Include both the name of the constant, if any, and the point of use in
  129. // the name of the variable.
  130. llvm::StringRef const_name;
  131. llvm::StringRef use_name;
  132. if (inst_namer_) {
  133. const_name = inst_namer_->GetUnscopedNameFor(const_inst_id);
  134. use_name = inst_namer_->GetUnscopedNameFor(inst_id);
  135. }
  136. // We always need to give the global a name even if the instruction namer
  137. // doesn't have one to use.
  138. if (const_name.empty()) {
  139. const_name = "const";
  140. }
  141. if (use_name.empty()) {
  142. use_name = "anon";
  143. }
  144. llvm::StringRef sep = (use_name[0] == '.') ? "" : ".";
  145. return new llvm::GlobalVariable(
  146. llvm_module(), GetType(sem_ir().GetPointeeType(value_rep.type_id)),
  147. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage,
  148. const_value, const_name + sep + use_name);
  149. }
  150. // Otherwise, we can use the constant value directly.
  151. return const_value;
  152. }
  153. // TODO: For generics, handle references to symbolic constants.
  154. CARBON_FATAL("Missing value: {0} {1}", inst_id,
  155. sem_ir().insts().Get(inst_id));
  156. }
  157. auto FileContext::GetOrCreateFunction(SemIR::FunctionId function_id,
  158. SemIR::SpecificId specific_id)
  159. -> llvm::Function* {
  160. // Non-generic functions are declared eagerly.
  161. if (!specific_id.has_value()) {
  162. return GetFunction(function_id);
  163. }
  164. if (auto* result = specific_functions_[specific_id.index]) {
  165. return result;
  166. }
  167. auto* result = BuildFunctionDecl(function_id, specific_id);
  168. // TODO: Add this function to a list of specific functions whose definitions
  169. // we need to emit.
  170. specific_functions_[specific_id.index] = result;
  171. // TODO: Use this to generate definitions for these functions.
  172. specific_function_definitions_.push_back({function_id, specific_id});
  173. return result;
  174. }
  175. auto FileContext::BuildFunctionTypeInfo(const SemIR::Function& function,
  176. SemIR::SpecificId specific_id)
  177. -> FunctionTypeInfo {
  178. const auto return_info =
  179. SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id);
  180. if (!return_info.is_valid()) {
  181. // The return type has not been completed, create a trivial type instead.
  182. return {.type =
  183. llvm::FunctionType::get(llvm::Type::getVoidTy(llvm_context()),
  184. /*isVarArg=*/false)};
  185. }
  186. // TODO nit: add is_symbolic() to type_id to forward to
  187. // type_id.AsConstantId().is_symbolic(). Update call below too.
  188. auto get_llvm_type = [&](SemIR::TypeId type_id) -> llvm::Type* {
  189. if (!type_id.has_value()) {
  190. return nullptr;
  191. }
  192. return GetType(SemIR::GetTypeInSpecific(sem_ir(), specific_id, type_id));
  193. };
  194. auto implicit_param_patterns =
  195. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_patterns_id);
  196. // TODO: Include parameters corresponding to positional parameters.
  197. auto param_patterns =
  198. sem_ir().inst_blocks().GetOrEmpty(function.param_patterns_id);
  199. auto* return_type = get_llvm_type(return_info.type_id);
  200. llvm::SmallVector<llvm::Type*> param_types;
  201. // Compute the return type to use for the LLVM function. If the initializing
  202. // representation doesn't produce a value, set the return type to void.
  203. // TODO: For the `Run` entry point, remap return type to i32 if it doesn't
  204. // return a value.
  205. llvm::Type* function_return_type =
  206. (return_info.is_valid() &&
  207. return_info.init_repr.kind == SemIR::InitRepr::ByCopy)
  208. ? return_type
  209. : llvm::Type::getVoidTy(llvm_context());
  210. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  211. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  212. // out a mechanism to compute the mapping between parameters and arguments on
  213. // demand.
  214. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  215. auto max_llvm_params = (return_info.has_return_slot() ? 1 : 0) +
  216. implicit_param_patterns.size() + param_patterns.size();
  217. param_types.reserve(max_llvm_params);
  218. param_inst_ids.reserve(max_llvm_params);
  219. auto return_param_id = SemIR::InstId::None;
  220. if (return_info.has_return_slot()) {
  221. param_types.push_back(
  222. llvm::PointerType::get(return_type, /*AddressSpace=*/0));
  223. return_param_id = function.return_slot_pattern_id;
  224. param_inst_ids.push_back(return_param_id);
  225. }
  226. for (auto param_pattern_id : llvm::concat<const SemIR::InstId>(
  227. implicit_param_patterns, param_patterns)) {
  228. auto param_pattern_info = SemIR::Function::GetParamPatternInfoFromPatternId(
  229. sem_ir(), param_pattern_id);
  230. if (!param_pattern_info) {
  231. continue;
  232. }
  233. auto param_type_id = SemIR::GetTypeInSpecific(
  234. sem_ir(), specific_id, param_pattern_info->inst.type_id);
  235. CARBON_CHECK(
  236. !param_type_id.AsConstantId().is_symbolic(),
  237. "Found symbolic type id after resolution when lowering type {0}.",
  238. param_pattern_info->inst.type_id);
  239. switch (auto value_rep = SemIR::ValueRepr::ForType(sem_ir(), param_type_id);
  240. value_rep.kind) {
  241. case SemIR::ValueRepr::Unknown:
  242. // This parameter type is incomplete. Fallback to describing the
  243. // function type as `void()`.
  244. return {.type = llvm::FunctionType::get(
  245. llvm::Type::getVoidTy(llvm_context()),
  246. /*isVarArg=*/false)};
  247. case SemIR::ValueRepr::None:
  248. break;
  249. case SemIR::ValueRepr::Copy:
  250. case SemIR::ValueRepr::Custom:
  251. case SemIR::ValueRepr::Pointer:
  252. auto* param_types_to_add = get_llvm_type(value_rep.type_id);
  253. param_types.push_back(param_types_to_add);
  254. param_inst_ids.push_back(param_pattern_id);
  255. break;
  256. }
  257. }
  258. return {.type = llvm::FunctionType::get(function_return_type, param_types,
  259. /*isVarArg=*/false),
  260. .param_inst_ids = std::move(param_inst_ids),
  261. .return_type = return_type,
  262. .return_param_id = return_param_id};
  263. }
  264. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id,
  265. SemIR::SpecificId specific_id)
  266. -> llvm::Function* {
  267. const auto& function = sem_ir().functions().Get(function_id);
  268. // Don't lower generic functions. Note that associated functions in interfaces
  269. // have `Self` in scope, so are implicitly generic functions.
  270. if (function.generic_id.has_value() && !specific_id.has_value()) {
  271. return nullptr;
  272. }
  273. // Don't lower builtins.
  274. if (function.builtin_function_kind != SemIR::BuiltinFunctionKind::None) {
  275. return nullptr;
  276. }
  277. // TODO: Consider tracking whether the function has been used, and only
  278. // lowering it if it's needed.
  279. auto function_type_info = BuildFunctionTypeInfo(function, specific_id);
  280. Mangler m(*this);
  281. std::string mangled_name = m.Mangle(function_id, specific_id);
  282. auto* llvm_function = llvm::Function::Create(function_type_info.type,
  283. llvm::Function::ExternalLinkage,
  284. mangled_name, llvm_module());
  285. CARBON_CHECK(llvm_function->getName() == mangled_name,
  286. "Mangled name collision: {0}", mangled_name);
  287. // Set up parameters and the return slot.
  288. for (auto [inst_id, arg] : llvm::zip_equal(function_type_info.param_inst_ids,
  289. llvm_function->args())) {
  290. auto name_id = SemIR::NameId::None;
  291. if (inst_id == function_type_info.return_param_id) {
  292. name_id = SemIR::NameId::ReturnSlot;
  293. arg.addAttr(llvm::Attribute::getWithStructRetType(
  294. llvm_context(), function_type_info.return_type));
  295. } else {
  296. name_id = SemIR::Function::GetNameFromPatternId(sem_ir(), inst_id);
  297. }
  298. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  299. }
  300. return llvm_function;
  301. }
  302. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id,
  303. SemIR::SpecificId specific_id)
  304. -> void {
  305. const auto& function = sem_ir().functions().Get(function_id);
  306. const auto& body_block_ids = function.body_block_ids;
  307. if (body_block_ids.empty()) {
  308. // Function is probably defined in another file; not an error.
  309. return;
  310. }
  311. llvm::Function* llvm_function;
  312. if (specific_id.has_value()) {
  313. llvm_function = specific_functions_[specific_id.index];
  314. } else {
  315. llvm_function = GetFunction(function_id);
  316. if (!llvm_function) {
  317. // We chose not to lower this function at all, for example because it's a
  318. // generic function.
  319. return;
  320. }
  321. }
  322. // For non-generics we do not lower. For generics, the llvm function was
  323. // created via GetOrCreateFunction prior to this when building the
  324. // declaration.
  325. BuildFunctionBody(function_id, function, llvm_function, specific_id);
  326. }
  327. auto FileContext::BuildFunctionBody(SemIR::FunctionId function_id,
  328. const SemIR::Function& function,
  329. llvm::Function* llvm_function,
  330. SemIR::SpecificId specific_id) -> void {
  331. const auto& body_block_ids = function.body_block_ids;
  332. CARBON_DCHECK(llvm_function, "LLVM Function not found when lowering body.");
  333. CARBON_DCHECK(!body_block_ids.empty(),
  334. "No function body blocks found during lowering.");
  335. FunctionContext function_lowering(*this, llvm_function, specific_id,
  336. BuildDISubprogram(function, llvm_function),
  337. vlog_stream_);
  338. // Add parameters to locals.
  339. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  340. // function parameters that was already computed in BuildFunctionDecl.
  341. // We should only do that once.
  342. auto call_param_ids =
  343. sem_ir().inst_blocks().GetOrEmpty(function.call_params_id);
  344. int param_index = 0;
  345. // TODO: Find a way to ensure this code and the function-call lowering use
  346. // the same parameter ordering.
  347. // Lowers the given parameter. Must be called in LLVM calling convention
  348. // parameter order.
  349. auto lower_param = [&](SemIR::InstId param_id) {
  350. // Get the value of the parameter from the function argument.
  351. auto param_inst = sem_ir().insts().GetAs<SemIR::AnyParam>(param_id);
  352. llvm::Value* param_value;
  353. if (SemIR::ValueRepr::ForType(sem_ir(), param_inst.type_id).kind !=
  354. SemIR::ValueRepr::None) {
  355. param_value = llvm_function->getArg(param_index);
  356. ++param_index;
  357. } else {
  358. param_value = llvm::PoisonValue::get(GetType(
  359. SemIR::GetTypeInSpecific(sem_ir(), specific_id, param_inst.type_id)));
  360. }
  361. // The value of the parameter is the value of the argument.
  362. function_lowering.SetLocal(param_id, param_value);
  363. };
  364. // The subset of call_param_ids that is already in the order that the LLVM
  365. // calling convention expects.
  366. llvm::ArrayRef<SemIR::InstId> sequential_param_ids;
  367. if (function.return_slot_pattern_id.has_value()) {
  368. // The LLVM calling convention has the return slot first rather than last.
  369. // Note that this queries whether there is a return slot at the LLVM level,
  370. // whereas `function.return_slot_pattern_id.has_value()` queries whether
  371. // there is a return slot at the SemIR level.
  372. if (SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id)
  373. .has_return_slot()) {
  374. lower_param(call_param_ids.back());
  375. }
  376. sequential_param_ids = call_param_ids.drop_back();
  377. } else {
  378. sequential_param_ids = call_param_ids;
  379. }
  380. for (auto param_id : sequential_param_ids) {
  381. lower_param(param_id);
  382. }
  383. auto decl_block_id = SemIR::InstBlockId::None;
  384. if (function_id == sem_ir().global_ctor_id()) {
  385. decl_block_id = SemIR::InstBlockId::Empty;
  386. } else {
  387. decl_block_id = sem_ir()
  388. .insts()
  389. .GetAs<SemIR::FunctionDecl>(function.latest_decl_id())
  390. .decl_block_id;
  391. }
  392. // Lowers the contents of block_id into the corresponding LLVM block,
  393. // creating it if it doesn't already exist.
  394. auto lower_block = [&](SemIR::InstBlockId block_id) {
  395. CARBON_VLOG("Lowering {0}\n", block_id);
  396. auto* llvm_block = function_lowering.GetBlock(block_id);
  397. // Keep the LLVM blocks in lexical order.
  398. llvm_block->moveBefore(llvm_function->end());
  399. function_lowering.builder().SetInsertPoint(llvm_block);
  400. function_lowering.LowerBlockContents(block_id);
  401. };
  402. lower_block(decl_block_id);
  403. // If the decl block is empty, reuse it as the first body block. We don't do
  404. // this when the decl block is non-empty so that any branches back to the
  405. // first body block don't also re-execute the decl.
  406. llvm::BasicBlock* block = function_lowering.builder().GetInsertBlock();
  407. if (block->empty() &&
  408. function_lowering.TryToReuseBlock(body_block_ids.front(), block)) {
  409. // Reuse this block as the first block of the function body.
  410. } else {
  411. function_lowering.builder().CreateBr(
  412. function_lowering.GetBlock(body_block_ids.front()));
  413. }
  414. // Lower all blocks.
  415. for (auto block_id : body_block_ids) {
  416. lower_block(block_id);
  417. }
  418. // LLVM requires that the entry block has no predecessors.
  419. auto* entry_block = &llvm_function->getEntryBlock();
  420. if (entry_block->hasNPredecessorsOrMore(1)) {
  421. auto* new_entry_block = llvm::BasicBlock::Create(
  422. llvm_context(), "entry", llvm_function, entry_block);
  423. llvm::BranchInst::Create(entry_block, new_entry_block);
  424. }
  425. }
  426. auto FileContext::BuildDISubprogram(const SemIR::Function& function,
  427. const llvm::Function* llvm_function)
  428. -> llvm::DISubprogram* {
  429. if (!di_compile_unit_) {
  430. return nullptr;
  431. }
  432. auto name = sem_ir().names().GetAsStringIfIdentifier(function.name_id);
  433. CARBON_CHECK(name, "Unexpected special name for function: {0}",
  434. function.name_id);
  435. auto loc = GetLocForDI(function.definition_id);
  436. // TODO: Add more details here, including real subroutine type (once type
  437. // information is built), etc.
  438. return di_builder_.createFunction(
  439. di_compile_unit_, *name, llvm_function->getName(),
  440. /*File=*/di_builder_.createFile(loc.filename, ""),
  441. /*LineNo=*/loc.line_number,
  442. di_builder_.createSubroutineType(
  443. di_builder_.getOrCreateTypeArray(std::nullopt)),
  444. /*ScopeLine=*/0, llvm::DINode::FlagZero,
  445. llvm::DISubprogram::SPFlagDefinition);
  446. }
  447. // BuildTypeForInst is used to construct types for FileContext::BuildType below.
  448. // Implementations return the LLVM type for the instruction. This first overload
  449. // is the fallback handler for non-type instructions.
  450. template <typename InstT>
  451. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  452. static auto BuildTypeForInst(FileContext& /*context*/, InstT inst)
  453. -> llvm::Type* {
  454. CARBON_FATAL("Cannot use inst as type: {0}", inst);
  455. }
  456. template <typename InstT>
  457. requires(InstT::Kind.constant_kind() ==
  458. SemIR::InstConstantKind::SymbolicOnly &&
  459. InstT::Kind.is_type() != SemIR::InstIsType::Never)
  460. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  461. -> llvm::Type* {
  462. // Treat non-monomorphized symbolic types as opaque.
  463. return llvm::StructType::get(context.llvm_context());
  464. }
  465. static auto BuildTypeForInst(FileContext& context, SemIR::ArrayType inst)
  466. -> llvm::Type* {
  467. return llvm::ArrayType::get(
  468. context.GetType(inst.element_type_id),
  469. *context.sem_ir().GetArrayBoundValue(inst.bound_id));
  470. }
  471. static auto BuildTypeForInst(FileContext& /*context*/, SemIR::AutoType inst)
  472. -> llvm::Type* {
  473. CARBON_FATAL("Unexpected builtin type in lowering: {0}", inst);
  474. }
  475. static auto BuildTypeForInst(FileContext& context, SemIR::BoolType /*inst*/)
  476. -> llvm::Type* {
  477. // TODO: We may want to have different representations for `bool` storage
  478. // (`i8`) versus for `bool` values (`i1`).
  479. return llvm::Type::getInt1Ty(context.llvm_context());
  480. }
  481. static auto BuildTypeForInst(FileContext& context, SemIR::ClassType inst)
  482. -> llvm::Type* {
  483. auto object_repr_id = context.sem_ir()
  484. .classes()
  485. .Get(inst.class_id)
  486. .GetObjectRepr(context.sem_ir(), inst.specific_id);
  487. return context.GetType(object_repr_id);
  488. }
  489. static auto BuildTypeForInst(FileContext& context, SemIR::ConstType inst)
  490. -> llvm::Type* {
  491. return context.GetType(inst.inner_id);
  492. }
  493. static auto BuildTypeForInst(FileContext& /*context*/,
  494. SemIR::ErrorInst /*inst*/) -> llvm::Type* {
  495. // This is a complete type but uses of it should never be lowered.
  496. return nullptr;
  497. }
  498. static auto BuildTypeForInst(FileContext& context, SemIR::FloatType /*inst*/)
  499. -> llvm::Type* {
  500. // TODO: Handle different sizes.
  501. return llvm::Type::getDoubleTy(context.llvm_context());
  502. }
  503. static auto BuildTypeForInst(FileContext& context, SemIR::IntType inst)
  504. -> llvm::Type* {
  505. auto width =
  506. context.sem_ir().insts().TryGetAs<SemIR::IntValue>(inst.bit_width_id);
  507. CARBON_CHECK(width, "Can't lower int type with symbolic width");
  508. return llvm::IntegerType::get(
  509. context.llvm_context(),
  510. context.sem_ir().ints().Get(width->int_id).getZExtValue());
  511. }
  512. static auto BuildTypeForInst(FileContext& context,
  513. SemIR::LegacyFloatType /*inst*/) -> llvm::Type* {
  514. return llvm::Type::getDoubleTy(context.llvm_context());
  515. }
  516. static auto BuildTypeForInst(FileContext& context, SemIR::PointerType /*inst*/)
  517. -> llvm::Type* {
  518. return llvm::PointerType::get(context.llvm_context(), /*AddressSpace=*/0);
  519. }
  520. static auto BuildTypeForInst(FileContext& context, SemIR::StructType inst)
  521. -> llvm::Type* {
  522. auto fields = context.sem_ir().struct_type_fields().Get(inst.fields_id);
  523. llvm::SmallVector<llvm::Type*> subtypes;
  524. subtypes.reserve(fields.size());
  525. for (auto field : fields) {
  526. subtypes.push_back(context.GetType(field.type_id));
  527. }
  528. return llvm::StructType::get(context.llvm_context(), subtypes);
  529. }
  530. static auto BuildTypeForInst(FileContext& context, SemIR::TupleType inst)
  531. -> llvm::Type* {
  532. // TODO: Investigate special-casing handling of empty tuples so that they
  533. // can be collectively replaced with LLVM's void, particularly around
  534. // function returns. LLVM doesn't allow declaring variables with a void
  535. // type, so that may require significant special casing.
  536. auto elements = context.sem_ir().type_blocks().Get(inst.elements_id);
  537. llvm::SmallVector<llvm::Type*> subtypes;
  538. subtypes.reserve(elements.size());
  539. for (auto element_id : elements) {
  540. subtypes.push_back(context.GetType(element_id));
  541. }
  542. return llvm::StructType::get(context.llvm_context(), subtypes);
  543. }
  544. static auto BuildTypeForInst(FileContext& context, SemIR::TypeType /*inst*/)
  545. -> llvm::Type* {
  546. return context.GetTypeType();
  547. }
  548. static auto BuildTypeForInst(FileContext& context, SemIR::VtableType /*inst*/)
  549. -> llvm::Type* {
  550. return llvm::Type::getVoidTy(context.llvm_context());
  551. }
  552. template <typename InstT>
  553. requires(InstT::Kind.template IsAnyOf<SemIR::SpecificFunctionType,
  554. SemIR::StringType>())
  555. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  556. -> llvm::Type* {
  557. // TODO: Decide how we want to represent `StringType`.
  558. return llvm::PointerType::get(context.llvm_context(), 0);
  559. }
  560. template <typename InstT>
  561. requires(InstT::Kind
  562. .template IsAnyOf<SemIR::BoundMethodType, SemIR::IntLiteralType,
  563. SemIR::NamespaceType, SemIR::WitnessType>())
  564. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  565. -> llvm::Type* {
  566. // Return an empty struct as a placeholder.
  567. return llvm::StructType::get(context.llvm_context());
  568. }
  569. template <typename InstT>
  570. requires(InstT::Kind.template IsAnyOf<
  571. SemIR::AssociatedEntityType, SemIR::FacetType, SemIR::FunctionType,
  572. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  573. SemIR::GenericInterfaceType, SemIR::UnboundElementType,
  574. SemIR::WhereExpr>())
  575. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  576. -> llvm::Type* {
  577. // Return an empty struct as a placeholder.
  578. // TODO: Should we model an interface as a witness table, or an associated
  579. // entity as an index?
  580. return llvm::StructType::get(context.llvm_context());
  581. }
  582. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  583. // Use overload resolution to select the implementation, producing compile
  584. // errors when BuildTypeForInst isn't defined for a given instruction.
  585. CARBON_KIND_SWITCH(sem_ir_->insts().Get(inst_id)) {
  586. #define CARBON_SEM_IR_INST_KIND(Name) \
  587. case CARBON_KIND(SemIR::Name inst): { \
  588. return BuildTypeForInst(*this, inst); \
  589. }
  590. #include "toolchain/sem_ir/inst_kind.def"
  591. }
  592. }
  593. auto FileContext::BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  594. -> llvm::GlobalVariable* {
  595. // TODO: Mangle name.
  596. auto mangled_name =
  597. *sem_ir().names().GetAsStringIfIdentifier(var_storage.pretty_name_id);
  598. auto* type = GetType(var_storage.type_id);
  599. return new llvm::GlobalVariable(
  600. llvm_module(), type,
  601. /*isConstant=*/false, llvm::GlobalVariable::InternalLinkage,
  602. llvm::Constant::getNullValue(type), mangled_name);
  603. }
  604. auto FileContext::GetLocForDI(SemIR::InstId inst_id) -> LocForDI {
  605. SemIR::AbsoluteNodeId resolved = GetAbsoluteNodeId(sem_ir_, inst_id).back();
  606. const auto& tree_and_subtrees =
  607. (*tree_and_subtrees_getters_for_debug_info_)[resolved.check_ir_id
  608. .index]();
  609. const auto& tokens = tree_and_subtrees.tree().tokens();
  610. if (resolved.node_id.has_value()) {
  611. auto token = tree_and_subtrees.GetSubtreeTokenRange(resolved.node_id).begin;
  612. return {.filename = tokens.source().filename(),
  613. .line_number = tokens.GetLineNumber(token),
  614. .column_number = tokens.GetColumnNumber(token)};
  615. } else {
  616. return {.filename = tokens.source().filename(),
  617. .line_number = 0,
  618. .column_number = 0};
  619. }
  620. }
  621. } // namespace Carbon::Lower