file_context.cpp 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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 <memory>
  6. #include <optional>
  7. #include <string>
  8. #include <utility>
  9. #include "clang/CodeGen/ModuleBuilder.h"
  10. #include "common/check.h"
  11. #include "common/pretty_stack_trace_function.h"
  12. #include "common/vlog.h"
  13. #include "llvm/ADT/STLExtras.h"
  14. #include "llvm/ADT/Sequence.h"
  15. #include "llvm/Linker/Linker.h"
  16. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  17. #include "llvm/Transforms/Utils/ModuleUtils.h"
  18. #include "toolchain/base/kind_switch.h"
  19. #include "toolchain/lower/clang_global_decl.h"
  20. #include "toolchain/lower/constant.h"
  21. #include "toolchain/lower/function_context.h"
  22. #include "toolchain/lower/mangler.h"
  23. #include "toolchain/lower/options.h"
  24. #include "toolchain/lower/specific_coalescer.h"
  25. #include "toolchain/sem_ir/absolute_node_id.h"
  26. #include "toolchain/sem_ir/diagnostic_loc_converter.h"
  27. #include "toolchain/sem_ir/entry_point.h"
  28. #include "toolchain/sem_ir/expr_info.h"
  29. #include "toolchain/sem_ir/file.h"
  30. #include "toolchain/sem_ir/function.h"
  31. #include "toolchain/sem_ir/generic.h"
  32. #include "toolchain/sem_ir/ids.h"
  33. #include "toolchain/sem_ir/inst.h"
  34. #include "toolchain/sem_ir/inst_categories.h"
  35. #include "toolchain/sem_ir/inst_kind.h"
  36. #include "toolchain/sem_ir/pattern.h"
  37. #include "toolchain/sem_ir/stringify.h"
  38. #include "toolchain/sem_ir/typed_insts.h"
  39. namespace Carbon::Lower {
  40. FileContext::FileContext(Context& context, const SemIR::File& sem_ir,
  41. const SemIR::InstNamer* inst_namer,
  42. llvm::raw_ostream* vlog_stream)
  43. : context_(&context),
  44. sem_ir_(&sem_ir),
  45. inst_namer_(inst_namer),
  46. vlog_stream_(vlog_stream),
  47. functions_(LoweredFunctionStore::MakeForOverwrite(sem_ir.functions())),
  48. specific_functions_(sem_ir.specifics(), nullptr),
  49. types_(LoweredTypeStore::MakeWithExplicitSize(
  50. sem_ir.insts().GetIdTag(), sem_ir.insts().size(), nullptr)),
  51. constants_(LoweredConstantStore::MakeWithExplicitSize(
  52. sem_ir.insts().GetIdTag(), sem_ir.insts().size(), nullptr)),
  53. lowered_specifics_(sem_ir.generics(),
  54. llvm::SmallVector<SemIR::SpecificId>()),
  55. coalescer_(vlog_stream_, sem_ir.specifics()),
  56. vtables_(decltype(vtables_)::MakeForOverwrite(sem_ir.vtables())),
  57. specific_vtables_(sem_ir.specifics(), nullptr) {
  58. // Initialization that relies on invariants of the class.
  59. cpp_code_generator_ = CreateCppCodeGenerator();
  60. CARBON_CHECK(!sem_ir.has_errors(),
  61. "Generating LLVM IR from invalid SemIR::File is unsupported.");
  62. }
  63. // TODO: Move this to lower.cpp.
  64. auto FileContext::PrepareToLower() -> void {
  65. if (cpp_code_generator_) {
  66. // Clang code generation should not actually modify the AST, but isn't
  67. // const-correct.
  68. cpp_code_generator_->Initialize(
  69. const_cast<clang::ASTContext&>(clang_ast_unit()->getASTContext()));
  70. // Work around `visitLocalTopLevelDecls` not being const. It doesn't modify
  71. // the AST unit other than triggering deserialization.
  72. auto* non_const_ast_unit = const_cast<clang::ASTUnit*>(clang_ast_unit());
  73. // Emit any top-level declarations now.
  74. // TODO: This may miss things that we need to emit which are handed to the
  75. // ASTConsumer in other ways. Instead of doing this, we should create the
  76. // CodeGenerator earlier and register it as an ASTConsumer before we parse
  77. // the C++ inputs.
  78. non_const_ast_unit->visitLocalTopLevelDecls(
  79. cpp_code_generator_.get(),
  80. [](void* codegen_ptr, const clang::Decl* decl) {
  81. auto* codegen = static_cast<clang::CodeGenerator*>(codegen_ptr);
  82. // CodeGenerator won't modify the declaration it's given, but we can
  83. // only call it via the ASTConsumer interface which doesn't know that.
  84. auto* non_const_decl = const_cast<clang::Decl*>(decl);
  85. codegen->HandleTopLevelDecl(clang::DeclGroupRef(non_const_decl));
  86. return true;
  87. });
  88. }
  89. // Lower all types that were required to be complete.
  90. for (auto type_id : sem_ir_->types().complete_types()) {
  91. if (type_id.index >= 0) {
  92. types_.Set(type_id, BuildType(sem_ir_->types().GetInstId(type_id)));
  93. }
  94. }
  95. // Lower function declarations.
  96. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  97. functions_.Set(id, BuildFunctionDecl(id));
  98. }
  99. // TODO: Split vtable declaration creation from definition creation to avoid
  100. // redundant vtable definitions for imported vtables.
  101. for (const auto& [id, vtable] : sem_ir_->vtables().enumerate()) {
  102. const auto& class_info = sem_ir().classes().Get(vtable.class_id);
  103. // Vtables can't be generated for generics, only for their specifics - and
  104. // must be done lazily based on the use of those specifics.
  105. if (!class_info.generic_id.has_value()) {
  106. vtables_.Set(id, BuildVtable(vtable, SemIR::SpecificId::None));
  107. }
  108. }
  109. // Lower constants.
  110. LowerConstants(*this, constants_);
  111. }
  112. // TODO: Move this to lower.cpp.
  113. auto FileContext::LowerDefinitions() -> void {
  114. // Lower global variable definitions.
  115. // TODO: Storing both a `constants_` array and a separate `global_variables_`
  116. // map is redundant.
  117. for (auto inst_id :
  118. sem_ir().inst_blocks().Get(sem_ir().top_inst_block_id())) {
  119. // Only `VarStorage` indicates a global variable declaration in the
  120. // top instruction block.
  121. if (auto var = sem_ir().insts().TryGetAs<SemIR::VarStorage>(inst_id)) {
  122. // Get the global variable declaration. We created this when lowering the
  123. // constant unless the variable is unnamed, in which case we need to
  124. // create it now.
  125. llvm::GlobalVariable* llvm_var = nullptr;
  126. if (auto const_id = sem_ir().constant_values().Get(inst_id);
  127. const_id.is_constant()) {
  128. llvm_var = cast<llvm::GlobalVariable>(GetConstant(const_id, inst_id));
  129. } else {
  130. llvm_var = BuildGlobalVariableDecl(*var);
  131. }
  132. // Convert the declaration of this variable into a definition by adding an
  133. // initializer.
  134. global_variables_.Insert(inst_id, llvm_var);
  135. llvm_var->setInitializer(
  136. llvm::Constant::getNullValue(llvm_var->getValueType()));
  137. }
  138. }
  139. // Lower function definitions.
  140. for (auto [id, fn_info] : sem_ir_->functions().enumerate()) {
  141. // If we created a declaration and the function definition is not imported,
  142. // build a definition.
  143. if (functions_.Get(id) && fn_info.definition_id.has_value() &&
  144. !sem_ir().insts().GetImportSource(fn_info.definition_id).has_value()) {
  145. BuildFunctionDefinition(id);
  146. }
  147. }
  148. // Append `__global_init` to `llvm::global_ctors` to initialize global
  149. // variables.
  150. if (auto global_ctor_id = sem_ir().global_ctor_id();
  151. global_ctor_id.has_value()) {
  152. const auto& global_ctor = sem_ir().functions().Get(global_ctor_id);
  153. BuildFunctionBody(global_ctor_id, SemIR::SpecificId::None, global_ctor,
  154. *this, global_ctor);
  155. llvm::appendToGlobalCtors(llvm_module(),
  156. GetFunction(sem_ir().global_ctor_id()),
  157. /*Priority=*/0);
  158. }
  159. }
  160. auto FileContext::Finalize() -> void {
  161. if (cpp_code_generator_) {
  162. // Clang code generation should not actually modify the AST, but isn't
  163. // const-correct.
  164. cpp_code_generator_->HandleTranslationUnit(
  165. const_cast<clang::ASTContext&>(clang_ast_unit()->getASTContext()));
  166. bool link_error = llvm::Linker::linkModules(
  167. /*Dest=*/llvm_module(),
  168. /*Src=*/std::unique_ptr<llvm::Module>(
  169. cpp_code_generator_->ReleaseModule()));
  170. CARBON_CHECK(!link_error);
  171. }
  172. // Find equivalent specifics (from the same generic), replace all uses and
  173. // remove duplicately lowered function definitions.
  174. coalescer_.CoalesceEquivalentSpecifics(lowered_specifics_,
  175. specific_functions_);
  176. }
  177. auto FileContext::CreateCppCodeGenerator()
  178. -> std::unique_ptr<clang::CodeGenerator> {
  179. if (!clang_ast_unit()) {
  180. return nullptr;
  181. }
  182. RawStringOstream clang_module_name_stream;
  183. clang_module_name_stream << llvm_module().getName() << ".clang";
  184. // Do not emit Clang's name and version as the creator of the output file.
  185. cpp_code_gen_options_.EmitVersionIdentMetadata = false;
  186. return std::unique_ptr<clang::CodeGenerator>(clang::CreateLLVMCodeGen(
  187. clang_ast_unit()->getASTContext().getDiagnostics(),
  188. clang_module_name_stream.TakeStr(), context().file_system(),
  189. cpp_header_search_options_, cpp_preprocessor_options_,
  190. cpp_code_gen_options_, llvm_context()));
  191. }
  192. auto FileContext::GetConstant(SemIR::ConstantId const_id,
  193. SemIR::InstId use_inst_id) -> llvm::Value* {
  194. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  195. auto* const_value = constants_.Get(const_inst_id);
  196. // For value expressions and initializing expressions, the value produced by
  197. // a constant instruction is a value representation of the constant. For
  198. // initializing expressions, `FinishInit` will perform a copy if needed.
  199. switch (auto cat = SemIR::GetExprCategory(sem_ir(), const_inst_id)) {
  200. case SemIR::ExprCategory::Value:
  201. case SemIR::ExprCategory::Initializing:
  202. break;
  203. case SemIR::ExprCategory::DurableRef:
  204. case SemIR::ExprCategory::EphemeralRef:
  205. // Constant reference expressions lower to an address.
  206. return const_value;
  207. case SemIR::ExprCategory::NotExpr:
  208. case SemIR::ExprCategory::Error:
  209. case SemIR::ExprCategory::Mixed:
  210. CARBON_FATAL("Unexpected category {0} for lowered constant {1}", cat,
  211. sem_ir().insts().Get(const_inst_id));
  212. };
  213. auto value_rep = SemIR::ValueRepr::ForType(
  214. sem_ir(), sem_ir().insts().Get(const_inst_id).type_id());
  215. if (value_rep.kind != SemIR::ValueRepr::Pointer) {
  216. return const_value;
  217. }
  218. // The value representation is a pointer. Generate a variable to hold the
  219. // value, or find and reuse an existing one.
  220. if (auto result = global_variables().Lookup(const_inst_id)) {
  221. return result.value();
  222. }
  223. // Include both the name of the constant, if any, and the point of use in
  224. // the name of the variable.
  225. llvm::StringRef const_name;
  226. llvm::StringRef use_name;
  227. if (inst_namer_) {
  228. const_name = inst_namer_->GetUnscopedNameFor(const_inst_id);
  229. if (use_inst_id.has_value()) {
  230. use_name = inst_namer_->GetUnscopedNameFor(use_inst_id);
  231. }
  232. }
  233. // We always need to give the global a name even if the instruction namer
  234. // doesn't have one to use.
  235. if (const_name.empty()) {
  236. const_name = "const";
  237. }
  238. if (use_name.empty()) {
  239. use_name = "anon";
  240. }
  241. llvm::StringRef sep = (use_name[0] == '.') ? "" : ".";
  242. auto* global_variable = new llvm::GlobalVariable(
  243. llvm_module(), GetType(sem_ir().GetPointeeType(value_rep.type_id)),
  244. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage, const_value,
  245. const_name + sep + use_name);
  246. global_variables_.Insert(const_inst_id, global_variable);
  247. return global_variable;
  248. }
  249. auto FileContext::GetOrCreateFunction(SemIR::FunctionId function_id,
  250. SemIR::SpecificId specific_id)
  251. -> llvm::Function* {
  252. // If we have already lowered a declaration of this function, just return it.
  253. auto** result = GetFunctionAddr(function_id, specific_id);
  254. if (!*result) {
  255. *result = BuildFunctionDecl(function_id, specific_id);
  256. }
  257. return *result;
  258. }
  259. auto FileContext::BuildFunctionTypeInfo(const SemIR::Function& function,
  260. SemIR::SpecificId specific_id)
  261. -> FunctionTypeInfo {
  262. const auto return_info =
  263. SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id);
  264. if (!return_info.is_valid()) {
  265. // The return type has not been completed, create a trivial type instead.
  266. return {.type =
  267. llvm::FunctionType::get(llvm::Type::getVoidTy(llvm_context()),
  268. /*isVarArg=*/false)};
  269. }
  270. auto get_llvm_type = [&](SemIR::TypeId type_id) -> llvm::Type* {
  271. if (!type_id.has_value()) {
  272. return nullptr;
  273. }
  274. return GetType(type_id);
  275. };
  276. // TODO: expose the `Call` parameter patterns in `Function`, and use them here
  277. // instead of reconstructing them via the syntactic parameter lists.
  278. auto implicit_param_patterns =
  279. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_patterns_id);
  280. auto param_patterns =
  281. sem_ir().inst_blocks().GetOrEmpty(function.param_patterns_id);
  282. auto* return_type = get_llvm_type(return_info.type_id);
  283. llvm::SmallVector<llvm::Type*> param_types;
  284. // Compute the return type to use for the LLVM function. If the initializing
  285. // representation doesn't produce a value, set the return type to void.
  286. // TODO: For the `Run` entry point, remap return type to i32 if it doesn't
  287. // return a value.
  288. llvm::Type* function_return_type =
  289. (return_info.is_valid() &&
  290. return_info.init_repr.kind == SemIR::InitRepr::ByCopy)
  291. ? return_type
  292. : llvm::Type::getVoidTy(llvm_context());
  293. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  294. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  295. // out a mechanism to compute the mapping between parameters and arguments on
  296. // demand.
  297. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  298. auto max_llvm_params = (return_info.has_return_slot() ? 1 : 0) +
  299. implicit_param_patterns.size() + param_patterns.size();
  300. param_types.reserve(max_llvm_params);
  301. param_inst_ids.reserve(max_llvm_params);
  302. auto return_param_id = SemIR::InstId::None;
  303. if (return_info.has_return_slot()) {
  304. param_types.push_back(
  305. llvm::PointerType::get(llvm_context(), /*AddressSpace=*/0));
  306. return_param_id = function.return_slot_pattern_id;
  307. param_inst_ids.push_back(return_param_id);
  308. }
  309. for (auto param_pattern_id : llvm::concat<const SemIR::InstId>(
  310. implicit_param_patterns, param_patterns)) {
  311. // TODO: Handle a general pattern here, rather than assuming that each
  312. // parameter pattern contains at most one binding.
  313. auto param_pattern_info = SemIR::Function::GetParamPatternInfoFromPatternId(
  314. sem_ir(), param_pattern_id);
  315. if (!param_pattern_info) {
  316. continue;
  317. }
  318. // TODO: Use a more general mechanism to determine if the binding is a
  319. // reference binding.
  320. if (param_pattern_info->inst.kind == SemIR::RefParamPattern::Kind) {
  321. param_types.push_back(
  322. llvm::PointerType::get(llvm_context(), /*AddressSpace=*/0));
  323. param_inst_ids.push_back(param_pattern_id);
  324. continue;
  325. }
  326. auto param_type_id = ExtractScrutineeType(
  327. sem_ir(), SemIR::GetTypeOfInstInSpecific(sem_ir(), specific_id,
  328. param_pattern_info->inst_id));
  329. CARBON_CHECK(
  330. !param_type_id.AsConstantId().is_symbolic(),
  331. "Found symbolic type id after resolution when lowering type {0}.",
  332. param_pattern_info->inst.type_id);
  333. switch (auto value_rep = SemIR::ValueRepr::ForType(sem_ir(), param_type_id);
  334. value_rep.kind) {
  335. case SemIR::ValueRepr::Unknown:
  336. // This parameter type is incomplete. Fallback to describing the
  337. // function type as `void()`.
  338. return {.type = llvm::FunctionType::get(
  339. llvm::Type::getVoidTy(llvm_context()),
  340. /*isVarArg=*/false)};
  341. case SemIR::ValueRepr::Dependent:
  342. CARBON_FATAL("Lowering function with dependent parameter type");
  343. case SemIR::ValueRepr::None:
  344. break;
  345. case SemIR::ValueRepr::Copy:
  346. case SemIR::ValueRepr::Custom:
  347. case SemIR::ValueRepr::Pointer:
  348. auto* param_types_to_add = get_llvm_type(value_rep.type_id);
  349. param_types.push_back(param_types_to_add);
  350. param_inst_ids.push_back(param_pattern_id);
  351. break;
  352. }
  353. }
  354. return {.type = llvm::FunctionType::get(function_return_type, param_types,
  355. /*isVarArg=*/false),
  356. .param_inst_ids = std::move(param_inst_ids),
  357. .return_type = return_type,
  358. .return_param_id = return_param_id};
  359. }
  360. auto FileContext::HandleReferencedCppFunction(clang::FunctionDecl* cpp_decl)
  361. -> void {
  362. // TODO: To support recursive inline functions, collect all calls to
  363. // `HandleTopLevelDecl()` in a custom `ASTConsumer` configured in the
  364. // `ASTUnit`, and replay them in lowering in the `CodeGenerator`. See
  365. // https://discord.com/channels/655572317891461132/768530752592805919/1370509111585935443
  366. clang::FunctionDecl* cpp_def = cpp_decl->getDefinition();
  367. if (!cpp_def) {
  368. return;
  369. }
  370. // Create the LLVM function (`CodeGenModule::GetOrCreateLLVMFunction()`)
  371. // so that code generation (`CodeGenModule::EmitGlobal()`) would see this
  372. // function name (`CodeGenModule::getMangledName()`), and will generate
  373. // its definition.
  374. llvm::Constant* function_address =
  375. cpp_code_generator_->GetAddrOfGlobal(CreateGlobalDecl(cpp_def),
  376. /*isForDefinition=*/false);
  377. CARBON_CHECK(function_address);
  378. }
  379. auto FileContext::HandleReferencedSpecificFunction(
  380. SemIR::FunctionId function_id, SemIR::SpecificId specific_id,
  381. llvm::Type* llvm_type) -> void {
  382. CARBON_CHECK(specific_id.has_value());
  383. // Add this specific function to a list of specific functions whose
  384. // definitions we need to emit.
  385. // TODO: Don't do this if we know this function is emitted as a
  386. // non-discardable symbol in the IR for some other file.
  387. context().AddPendingSpecificFunctionDefinition({.context = this,
  388. .function_id = function_id,
  389. .specific_id = specific_id});
  390. // Create a unique fingerprint for the function type.
  391. // For now, we compute the function type fingerprint only for specifics,
  392. // though we might need it for all functions in order to create a canonical
  393. // fingerprint across translation units.
  394. coalescer_.CreateTypeFingerprint(specific_id, llvm_type);
  395. }
  396. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id,
  397. SemIR::SpecificId specific_id)
  398. -> llvm::Function* {
  399. const auto& function = sem_ir().functions().Get(function_id);
  400. // Don't lower generic functions. Note that associated functions in interfaces
  401. // have `Self` in scope, so are implicitly generic functions.
  402. if (function.generic_id.has_value() && !specific_id.has_value()) {
  403. return nullptr;
  404. }
  405. // Don't lower builtins.
  406. if (function.builtin_function_kind() != SemIR::BuiltinFunctionKind::None) {
  407. return nullptr;
  408. }
  409. // Don't lower C++ functions that use a thunk. We will never reference them
  410. // directly, and their signatures would not be expected to match the
  411. // corresponding C++ function anyway.
  412. if (function.special_function_kind ==
  413. SemIR::Function::SpecialFunctionKind::HasCppThunk) {
  414. return nullptr;
  415. }
  416. // TODO: Consider tracking whether the function has been used, and only
  417. // lowering it if it's needed.
  418. auto function_type_info = BuildFunctionTypeInfo(function, specific_id);
  419. // TODO: For an imported inline function, consider generating an
  420. // `available_externally` definition.
  421. auto linkage = specific_id.has_value() ? llvm::Function::LinkOnceODRLinkage
  422. : llvm::Function::ExternalLinkage;
  423. Mangler m(*this);
  424. std::string mangled_name = m.Mangle(function_id, specific_id);
  425. if (auto* existing = llvm_module().getFunction(mangled_name)) {
  426. // We might have already lowered this function while lowering a different
  427. // file. That's OK.
  428. // TODO: Check-fail or maybe diagnose if the two LLVM functions are not
  429. // produced by declarations of the same Carbon function. Name collisions
  430. // between non-private members of the same library should have been
  431. // diagnosed by check if detected, but it's not clear that check will always
  432. // be able to see this problem. In theory, name collisions could also occur
  433. // due to fingerprint collision.
  434. return existing;
  435. }
  436. // If this is a C++ function, tell Clang that we referenced it.
  437. if (auto clang_decl_id = sem_ir().functions().Get(function_id).clang_decl_id;
  438. clang_decl_id.has_value()) {
  439. CARBON_CHECK(!specific_id.has_value(),
  440. "Specific functions cannot have C++ definitions");
  441. HandleReferencedCppFunction(
  442. sem_ir().clang_decls().Get(clang_decl_id).key.decl->getAsFunction());
  443. // TODO: Check that the signature and mangling generated by Clang and the
  444. // one we generated are the same.
  445. }
  446. // If this is a specific function, we may need to do additional work to emit
  447. // its definition.
  448. if (specific_id.has_value()) {
  449. HandleReferencedSpecificFunction(function_id, specific_id,
  450. function_type_info.type);
  451. }
  452. auto* llvm_function = llvm::Function::Create(function_type_info.type, linkage,
  453. mangled_name, llvm_module());
  454. CARBON_CHECK(llvm_function->getName() == mangled_name,
  455. "Mangled name collision: {0}", mangled_name);
  456. // Set up parameters and the return slot.
  457. for (auto [inst_id, arg] : llvm::zip_equal(function_type_info.param_inst_ids,
  458. llvm_function->args())) {
  459. auto name_id = SemIR::NameId::None;
  460. if (inst_id == function_type_info.return_param_id) {
  461. name_id = SemIR::NameId::ReturnSlot;
  462. arg.addAttr(llvm::Attribute::getWithStructRetType(
  463. llvm_context(), function_type_info.return_type));
  464. } else {
  465. name_id = SemIR::GetPrettyNameFromPatternId(sem_ir(), inst_id);
  466. }
  467. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  468. }
  469. return llvm_function;
  470. }
  471. // Find the file and function ID describing the definition of a function.
  472. static auto GetFunctionDefinition(const SemIR::File* decl_ir,
  473. SemIR::FunctionId function_id)
  474. -> std::pair<const SemIR::File*, SemIR::FunctionId> {
  475. // Find the file containing the definition.
  476. auto decl_id = decl_ir->functions().Get(function_id).definition_id;
  477. if (!decl_id.has_value()) {
  478. // Function is not defined.
  479. return {nullptr, SemIR::FunctionId::None};
  480. }
  481. // Find the function declaration this function was originally imported from.
  482. while (true) {
  483. auto import_inst_id = decl_ir->insts().GetImportSource(decl_id);
  484. if (!import_inst_id.has_value()) {
  485. break;
  486. }
  487. auto import_inst = decl_ir->import_ir_insts().Get(import_inst_id);
  488. decl_ir = decl_ir->import_irs().Get(import_inst.ir_id()).sem_ir;
  489. decl_id = import_inst.inst_id();
  490. }
  491. auto decl_ir_function_id =
  492. decl_ir->insts().GetAs<SemIR::FunctionDecl>(decl_id).function_id;
  493. return {decl_ir, decl_ir_function_id};
  494. }
  495. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id,
  496. SemIR::SpecificId specific_id)
  497. -> void {
  498. auto [definition_ir, definition_ir_function_id] =
  499. GetFunctionDefinition(&sem_ir(), function_id);
  500. if (!definition_ir) {
  501. // Function is probably defined in another file; not an error.
  502. return;
  503. }
  504. const auto& definition_function =
  505. definition_ir->functions().Get(definition_ir_function_id);
  506. BuildFunctionBody(
  507. function_id, specific_id, sem_ir().functions().Get(function_id),
  508. context().GetFileContext(definition_ir), definition_function);
  509. }
  510. auto FileContext::BuildFunctionBody(SemIR::FunctionId function_id,
  511. SemIR::SpecificId specific_id,
  512. const SemIR::Function& declaration_function,
  513. FileContext& definition_context,
  514. const SemIR::Function& definition_function)
  515. -> void {
  516. // On crash, report the function we were lowering.
  517. PrettyStackTraceFunction stack_trace_entry([&](llvm::raw_ostream& output) {
  518. SemIR::DiagnosticLocConverter converter(
  519. &context().tree_and_subtrees_getters(), &sem_ir());
  520. auto converted =
  521. converter.Convert(SemIR::LocId(declaration_function.definition_id),
  522. /*token_only=*/false);
  523. converted.loc.FormatLocation(output);
  524. output << "Lowering function ";
  525. if (specific_id.has_value()) {
  526. output << SemIR::StringifySpecific(sem_ir(), specific_id);
  527. } else {
  528. output << SemIR::StringifyConstantInst(
  529. sem_ir(), declaration_function.definition_id);
  530. }
  531. output << "\n";
  532. // Crash output has a tab indent; try to indent slightly past that.
  533. converted.loc.FormatSnippet(output, /*indent=*/10);
  534. });
  535. // Note that `definition_function` is potentially from a different SemIR::File
  536. // than the one that this file context represents. Any lowering done for
  537. // values derived from `definition_function` should use `definition_context`
  538. // instead of our context.
  539. const auto& definition_ir = definition_context.sem_ir();
  540. auto* llvm_function = GetFunction(function_id, specific_id);
  541. CARBON_CHECK(llvm_function,
  542. "Attempting to define function that was not declared");
  543. const auto& body_block_ids = definition_function.body_block_ids;
  544. CARBON_DCHECK(!body_block_ids.empty(),
  545. "No function body blocks found during lowering.");
  546. // Store which specifics were already lowered (with definitions) for each
  547. // generic.
  548. if (declaration_function.generic_id.has_value() && specific_id.has_value()) {
  549. // TODO: We should track this in the definition context instead so that we
  550. // can deduplicate specifics from different files.
  551. AddLoweredSpecificForGeneric(declaration_function.generic_id, specific_id);
  552. }
  553. // Set attributes on the function definition.
  554. {
  555. llvm::AttrBuilder attr_builder(llvm_context());
  556. attr_builder.addAttribute(llvm::Attribute::NoUnwind);
  557. // TODO: We should take the opt level from the SemIR file; it might not be
  558. // the same for all files in a compilation.
  559. if (context().opt_level() == Lower::OptimizationLevel::None) {
  560. // --optimize=none disables all optimizations for this function.
  561. attr_builder.addAttribute(llvm::Attribute::OptimizeNone);
  562. attr_builder.addAttribute(llvm::Attribute::NoInline);
  563. } else {
  564. // Otherwise, always inline thunks.
  565. if (definition_function.special_function_kind ==
  566. SemIR::Function::SpecialFunctionKind::Thunk) {
  567. attr_builder.addAttribute(llvm::Attribute::AlwaysInline);
  568. }
  569. // Convert --optimize=size into optsize and minsize.
  570. if (context().opt_level() == Lower::OptimizationLevel::Size) {
  571. attr_builder.addAttribute(llvm::Attribute::OptimizeForSize);
  572. attr_builder.addAttribute(llvm::Attribute::MinSize);
  573. }
  574. // TODO: Should we generate an InlineHint for some functions? Perhaps for
  575. // those defined in the API file?
  576. }
  577. llvm_function->addFnAttrs(attr_builder);
  578. }
  579. FunctionContext function_lowering(
  580. definition_context, llvm_function, *this, specific_id,
  581. coalescer_.InitializeFingerprintForSpecific(specific_id),
  582. definition_context.BuildDISubprogram(definition_function, llvm_function),
  583. vlog_stream_);
  584. // Add parameters to locals.
  585. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  586. // function parameters that was already computed in BuildFunctionDecl.
  587. // We should only do that once.
  588. auto call_param_ids = definition_ir.inst_blocks().GetOrEmpty(
  589. definition_function.call_params_id);
  590. int param_index = 0;
  591. // TODO: Find a way to ensure this code and the function-call lowering use
  592. // the same parameter ordering.
  593. // Lowers the given parameter. Must be called in LLVM calling convention
  594. // parameter order.
  595. auto lower_param = [&](SemIR::InstId param_id) {
  596. // Get the value of the parameter from the function argument.
  597. llvm::Value* param_value;
  598. // The `type_id` of a parameter tracks the parameter's type.
  599. CARBON_CHECK(definition_ir.insts().Is<SemIR::AnyParam>(param_id));
  600. auto param_type = function_lowering.GetTypeIdOfInst(param_id);
  601. if (function_lowering.GetValueRepr(param_type).repr.kind !=
  602. SemIR::ValueRepr::None) {
  603. param_value = llvm_function->getArg(param_index);
  604. ++param_index;
  605. } else {
  606. param_value =
  607. llvm::PoisonValue::get(function_lowering.GetType(param_type));
  608. }
  609. // The value of the parameter is the value of the argument.
  610. function_lowering.SetLocal(param_id, param_value);
  611. };
  612. // Lower the return slot parameter.
  613. if (declaration_function.return_slot_pattern_id.has_value()) {
  614. auto call_param_id = call_param_ids.consume_back();
  615. // The LLVM calling convention has the return slot first rather than last.
  616. // Note that this queries whether there is a return slot at the LLVM level,
  617. // whereas `function.return_slot_pattern_id.has_value()` queries whether
  618. // there is a return slot at the SemIR level.
  619. if (SemIR::ReturnTypeInfo::ForFunction(sem_ir(), declaration_function,
  620. specific_id)
  621. .has_return_slot()) {
  622. lower_param(call_param_id);
  623. } else {
  624. // The return slot might still be mentioned as a destination location, but
  625. // shouldn't actually be used for anything, so we can use a poison value
  626. // for it.
  627. function_lowering.SetLocal(call_param_id,
  628. llvm::PoisonValue::get(llvm::PointerType::get(
  629. llvm_context(), /*AddressSpace=*/0)));
  630. }
  631. }
  632. // Lower the remaining call parameters.
  633. for (auto param_id : call_param_ids) {
  634. lower_param(param_id);
  635. }
  636. auto decl_block_id = SemIR::InstBlockId::None;
  637. if (function_id == sem_ir().global_ctor_id()) {
  638. decl_block_id = SemIR::InstBlockId::Empty;
  639. } else {
  640. decl_block_id =
  641. definition_ir.insts()
  642. .GetAs<SemIR::FunctionDecl>(definition_function.latest_decl_id())
  643. .decl_block_id;
  644. }
  645. // Lowers the contents of decl_block_id into the corresponding LLVM block,
  646. // creating it if it doesn't already exist.
  647. auto lower_block = [&](SemIR::InstBlockId block_id) {
  648. CARBON_VLOG("Lowering {0}\n", block_id);
  649. auto* llvm_block = function_lowering.GetBlock(block_id);
  650. // Keep the LLVM blocks in lexical order.
  651. llvm_block->moveBefore(llvm_function->end());
  652. function_lowering.builder().SetInsertPoint(llvm_block);
  653. function_lowering.LowerBlockContents(block_id);
  654. };
  655. lower_block(decl_block_id);
  656. // If the decl block is empty, reuse it as the first body block. We don't do
  657. // this when the decl block is non-empty so that any branches back to the
  658. // first body block don't also re-execute the decl.
  659. llvm::BasicBlock* block = function_lowering.builder().GetInsertBlock();
  660. if (block->empty() &&
  661. function_lowering.TryToReuseBlock(body_block_ids.front(), block)) {
  662. // Reuse this block as the first block of the function body.
  663. } else {
  664. function_lowering.builder().CreateBr(
  665. function_lowering.GetBlock(body_block_ids.front()));
  666. }
  667. // Lower all blocks.
  668. for (auto block_id : body_block_ids) {
  669. lower_block(block_id);
  670. }
  671. // LLVM requires that the entry block has no predecessors.
  672. auto* entry_block = &llvm_function->getEntryBlock();
  673. if (entry_block->hasNPredecessorsOrMore(1)) {
  674. auto* new_entry_block = llvm::BasicBlock::Create(
  675. llvm_context(), "entry", llvm_function, entry_block);
  676. llvm::BranchInst::Create(entry_block, new_entry_block);
  677. }
  678. // Emit fingerprint accumulated inside the function context.
  679. function_lowering.EmitFinalFingerprint();
  680. }
  681. auto FileContext::BuildDISubprogram(const SemIR::Function& function,
  682. const llvm::Function* llvm_function)
  683. -> llvm::DISubprogram* {
  684. if (!context().di_compile_unit()) {
  685. return nullptr;
  686. }
  687. auto name = sem_ir().names().GetAsStringIfIdentifier(function.name_id);
  688. CARBON_CHECK(name, "Unexpected special name for function: {0}",
  689. function.name_id);
  690. auto loc = GetLocForDI(function.definition_id);
  691. // TODO: Add more details here, including real subroutine type (once type
  692. // information is built), etc.
  693. return context().di_builder().createFunction(
  694. context().di_compile_unit(), *name, llvm_function->getName(),
  695. /*File=*/context().di_builder().createFile(loc.filename, ""),
  696. /*LineNo=*/loc.line_number,
  697. context().di_builder().createSubroutineType(
  698. context().di_builder().getOrCreateTypeArray({})),
  699. /*ScopeLine=*/0, llvm::DINode::FlagZero,
  700. llvm::DISubprogram::SPFlagDefinition);
  701. }
  702. // BuildTypeForInst is used to construct types for FileContext::BuildType below.
  703. // Implementations return the LLVM type for the instruction. This first overload
  704. // is the fallback handler for non-type instructions.
  705. template <typename InstT>
  706. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  707. static auto BuildTypeForInst(FileContext& /*context*/, InstT inst)
  708. -> llvm::Type* {
  709. CARBON_FATAL("Cannot use inst as type: {0}", inst);
  710. }
  711. template <typename InstT>
  712. requires(InstT::Kind.is_symbolic_when_type())
  713. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  714. -> llvm::Type* {
  715. // Treat non-monomorphized symbolic types as opaque.
  716. return llvm::StructType::get(context.llvm_context());
  717. }
  718. static auto BuildTypeForInst(FileContext& context, SemIR::ArrayType inst)
  719. -> llvm::Type* {
  720. return llvm::ArrayType::get(
  721. context.GetType(context.sem_ir().types().GetTypeIdForTypeInstId(
  722. inst.element_type_inst_id)),
  723. *context.sem_ir().GetArrayBoundValue(inst.bound_id));
  724. }
  725. static auto BuildTypeForInst(FileContext& context, SemIR::BoolType /*inst*/)
  726. -> llvm::Type* {
  727. // TODO: We may want to have different representations for `bool` storage
  728. // (`i8`) versus for `bool` values (`i1`).
  729. return llvm::Type::getInt1Ty(context.llvm_context());
  730. }
  731. static auto BuildTypeForInst(FileContext& context, SemIR::ClassType inst)
  732. -> llvm::Type* {
  733. auto object_repr_id = context.sem_ir()
  734. .classes()
  735. .Get(inst.class_id)
  736. .GetObjectRepr(context.sem_ir(), inst.specific_id);
  737. return context.GetType(object_repr_id);
  738. }
  739. template <typename InstT>
  740. requires(SemIR::Internal::HasInstCategory<SemIR::AnyQualifiedType, InstT>)
  741. static auto BuildTypeForInst(FileContext& context, InstT inst) -> llvm::Type* {
  742. return context.GetType(
  743. context.sem_ir().types().GetTypeIdForTypeInstId(inst.inner_id));
  744. }
  745. static auto BuildTypeForInst(FileContext& context, SemIR::CustomLayoutType inst)
  746. -> llvm::Type* {
  747. auto layout = context.sem_ir().custom_layouts().Get(inst.layout_id);
  748. return llvm::ArrayType::get(llvm::Type::getInt8Ty(context.llvm_context()),
  749. layout[SemIR::CustomLayoutId::SizeIndex]);
  750. }
  751. static auto BuildTypeForInst(FileContext& context,
  752. SemIR::ImplWitnessAssociatedConstant inst)
  753. -> llvm::Type* {
  754. return context.GetType(inst.type_id);
  755. }
  756. static auto BuildTypeForInst(FileContext& /*context*/,
  757. SemIR::ErrorInst /*inst*/) -> llvm::Type* {
  758. // This is a complete type but uses of it should never be lowered.
  759. return nullptr;
  760. }
  761. static auto BuildTypeForInst(FileContext& context, SemIR::FloatType inst)
  762. -> llvm::Type* {
  763. return llvm::Type::getFloatingPointTy(context.llvm_context(),
  764. inst.float_kind.Semantics());
  765. }
  766. static auto BuildTypeForInst(FileContext& context, SemIR::IntType inst)
  767. -> llvm::Type* {
  768. auto width =
  769. context.sem_ir().insts().TryGetAs<SemIR::IntValue>(inst.bit_width_id);
  770. CARBON_CHECK(width, "Can't lower int type with symbolic width");
  771. return llvm::IntegerType::get(
  772. context.llvm_context(),
  773. context.sem_ir().ints().Get(width->int_id).getZExtValue());
  774. }
  775. static auto BuildTypeForInst(FileContext& context, SemIR::PointerType /*inst*/)
  776. -> llvm::Type* {
  777. return llvm::PointerType::get(context.llvm_context(), /*AddressSpace=*/0);
  778. }
  779. static auto BuildTypeForInst(FileContext& /*context*/,
  780. SemIR::PatternType /*inst*/) -> llvm::Type* {
  781. CARBON_FATAL("Unexpected pattern type in lowering");
  782. }
  783. static auto BuildTypeForInst(FileContext& context, SemIR::StructType inst)
  784. -> llvm::Type* {
  785. auto fields = context.sem_ir().struct_type_fields().Get(inst.fields_id);
  786. llvm::SmallVector<llvm::Type*> subtypes;
  787. subtypes.reserve(fields.size());
  788. for (auto field : fields) {
  789. subtypes.push_back(context.GetType(
  790. context.sem_ir().types().GetTypeIdForTypeInstId(field.type_inst_id)));
  791. }
  792. return llvm::StructType::get(context.llvm_context(), subtypes);
  793. }
  794. static auto BuildTypeForInst(FileContext& context, SemIR::TupleType inst)
  795. -> llvm::Type* {
  796. // TODO: Investigate special-casing handling of empty tuples so that they
  797. // can be collectively replaced with LLVM's void, particularly around
  798. // function returns. LLVM doesn't allow declaring variables with a void
  799. // type, so that may require significant special casing.
  800. auto elements = context.sem_ir().inst_blocks().Get(inst.type_elements_id);
  801. llvm::SmallVector<llvm::Type*> subtypes;
  802. subtypes.reserve(elements.size());
  803. for (auto type_id : context.sem_ir().types().GetBlockAsTypeIds(elements)) {
  804. subtypes.push_back(context.GetType(type_id));
  805. }
  806. return llvm::StructType::get(context.llvm_context(), subtypes);
  807. }
  808. static auto BuildTypeForInst(FileContext& context, SemIR::TypeType /*inst*/)
  809. -> llvm::Type* {
  810. return context.GetTypeType();
  811. }
  812. static auto BuildTypeForInst(FileContext& context, SemIR::VtableType /*inst*/)
  813. -> llvm::Type* {
  814. return llvm::Type::getVoidTy(context.llvm_context());
  815. }
  816. static auto BuildTypeForInst(FileContext& context,
  817. SemIR::SpecificFunctionType /*inst*/)
  818. -> llvm::Type* {
  819. return llvm::PointerType::get(context.llvm_context(), 0);
  820. }
  821. template <typename InstT>
  822. requires(
  823. InstT::Kind.template IsAnyOf<
  824. SemIR::AssociatedEntityType, SemIR::AutoType, SemIR::BoundMethodType,
  825. SemIR::CharLiteralType, SemIR::CppOverloadSetType, SemIR::CppVoidType,
  826. SemIR::FacetType, SemIR::FloatLiteralType, SemIR::FunctionType,
  827. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  828. SemIR::GenericInterfaceType, SemIR::GenericNamedConstraintType,
  829. SemIR::InstType, SemIR::IntLiteralType, SemIR::NamespaceType,
  830. SemIR::WhereExpr, SemIR::WitnessType, SemIR::UnboundElementType>())
  831. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  832. -> llvm::Type* {
  833. // Return an empty struct as a placeholder.
  834. // TODO: Should we model an interface as a witness table, or an associated
  835. // entity as an index?
  836. return llvm::StructType::get(context.llvm_context());
  837. }
  838. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  839. // Use overload resolution to select the implementation, producing compile
  840. // errors when BuildTypeForInst isn't defined for a given instruction.
  841. CARBON_KIND_SWITCH(sem_ir_->insts().Get(inst_id)) {
  842. #define CARBON_SEM_IR_INST_KIND(Name) \
  843. case CARBON_KIND(SemIR::Name inst): { \
  844. return BuildTypeForInst(*this, inst); \
  845. }
  846. #include "toolchain/sem_ir/inst_kind.def"
  847. }
  848. }
  849. auto FileContext::BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  850. -> llvm::GlobalVariable* {
  851. Mangler m(*this);
  852. auto mangled_name = m.MangleGlobalVariable(var_storage.pattern_id);
  853. auto linkage = llvm::GlobalVariable::ExternalLinkage;
  854. // If the variable doesn't have an externally-visible name, demote it to
  855. // internal linkage and invent a plausible name that shouldn't collide with
  856. // any of our real manglings.
  857. if (mangled_name.empty()) {
  858. linkage = llvm::GlobalVariable::InternalLinkage;
  859. if (inst_namer_) {
  860. mangled_name =
  861. ("var.anon" + inst_namer_->GetUnscopedNameFor(var_storage.pattern_id))
  862. .str();
  863. }
  864. }
  865. auto* type = GetType(var_storage.type_id);
  866. return new llvm::GlobalVariable(llvm_module(), type,
  867. /*isConstant=*/false, linkage,
  868. /*Initializer=*/nullptr, mangled_name);
  869. }
  870. auto FileContext::GetLocForDI(SemIR::InstId inst_id) -> Context::LocForDI {
  871. return context().GetLocForDI(
  872. GetAbsoluteNodeId(sem_ir_, SemIR::LocId(inst_id)).back());
  873. }
  874. auto FileContext::BuildVtable(const SemIR::Vtable& vtable,
  875. SemIR::SpecificId specific_id)
  876. -> llvm::GlobalVariable* {
  877. const auto& class_info = sem_ir().classes().Get(vtable.class_id);
  878. Mangler m(*this);
  879. std::string mangled_name = m.MangleVTable(class_info, specific_id);
  880. if (sem_ir()
  881. .insts()
  882. .GetImportSource(class_info.first_owning_decl_id)
  883. .has_value()) {
  884. // Emit a declaration of an imported vtable using a(n opaque) pointer type.
  885. // This doesn't have to match the definition that appears elsewhere, it'll
  886. // still get merged correctly.
  887. auto* gv = new llvm::GlobalVariable(
  888. llvm_module(),
  889. llvm::PointerType::get(llvm_context(), /*AddressSpace=*/0),
  890. /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
  891. mangled_name);
  892. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  893. return gv;
  894. }
  895. auto vtable_inst_block =
  896. sem_ir().inst_blocks().Get(vtable.virtual_functions_id);
  897. auto* entry_type = llvm::IntegerType::getInt32Ty(llvm_context());
  898. auto* table_type = llvm::ArrayType::get(entry_type, vtable_inst_block.size());
  899. auto* llvm_vtable = new llvm::GlobalVariable(
  900. llvm_module(), table_type, /*isConstant=*/true,
  901. llvm::GlobalValue::ExternalLinkage, nullptr, mangled_name);
  902. auto* i32_type = llvm::IntegerType::getInt32Ty(llvm_context());
  903. auto* i64_type = llvm::IntegerType::getInt64Ty(llvm_context());
  904. auto* vtable_const_int =
  905. llvm::ConstantExpr::getPtrToInt(llvm_vtable, i64_type);
  906. llvm::SmallVector<llvm::Constant*> vfuncs;
  907. vfuncs.reserve(vtable_inst_block.size());
  908. for (auto fn_decl_id : vtable_inst_block) {
  909. auto [_1, _2, fn_id, fn_specific_id] =
  910. DecomposeVirtualFunction(sem_ir(), fn_decl_id, specific_id);
  911. vfuncs.push_back(llvm::ConstantExpr::getTrunc(
  912. llvm::ConstantExpr::getSub(
  913. llvm::ConstantExpr::getPtrToInt(
  914. GetOrCreateFunction(fn_id, fn_specific_id), i64_type),
  915. vtable_const_int),
  916. i32_type));
  917. }
  918. llvm_vtable->setInitializer(llvm::ConstantArray::get(table_type, vfuncs));
  919. llvm_vtable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  920. return llvm_vtable;
  921. }
  922. } // namespace Carbon::Lower