file_context.cpp 51 KB

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