file_context.cpp 48 KB

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