file_context.cpp 46 KB

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