file_context.cpp 28 KB

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