file_context.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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/ModuleUtils.h"
  16. #include "toolchain/base/kind_switch.h"
  17. #include "toolchain/lower/constant.h"
  18. #include "toolchain/lower/function_context.h"
  19. #include "toolchain/lower/mangler.h"
  20. #include "toolchain/sem_ir/absolute_node_id.h"
  21. #include "toolchain/sem_ir/entry_point.h"
  22. #include "toolchain/sem_ir/file.h"
  23. #include "toolchain/sem_ir/function.h"
  24. #include "toolchain/sem_ir/generic.h"
  25. #include "toolchain/sem_ir/ids.h"
  26. #include "toolchain/sem_ir/inst.h"
  27. #include "toolchain/sem_ir/inst_kind.h"
  28. #include "toolchain/sem_ir/pattern.h"
  29. #include "toolchain/sem_ir/typed_insts.h"
  30. namespace Carbon::Lower {
  31. FileContext::FileContext(
  32. llvm::LLVMContext& llvm_context,
  33. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  34. std::optional<llvm::ArrayRef<Parse::GetTreeAndSubtreesFn>>
  35. tree_and_subtrees_getters_for_debug_info,
  36. llvm::StringRef module_name, const SemIR::File& sem_ir,
  37. clang::ASTUnit* cpp_ast, const SemIR::InstNamer* inst_namer,
  38. llvm::raw_ostream* vlog_stream)
  39. : llvm_context_(&llvm_context),
  40. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  41. fs_(std::move(fs)),
  42. di_builder_(*llvm_module_),
  43. di_compile_unit_(
  44. tree_and_subtrees_getters_for_debug_info
  45. ? BuildDICompileUnit(module_name, *llvm_module_, di_builder_)
  46. : nullptr),
  47. tree_and_subtrees_getters_for_debug_info_(
  48. tree_and_subtrees_getters_for_debug_info),
  49. sem_ir_(&sem_ir),
  50. cpp_ast_(cpp_ast),
  51. inst_namer_(inst_namer),
  52. vlog_stream_(vlog_stream) {
  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::Run() -> std::unique_ptr<llvm::Module> {
  60. CARBON_CHECK(llvm_module_, "Run can only be called once.");
  61. if (cpp_code_generator_) {
  62. cpp_code_generator_->Initialize(cpp_ast()->getASTContext());
  63. }
  64. // Lower all types that were required to be complete.
  65. types_.resize(sem_ir_->insts().size());
  66. for (auto type_id : sem_ir_->types().complete_types()) {
  67. if (type_id.index >= 0) {
  68. types_[type_id.index] = BuildType(sem_ir_->types().GetInstId(type_id));
  69. }
  70. }
  71. // Lower function declarations.
  72. functions_.resize_for_overwrite(sem_ir_->functions().size());
  73. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  74. functions_[id.index] = BuildFunctionDecl(id);
  75. }
  76. for (const auto& class_info : sem_ir_->classes().array_ref()) {
  77. if (auto* llvm_vtable = BuildVtable(class_info)) {
  78. global_variables_.Insert(class_info.vtable_id, llvm_vtable);
  79. }
  80. }
  81. // Specific functions are lowered when we emit a reference to them.
  82. specific_functions_.resize(sem_ir_->specifics().size());
  83. // Lower global variable declarations.
  84. // TODO: Storing both a `constants_` array and a separate `global_variables_`
  85. // map is redundant.
  86. for (auto inst_id :
  87. sem_ir().inst_blocks().Get(sem_ir().top_inst_block_id())) {
  88. // Only `VarStorage` indicates a global variable declaration in the
  89. // top instruction block.
  90. if (auto var = sem_ir().insts().TryGetAs<SemIR::VarStorage>(inst_id)) {
  91. auto* var_decl = BuildGlobalVariableDecl(*var);
  92. global_variables_.Insert(inst_id, var_decl);
  93. // Also store the global variable with the ID of the pattern so
  94. // constant lowering can find it.
  95. global_variables_.Insert(var->pattern_id, var_decl);
  96. }
  97. }
  98. // Lower constants.
  99. constants_.resize(sem_ir_->insts().size());
  100. LowerConstants(*this, constants_);
  101. // Lower function definitions.
  102. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  103. BuildFunctionDefinition(id);
  104. }
  105. // Lower function definitions for generics.
  106. // This cannot be a range-based loop, as new definitions can be added
  107. // while building other definitions.
  108. // NOLINTNEXTLINE
  109. for (size_t i = 0; i != specific_function_definitions_.size(); ++i) {
  110. auto [function_id, specific_id] = specific_function_definitions_[i];
  111. BuildFunctionDefinition(function_id, specific_id);
  112. }
  113. // Append `__global_init` to `llvm::global_ctors` to initialize global
  114. // variables.
  115. if (sem_ir().global_ctor_id().has_value()) {
  116. llvm::appendToGlobalCtors(llvm_module(),
  117. GetFunction(sem_ir().global_ctor_id()),
  118. /*Priority=*/0);
  119. }
  120. if (cpp_code_generator_) {
  121. cpp_code_generator_->HandleTranslationUnit(cpp_ast()->getASTContext());
  122. bool link_error = llvm::Linker::linkModules(
  123. /*Dest=*/*llvm_module_,
  124. /*Src=*/std::unique_ptr<llvm::Module>(
  125. cpp_code_generator_->ReleaseModule()));
  126. CARBON_CHECK(!link_error);
  127. }
  128. return std::move(llvm_module_);
  129. }
  130. auto FileContext::BuildDICompileUnit(llvm::StringRef module_name,
  131. llvm::Module& llvm_module,
  132. llvm::DIBuilder& di_builder)
  133. -> llvm::DICompileUnit* {
  134. llvm_module.addModuleFlag(llvm::Module::Max, "Dwarf Version", 5);
  135. llvm_module.addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  136. llvm::DEBUG_METADATA_VERSION);
  137. // TODO: Include directory path in the compile_unit_file.
  138. llvm::DIFile* compile_unit_file = di_builder.createFile(module_name, "");
  139. // TODO: Introduce a new language code for Carbon. C works well for now since
  140. // it's something debuggers will already know/have support for at least.
  141. // Probably have to bump to C++ at some point for virtual functions,
  142. // templates, etc.
  143. return di_builder.createCompileUnit(llvm::dwarf::DW_LANG_C, compile_unit_file,
  144. "carbon",
  145. /*isOptimized=*/false, /*Flags=*/"",
  146. /*RV=*/0);
  147. }
  148. auto FileContext::CreateCppCodeGenerator()
  149. -> std::unique_ptr<clang::CodeGenerator> {
  150. if (!cpp_ast()) {
  151. return nullptr;
  152. }
  153. RawStringOstream clang_module_name_stream;
  154. clang_module_name_stream << llvm_module_->getName() << ".clang";
  155. return std::unique_ptr<clang::CodeGenerator>(clang::CreateLLVMCodeGen(
  156. cpp_ast()->getASTContext().getDiagnostics(),
  157. clang_module_name_stream.TakeStr(), fs_, cpp_header_search_options_,
  158. cpp_preprocessor_options_, cpp_code_gen_options_, *llvm_context_));
  159. }
  160. auto FileContext::GetGlobal(SemIR::InstId inst_id,
  161. SemIR::SpecificId specific_id) -> llvm::Value* {
  162. auto const_id = GetConstantValueInSpecific(sem_ir(), specific_id, inst_id);
  163. CARBON_CHECK(const_id.is_concrete(), "Missing value: {0} {1} {2}", inst_id,
  164. specific_id, sem_ir().insts().Get(inst_id));
  165. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  166. // For value expressions and initializing expressions, the value produced by
  167. // a constant instruction is a value representation of the constant. For
  168. // initializing expressions, `FinishInit` will perform a copy if needed.
  169. // TODO: Handle reference expression constants.
  170. auto* const_value = constants_[const_inst_id.index];
  171. auto value_rep = SemIR::ValueRepr::ForType(
  172. sem_ir(), sem_ir().insts().Get(const_inst_id).type_id());
  173. if (value_rep.kind != SemIR::ValueRepr::Pointer) {
  174. return const_value;
  175. }
  176. if (auto result = global_variables().Lookup(const_inst_id)) {
  177. return result.value();
  178. }
  179. // Include both the name of the constant, if any, and the point of use in
  180. // the name of the variable.
  181. llvm::StringRef const_name;
  182. llvm::StringRef use_name;
  183. if (inst_namer_) {
  184. const_name = inst_namer_->GetUnscopedNameFor(const_inst_id);
  185. use_name = inst_namer_->GetUnscopedNameFor(inst_id);
  186. }
  187. // We always need to give the global a name even if the instruction namer
  188. // doesn't have one to use.
  189. if (const_name.empty()) {
  190. const_name = "const";
  191. }
  192. if (use_name.empty()) {
  193. use_name = "anon";
  194. }
  195. llvm::StringRef sep = (use_name[0] == '.') ? "" : ".";
  196. auto* global_variable = new llvm::GlobalVariable(
  197. llvm_module(), GetType(sem_ir().GetPointeeType(value_rep.type_id)),
  198. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage, const_value,
  199. const_name + sep + use_name);
  200. global_variables_.Insert(const_inst_id, global_variable);
  201. return global_variable;
  202. }
  203. auto FileContext::GetOrCreateFunction(SemIR::FunctionId function_id,
  204. SemIR::SpecificId specific_id)
  205. -> llvm::Function* {
  206. // Non-generic functions are declared eagerly.
  207. if (!specific_id.has_value()) {
  208. return GetFunction(function_id);
  209. }
  210. if (auto* result = specific_functions_[specific_id.index]) {
  211. return result;
  212. }
  213. auto* result = BuildFunctionDecl(function_id, specific_id);
  214. // TODO: Add this function to a list of specific functions whose definitions
  215. // we need to emit.
  216. specific_functions_[specific_id.index] = result;
  217. // TODO: Use this to generate definitions for these functions.
  218. specific_function_definitions_.push_back({function_id, specific_id});
  219. return result;
  220. }
  221. auto FileContext::BuildFunctionTypeInfo(const SemIR::Function& function,
  222. SemIR::SpecificId specific_id)
  223. -> FunctionTypeInfo {
  224. const auto return_info =
  225. SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id);
  226. if (!return_info.is_valid()) {
  227. // The return type has not been completed, create a trivial type instead.
  228. return {.type =
  229. llvm::FunctionType::get(llvm::Type::getVoidTy(llvm_context()),
  230. /*isVarArg=*/false)};
  231. }
  232. auto get_llvm_type = [&](SemIR::TypeId type_id) -> llvm::Type* {
  233. if (!type_id.has_value()) {
  234. return nullptr;
  235. }
  236. return GetType(type_id);
  237. };
  238. // TODO: expose the `Call` parameter patterns in `Function`, and use them here
  239. // instead of reconstructing them via the syntactic parameter lists.
  240. auto implicit_param_patterns =
  241. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_patterns_id);
  242. auto param_patterns =
  243. sem_ir().inst_blocks().GetOrEmpty(function.param_patterns_id);
  244. auto* return_type = get_llvm_type(return_info.type_id);
  245. llvm::SmallVector<llvm::Type*> param_types;
  246. // Compute the return type to use for the LLVM function. If the initializing
  247. // representation doesn't produce a value, set the return type to void.
  248. // TODO: For the `Run` entry point, remap return type to i32 if it doesn't
  249. // return a value.
  250. llvm::Type* function_return_type =
  251. (return_info.is_valid() &&
  252. return_info.init_repr.kind == SemIR::InitRepr::ByCopy)
  253. ? return_type
  254. : llvm::Type::getVoidTy(llvm_context());
  255. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  256. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  257. // out a mechanism to compute the mapping between parameters and arguments on
  258. // demand.
  259. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  260. auto max_llvm_params = (return_info.has_return_slot() ? 1 : 0) +
  261. implicit_param_patterns.size() + param_patterns.size();
  262. param_types.reserve(max_llvm_params);
  263. param_inst_ids.reserve(max_llvm_params);
  264. auto return_param_id = SemIR::InstId::None;
  265. if (return_info.has_return_slot()) {
  266. param_types.push_back(
  267. llvm::PointerType::get(llvm_context(), /*AddressSpace=*/0));
  268. return_param_id = function.return_slot_pattern_id;
  269. param_inst_ids.push_back(return_param_id);
  270. }
  271. for (auto param_pattern_id : llvm::concat<const SemIR::InstId>(
  272. implicit_param_patterns, param_patterns)) {
  273. auto param_pattern_info = SemIR::Function::GetParamPatternInfoFromPatternId(
  274. sem_ir(), param_pattern_id);
  275. if (!param_pattern_info) {
  276. continue;
  277. }
  278. auto param_type_id = ExtractScrutineeType(
  279. sem_ir(), SemIR::GetTypeOfInstInSpecific(sem_ir(), specific_id,
  280. param_pattern_info->inst_id));
  281. CARBON_CHECK(
  282. !param_type_id.AsConstantId().is_symbolic(),
  283. "Found symbolic type id after resolution when lowering type {0}.",
  284. param_pattern_info->inst.type_id);
  285. switch (auto value_rep = SemIR::ValueRepr::ForType(sem_ir(), param_type_id);
  286. value_rep.kind) {
  287. case SemIR::ValueRepr::Unknown:
  288. // This parameter type is incomplete. Fallback to describing the
  289. // function type as `void()`.
  290. return {.type = llvm::FunctionType::get(
  291. llvm::Type::getVoidTy(llvm_context()),
  292. /*isVarArg=*/false)};
  293. case SemIR::ValueRepr::None:
  294. break;
  295. case SemIR::ValueRepr::Copy:
  296. case SemIR::ValueRepr::Custom:
  297. case SemIR::ValueRepr::Pointer:
  298. auto* param_types_to_add = get_llvm_type(value_rep.type_id);
  299. param_types.push_back(param_types_to_add);
  300. param_inst_ids.push_back(param_pattern_id);
  301. break;
  302. }
  303. }
  304. return {.type = llvm::FunctionType::get(function_return_type, param_types,
  305. /*isVarArg=*/false),
  306. .param_inst_ids = std::move(param_inst_ids),
  307. .return_type = return_type,
  308. .return_param_id = return_param_id};
  309. }
  310. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id,
  311. SemIR::SpecificId specific_id)
  312. -> llvm::Function* {
  313. const auto& function = sem_ir().functions().Get(function_id);
  314. // Don't lower generic functions. Note that associated functions in interfaces
  315. // have `Self` in scope, so are implicitly generic functions.
  316. if (function.generic_id.has_value() && !specific_id.has_value()) {
  317. return nullptr;
  318. }
  319. // Don't lower builtins.
  320. if (function.builtin_function_kind != SemIR::BuiltinFunctionKind::None) {
  321. return nullptr;
  322. }
  323. // TODO: Consider tracking whether the function has been used, and only
  324. // lowering it if it's needed.
  325. auto function_type_info = BuildFunctionTypeInfo(function, specific_id);
  326. Mangler m(*this);
  327. std::string mangled_name = m.Mangle(function_id, specific_id);
  328. auto* llvm_function = llvm::Function::Create(function_type_info.type,
  329. llvm::Function::ExternalLinkage,
  330. mangled_name, llvm_module());
  331. CARBON_CHECK(llvm_function->getName() == mangled_name,
  332. "Mangled name collision: {0}", mangled_name);
  333. // Set up parameters and the return slot.
  334. for (auto [inst_id, arg] : llvm::zip_equal(function_type_info.param_inst_ids,
  335. llvm_function->args())) {
  336. auto name_id = SemIR::NameId::None;
  337. if (inst_id == function_type_info.return_param_id) {
  338. name_id = SemIR::NameId::ReturnSlot;
  339. arg.addAttr(llvm::Attribute::getWithStructRetType(
  340. llvm_context(), function_type_info.return_type));
  341. } else {
  342. name_id = SemIR::GetPrettyNameFromPatternId(sem_ir(), inst_id);
  343. }
  344. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  345. }
  346. return llvm_function;
  347. }
  348. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id,
  349. SemIR::SpecificId specific_id)
  350. -> void {
  351. const auto& function = sem_ir().functions().Get(function_id);
  352. const auto& body_block_ids = function.body_block_ids;
  353. if (body_block_ids.empty() &&
  354. (!function.cpp_decl || !function.cpp_decl->isDefined())) {
  355. // Function is probably defined in another file; not an error.
  356. return;
  357. }
  358. llvm::Function* llvm_function;
  359. if (specific_id.has_value()) {
  360. llvm_function = specific_functions_[specific_id.index];
  361. } else {
  362. llvm_function = GetFunction(function_id);
  363. if (!llvm_function) {
  364. // We chose not to lower this function at all, for example because it's a
  365. // generic function.
  366. return;
  367. }
  368. }
  369. // For non-generics we do not lower. For generics, the llvm function was
  370. // created via GetOrCreateFunction prior to this when building the
  371. // declaration.
  372. BuildFunctionBody(function_id, function, llvm_function, specific_id);
  373. }
  374. auto FileContext::BuildFunctionBody(SemIR::FunctionId function_id,
  375. const SemIR::Function& function,
  376. llvm::Function* llvm_function,
  377. SemIR::SpecificId specific_id) -> void {
  378. const auto& body_block_ids = function.body_block_ids;
  379. CARBON_DCHECK(llvm_function, "LLVM Function not found when lowering body.");
  380. if (function.cpp_decl) {
  381. // TODO: To support recursive inline functions, collect all calls to
  382. // `HandleTopLevelDecl()` in a custom `ASTConsumer` configured in the
  383. // `ASTUnit`, and replay them in lowering in the `CodeGenerator`. See
  384. // https://discord.com/channels/655572317891461132/768530752592805919/1370509111585935443
  385. clang::FunctionDecl* cpp_def = function.cpp_decl->getDefinition();
  386. CARBON_DCHECK(cpp_def, "No Clang function body found during lowering");
  387. // Create the LLVM function (`CodeGenModule::GetOrCreateLLVMFunction()`) so
  388. // that code generation (`CodeGenModule::EmitGlobal()`) would see this
  389. // function name (`CodeGenModule::getMangledName()`), and will generate its
  390. // definition.
  391. llvm::Constant* function_address =
  392. cpp_code_generator_->GetAddrOfGlobal(clang::GlobalDecl(cpp_def),
  393. /*isForDefinition=*/false);
  394. CARBON_DCHECK(function_address);
  395. // Emit the function code.
  396. cpp_code_generator_->HandleTopLevelDecl(clang::DeclGroupRef(cpp_def));
  397. return;
  398. }
  399. CARBON_DCHECK(!body_block_ids.empty(),
  400. "No function body blocks found during lowering.");
  401. FunctionContext function_lowering(*this, llvm_function, specific_id,
  402. BuildDISubprogram(function, llvm_function),
  403. vlog_stream_);
  404. // Add parameters to locals.
  405. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  406. // function parameters that was already computed in BuildFunctionDecl.
  407. // We should only do that once.
  408. auto call_param_ids =
  409. sem_ir().inst_blocks().GetOrEmpty(function.call_params_id);
  410. int param_index = 0;
  411. // TODO: Find a way to ensure this code and the function-call lowering use
  412. // the same parameter ordering.
  413. // Lowers the given parameter. Must be called in LLVM calling convention
  414. // parameter order.
  415. auto lower_param = [&](SemIR::InstId param_id) {
  416. // Get the value of the parameter from the function argument.
  417. auto param_inst = sem_ir().insts().GetAs<SemIR::AnyParam>(param_id);
  418. llvm::Value* param_value;
  419. if (SemIR::ValueRepr::ForType(sem_ir(), param_inst.type_id).kind !=
  420. SemIR::ValueRepr::None) {
  421. param_value = llvm_function->getArg(param_index);
  422. ++param_index;
  423. } else {
  424. param_value = llvm::PoisonValue::get(GetType(
  425. SemIR::GetTypeOfInstInSpecific(sem_ir(), specific_id, param_id)));
  426. }
  427. // The value of the parameter is the value of the argument.
  428. function_lowering.SetLocal(param_id, param_value);
  429. };
  430. // The subset of call_param_ids that is already in the order that the LLVM
  431. // calling convention expects.
  432. llvm::ArrayRef<SemIR::InstId> sequential_param_ids;
  433. if (function.return_slot_pattern_id.has_value()) {
  434. // The LLVM calling convention has the return slot first rather than last.
  435. // Note that this queries whether there is a return slot at the LLVM level,
  436. // whereas `function.return_slot_pattern_id.has_value()` queries whether
  437. // there is a return slot at the SemIR level.
  438. if (SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id)
  439. .has_return_slot()) {
  440. lower_param(call_param_ids.back());
  441. }
  442. sequential_param_ids = call_param_ids.drop_back();
  443. } else {
  444. sequential_param_ids = call_param_ids;
  445. }
  446. for (auto param_id : sequential_param_ids) {
  447. lower_param(param_id);
  448. }
  449. auto decl_block_id = SemIR::InstBlockId::None;
  450. if (function_id == sem_ir().global_ctor_id()) {
  451. decl_block_id = SemIR::InstBlockId::Empty;
  452. } else {
  453. decl_block_id = sem_ir()
  454. .insts()
  455. .GetAs<SemIR::FunctionDecl>(function.latest_decl_id())
  456. .decl_block_id;
  457. }
  458. // Lowers the contents of block_id into the corresponding LLVM block,
  459. // creating it if it doesn't already exist.
  460. auto lower_block = [&](SemIR::InstBlockId block_id) {
  461. CARBON_VLOG("Lowering {0}\n", block_id);
  462. auto* llvm_block = function_lowering.GetBlock(block_id);
  463. // Keep the LLVM blocks in lexical order.
  464. llvm_block->moveBefore(llvm_function->end());
  465. function_lowering.builder().SetInsertPoint(llvm_block);
  466. function_lowering.LowerBlockContents(block_id);
  467. };
  468. lower_block(decl_block_id);
  469. // If the decl block is empty, reuse it as the first body block. We don't do
  470. // this when the decl block is non-empty so that any branches back to the
  471. // first body block don't also re-execute the decl.
  472. llvm::BasicBlock* block = function_lowering.builder().GetInsertBlock();
  473. if (block->empty() &&
  474. function_lowering.TryToReuseBlock(body_block_ids.front(), block)) {
  475. // Reuse this block as the first block of the function body.
  476. } else {
  477. function_lowering.builder().CreateBr(
  478. function_lowering.GetBlock(body_block_ids.front()));
  479. }
  480. // Lower all blocks.
  481. for (auto block_id : body_block_ids) {
  482. lower_block(block_id);
  483. }
  484. // LLVM requires that the entry block has no predecessors.
  485. auto* entry_block = &llvm_function->getEntryBlock();
  486. if (entry_block->hasNPredecessorsOrMore(1)) {
  487. auto* new_entry_block = llvm::BasicBlock::Create(
  488. llvm_context(), "entry", llvm_function, entry_block);
  489. llvm::BranchInst::Create(entry_block, new_entry_block);
  490. }
  491. }
  492. auto FileContext::BuildDISubprogram(const SemIR::Function& function,
  493. const llvm::Function* llvm_function)
  494. -> llvm::DISubprogram* {
  495. if (!di_compile_unit_) {
  496. return nullptr;
  497. }
  498. auto name = sem_ir().names().GetAsStringIfIdentifier(function.name_id);
  499. CARBON_CHECK(name, "Unexpected special name for function: {0}",
  500. function.name_id);
  501. auto loc = GetLocForDI(function.definition_id);
  502. // TODO: Add more details here, including real subroutine type (once type
  503. // information is built), etc.
  504. return di_builder_.createFunction(
  505. di_compile_unit_, *name, llvm_function->getName(),
  506. /*File=*/di_builder_.createFile(loc.filename, ""),
  507. /*LineNo=*/loc.line_number,
  508. di_builder_.createSubroutineType(
  509. di_builder_.getOrCreateTypeArray(std::nullopt)),
  510. /*ScopeLine=*/0, llvm::DINode::FlagZero,
  511. llvm::DISubprogram::SPFlagDefinition);
  512. }
  513. // BuildTypeForInst is used to construct types for FileContext::BuildType below.
  514. // Implementations return the LLVM type for the instruction. This first overload
  515. // is the fallback handler for non-type instructions.
  516. template <typename InstT>
  517. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  518. static auto BuildTypeForInst(FileContext& /*context*/, InstT inst)
  519. -> llvm::Type* {
  520. CARBON_FATAL("Cannot use inst as type: {0}", inst);
  521. }
  522. template <typename InstT>
  523. requires(InstT::Kind.is_symbolic_when_type())
  524. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  525. -> llvm::Type* {
  526. // Treat non-monomorphized symbolic types as opaque.
  527. return llvm::StructType::get(context.llvm_context());
  528. }
  529. static auto BuildTypeForInst(FileContext& context, SemIR::ArrayType inst)
  530. -> llvm::Type* {
  531. return llvm::ArrayType::get(
  532. context.GetType(context.sem_ir().types().GetTypeIdForTypeInstId(
  533. inst.element_type_inst_id)),
  534. *context.sem_ir().GetArrayBoundValue(inst.bound_id));
  535. }
  536. static auto BuildTypeForInst(FileContext& /*context*/, SemIR::AutoType inst)
  537. -> llvm::Type* {
  538. CARBON_FATAL("Unexpected builtin type in lowering: {0}", inst);
  539. }
  540. static auto BuildTypeForInst(FileContext& context, SemIR::BoolType /*inst*/)
  541. -> llvm::Type* {
  542. // TODO: We may want to have different representations for `bool` storage
  543. // (`i8`) versus for `bool` values (`i1`).
  544. return llvm::Type::getInt1Ty(context.llvm_context());
  545. }
  546. static auto BuildTypeForInst(FileContext& context, SemIR::ClassType inst)
  547. -> llvm::Type* {
  548. auto object_repr_id = context.sem_ir()
  549. .classes()
  550. .Get(inst.class_id)
  551. .GetObjectRepr(context.sem_ir(), inst.specific_id);
  552. return context.GetType(object_repr_id);
  553. }
  554. static auto BuildTypeForInst(FileContext& context, SemIR::ConstType inst)
  555. -> llvm::Type* {
  556. return context.GetType(
  557. context.sem_ir().types().GetTypeIdForTypeInstId(inst.inner_id));
  558. }
  559. static auto BuildTypeForInst(FileContext& context,
  560. SemIR::ImplWitnessAssociatedConstant inst)
  561. -> llvm::Type* {
  562. return context.GetType(inst.type_id);
  563. }
  564. static auto BuildTypeForInst(FileContext& /*context*/,
  565. SemIR::ErrorInst /*inst*/) -> llvm::Type* {
  566. // This is a complete type but uses of it should never be lowered.
  567. return nullptr;
  568. }
  569. static auto BuildTypeForInst(FileContext& context, SemIR::FloatType /*inst*/)
  570. -> llvm::Type* {
  571. // TODO: Handle different sizes.
  572. return llvm::Type::getDoubleTy(context.llvm_context());
  573. }
  574. static auto BuildTypeForInst(FileContext& context, SemIR::IntType inst)
  575. -> llvm::Type* {
  576. auto width =
  577. context.sem_ir().insts().TryGetAs<SemIR::IntValue>(inst.bit_width_id);
  578. CARBON_CHECK(width, "Can't lower int type with symbolic width");
  579. return llvm::IntegerType::get(
  580. context.llvm_context(),
  581. context.sem_ir().ints().Get(width->int_id).getZExtValue());
  582. }
  583. static auto BuildTypeForInst(FileContext& context,
  584. SemIR::LegacyFloatType /*inst*/) -> llvm::Type* {
  585. return llvm::Type::getDoubleTy(context.llvm_context());
  586. }
  587. static auto BuildTypeForInst(FileContext& context, SemIR::PointerType /*inst*/)
  588. -> llvm::Type* {
  589. return llvm::PointerType::get(context.llvm_context(), /*AddressSpace=*/0);
  590. }
  591. static auto BuildTypeForInst(FileContext& /*context*/,
  592. SemIR::PatternType /*inst*/) -> llvm::Type* {
  593. CARBON_FATAL("Unexpected pattern type in lowering");
  594. }
  595. static auto BuildTypeForInst(FileContext& context, SemIR::StructType inst)
  596. -> llvm::Type* {
  597. auto fields = context.sem_ir().struct_type_fields().Get(inst.fields_id);
  598. llvm::SmallVector<llvm::Type*> subtypes;
  599. subtypes.reserve(fields.size());
  600. for (auto field : fields) {
  601. subtypes.push_back(context.GetType(
  602. context.sem_ir().types().GetTypeIdForTypeInstId(field.type_inst_id)));
  603. }
  604. return llvm::StructType::get(context.llvm_context(), subtypes);
  605. }
  606. static auto BuildTypeForInst(FileContext& context, SemIR::TupleType inst)
  607. -> llvm::Type* {
  608. // TODO: Investigate special-casing handling of empty tuples so that they
  609. // can be collectively replaced with LLVM's void, particularly around
  610. // function returns. LLVM doesn't allow declaring variables with a void
  611. // type, so that may require significant special casing.
  612. auto elements = context.sem_ir().inst_blocks().Get(inst.type_elements_id);
  613. llvm::SmallVector<llvm::Type*> subtypes;
  614. subtypes.reserve(elements.size());
  615. for (auto type_id : context.sem_ir().types().GetBlockAsTypeIds(elements)) {
  616. subtypes.push_back(context.GetType(type_id));
  617. }
  618. return llvm::StructType::get(context.llvm_context(), subtypes);
  619. }
  620. static auto BuildTypeForInst(FileContext& context, SemIR::TypeType /*inst*/)
  621. -> llvm::Type* {
  622. return context.GetTypeType();
  623. }
  624. static auto BuildTypeForInst(FileContext& context, SemIR::VtableType /*inst*/)
  625. -> llvm::Type* {
  626. return llvm::Type::getVoidTy(context.llvm_context());
  627. }
  628. template <typename InstT>
  629. requires(InstT::Kind.template IsAnyOf<SemIR::SpecificFunctionType,
  630. SemIR::StringType>())
  631. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  632. -> llvm::Type* {
  633. // TODO: Decide how we want to represent `StringType`.
  634. return llvm::PointerType::get(context.llvm_context(), 0);
  635. }
  636. template <typename InstT>
  637. requires(InstT::Kind
  638. .template IsAnyOf<SemIR::BoundMethodType, SemIR::IntLiteralType,
  639. SemIR::NamespaceType, SemIR::WitnessType>())
  640. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  641. -> llvm::Type* {
  642. // Return an empty struct as a placeholder.
  643. return llvm::StructType::get(context.llvm_context());
  644. }
  645. template <typename InstT>
  646. requires(InstT::Kind.template IsAnyOf<
  647. SemIR::AssociatedEntityType, SemIR::FacetType, SemIR::FunctionType,
  648. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  649. SemIR::GenericInterfaceType, SemIR::InstType,
  650. SemIR::UnboundElementType, SemIR::WhereExpr>())
  651. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  652. -> llvm::Type* {
  653. // Return an empty struct as a placeholder.
  654. // TODO: Should we model an interface as a witness table, or an associated
  655. // entity as an index?
  656. return llvm::StructType::get(context.llvm_context());
  657. }
  658. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  659. // Use overload resolution to select the implementation, producing compile
  660. // errors when BuildTypeForInst isn't defined for a given instruction.
  661. CARBON_KIND_SWITCH(sem_ir_->insts().Get(inst_id)) {
  662. #define CARBON_SEM_IR_INST_KIND(Name) \
  663. case CARBON_KIND(SemIR::Name inst): { \
  664. return BuildTypeForInst(*this, inst); \
  665. }
  666. #include "toolchain/sem_ir/inst_kind.def"
  667. }
  668. }
  669. auto FileContext::BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  670. -> llvm::GlobalVariable* {
  671. Mangler m(*this);
  672. auto mangled_name = m.MangleGlobalVariable(var_storage.pattern_id);
  673. auto linkage = llvm::GlobalVariable::ExternalLinkage;
  674. // If the variable doesn't have an externally-visible name, demote it to
  675. // internal linkage and invent a plausible name that shouldn't collide with
  676. // any of our real manglings.
  677. if (mangled_name.empty()) {
  678. linkage = llvm::GlobalVariable::InternalLinkage;
  679. if (inst_namer_) {
  680. mangled_name =
  681. ("var.anon" + inst_namer_->GetUnscopedNameFor(var_storage.pattern_id))
  682. .str();
  683. }
  684. }
  685. auto* type = GetType(var_storage.type_id);
  686. // TODO: Create a declaration instead of a definition if this variable was
  687. // imported.
  688. return new llvm::GlobalVariable(llvm_module(), type,
  689. /*isConstant=*/false, linkage,
  690. llvm::Constant::getNullValue(type),
  691. mangled_name);
  692. }
  693. auto FileContext::GetLocForDI(SemIR::InstId inst_id) -> LocForDI {
  694. SemIR::AbsoluteNodeId resolved =
  695. GetAbsoluteNodeId(sem_ir_, SemIR::LocId(inst_id)).back();
  696. const auto& tree_and_subtrees =
  697. (*tree_and_subtrees_getters_for_debug_info_)[resolved.check_ir_id()
  698. .index]();
  699. const auto& tokens = tree_and_subtrees.tree().tokens();
  700. if (resolved.node_id().has_value()) {
  701. auto token =
  702. tree_and_subtrees.GetSubtreeTokenRange(resolved.node_id()).begin;
  703. return {.filename = tokens.source().filename(),
  704. .line_number = tokens.GetLineNumber(token),
  705. .column_number = tokens.GetColumnNumber(token)};
  706. } else {
  707. return {.filename = tokens.source().filename(),
  708. .line_number = 0,
  709. .column_number = 0};
  710. }
  711. }
  712. auto FileContext::BuildVtable(const SemIR::Class& class_info)
  713. -> llvm::GlobalVariable* {
  714. // Bail out if this class is not dynamic (this will account for classes that
  715. // are declared-and-not-defined (including extern declarations) as well).
  716. if (!class_info.is_dynamic) {
  717. return nullptr;
  718. }
  719. // Vtables can't be generated for generics, only for their specifics - and
  720. // must be done lazily based on the use of those specifics.
  721. if (class_info.generic_id != SemIR::GenericId::None) {
  722. return nullptr;
  723. }
  724. Mangler m(*this);
  725. std::string mangled_name = m.MangleVTable(class_info);
  726. auto first_owning_decl_loc =
  727. sem_ir().insts().GetCanonicalLocId(class_info.first_owning_decl_id);
  728. if (first_owning_decl_loc.kind() == SemIR::LocId::Kind::ImportIRInstId) {
  729. // Emit a declaration of an imported vtable using a(n opaque) pointer type.
  730. // This doesn't have to match the definition that appears elsewhere, it'll
  731. // still get merged correctly.
  732. auto* gv = new llvm::GlobalVariable(
  733. llvm_module(),
  734. llvm::PointerType::get(llvm_context(), /*AddressSpace=*/0),
  735. /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
  736. mangled_name);
  737. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  738. return gv;
  739. }
  740. auto canonical_vtable_id =
  741. sem_ir().constant_values().GetConstantInstId(class_info.vtable_id);
  742. auto vtable_inst_block =
  743. sem_ir().inst_blocks().Get(sem_ir()
  744. .insts()
  745. .GetAs<SemIR::Vtable>(canonical_vtable_id)
  746. .virtual_functions_id);
  747. auto* entry_type = llvm::IntegerType::getInt32Ty(llvm_context());
  748. auto* table_type = llvm::ArrayType::get(entry_type, vtable_inst_block.size());
  749. auto* llvm_vtable = new llvm::GlobalVariable(
  750. llvm_module(), table_type, /*isConstant=*/true,
  751. llvm::GlobalValue::ExternalLinkage, nullptr, mangled_name);
  752. auto* i32_type = llvm::IntegerType::getInt32Ty(llvm_context());
  753. auto* i64_type = llvm::IntegerType::getInt64Ty(llvm_context());
  754. auto* vtable_const_int =
  755. llvm::ConstantExpr::getPtrToInt(llvm_vtable, i64_type);
  756. llvm::SmallVector<llvm::Constant*> vfuncs;
  757. vfuncs.reserve(vtable_inst_block.size());
  758. for (auto fn_decl_id : vtable_inst_block) {
  759. auto fn_decl = GetCalleeFunction(sem_ir(), fn_decl_id);
  760. vfuncs.push_back(llvm::ConstantExpr::getTrunc(
  761. llvm::ConstantExpr::getSub(
  762. llvm::ConstantExpr::getPtrToInt(
  763. GetOrCreateFunction(fn_decl.function_id,
  764. SemIR::SpecificId::None),
  765. i64_type),
  766. vtable_const_int),
  767. i32_type));
  768. }
  769. llvm_vtable->setInitializer(llvm::ConstantArray::get(table_type, vfuncs));
  770. llvm_vtable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  771. return llvm_vtable;
  772. }
  773. } // namespace Carbon::Lower