file_context.cpp 31 KB

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