file_context.cpp 35 KB

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