file_context.cpp 39 KB

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