file_context.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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 "common/vlog.h"
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "llvm/ADT/Sequence.h"
  8. #include "llvm/Transforms/Utils/ModuleUtils.h"
  9. #include "toolchain/base/kind_switch.h"
  10. #include "toolchain/lower/constant.h"
  11. #include "toolchain/lower/function_context.h"
  12. #include "toolchain/lower/mangler.h"
  13. #include "toolchain/sem_ir/entry_point.h"
  14. #include "toolchain/sem_ir/file.h"
  15. #include "toolchain/sem_ir/function.h"
  16. #include "toolchain/sem_ir/ids.h"
  17. #include "toolchain/sem_ir/inst.h"
  18. #include "toolchain/sem_ir/typed_insts.h"
  19. namespace Carbon::Lower {
  20. FileContext::FileContext(llvm::LLVMContext& llvm_context,
  21. bool include_debug_info,
  22. const Check::SemIRDiagnosticConverter& converter,
  23. llvm::StringRef module_name, const SemIR::File& sem_ir,
  24. const SemIR::InstNamer* inst_namer,
  25. llvm::raw_ostream* vlog_stream)
  26. : llvm_context_(&llvm_context),
  27. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  28. di_builder_(*llvm_module_),
  29. di_compile_unit_(
  30. include_debug_info
  31. ? BuildDICompileUnit(module_name, *llvm_module_, di_builder_)
  32. : nullptr),
  33. converter_(converter),
  34. sem_ir_(&sem_ir),
  35. inst_namer_(inst_namer),
  36. vlog_stream_(vlog_stream) {
  37. CARBON_CHECK(!sem_ir.has_errors())
  38. << "Generating LLVM IR from invalid SemIR::File is unsupported.";
  39. }
  40. // TODO: Move this to lower.cpp.
  41. auto FileContext::Run() -> std::unique_ptr<llvm::Module> {
  42. CARBON_CHECK(llvm_module_) << "Run can only be called once.";
  43. // Lower all types that were required to be complete.
  44. types_.resize(sem_ir_->insts().size());
  45. for (auto type_id : sem_ir_->types().complete_types()) {
  46. if (type_id.index >= 0) {
  47. types_[type_id.index] = BuildType(sem_ir_->types().GetInstId(type_id));
  48. }
  49. }
  50. // Lower function declarations.
  51. functions_.resize_for_overwrite(sem_ir_->functions().size());
  52. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  53. functions_[i] = BuildFunctionDecl(SemIR::FunctionId(i));
  54. }
  55. // Lower global variable declarations.
  56. for (auto inst_id :
  57. sem_ir().inst_blocks().Get(sem_ir().top_inst_block_id())) {
  58. // Only `VarStorage` indicates a global variable declaration in the
  59. // top instruction block.
  60. if (auto var = sem_ir().insts().TryGetAs<SemIR::VarStorage>(inst_id)) {
  61. global_variables_.Insert(inst_id, BuildGlobalVariableDecl(*var));
  62. }
  63. }
  64. // Lower constants.
  65. constants_.resize(sem_ir_->insts().size());
  66. LowerConstants(*this, constants_);
  67. // Lower function definitions.
  68. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  69. BuildFunctionDefinition(SemIR::FunctionId(i));
  70. }
  71. // Append `__global_init` to `llvm::global_ctors` to initialize global
  72. // variables.
  73. if (sem_ir().global_ctor_id().is_valid()) {
  74. llvm::appendToGlobalCtors(llvm_module(),
  75. GetFunction(sem_ir().global_ctor_id()),
  76. /*Priority=*/0);
  77. }
  78. return std::move(llvm_module_);
  79. }
  80. auto FileContext::BuildDICompileUnit(llvm::StringRef module_name,
  81. llvm::Module& llvm_module,
  82. llvm::DIBuilder& di_builder)
  83. -> llvm::DICompileUnit* {
  84. llvm_module.addModuleFlag(llvm::Module::Max, "Dwarf Version", 5);
  85. llvm_module.addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  86. llvm::DEBUG_METADATA_VERSION);
  87. // FIXME: Include directory path in the compile_unit_file.
  88. llvm::DIFile* compile_unit_file = di_builder.createFile(module_name, "");
  89. // FIXME: Introduce a new language code for Carbon. C works well for now since
  90. // it's something debuggers will already know/have support for at least.
  91. // Probably have to bump to C++ at some point for virtual functions,
  92. // templates, etc.
  93. return di_builder.createCompileUnit(llvm::dwarf::DW_LANG_C, compile_unit_file,
  94. "carbon",
  95. /*isOptimized=*/false, /*Flags=*/"",
  96. /*RV=*/0);
  97. }
  98. auto FileContext::GetGlobal(SemIR::InstId inst_id) -> llvm::Value* {
  99. auto inst = sem_ir().insts().Get(inst_id);
  100. auto const_id = sem_ir().constant_values().Get(inst_id);
  101. if (const_id.is_template()) {
  102. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  103. // For value expressions and initializing expressions, the value produced by
  104. // a constant instruction is a value representation of the constant. For
  105. // initializing expressions, `FinishInit` will perform a copy if needed.
  106. // TODO: Handle reference expression constants.
  107. auto* const_value = constants_[const_inst_id.index];
  108. // If we want a pointer to the constant, materialize a global to hold it.
  109. // TODO: We could reuse the same global if the constant is used more than
  110. // once.
  111. auto value_rep = SemIR::ValueRepr::ForType(sem_ir(), inst.type_id());
  112. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  113. // Include both the name of the constant, if any, and the point of use in
  114. // the name of the variable.
  115. llvm::StringRef const_name;
  116. llvm::StringRef use_name;
  117. if (inst_namer_) {
  118. const_name = inst_namer_->GetUnscopedNameFor(const_inst_id);
  119. use_name = inst_namer_->GetUnscopedNameFor(inst_id);
  120. }
  121. // We always need to give the global a name even if the instruction namer
  122. // doesn't have one to use.
  123. if (const_name.empty()) {
  124. const_name = "const";
  125. }
  126. if (use_name.empty()) {
  127. use_name = "anon";
  128. }
  129. llvm::StringRef sep = (use_name[0] == '.') ? "" : ".";
  130. return new llvm::GlobalVariable(
  131. llvm_module(), GetType(sem_ir().GetPointeeType(value_rep.type_id)),
  132. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage,
  133. const_value, const_name + sep + use_name);
  134. }
  135. // Otherwise, we can use the constant value directly.
  136. return const_value;
  137. }
  138. // TODO: For generics, handle references to symbolic constants.
  139. CARBON_FATAL() << "Missing value: " << inst_id << " "
  140. << sem_ir().insts().Get(inst_id);
  141. }
  142. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id)
  143. -> llvm::Function* {
  144. const auto& function = sem_ir().functions().Get(function_id);
  145. // Don't lower generic functions or associated functions.
  146. // TODO: Associated functions have `Self` in scope so should be treated as
  147. // generic functions.
  148. if (function.generic_id.is_valid() ||
  149. sem_ir().insts().Is<SemIR::InterfaceDecl>(
  150. sem_ir().name_scopes().Get(function.parent_scope_id).inst_id)) {
  151. return nullptr;
  152. }
  153. // Don't lower builtins.
  154. if (function.builtin_function_kind != SemIR::BuiltinFunctionKind::None) {
  155. return nullptr;
  156. }
  157. // TODO: Consider tracking whether the function has been used, and only
  158. // lowering it if it's needed.
  159. // TODO: Pass in a specific ID for generic functions.
  160. const auto specific_id = SemIR::SpecificId::Invalid;
  161. const auto return_info =
  162. SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id);
  163. CARBON_CHECK(return_info.is_valid()) << "Should not lower invalid functions.";
  164. auto implicit_param_refs =
  165. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_refs_id);
  166. // TODO: Include parameters corresponding to positional parameters.
  167. auto param_refs = sem_ir().inst_blocks().GetOrEmpty(function.param_refs_id);
  168. auto* return_type =
  169. return_info.type_id.is_valid() ? GetType(return_info.type_id) : nullptr;
  170. llvm::SmallVector<llvm::Type*> param_types;
  171. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  172. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  173. // out a mechanism to compute the mapping between parameters and arguments on
  174. // demand.
  175. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  176. auto max_llvm_params = (return_info.has_return_slot() ? 1 : 0) +
  177. implicit_param_refs.size() + param_refs.size();
  178. param_types.reserve(max_llvm_params);
  179. param_inst_ids.reserve(max_llvm_params);
  180. if (return_info.has_return_slot()) {
  181. param_types.push_back(return_type->getPointerTo());
  182. param_inst_ids.push_back(function.return_storage_id);
  183. }
  184. for (auto param_ref_id :
  185. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  186. auto param_type_id =
  187. SemIR::Function::GetParamFromParamRefId(sem_ir(), param_ref_id)
  188. .second.type_id;
  189. switch (auto value_rep = SemIR::ValueRepr::ForType(sem_ir(), param_type_id);
  190. value_rep.kind) {
  191. case SemIR::ValueRepr::Unknown:
  192. CARBON_FATAL()
  193. << "Incomplete parameter type lowering function declaration";
  194. case SemIR::ValueRepr::None:
  195. break;
  196. case SemIR::ValueRepr::Copy:
  197. case SemIR::ValueRepr::Custom:
  198. case SemIR::ValueRepr::Pointer:
  199. param_types.push_back(GetType(value_rep.type_id));
  200. param_inst_ids.push_back(param_ref_id);
  201. break;
  202. }
  203. }
  204. // Compute the return type to use for the LLVM function. If the initializing
  205. // representation doesn't produce a value, set the return type to void.
  206. // TODO: For the `Run` entry point, remap return type to i32 if it doesn't
  207. // return a value.
  208. llvm::Type* function_return_type =
  209. return_info.init_repr.kind == SemIR::InitRepr::ByCopy
  210. ? return_type
  211. : llvm::Type::getVoidTy(llvm_context());
  212. Mangler m(*this);
  213. std::string mangled_name = m.Mangle(function_id);
  214. llvm::FunctionType* function_type = llvm::FunctionType::get(
  215. function_return_type, param_types, /*isVarArg=*/false);
  216. auto* llvm_function =
  217. llvm::Function::Create(function_type, llvm::Function::ExternalLinkage,
  218. mangled_name, llvm_module());
  219. // Set up parameters and the return slot.
  220. for (auto [inst_id, arg] :
  221. llvm::zip_equal(param_inst_ids, llvm_function->args())) {
  222. auto name_id = SemIR::NameId::Invalid;
  223. if (inst_id == function.return_storage_id) {
  224. name_id = SemIR::NameId::ReturnSlot;
  225. arg.addAttr(
  226. llvm::Attribute::getWithStructRetType(llvm_context(), return_type));
  227. } else {
  228. name_id = SemIR::Function::GetParamFromParamRefId(sem_ir(), inst_id)
  229. .second.name_id;
  230. }
  231. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  232. }
  233. return llvm_function;
  234. }
  235. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id)
  236. -> void {
  237. const auto& function = sem_ir().functions().Get(function_id);
  238. const auto& body_block_ids = function.body_block_ids;
  239. if (body_block_ids.empty()) {
  240. // Function is probably defined in another file; not an error.
  241. return;
  242. }
  243. llvm::Function* llvm_function = GetFunction(function_id);
  244. if (!llvm_function) {
  245. // We chose not to lower this function at all, for example because it's a
  246. // generic function.
  247. return;
  248. }
  249. FunctionContext function_lowering(*this, llvm_function,
  250. BuildDISubprogram(function, llvm_function),
  251. vlog_stream_);
  252. // TODO: Pass in a specific ID for generic functions.
  253. const auto specific_id = SemIR::SpecificId::Invalid;
  254. // Add parameters to locals.
  255. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  256. // function parameters that was already computed in BuildFunctionDecl.
  257. // We should only do that once.
  258. auto implicit_param_refs =
  259. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_refs_id);
  260. auto param_refs = sem_ir().inst_blocks().GetOrEmpty(function.param_refs_id);
  261. int param_index = 0;
  262. if (SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id)
  263. .has_return_slot()) {
  264. function_lowering.SetLocal(function.return_storage_id,
  265. llvm_function->getArg(param_index));
  266. ++param_index;
  267. }
  268. for (auto param_ref_id :
  269. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  270. auto [param_id, param] =
  271. SemIR::Function::GetParamFromParamRefId(sem_ir(), param_ref_id);
  272. // Get the value of the parameter from the function argument.
  273. auto param_type_id = param.type_id;
  274. llvm::Value* param_value = llvm::PoisonValue::get(GetType(param_type_id));
  275. if (SemIR::ValueRepr::ForType(sem_ir(), param_type_id).kind !=
  276. SemIR::ValueRepr::None) {
  277. param_value = llvm_function->getArg(param_index);
  278. ++param_index;
  279. }
  280. // The value of the parameter is the value of the argument.
  281. function_lowering.SetLocal(param_id, param_value);
  282. // Match the portion of the pattern corresponding to the parameter against
  283. // the parameter value. For now this is always a single name binding,
  284. // possibly wrapped in `addr`.
  285. //
  286. // TODO: Support general patterns here.
  287. auto bind_name_id = param_ref_id;
  288. if (auto addr =
  289. sem_ir().insts().TryGetAs<SemIR::AddrPattern>(param_ref_id)) {
  290. bind_name_id = addr->inner_id;
  291. }
  292. auto bind_name = sem_ir().insts().Get(bind_name_id);
  293. // TODO: Should we stop passing compile-time bindings at runtime?
  294. CARBON_CHECK(bind_name.Is<SemIR::AnyBindName>());
  295. function_lowering.SetLocal(bind_name_id, param_value);
  296. }
  297. // Lower all blocks.
  298. for (auto block_id : body_block_ids) {
  299. CARBON_VLOG("Lowering {0}\n", block_id);
  300. auto* llvm_block = function_lowering.GetBlock(block_id);
  301. // Keep the LLVM blocks in lexical order.
  302. llvm_block->moveBefore(llvm_function->end());
  303. function_lowering.builder().SetInsertPoint(llvm_block);
  304. function_lowering.LowerBlock(block_id);
  305. }
  306. // LLVM requires that the entry block has no predecessors.
  307. auto* entry_block = &llvm_function->getEntryBlock();
  308. if (entry_block->hasNPredecessorsOrMore(1)) {
  309. auto* new_entry_block = llvm::BasicBlock::Create(
  310. llvm_context(), "entry", llvm_function, entry_block);
  311. llvm::BranchInst::Create(entry_block, new_entry_block);
  312. }
  313. }
  314. auto FileContext::BuildDISubprogram(const SemIR::Function& function,
  315. const llvm::Function* llvm_function)
  316. -> llvm::DISubprogram* {
  317. if (!di_compile_unit_) {
  318. return nullptr;
  319. }
  320. auto name = sem_ir().names().GetAsStringIfIdentifier(function.name_id);
  321. CARBON_CHECK(name) << "Unexpected special name for function: "
  322. << function.name_id;
  323. auto loc = GetLocForDI(function.definition_id);
  324. // FIXME: Add more details here, including real subroutine type (once type
  325. // information is built), etc.
  326. return di_builder_.createFunction(
  327. di_compile_unit_, *name, llvm_function->getName(),
  328. /*File=*/di_builder_.createFile(loc.filename, ""),
  329. /*LineNo=*/loc.line_number,
  330. di_builder_.createSubroutineType(
  331. di_builder_.getOrCreateTypeArray(std::nullopt)),
  332. /*ScopeLine=*/0, llvm::DINode::FlagZero,
  333. llvm::DISubprogram::SPFlagDefinition);
  334. }
  335. static auto BuildTypeForInst(FileContext& context, SemIR::ArrayType inst)
  336. -> llvm::Type* {
  337. return llvm::ArrayType::get(
  338. context.GetType(inst.element_type_id),
  339. context.sem_ir().GetArrayBoundValue(inst.bound_id));
  340. }
  341. static auto BuildTypeForInst(FileContext& context, SemIR::BuiltinInst inst)
  342. -> llvm::Type* {
  343. switch (inst.builtin_inst_kind) {
  344. case SemIR::BuiltinInstKind::Invalid:
  345. CARBON_FATAL() << "Unexpected builtin type in lowering.";
  346. case SemIR::BuiltinInstKind::Error:
  347. // This is a complete type but uses of it should never be lowered.
  348. return nullptr;
  349. case SemIR::BuiltinInstKind::TypeType:
  350. return context.GetTypeType();
  351. case SemIR::BuiltinInstKind::FloatType:
  352. return llvm::Type::getDoubleTy(context.llvm_context());
  353. case SemIR::BuiltinInstKind::IntType:
  354. return llvm::Type::getInt32Ty(context.llvm_context());
  355. case SemIR::BuiltinInstKind::BoolType:
  356. // TODO: We may want to have different representations for `bool`
  357. // storage
  358. // (`i8`) versus for `bool` values (`i1`).
  359. return llvm::Type::getInt1Ty(context.llvm_context());
  360. case SemIR::BuiltinInstKind::StringType:
  361. // TODO: Decide how we want to represent `StringType`.
  362. return llvm::PointerType::get(context.llvm_context(), 0);
  363. case SemIR::BuiltinInstKind::BoundMethodType:
  364. case SemIR::BuiltinInstKind::NamespaceType:
  365. case SemIR::BuiltinInstKind::WitnessType:
  366. // Return an empty struct as a placeholder.
  367. return llvm::StructType::get(context.llvm_context());
  368. }
  369. }
  370. // BuildTypeForInst is used to construct types for FileContext::BuildType below.
  371. // Implementations return the LLVM type for the instruction. This first overload
  372. // is the fallback handler for non-type instructions.
  373. template <typename InstT>
  374. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  375. static auto BuildTypeForInst(FileContext& /*context*/, InstT inst)
  376. -> llvm::Type* {
  377. CARBON_FATAL() << "Cannot use inst as type: " << inst;
  378. }
  379. static auto BuildTypeForInst(FileContext& context, SemIR::ClassType inst)
  380. -> llvm::Type* {
  381. auto object_repr_id =
  382. context.sem_ir().classes().Get(inst.class_id).object_repr_id;
  383. return context.GetType(object_repr_id);
  384. }
  385. static auto BuildTypeForInst(FileContext& context, SemIR::ConstType inst)
  386. -> llvm::Type* {
  387. return context.GetType(inst.inner_id);
  388. }
  389. static auto BuildTypeForInst(FileContext& context, SemIR::FloatType /*inst*/)
  390. -> llvm::Type* {
  391. // TODO: Handle different sizes.
  392. return llvm::Type::getDoubleTy(context.llvm_context());
  393. }
  394. static auto BuildTypeForInst(FileContext& context, SemIR::IntType inst)
  395. -> llvm::Type* {
  396. auto width =
  397. context.sem_ir().insts().TryGetAs<SemIR::IntLiteral>(inst.bit_width_id);
  398. CARBON_CHECK(width) << "Can't lower int type with symbolic width";
  399. return llvm::IntegerType::get(
  400. context.llvm_context(),
  401. context.sem_ir().ints().Get(width->int_id).getZExtValue());
  402. }
  403. static auto BuildTypeForInst(FileContext& context, SemIR::PointerType /*inst*/)
  404. -> llvm::Type* {
  405. return llvm::PointerType::get(context.llvm_context(), /*AddressSpace=*/0);
  406. }
  407. static auto BuildTypeForInst(FileContext& context, SemIR::StructType inst)
  408. -> llvm::Type* {
  409. auto fields = context.sem_ir().inst_blocks().Get(inst.fields_id);
  410. llvm::SmallVector<llvm::Type*> subtypes;
  411. subtypes.reserve(fields.size());
  412. for (auto field_id : fields) {
  413. auto field =
  414. context.sem_ir().insts().GetAs<SemIR::StructTypeField>(field_id);
  415. subtypes.push_back(context.GetType(field.field_type_id));
  416. }
  417. return llvm::StructType::get(context.llvm_context(), subtypes);
  418. }
  419. static auto BuildTypeForInst(FileContext& context, SemIR::TupleType inst)
  420. -> llvm::Type* {
  421. // TODO: Investigate special-casing handling of empty tuples so that they
  422. // can be collectively replaced with LLVM's void, particularly around
  423. // function returns. LLVM doesn't allow declaring variables with a void
  424. // type, so that may require significant special casing.
  425. auto elements = context.sem_ir().type_blocks().Get(inst.elements_id);
  426. llvm::SmallVector<llvm::Type*> subtypes;
  427. subtypes.reserve(elements.size());
  428. for (auto element_id : elements) {
  429. subtypes.push_back(context.GetType(element_id));
  430. }
  431. return llvm::StructType::get(context.llvm_context(), subtypes);
  432. }
  433. template <typename InstT>
  434. requires(InstT::Kind.template IsAnyOf<
  435. SemIR::AssociatedEntityType, SemIR::FunctionType,
  436. SemIR::GenericClassType, SemIR::GenericInterfaceType,
  437. SemIR::InterfaceType, SemIR::UnboundElementType>())
  438. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  439. -> llvm::Type* {
  440. // Return an empty struct as a placeholder.
  441. // TODO: Should we model an interface as a witness table, or an associated
  442. // entity as an index?
  443. return llvm::StructType::get(context.llvm_context());
  444. }
  445. // Treat non-monomorphized symbolic types as opaque.
  446. template <typename InstT>
  447. requires(InstT::Kind.template IsAnyOf<SemIR::BindSymbolicName,
  448. SemIR::InterfaceWitnessAccess>())
  449. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  450. -> llvm::Type* {
  451. return llvm::StructType::get(context.llvm_context());
  452. }
  453. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  454. // Use overload resolution to select the implementation, producing compile
  455. // errors when BuildTypeForInst isn't defined for a given instruction.
  456. CARBON_KIND_SWITCH(sem_ir_->insts().Get(inst_id)) {
  457. #define CARBON_SEM_IR_INST_KIND(Name) \
  458. case CARBON_KIND(SemIR::Name inst): { \
  459. return BuildTypeForInst(*this, inst); \
  460. }
  461. #include "toolchain/sem_ir/inst_kind.def"
  462. }
  463. }
  464. auto FileContext::BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  465. -> llvm::GlobalVariable* {
  466. // TODO: Mangle name.
  467. auto mangled_name =
  468. *sem_ir().names().GetAsStringIfIdentifier(var_storage.name_id);
  469. auto* type =
  470. var_storage.type_id.is_valid() ? GetType(var_storage.type_id) : nullptr;
  471. return new llvm::GlobalVariable(llvm_module(), type,
  472. /*isConstant=*/false,
  473. llvm::GlobalVariable::InternalLinkage,
  474. /*Initializer=*/nullptr, mangled_name);
  475. }
  476. auto FileContext::GetLocForDI(SemIR::InstId inst_id) -> LocForDI {
  477. auto diag_loc = converter_.ConvertLoc(
  478. inst_id,
  479. [&](DiagnosticLoc /*context_loc*/,
  480. const Internal::DiagnosticBase<>& /*context_diagnostic_base*/) {});
  481. return {.filename = diag_loc.filename,
  482. .line_number = diag_loc.line_number == -1 ? 0 : diag_loc.line_number,
  483. .column_number =
  484. diag_loc.column_number == -1 ? 0 : diag_loc.column_number};
  485. }
  486. } // namespace Carbon::Lower