file_context.cpp 31 KB

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