file_context.cpp 47 KB

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