import.cpp 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188
  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/check/cpp/import.h"
  5. #include <algorithm>
  6. #include <memory>
  7. #include <optional>
  8. #include <string>
  9. #include <tuple>
  10. #include <utility>
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/RecordLayout.h"
  13. #include "clang/AST/UnresolvedSet.h"
  14. #include "clang/AST/VTableBuilder.h"
  15. #include "clang/Frontend/CompilerInvocation.h"
  16. #include "clang/Sema/Lookup.h"
  17. #include "clang/Sema/Overload.h"
  18. #include "common/check.h"
  19. #include "common/ostream.h"
  20. #include "common/raw_string_ostream.h"
  21. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/Support/raw_ostream.h"
  24. #include "toolchain/base/int.h"
  25. #include "toolchain/base/kind_switch.h"
  26. #include "toolchain/base/value_ids.h"
  27. #include "toolchain/check/call.h"
  28. #include "toolchain/check/class.h"
  29. #include "toolchain/check/context.h"
  30. #include "toolchain/check/control_flow.h"
  31. #include "toolchain/check/convert.h"
  32. #include "toolchain/check/core_identifier.h"
  33. #include "toolchain/check/cpp/access.h"
  34. #include "toolchain/check/cpp/custom_type_mapping.h"
  35. #include "toolchain/check/cpp/generate_ast.h"
  36. #include "toolchain/check/cpp/location.h"
  37. #include "toolchain/check/cpp/macros.h"
  38. #include "toolchain/check/cpp/thunk.h"
  39. #include "toolchain/check/diagnostic_helpers.h"
  40. #include "toolchain/check/eval.h"
  41. #include "toolchain/check/function.h"
  42. #include "toolchain/check/import.h"
  43. #include "toolchain/check/inst.h"
  44. #include "toolchain/check/literal.h"
  45. #include "toolchain/check/member_access.h"
  46. #include "toolchain/check/name_lookup.h"
  47. #include "toolchain/check/operator.h"
  48. #include "toolchain/check/pattern.h"
  49. #include "toolchain/check/pattern_match.h"
  50. #include "toolchain/check/type.h"
  51. #include "toolchain/check/type_completion.h"
  52. #include "toolchain/parse/node_ids.h"
  53. #include "toolchain/sem_ir/clang_decl.h"
  54. #include "toolchain/sem_ir/class.h"
  55. #include "toolchain/sem_ir/cpp_file.h"
  56. #include "toolchain/sem_ir/cpp_overload_set.h"
  57. #include "toolchain/sem_ir/function.h"
  58. #include "toolchain/sem_ir/ids.h"
  59. #include "toolchain/sem_ir/inst.h"
  60. #include "toolchain/sem_ir/name_scope.h"
  61. #include "toolchain/sem_ir/typed_insts.h"
  62. namespace Carbon::Check {
  63. // Adds the name to the scope with the given `access_kind` and `inst_id`.
  64. // `inst_id` must have a value.
  65. static auto AddNameToScope(Context& context, SemIR::NameScopeId scope_id,
  66. SemIR::NameId name_id, SemIR::AccessKind access_kind,
  67. SemIR::InstId inst_id) -> void {
  68. CARBON_CHECK(inst_id.has_value());
  69. context.name_scopes().Get(scope_id).AddRequired(
  70. {.name_id = name_id,
  71. .result = SemIR::ScopeLookupResult::MakeFound(inst_id, access_kind)});
  72. }
  73. // Maps a Clang name to a Carbon `NameId`.
  74. static auto AddIdentifierName(Context& context, llvm::StringRef name)
  75. -> SemIR::NameId {
  76. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  77. }
  78. // Adds the given source location and an `ImportIRInst` referring to it in
  79. // `ImportIRId::Cpp`.
  80. static auto AddImportIRInst(SemIR::File& file,
  81. clang::SourceLocation clang_source_loc)
  82. -> SemIR::ImportIRInstId {
  83. SemIR::ClangSourceLocId clang_source_loc_id =
  84. file.clang_source_locs().Add(clang_source_loc);
  85. return file.import_ir_insts().Add(SemIR::ImportIRInst(clang_source_loc_id));
  86. }
  87. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  88. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  89. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  90. -> SemIR::NameScopeId {
  91. return AddImportNamespaceToScope(
  92. context,
  93. GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  94. SemIR::NameId::ForPackageName(cpp_package_id),
  95. SemIR::NameScopeId::Package,
  96. /*diagnose_duplicate_namespace=*/false,
  97. [&]() {
  98. return AddInst<SemIR::ImportCppDecl>(
  99. context,
  100. context.parse_tree().As<Parse::ImportDeclId>(
  101. imports.front().node_id),
  102. {});
  103. })
  104. .add_result.name_scope_id;
  105. }
  106. auto ImportCpp(Context& context,
  107. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  108. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  109. std::shared_ptr<clang::CompilerInvocation> invocation) -> void {
  110. if (imports.empty()) {
  111. // TODO: Consider always having a (non-null) AST even if there are no Cpp
  112. // imports.
  113. return;
  114. }
  115. PackageNameId package_id = imports.front().package_id;
  116. CARBON_CHECK(
  117. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  118. return import.package_id == package_id;
  119. }));
  120. auto name_scope_id = AddNamespace(context, package_id, imports);
  121. bool ast_has_error =
  122. !GenerateAst(context, imports, fs, std::move(invocation));
  123. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  124. name_scope.set_is_closed_import(true);
  125. name_scope.set_clang_decl_context_id(context.clang_decls().Add(
  126. {.key =
  127. SemIR::ClangDeclKey(context.ast_context().getTranslationUnitDecl()),
  128. .inst_id = name_scope.inst_id()}));
  129. if (ast_has_error) {
  130. name_scope.set_has_error();
  131. }
  132. }
  133. // Returns the Clang `DeclContext` for the given name scope. Return the
  134. // translation unit decl if no scope is provided.
  135. static auto GetDeclContext(Context& context, SemIR::NameScopeId scope_id)
  136. -> clang::DeclContext* {
  137. if (!scope_id.has_value()) {
  138. return context.ast_context().getTranslationUnitDecl();
  139. }
  140. auto scope_clang_decl_context_id =
  141. context.name_scopes().Get(scope_id).clang_decl_context_id();
  142. return dyn_cast<clang::DeclContext>(
  143. context.clang_decls().Get(scope_clang_decl_context_id).key.decl);
  144. }
  145. // Returns true if the given Clang declaration is the implicit injected class
  146. // name within the class.
  147. static auto IsDeclInjectedClassName(Context& context,
  148. SemIR::NameScopeId scope_id,
  149. SemIR::NameId name_id,
  150. const clang::NamedDecl* named_decl)
  151. -> bool {
  152. if (!named_decl->isImplicit()) {
  153. return false;
  154. }
  155. const auto* record_decl = dyn_cast<clang::CXXRecordDecl>(named_decl);
  156. if (!record_decl) {
  157. return false;
  158. }
  159. const SemIR::ClangDecl& clang_decl = context.clang_decls().Get(
  160. context.name_scopes().Get(scope_id).clang_decl_context_id());
  161. const auto* scope_record_decl =
  162. cast<clang::CXXRecordDecl>(clang_decl.key.decl);
  163. const clang::ASTContext& ast_context = context.ast_context();
  164. CARBON_CHECK(ast_context.getCanonicalTagType(scope_record_decl) ==
  165. ast_context.getCanonicalTagType(record_decl));
  166. auto class_decl = context.insts().GetAs<SemIR::ClassDecl>(clang_decl.inst_id);
  167. CARBON_CHECK(name_id == context.classes().Get(class_decl.class_id).name_id);
  168. return true;
  169. }
  170. // Performs a qualified name lookup of the identifier in the given scope.
  171. // Returns the lookup result if lookup was successful.
  172. static auto ClangLookupName(Context& context, SemIR::NameScopeId scope_id,
  173. clang::IdentifierInfo* identifier_name)
  174. -> std::optional<clang::LookupResult> {
  175. CARBON_CHECK(identifier_name, "Identifier name is empty");
  176. clang::Sema& sema = context.clang_sema();
  177. // TODO: Map the LocId of the lookup to a clang SourceLocation and provide it
  178. // here so that clang's diagnostics can point into the carbon code that uses
  179. // the name.
  180. clang::LookupResult lookup(
  181. sema,
  182. clang::DeclarationNameInfo(clang::DeclarationName(identifier_name),
  183. clang::SourceLocation()),
  184. clang::Sema::LookupNameKind::LookupOrdinaryName);
  185. bool found =
  186. sema.LookupQualifiedName(lookup, GetDeclContext(context, scope_id));
  187. if (!found) {
  188. return std::nullopt;
  189. }
  190. return lookup;
  191. }
  192. // Returns whether `decl` already mapped to an instruction.
  193. static auto IsClangDeclImported(Context& context, SemIR::ClangDeclKey key)
  194. -> bool {
  195. return context.clang_decls().Lookup(key).has_value();
  196. }
  197. // If `decl` already mapped to an instruction, returns that instruction.
  198. // Otherwise returns `None`.
  199. static auto LookupClangDeclInstId(Context& context, SemIR::ClangDeclKey key)
  200. -> SemIR::InstId {
  201. const auto& clang_decls = context.clang_decls();
  202. if (auto context_clang_decl_id = clang_decls.Lookup(key);
  203. context_clang_decl_id.has_value()) {
  204. return clang_decls.Get(context_clang_decl_id).inst_id;
  205. }
  206. return SemIR::InstId::None;
  207. }
  208. // Returns the parent of the given declaration. Skips declaration types we
  209. // ignore.
  210. static auto GetParentDecl(clang::Decl* clang_decl) -> clang::Decl* {
  211. auto* parent_dc = clang_decl->getDeclContext();
  212. while (!parent_dc->isLookupContext()) {
  213. parent_dc = parent_dc->getParent();
  214. }
  215. return cast<clang::Decl>(parent_dc);
  216. }
  217. // Returns the given declaration's parent scope. Assumes the parent declaration
  218. // was already imported.
  219. static auto GetParentNameScopeId(Context& context, clang::Decl* clang_decl)
  220. -> SemIR::NameScopeId {
  221. auto* parent_decl = GetParentDecl(clang_decl);
  222. if (auto* tag_decl = dyn_cast<clang::TagDecl>(parent_decl)) {
  223. auto class_inst_id =
  224. LookupClangDeclInstId(context, SemIR::ClangDeclKey(tag_decl));
  225. CARBON_CHECK(class_inst_id.has_value());
  226. return context.classes()
  227. .Get(context.insts().GetAs<SemIR::ClassDecl>(class_inst_id).class_id)
  228. .scope_id;
  229. }
  230. if (isa<clang::NamespaceDecl, clang::TranslationUnitDecl>(parent_decl)) {
  231. auto namespace_inst_id = LookupClangDeclInstId(
  232. context, SemIR::ClangDeclKey::ForNonFunctionDecl(parent_decl));
  233. CARBON_CHECK(namespace_inst_id.has_value());
  234. return context.insts()
  235. .GetAs<SemIR::Namespace>(namespace_inst_id)
  236. .name_scope_id;
  237. }
  238. CARBON_FATAL("Unexpected kind of parent {0}", parent_decl->getDeclKindName());
  239. }
  240. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  241. // the new Carbon namespace declaration `InstId`. If the declaration was already
  242. // imported, returns the mapped instruction.
  243. static auto ImportNamespaceDecl(Context& context,
  244. clang::NamespaceDecl* clang_decl)
  245. -> SemIR::InstId {
  246. auto key = SemIR::ClangDeclKey(clang_decl);
  247. // Check if the declaration is already mapped.
  248. if (SemIR::InstId existing_inst_id = LookupClangDeclInstId(context, key);
  249. existing_inst_id.has_value()) {
  250. return existing_inst_id;
  251. }
  252. auto result = AddImportNamespace(
  253. context, GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  254. AddIdentifierName(context, clang_decl->getName()),
  255. GetParentNameScopeId(context, clang_decl),
  256. /*import_id=*/SemIR::InstId::None);
  257. context.name_scopes()
  258. .Get(result.name_scope_id)
  259. .set_clang_decl_context_id(
  260. context.clang_decls().Add({.key = key, .inst_id = result.inst_id}));
  261. return result.inst_id;
  262. }
  263. static auto ImportTypeAndDependencies(Context& context, SemIR::LocId loc_id,
  264. clang::QualType type) -> TypeExpr;
  265. // Creates a class declaration for the given class name in the given scope.
  266. // Returns the `InstId` for the declaration.
  267. static auto BuildClassDecl(Context& context,
  268. SemIR::ImportIRInstId import_ir_inst_id,
  269. SemIR::NameScopeId parent_scope_id,
  270. SemIR::NameId name_id)
  271. -> std::tuple<SemIR::ClassId, SemIR::TypeInstId> {
  272. // Add the class declaration.
  273. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeType::TypeId,
  274. .class_id = SemIR::ClassId::None,
  275. .decl_block_id = SemIR::InstBlockId::None};
  276. auto class_decl_id = AddPlaceholderImportedInstInNoBlock(
  277. context,
  278. MakeImportedLocIdAndInst(context, import_ir_inst_id, class_decl));
  279. SemIR::Class class_info = {
  280. {.name_id = name_id,
  281. .parent_scope_id = parent_scope_id,
  282. .generic_id = SemIR::GenericId::None,
  283. .first_param_node_id = Parse::NodeId::None,
  284. .last_param_node_id = Parse::NodeId::None,
  285. .pattern_block_id = SemIR::InstBlockId::None,
  286. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  287. .param_patterns_id = SemIR::InstBlockId::None,
  288. .is_extern = false,
  289. .extern_library_id = SemIR::LibraryNameId::None,
  290. .non_owning_decl_id = SemIR::InstId::None,
  291. .first_owning_decl_id = class_decl_id},
  292. {// `.self_type_id` depends on the ClassType, so is set below.
  293. .self_type_id = SemIR::TypeId::None,
  294. // TODO: Support Dynamic classes.
  295. // TODO: Support Final classes.
  296. .inheritance_kind = SemIR::Class::Base}};
  297. class_decl.class_id = context.classes().Add(class_info);
  298. // Write the class ID into the ClassDecl.
  299. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  300. SetClassSelfType(context, class_decl.class_id);
  301. return {class_decl.class_id, context.types().GetAsTypeInstId(class_decl_id)};
  302. }
  303. // Imports a tag declaration from Clang to Carbon. This covers classes (which
  304. // includes structs and unions) as well as enums. If successful, returns the new
  305. // Carbon class declaration `InstId`.
  306. static auto ImportTagDecl(Context& context, clang::TagDecl* clang_decl)
  307. -> SemIR::InstId {
  308. auto import_ir_inst_id =
  309. AddImportIRInst(context.sem_ir(), clang_decl->getLocation());
  310. auto [class_id, class_inst_id] = BuildClassDecl(
  311. context, import_ir_inst_id, GetParentNameScopeId(context, clang_decl),
  312. AddIdentifierName(context, clang_decl->getName()));
  313. // TODO: The caller does the same lookup. Avoid doing it twice.
  314. auto key = SemIR::ClangDeclKey(clang_decl);
  315. auto clang_decl_id =
  316. context.clang_decls().Add({.key = key, .inst_id = class_inst_id});
  317. // Name lookup into the Carbon class looks in the C++ class definition.
  318. auto& class_info = context.classes().Get(class_id);
  319. class_info.scope_id = context.name_scopes().Add(
  320. class_inst_id, SemIR::NameId::None, class_info.parent_scope_id);
  321. context.name_scopes()
  322. .Get(class_info.scope_id)
  323. .set_clang_decl_context_id(clang_decl_id);
  324. return class_inst_id;
  325. }
  326. // Determines the Carbon inheritance kind to use for a C++ class definition.
  327. static auto GetInheritanceKind(clang::CXXRecordDecl* class_def)
  328. -> SemIR::Class::InheritanceKind {
  329. if (class_def->isUnion()) {
  330. // Treat all unions as final classes to match their C++ semantics. While we
  331. // could support this, the author of a C++ union has no way to mark their
  332. // type as `final` to prevent it, and so we assume the intent was to
  333. // disallow inheritance.
  334. return SemIR::Class::Final;
  335. }
  336. if (class_def->hasAttr<clang::FinalAttr>()) {
  337. // The class is final in C++; don't allow Carbon types to derive from it.
  338. // Note that such a type might also be abstract in C++; we treat final as
  339. // taking precedence.
  340. //
  341. // We could also treat classes with a final destructor as being final, as
  342. // Clang does when determining whether a class is "effectively final", but
  343. // to keep our rules simpler we do not.
  344. return SemIR::Class::Final;
  345. }
  346. if (class_def->getNumVBases()) {
  347. // TODO: We treat classes with virtual bases as final for now. We use the
  348. // layout of the class including its virtual bases as its Carbon type
  349. // layout, so we wouldn't behave correctly if we derived from it.
  350. return SemIR::Class::Final;
  351. }
  352. if (class_def->isAbstract()) {
  353. // If the class has any abstract members, it's abstract.
  354. return SemIR::Class::Abstract;
  355. }
  356. // Allow inheritance from any other C++ class type.
  357. return SemIR::Class::Base;
  358. }
  359. // Checks that the specified finished class definition is valid and builds and
  360. // returns a corresponding complete type witness instruction.
  361. static auto ImportClassObjectRepr(Context& context, SemIR::ClassId class_id,
  362. SemIR::ImportIRInstId import_ir_inst_id,
  363. SemIR::TypeInstId class_type_inst_id,
  364. const clang::CXXRecordDecl* clang_def)
  365. -> SemIR::TypeInstId {
  366. if (clang_def->isInvalidDecl()) {
  367. // Clang already diagnosed this error.
  368. return SemIR::ErrorInst::TypeInstId;
  369. }
  370. // For now, if the class is empty, produce an empty struct as the object
  371. // representation. This allows our tests to continue to pass while we don't
  372. // properly support initializing imported C++ classes.
  373. // TODO: Remove this.
  374. if (clang_def->isEmpty() && !clang_def->getNumBases()) {
  375. return context.types().GetAsTypeInstId(AddInst(
  376. context,
  377. MakeImportedLocIdAndInst(
  378. context, import_ir_inst_id,
  379. SemIR::StructType{.type_id = SemIR::TypeType::TypeId,
  380. .fields_id = SemIR::StructTypeFieldsId::Empty})));
  381. }
  382. const auto& clang_layout =
  383. context.ast_context().getASTRecordLayout(clang_def);
  384. llvm::SmallVector<uint64_t> layout;
  385. llvm::SmallVector<SemIR::StructTypeField> fields;
  386. static_assert(SemIR::CustomLayoutId::SizeIndex == 0);
  387. layout.push_back(clang_layout.getSize().getQuantity());
  388. static_assert(SemIR::CustomLayoutId::AlignIndex == 1);
  389. layout.push_back(clang_layout.getAlignment().getQuantity());
  390. static_assert(SemIR::CustomLayoutId::FirstFieldIndex == 2);
  391. // TODO: Import vptr(s).
  392. // The kind of base class we've picked so far. These are ordered in increasing
  393. // preference order.
  394. enum class BaseKind {
  395. None,
  396. Empty,
  397. NonEmpty,
  398. Polymorphic,
  399. };
  400. BaseKind base_kind = BaseKind::None;
  401. // Import bases.
  402. for (const auto& base : clang_def->bases()) {
  403. if (base.isVirtual()) {
  404. // If the base is virtual, skip it from the layout. We don't know where it
  405. // will actually appear within the complete object layout, as a pointer to
  406. // this class might point to a derived type that puts the vbase in a
  407. // different place.
  408. // TODO: Track that the virtual base existed. Support derived-to-vbase
  409. // conversions by generating a clang AST fragment.
  410. continue;
  411. }
  412. auto [base_type_inst_id, base_type_id] =
  413. ImportTypeAndDependencies(context, import_ir_inst_id, base.getType());
  414. if (!base_type_id.has_value()) {
  415. // TODO: If the base class's type can't be mapped, skip it.
  416. continue;
  417. }
  418. auto base_decl_id = AddInst(
  419. context,
  420. MakeImportedLocIdAndInst(
  421. context, import_ir_inst_id,
  422. SemIR::BaseDecl{.type_id = GetUnboundElementType(
  423. context, class_type_inst_id, base_type_inst_id),
  424. .base_type_inst_id = base_type_inst_id,
  425. .index = SemIR::ElementIndex(fields.size())}));
  426. auto* base_class = base.getType()->getAsCXXRecordDecl();
  427. CARBON_CHECK(base_class, "Base class {0} is not a class",
  428. base.getType().getAsString());
  429. // If there's a unique "best" base class, treat it as a Carbon base class
  430. // too.
  431. // TODO: Improve handling for the case where the class has multiple base
  432. // classes.
  433. BaseKind kind = base_class->isPolymorphic() ? BaseKind::Polymorphic
  434. : base_class->isEmpty() ? BaseKind::Empty
  435. : BaseKind::NonEmpty;
  436. auto& class_info = context.classes().Get(class_id);
  437. if (kind > base_kind) {
  438. // This base is better than the previous best.
  439. class_info.base_id = base_decl_id;
  440. base_kind = kind;
  441. } else if (kind == base_kind) {
  442. // Multiple base classes of this kind: no unique best.
  443. class_info.base_id = SemIR::InstId::None;
  444. }
  445. // TODO: If the base class has virtual bases, the size of the type that we
  446. // add to the layout here will be the full size of the class (including
  447. // virtual bases), whereas the size actually occupied by this base class is
  448. // only the nvsize (excluding virtual bases).
  449. auto base_offset = base.isVirtual()
  450. ? clang_layout.getVBaseClassOffset(base_class)
  451. : clang_layout.getBaseClassOffset(base_class);
  452. layout.push_back(base_offset.getQuantity());
  453. fields.push_back(
  454. {.name_id = SemIR::NameId::Base, .type_inst_id = base_type_inst_id});
  455. }
  456. // Import fields.
  457. for (auto* decl : clang_def->decls()) {
  458. auto* field = dyn_cast<clang::FieldDecl>(decl);
  459. // Track the chain of fields from the class to this field. This chain is
  460. // only one element long unless the field is a member of an anonymous struct
  461. // or union.
  462. clang::NamedDecl* single_field_chain[1] = {field};
  463. llvm::ArrayRef<clang::NamedDecl*> chain = single_field_chain;
  464. // If this isn't a field, it might be an indirect field in an anonymous
  465. // struct or union.
  466. if (!field) {
  467. auto* indirect_field = dyn_cast<clang::IndirectFieldDecl>(decl);
  468. if (!indirect_field) {
  469. continue;
  470. }
  471. chain = indirect_field->chain();
  472. field = indirect_field->getAnonField();
  473. }
  474. if (field->isBitField()) {
  475. // TODO: Add a representation for named bitfield members.
  476. continue;
  477. }
  478. if (field->isAnonymousStructOrUnion()) {
  479. // Fields within an anonymous structure or union will be added via their
  480. // IndirectFieldDecls.
  481. continue;
  482. }
  483. auto field_name_id = AddIdentifierName(context, field->getName());
  484. auto [field_type_inst_id, field_type_id] =
  485. ImportTypeAndDependencies(context, import_ir_inst_id, field->getType());
  486. if (!field_type_inst_id.has_value()) {
  487. // TODO: For now, just skip over fields whose types we can't map.
  488. continue;
  489. }
  490. // Create a field now, as we know the index to use.
  491. // TODO: Consider doing this lazily instead.
  492. auto field_decl_id = AddInst(
  493. context, MakeImportedLocIdAndInst(
  494. context, import_ir_inst_id,
  495. SemIR::FieldDecl{
  496. .type_id = GetUnboundElementType(
  497. context, class_type_inst_id, field_type_inst_id),
  498. .name_id = field_name_id,
  499. .index = SemIR::ElementIndex(fields.size())}));
  500. // The imported SemIR::FieldDecl represents the original declaration `decl`,
  501. // which is either the field or the indirect field declaration.
  502. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(decl);
  503. context.clang_decls().Add({.key = key, .inst_id = field_decl_id});
  504. // Compute the offset to the field that appears directly in the class.
  505. uint64_t offset = clang_layout.getFieldOffset(
  506. cast<clang::FieldDecl>(chain.front())->getFieldIndex());
  507. // If this is an indirect field, walk the path and accumulate the offset to
  508. // the named field.
  509. for (auto* inner_decl : chain.drop_front()) {
  510. auto* inner_field = cast<clang::FieldDecl>(inner_decl);
  511. const auto& inner_layout =
  512. context.ast_context().getASTRecordLayout(inner_field->getParent());
  513. offset += inner_layout.getFieldOffset(inner_field->getFieldIndex());
  514. }
  515. layout.push_back(
  516. context.ast_context().toCharUnitsFromBits(offset).getQuantity());
  517. fields.push_back(
  518. {.name_id = field_name_id, .type_inst_id = field_type_inst_id});
  519. }
  520. // TODO: Add a field to prevent tail padding reuse if necessary.
  521. return AddTypeInst(context,
  522. MakeImportedLocIdAndInst<SemIR::CustomLayoutType>(
  523. context, import_ir_inst_id,
  524. {.type_id = SemIR::TypeType::TypeId,
  525. .fields_id = context.struct_type_fields().Add(fields),
  526. .layout_id = context.custom_layouts().Add(layout)}));
  527. }
  528. // Creates a Carbon class definition based on the information in the given Clang
  529. // class declaration, which is assumed to be for a class definition.
  530. static auto BuildClassDefinition(Context& context,
  531. SemIR::ImportIRInstId import_ir_inst_id,
  532. SemIR::ClassId class_id,
  533. SemIR::TypeInstId class_inst_id,
  534. clang::CXXRecordDecl* clang_def) -> void {
  535. auto& class_info = context.classes().Get(class_id);
  536. CARBON_CHECK(!class_info.has_definition_started());
  537. class_info.definition_id = class_inst_id;
  538. context.inst_block_stack().Push();
  539. class_info.inheritance_kind = GetInheritanceKind(clang_def);
  540. // Compute the class's object representation.
  541. auto object_repr_id = ImportClassObjectRepr(
  542. context, class_id, import_ir_inst_id, class_inst_id, clang_def);
  543. class_info.complete_type_witness_id = AddInst(
  544. context,
  545. MakeImportedLocIdAndInst<SemIR::CompleteTypeWitness>(
  546. context, import_ir_inst_id,
  547. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  548. .object_repr_type_inst_id = object_repr_id}));
  549. class_info.body_block_id = context.inst_block_stack().Pop();
  550. }
  551. // Computes and returns the Carbon type to use as the object representation of
  552. // the given C++ enum type. This is a builtin int type matching the enum's
  553. // representation.
  554. static auto ImportEnumObjectRepresentation(
  555. Context& context, SemIR::ImportIRInstId import_ir_inst_id,
  556. clang::EnumDecl* enum_decl) -> SemIR::TypeInstId {
  557. auto int_type = enum_decl->getIntegerType();
  558. CARBON_CHECK(!int_type.isNull(), "incomplete enum type {0}",
  559. enum_decl->getNameAsString());
  560. auto int_kind = int_type->isSignedIntegerType() ? SemIR::IntKind::Signed
  561. : SemIR::IntKind::Unsigned;
  562. auto bit_width_id = GetOrAddInst(
  563. context, MakeImportedLocIdAndInst<SemIR::IntValue>(
  564. context, import_ir_inst_id,
  565. {.type_id = GetSingletonType(
  566. context, SemIR::IntLiteralType::TypeInstId),
  567. .int_id = context.ints().AddUnsigned(llvm::APInt(
  568. 64, context.ast_context().getIntWidth(int_type)))}));
  569. return context.types().GetAsTypeInstId(
  570. GetOrAddInst(context, SemIR::LocIdAndInst::NoLoc(SemIR::IntType{
  571. .type_id = SemIR::TypeType::TypeId,
  572. .int_kind = int_kind,
  573. .bit_width_id = bit_width_id})));
  574. }
  575. // Creates a Carbon class definition based on the information in the given Clang
  576. // enum declaration.
  577. static auto BuildEnumDefinition(Context& context,
  578. SemIR::ImportIRInstId import_ir_inst_id,
  579. SemIR::ClassId class_id,
  580. SemIR::TypeInstId class_inst_id,
  581. clang::EnumDecl* enum_decl) -> void {
  582. auto& class_info = context.classes().Get(class_id);
  583. CARBON_CHECK(!class_info.has_definition_started());
  584. class_info.definition_id = class_inst_id;
  585. context.inst_block_stack().Push();
  586. // Don't allow inheritance from C++ enums, to match the behavior in C++.
  587. class_info.inheritance_kind = SemIR::Class::Final;
  588. // Compute the enum type's object representation. An enum is an adapter for
  589. // the corresponding builtin integer type.
  590. auto object_repr_id =
  591. ImportEnumObjectRepresentation(context, import_ir_inst_id, enum_decl);
  592. class_info.adapt_id = AddInst(
  593. context, MakeImportedLocIdAndInst(
  594. context, import_ir_inst_id,
  595. SemIR::AdaptDecl{.adapted_type_inst_id = object_repr_id}));
  596. class_info.complete_type_witness_id = AddInst(
  597. context,
  598. MakeImportedLocIdAndInst<SemIR::CompleteTypeWitness>(
  599. context, import_ir_inst_id,
  600. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  601. .object_repr_type_inst_id = object_repr_id}));
  602. class_info.body_block_id = context.inst_block_stack().Pop();
  603. }
  604. // Imports an enumerator declaration from Clang to Carbon.
  605. static auto ImportEnumConstantDecl(Context& context,
  606. clang::EnumConstantDecl* enumerator_decl)
  607. -> SemIR::InstId {
  608. auto key = SemIR::ClangDeclKey(enumerator_decl);
  609. CARBON_CHECK(!IsClangDeclImported(context, key));
  610. // Find the enclosing enum type.
  611. auto enum_key = SemIR::ClangDeclKey(
  612. cast<clang::EnumDecl>(enumerator_decl->getDeclContext()));
  613. auto type_inst_id = LookupClangDeclInstId(context, enum_key);
  614. auto type_id = context.types().GetTypeIdForTypeInstId(type_inst_id);
  615. // Build a corresponding IntValue.
  616. auto int_id = context.ints().Add(enumerator_decl->getInitVal());
  617. auto import_ir_inst_id =
  618. AddImportIRInst(context.sem_ir(), enumerator_decl->getLocation());
  619. auto inst_id = AddInstInNoBlock(
  620. context,
  621. MakeImportedLocIdAndInst<SemIR::IntValue>(
  622. context, import_ir_inst_id, {.type_id = type_id, .int_id = int_id}));
  623. context.imports().push_back(inst_id);
  624. context.clang_decls().Add({.key = key, .inst_id = inst_id});
  625. return inst_id;
  626. }
  627. // Mark the given `key` as failed in `clang_decls`.
  628. static auto MarkFailedDecl(Context& context, SemIR::ClangDeclKey key) {
  629. context.clang_decls().Add({.key = key, .inst_id = SemIR::ErrorInst::InstId});
  630. }
  631. // Creates an integer type of the given size.
  632. static auto MakeIntType(Context& context, IntId size_id, bool is_signed)
  633. -> TypeExpr {
  634. auto type_inst_id = MakeIntTypeLiteral(
  635. context, Parse::NodeId::None,
  636. is_signed ? SemIR::IntKind::Signed : SemIR::IntKind::Unsigned, size_id);
  637. return ExprAsType(context, Parse::NodeId::None, type_inst_id);
  638. }
  639. static auto MakeCppCompatType(Context& context, SemIR::LocId loc_id,
  640. CoreIdentifier name) -> TypeExpr {
  641. return ExprAsType(
  642. context, loc_id,
  643. LookupNameInCore(context, loc_id, {CoreIdentifier::CppCompat, name}));
  644. }
  645. // Maps a C++ builtin integer type to a Carbon `Core.CppCompat` type.
  646. static auto MapBuiltinCppCompatIntegerType(Context& context,
  647. unsigned int cpp_width,
  648. unsigned int carbon_width,
  649. CoreIdentifier cpp_compat_name)
  650. -> TypeExpr {
  651. if (cpp_width != carbon_width) {
  652. return TypeExpr::None;
  653. }
  654. return MakeCppCompatType(context, Parse::NodeId::None, cpp_compat_name);
  655. }
  656. // Maps a C++ builtin integer type to a Carbon type.
  657. // TODO: Handle integer types that map to named aliases.
  658. static auto MapBuiltinIntegerType(Context& context, SemIR::LocId loc_id,
  659. clang::QualType qual_type,
  660. const clang::BuiltinType& type) -> TypeExpr {
  661. clang::ASTContext& ast_context = context.ast_context();
  662. unsigned width = ast_context.getIntWidth(qual_type);
  663. bool is_signed = type.isSignedInteger();
  664. auto int_n_type = ast_context.getIntTypeForBitwidth(width, is_signed);
  665. if (clang::ASTContext::hasSameType(qual_type, int_n_type)) {
  666. TypeExpr type_expr =
  667. MakeIntType(context, context.ints().Add(width), is_signed);
  668. // Try to make sure integer types of 32 or 64 bits are complete so we can
  669. // check against them when deciding whether we need to generate a thunk.
  670. if (width == 32 || width == 64) {
  671. SemIR::TypeId type_id = type_expr.type_id;
  672. if (!context.types().IsComplete(type_id)) {
  673. TryToCompleteType(context, type_id, loc_id);
  674. }
  675. }
  676. return type_expr;
  677. }
  678. if (clang::ASTContext::hasSameType(qual_type, ast_context.CharTy)) {
  679. return ExprAsType(context, Parse::NodeId::None,
  680. MakeCharTypeLiteral(context, Parse::NodeId::None));
  681. }
  682. if (clang::ASTContext::hasSameType(qual_type, ast_context.LongTy)) {
  683. return MapBuiltinCppCompatIntegerType(context, width, 32,
  684. CoreIdentifier::Long32);
  685. }
  686. if (clang::ASTContext::hasSameType(qual_type, ast_context.UnsignedLongTy)) {
  687. return MapBuiltinCppCompatIntegerType(context, width, 32,
  688. CoreIdentifier::ULong32);
  689. }
  690. if (clang::ASTContext::hasSameType(qual_type, ast_context.LongLongTy)) {
  691. return MapBuiltinCppCompatIntegerType(context, width, 64,
  692. CoreIdentifier::LongLong64);
  693. }
  694. if (clang::ASTContext::hasSameType(qual_type,
  695. ast_context.UnsignedLongLongTy)) {
  696. return MapBuiltinCppCompatIntegerType(context, width, 64,
  697. CoreIdentifier::ULongLong64);
  698. }
  699. return TypeExpr::None;
  700. }
  701. static auto MapNullptrType(Context& context, SemIR::LocId loc_id) -> TypeExpr {
  702. return MakeCppCompatType(context, loc_id, CoreIdentifier::NullptrT);
  703. }
  704. // Maps a C++ builtin type to a Carbon type.
  705. // TODO: Support more builtin types.
  706. static auto MapBuiltinType(Context& context, SemIR::LocId loc_id,
  707. clang::QualType qual_type,
  708. const clang::BuiltinType& type) -> TypeExpr {
  709. clang::ASTContext& ast_context = context.ast_context();
  710. if (type.isBooleanType()) {
  711. CARBON_CHECK(ast_context.hasSameType(qual_type, ast_context.BoolTy));
  712. return ExprAsType(context, Parse::NodeId::None,
  713. context.types().GetInstId(GetSingletonType(
  714. context, SemIR::BoolType::TypeInstId)));
  715. }
  716. if (type.isInteger()) {
  717. return MapBuiltinIntegerType(context, loc_id, qual_type, type);
  718. }
  719. if (type.isFloatingPoint()) {
  720. if (type.isFloat16Type() || type.isFloat32Type() || type.isDoubleType() ||
  721. type.isFloat128Type()) {
  722. return ExprAsType(
  723. context, Parse::NodeId::None,
  724. MakeFloatTypeLiteral(
  725. context, Parse::NodeId::None,
  726. context.ints().Add(ast_context.getTypeSize(qual_type))));
  727. }
  728. // TODO: Handle floating-point types that map to named aliases.
  729. } else if (type.isVoidType()) {
  730. return MakeCppCompatType(context, loc_id, CoreIdentifier::VoidBase);
  731. } else if (type.isNullPtrType()) {
  732. return MapNullptrType(context, loc_id);
  733. }
  734. return TypeExpr::None;
  735. }
  736. // Determines whether record_decl is a C++ class that has a custom mapping into
  737. // Carbon, and if so, returns the corresponding Carbon type. Otherwise returns
  738. // None.
  739. static auto LookupCustomRecordType(Context& context,
  740. const clang::CXXRecordDecl* record_decl)
  741. -> TypeExpr {
  742. switch (GetCustomCppTypeMapping(record_decl)) {
  743. case CustomCppTypeMapping::None:
  744. return TypeExpr::None;
  745. case CustomCppTypeMapping::Str:
  746. return MakeStringType(
  747. context,
  748. AddImportIRInst(context.sem_ir(), record_decl->getLocation()));
  749. }
  750. }
  751. // Maps a C++ tag type (class, struct, union, enum) to a Carbon type.
  752. static auto MapTagType(Context& context, const clang::TagType& type)
  753. -> TypeExpr {
  754. auto* tag_decl = type.getDecl();
  755. CARBON_CHECK(tag_decl);
  756. // Check if the declaration is already mapped.
  757. auto key = SemIR::ClangDeclKey(tag_decl);
  758. SemIR::InstId tag_inst_id = LookupClangDeclInstId(context, key);
  759. if (!tag_inst_id.has_value()) {
  760. if (auto* record_decl = dyn_cast<clang::CXXRecordDecl>(tag_decl)) {
  761. auto custom_type = LookupCustomRecordType(context, record_decl);
  762. if (custom_type.inst_id.has_value()) {
  763. context.clang_decls().Add({.key = key, .inst_id = custom_type.inst_id});
  764. return custom_type;
  765. }
  766. }
  767. tag_inst_id = ImportTagDecl(context, tag_decl);
  768. }
  769. SemIR::TypeInstId record_type_inst_id =
  770. context.types().GetAsTypeInstId(tag_inst_id);
  771. return {
  772. // TODO: inst_id's location should be the location of the usage, not
  773. // the location of the type definition. Possibly we should synthesize a
  774. // NameRef inst, to match how this would work in Carbon code.
  775. .inst_id = record_type_inst_id,
  776. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  777. }
  778. // Maps a C++ type that is not a wrapper type such as a pointer to a Carbon
  779. // type.
  780. // TODO: Support more types.
  781. static auto MapNonWrapperType(Context& context, SemIR::LocId loc_id,
  782. clang::QualType type) -> TypeExpr {
  783. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  784. return MapBuiltinType(context, loc_id, type, *builtin_type);
  785. }
  786. if (const auto* tag_type = type->getAs<clang::TagType>()) {
  787. return MapTagType(context, *tag_type);
  788. }
  789. CARBON_CHECK(!type.hasQualifiers() && !type->isPointerType(),
  790. "Should not see wrapper types here");
  791. return TypeExpr::None;
  792. }
  793. // Maps a qualified C++ type to a Carbon type.
  794. static auto MapQualifiedType(Context& context, clang::QualType type,
  795. TypeExpr type_expr) -> TypeExpr {
  796. auto quals = type.getQualifiers();
  797. if (quals.hasConst()) {
  798. auto type_id = GetConstType(context, type_expr.inst_id);
  799. type_expr = TypeExpr::ForUnsugared(context, type_id);
  800. quals.removeConst();
  801. }
  802. // TODO: Support other qualifiers.
  803. if (!quals.empty()) {
  804. return TypeExpr::None;
  805. }
  806. return type_expr;
  807. }
  808. // Returns true if the type has the `_Nonnull` attribute.
  809. static auto IsClangTypeNonNull(clang::QualType type) -> bool {
  810. auto nullability = type->getNullability();
  811. return nullability.has_value() &&
  812. *nullability == clang::NullabilityKind::NonNull;
  813. }
  814. // Like `clang::QualType::getUnqualifiedType()`, retrieves the unqualified
  815. // variant of the given type, but preserves `_Nonnull`.
  816. static auto ClangGetUnqualifiedTypePreserveNonNull(
  817. Context& context, clang::QualType original_type) -> clang::QualType {
  818. clang::QualType type = original_type.getUnqualifiedType();
  819. // Preserve non-nullability.
  820. if (IsClangTypeNonNull(original_type) && !IsClangTypeNonNull(type)) {
  821. type = context.ast_context().getAttributedType(
  822. clang::NullabilityKind::NonNull, type, type);
  823. }
  824. return type;
  825. }
  826. // Returns the type `Core.Optional(T)`, where `T` is described by
  827. // `inner_type_inst_id`.
  828. static auto MakeOptionalType(Context& context, SemIR::LocId loc_id,
  829. SemIR::InstId inner_type_inst_id) -> TypeExpr {
  830. auto fn_inst_id = LookupNameInCore(context, loc_id, CoreIdentifier::Optional);
  831. auto call_id = PerformCall(context, loc_id, fn_inst_id, {inner_type_inst_id});
  832. return ExprAsType(context, loc_id, call_id);
  833. }
  834. // Maps a C++ pointer type to a Carbon pointer type.
  835. static auto MapPointerType(Context& context, SemIR::LocId loc_id,
  836. clang::QualType type, TypeExpr pointee_type_expr)
  837. -> TypeExpr {
  838. CARBON_CHECK(type->isPointerType());
  839. bool optional =
  840. !IsClangTypeNonNull(type) &&
  841. // If the type was produced by C++ template substitution, then we assume
  842. // it was deduced from a Carbon pointer type, so it's non-null.
  843. !type->getAs<clang::SubstTemplateTypeParmType>();
  844. TypeExpr pointer_type_expr = TypeExpr::ForUnsugared(
  845. context, GetPointerType(context, pointee_type_expr.inst_id));
  846. if (optional) {
  847. pointer_type_expr =
  848. MakeOptionalType(context, loc_id, pointer_type_expr.inst_id);
  849. }
  850. return pointer_type_expr;
  851. }
  852. // Maps a C++ reference type to a Carbon type. We map all references to
  853. // pointers for now. Note that when mapping function parameters and return
  854. // types, a different rule is used; see MapParameterType for details.
  855. // TODO: Revisit this and decide what we really want to do here.
  856. static auto MapReferenceType(Context& context, clang::QualType type,
  857. TypeExpr referenced_type_expr) -> TypeExpr {
  858. CARBON_CHECK(type->isReferenceType());
  859. SemIR::TypeId pointer_type_id =
  860. GetPointerType(context, referenced_type_expr.inst_id);
  861. pointer_type_id =
  862. GetConstType(context, context.types().GetInstId(pointer_type_id));
  863. return TypeExpr::ForUnsugared(context, pointer_type_id);
  864. }
  865. // Maps a C++ type to a Carbon type. `type` should not be canonicalized because
  866. // we check for pointer nullability and nullability will be lost by
  867. // canonicalization.
  868. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  869. -> TypeExpr {
  870. // Unwrap any type modifiers and wrappers.
  871. llvm::SmallVector<clang::QualType> wrapper_types;
  872. while (true) {
  873. clang::QualType orig_type = type;
  874. if (type.hasQualifiers()) {
  875. type = ClangGetUnqualifiedTypePreserveNonNull(context, type);
  876. } else if (type->isPointerType()) {
  877. type = type->getPointeeType();
  878. } else if (type->isReferenceType()) {
  879. type = type.getNonReferenceType();
  880. } else {
  881. break;
  882. }
  883. wrapper_types.push_back(orig_type);
  884. }
  885. auto mapped = MapNonWrapperType(context, loc_id, type);
  886. for (auto wrapper : llvm::reverse(wrapper_types)) {
  887. if (!mapped.inst_id.has_value() ||
  888. mapped.type_id == SemIR::ErrorInst::TypeId) {
  889. break;
  890. }
  891. if (wrapper.hasQualifiers()) {
  892. mapped = MapQualifiedType(context, wrapper, mapped);
  893. } else if (wrapper->isPointerType()) {
  894. mapped = MapPointerType(context, loc_id, wrapper, mapped);
  895. } else if (wrapper->isReferenceType()) {
  896. mapped = MapReferenceType(context, wrapper, mapped);
  897. } else {
  898. CARBON_FATAL("Unexpected wrapper type {0}", wrapper.getAsString());
  899. }
  900. }
  901. return mapped;
  902. }
  903. namespace {
  904. // Information about how to map a C++ parameter type into Carbon.
  905. struct ParameterTypeInfo {
  906. // The type to use for the Carbon parameter.
  907. TypeExpr type;
  908. // Whether to build a `ref` pattern.
  909. bool want_ref_pattern;
  910. };
  911. } // namespace
  912. // Given the type of a C++ function parameter, returns information about the
  913. // type to use for the corresponding Carbon parameter.
  914. //
  915. // Note that if the parameter has a type for which `IsSimpleAbiType` returns
  916. // true, we must produce a parameter type that has the same calling convention
  917. // as the C++ type.
  918. static auto MapParameterType(Context& context, SemIR::LocId loc_id,
  919. clang::QualType param_type) -> ParameterTypeInfo {
  920. ParameterTypeInfo info = {.type = TypeExpr::None, .want_ref_pattern = false};
  921. // Perform some custom mapping for parameters of reference type:
  922. //
  923. // * `T& x` -> `ref x: T`.
  924. // * `const T& x` -> `x: T`.
  925. // * `T&& x` -> `x: T`.
  926. //
  927. // TODO: For the `&&` mapping, we allow an rvalue reference to bind to a
  928. // durable reference expression. This should not be allowed.
  929. if (param_type->isReferenceType()) {
  930. clang::QualType pointee_type = param_type->getPointeeType();
  931. if (param_type->isLValueReferenceType()) {
  932. if (pointee_type.isConstQualified()) {
  933. // TODO: Consider only doing this if `const` is the only qualifier. For
  934. // now, any other qualifier will fail when mapping the type.
  935. auto split_type = pointee_type.getSplitUnqualifiedType();
  936. split_type.Quals.removeConst();
  937. pointee_type = context.ast_context().getQualifiedType(split_type);
  938. } else {
  939. // The reference will map to a `ref` pattern.
  940. info.want_ref_pattern = true;
  941. }
  942. }
  943. param_type = pointee_type;
  944. }
  945. info.type = MapType(context, loc_id, param_type);
  946. return info;
  947. }
  948. // Returns a block for the implicit parameters of the given function
  949. // declaration. Because function templates are not yet supported, this currently
  950. // only contains the `self` parameter. On error, produces a diagnostic and
  951. // returns None.
  952. static auto MakeImplicitParamPatternsBlockId(
  953. Context& context, SemIR::LocId loc_id,
  954. const clang::FunctionDecl& clang_decl) -> SemIR::InstBlockId {
  955. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(&clang_decl);
  956. if (!method_decl || method_decl->isStatic() ||
  957. isa<clang::CXXConstructorDecl>(clang_decl)) {
  958. return SemIR::InstBlockId::Empty;
  959. }
  960. // Build a `self` parameter from the object parameter.
  961. BeginSubpattern(context);
  962. clang::QualType param_type =
  963. method_decl->getFunctionObjectParameterReferenceType();
  964. auto param_info = MapParameterType(context, loc_id, param_type);
  965. auto [type_inst_id, type_id] = param_info.type;
  966. SemIR::ExprRegionId type_expr_region_id =
  967. EndSubpatternAsExpr(context, type_inst_id);
  968. if (!type_id.has_value()) {
  969. context.TODO(loc_id,
  970. llvm::formatv("Unsupported: object parameter type: {0}",
  971. param_type.getAsString()));
  972. return SemIR::InstBlockId::None;
  973. }
  974. // TODO: Fill in a location once available.
  975. auto pattern_id = AddParamPattern(context, loc_id, SemIR::NameId::SelfValue,
  976. type_expr_region_id, type_id,
  977. param_info.want_ref_pattern);
  978. return context.inst_blocks().Add({pattern_id});
  979. }
  980. // Returns a block id for the explicit parameters of the given function
  981. // declaration. If the function declaration has no parameters, it returns
  982. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  983. // produces an error and returns `SemIR::InstBlockId::None`.
  984. // TODO: Consider refactoring to extract and reuse more logic from
  985. // `HandleAnyBindingPattern()`.
  986. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  987. const clang::FunctionDecl& clang_decl,
  988. int num_params) -> SemIR::InstBlockId {
  989. if (clang_decl.parameters().empty() || num_params == 0) {
  990. return SemIR::InstBlockId::Empty;
  991. }
  992. llvm::SmallVector<SemIR::InstId> params;
  993. params.reserve(num_params);
  994. CARBON_CHECK(
  995. static_cast<int>(clang_decl.getNumNonObjectParams()) >= num_params,
  996. "varargs functions are not supported");
  997. const auto* function_type =
  998. clang_decl.getType()->castAs<clang::FunctionProtoType>();
  999. for (int i : llvm::seq(num_params)) {
  1000. const auto* param = clang_decl.getNonObjectParameter(i);
  1001. clang::QualType orig_param_type = function_type->getParamType(
  1002. clang_decl.hasCXXExplicitFunctionObjectParameter() + i);
  1003. // The parameter type is decayed but hasn't necessarily had its qualifiers
  1004. // removed.
  1005. // TODO: The presence of qualifiers here is probably a Clang bug.
  1006. clang::QualType param_type =
  1007. ClangGetUnqualifiedTypePreserveNonNull(context, orig_param_type);
  1008. // Mark the start of a region of insts, needed for the type expression
  1009. // created later with the call of `EndSubpatternAsExpr()`.
  1010. BeginSubpattern(context);
  1011. auto param_info = MapParameterType(context, loc_id, param_type);
  1012. auto [orig_type_inst_id, type_id] = param_info.type;
  1013. // Type expression of the binding pattern - a single-entry/single-exit
  1014. // region that allows control flow in the type expression e.g. fn F(x: if C
  1015. // then i32 else i64).
  1016. SemIR::ExprRegionId type_expr_region_id =
  1017. EndSubpatternAsExpr(context, orig_type_inst_id);
  1018. if (!type_id.has_value()) {
  1019. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  1020. orig_param_type.getAsString()));
  1021. return SemIR::InstBlockId::None;
  1022. }
  1023. llvm::StringRef param_name = param->getName();
  1024. SemIR::NameId name_id =
  1025. param_name.empty()
  1026. // Translate an unnamed parameter to an underscore to
  1027. // match Carbon's naming of unnamed/unused function params.
  1028. ? SemIR::NameId::Underscore
  1029. : AddIdentifierName(context, param_name);
  1030. SemIR::LocId param_loc_id =
  1031. AddImportIRInst(context.sem_ir(), param->getLocation());
  1032. // TODO: Add template support.
  1033. SemIR::InstId pattern_id =
  1034. AddParamPattern(context, param_loc_id, name_id, type_expr_region_id,
  1035. type_id, param_info.want_ref_pattern);
  1036. params.push_back(pattern_id);
  1037. }
  1038. return context.inst_blocks().Add(params);
  1039. }
  1040. // Returns the return `TypeExpr` of the given function declaration. In case of
  1041. // an unsupported return type, returns `SemIR::ErrorInst::InstId`. Constructors
  1042. // are treated as returning a class instance.
  1043. // TODO: Support more return types.
  1044. static auto GetReturnTypeExpr(Context& context, SemIR::LocId loc_id,
  1045. clang::FunctionDecl* clang_decl) -> TypeExpr {
  1046. clang::QualType orig_ret_type = clang_decl->getReturnType();
  1047. if (!orig_ret_type->isVoidType()) {
  1048. // TODO: We should eventually map reference returns to non-pointer types
  1049. // here. We should return by `ref` for `T&` return types once `ref` return
  1050. // is implemented.
  1051. auto [orig_type_inst_id, type_id] = MapType(context, loc_id, orig_ret_type);
  1052. if (!orig_type_inst_id.has_value()) {
  1053. context.TODO(loc_id, llvm::formatv("Unsupported: return type: {0}",
  1054. orig_ret_type.getAsString()));
  1055. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1056. .type_id = SemIR::ErrorInst::TypeId};
  1057. }
  1058. return {orig_type_inst_id, type_id};
  1059. }
  1060. auto* ctor = dyn_cast<clang::CXXConstructorDecl>(clang_decl);
  1061. if (!ctor) {
  1062. // void.
  1063. return TypeExpr::None;
  1064. }
  1065. // TODO: Make this a `PartialType`.
  1066. SemIR::TypeInstId record_type_inst_id = context.types().GetAsTypeInstId(
  1067. LookupClangDeclInstId(context, SemIR::ClangDeclKey(ctor->getParent())));
  1068. return {
  1069. .inst_id = record_type_inst_id,
  1070. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  1071. }
  1072. // Information about a function's declared return type, corresponding to the
  1073. // fields of SemIR::Function with the same names.
  1074. struct ReturnInfo {
  1075. SemIR::TypeInstId return_type_inst_id;
  1076. SemIR::InstBlockId return_patterns_id;
  1077. };
  1078. // Returns information about the declared return type of the given function
  1079. // declaration. In case of an unsupported return type, it produces a diagnostic,
  1080. // and the returned return_type_inst_id will be `SemIR::ErrorInst::InstId`.
  1081. // Constructors are treated as returning a class instance.
  1082. static auto GetReturnInfo(Context& context, SemIR::LocId loc_id,
  1083. clang::FunctionDecl* clang_decl) -> ReturnInfo {
  1084. auto [type_inst_id, type_id] = GetReturnTypeExpr(context, loc_id, clang_decl);
  1085. if (!type_inst_id.has_value()) {
  1086. // void.
  1087. return {.return_type_inst_id = type_inst_id,
  1088. .return_patterns_id = SemIR::InstBlockId::None};
  1089. }
  1090. if (type_inst_id == SemIR::ErrorInst::TypeInstId) {
  1091. return {.return_type_inst_id = type_inst_id,
  1092. .return_patterns_id = SemIR::InstBlockId::None};
  1093. }
  1094. auto pattern_type_id = GetPatternType(context, type_id);
  1095. clang::SourceLocation return_type_loc =
  1096. clang_decl->getReturnTypeSourceRange().getBegin();
  1097. if (return_type_loc.isInvalid()) {
  1098. // TODO: While `getReturnTypeSourceRange()` should work, it seems broken for
  1099. // trailing return type. See
  1100. // https://github.com/llvm/llvm-project/issues/162649. Until this is fixed,
  1101. // we fallback to `getTypeSpecStartLoc()`.
  1102. return_type_loc = clang_decl->getTypeSpecStartLoc();
  1103. }
  1104. SemIR::ImportIRInstId return_type_import_ir_inst_id =
  1105. AddImportIRInst(context.sem_ir(), return_type_loc);
  1106. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  1107. context, MakeImportedLocIdAndInst(
  1108. context, return_type_import_ir_inst_id,
  1109. SemIR::ReturnSlotPattern({.type_id = pattern_type_id,
  1110. .type_inst_id = type_inst_id})));
  1111. SemIR::InstId param_pattern_id = AddPatternInst(
  1112. context,
  1113. MakeImportedLocIdAndInst(
  1114. context, return_type_import_ir_inst_id,
  1115. SemIR::OutParamPattern({.type_id = pattern_type_id,
  1116. .subpattern_id = return_slot_pattern_id,
  1117. .index = SemIR::CallParamIndex::None})));
  1118. auto return_patterns_id = context.inst_blocks().Add({param_pattern_id});
  1119. return {.return_type_inst_id = type_inst_id,
  1120. .return_patterns_id = return_patterns_id};
  1121. }
  1122. namespace {
  1123. // Represents the insts and inst blocks associated with the parameters and
  1124. // returns of a function declaration, corresponding to the fields of
  1125. // SemIR::Function with the same names.
  1126. struct FunctionSignatureInsts {
  1127. SemIR::InstBlockId implicit_param_patterns_id;
  1128. SemIR::InstBlockId param_patterns_id;
  1129. SemIR::TypeInstId return_type_inst_id;
  1130. SemIR::InstBlockId return_patterns_id;
  1131. SemIR::InstBlockId call_params_id;
  1132. };
  1133. } // namespace
  1134. // Creates the insts and inst blocks that represent the parameters and returns
  1135. // of the given C++ function's Carbon counterpart, including emitting a callee
  1136. // pattern match to create the `Call` parameters, and returns a
  1137. // FunctionSignatureInsts containing the results. Produces a diagnostic and
  1138. // returns `std::nullopt` if the function declaration has an unsupported
  1139. // parameter type.
  1140. static auto CreateFunctionSignatureInsts(Context& context, SemIR::LocId loc_id,
  1141. clang::FunctionDecl* clang_decl,
  1142. int num_params)
  1143. -> std::optional<FunctionSignatureInsts> {
  1144. auto implicit_param_patterns_id =
  1145. MakeImplicitParamPatternsBlockId(context, loc_id, *clang_decl);
  1146. if (!implicit_param_patterns_id.has_value()) {
  1147. return std::nullopt;
  1148. }
  1149. auto param_patterns_id =
  1150. MakeParamPatternsBlockId(context, loc_id, *clang_decl, num_params);
  1151. if (!param_patterns_id.has_value()) {
  1152. return std::nullopt;
  1153. }
  1154. auto [return_type_inst_id, return_patterns_id] =
  1155. GetReturnInfo(context, loc_id, clang_decl);
  1156. if (return_type_inst_id == SemIR::ErrorInst::TypeInstId) {
  1157. return std::nullopt;
  1158. }
  1159. auto call_params_id =
  1160. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  1161. return_patterns_id);
  1162. return {{.implicit_param_patterns_id = implicit_param_patterns_id,
  1163. .param_patterns_id = param_patterns_id,
  1164. .return_type_inst_id = return_type_inst_id,
  1165. .return_patterns_id = return_patterns_id,
  1166. .call_params_id = call_params_id}};
  1167. }
  1168. // Returns the Carbon function name for the given function.
  1169. static auto GetFunctionName(Context& context, clang::FunctionDecl* clang_decl)
  1170. -> SemIR::NameId {
  1171. switch (clang_decl->getDeclName().getNameKind()) {
  1172. case clang::DeclarationName::CXXConstructorName: {
  1173. auto key = SemIR::ClangDeclKey(
  1174. cast<clang::CXXConstructorDecl>(clang_decl)->getParent());
  1175. return context.classes()
  1176. .Get(context.insts()
  1177. .GetAs<SemIR::ClassDecl>(LookupClangDeclInstId(context, key))
  1178. .class_id)
  1179. .name_id;
  1180. }
  1181. case clang::DeclarationName::CXXDestructorName: {
  1182. return SemIR::NameId::CppDestructor;
  1183. }
  1184. case clang::DeclarationName::CXXOperatorName: {
  1185. return SemIR::NameId::CppOperator;
  1186. }
  1187. default: {
  1188. return AddIdentifierName(context, clang_decl->getName());
  1189. }
  1190. }
  1191. }
  1192. // Creates a `FunctionDecl` and a `Function` without C++ thunk information.
  1193. // Returns std::nullopt on failure. The given Clang declaration is assumed to:
  1194. // * Have not been imported before.
  1195. // * Be of supported type (ignoring parameters).
  1196. static auto ImportFunction(Context& context, SemIR::LocId loc_id,
  1197. clang::FunctionDecl* clang_decl, int num_params)
  1198. -> std::optional<SemIR::FunctionId> {
  1199. context.scope_stack().PushForDeclName();
  1200. context.inst_block_stack().Push();
  1201. context.pattern_block_stack().Push();
  1202. auto function_params_insts =
  1203. CreateFunctionSignatureInsts(context, loc_id, clang_decl, num_params);
  1204. auto pattern_block_id = context.pattern_block_stack().Pop();
  1205. auto decl_block_id = context.inst_block_stack().Pop();
  1206. context.scope_stack().Pop();
  1207. if (!function_params_insts.has_value()) {
  1208. return std::nullopt;
  1209. }
  1210. auto function_decl = SemIR::FunctionDecl{
  1211. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  1212. auto decl_id = AddPlaceholderImportedInstInNoBlock(
  1213. context, SemIR::LocIdAndInst::NoLoc(function_decl));
  1214. auto virtual_modifier = SemIR::Function::VirtualModifier::None;
  1215. int32_t virtual_index = -1;
  1216. if (auto* method_decl = dyn_cast<clang::CXXMethodDecl>(clang_decl)) {
  1217. if (method_decl->size_overridden_methods()) {
  1218. virtual_modifier = SemIR::Function::VirtualModifier::Override;
  1219. } else if (method_decl->isVirtual()) {
  1220. virtual_modifier = SemIR::Function::VirtualModifier::Virtual;
  1221. }
  1222. if (virtual_modifier != SemIR::Function::VirtualModifier::None) {
  1223. // TODO: Add support for Microsoft/non-Itanium vtables.
  1224. virtual_index = dyn_cast<clang::ItaniumVTableContext>(
  1225. context.ast_context().getVTableContext())
  1226. ->getMethodVTableIndex(method_decl);
  1227. }
  1228. }
  1229. auto function_info = SemIR::Function{
  1230. {.name_id = GetFunctionName(context, clang_decl),
  1231. .parent_scope_id = GetParentNameScopeId(context, clang_decl),
  1232. .generic_id = SemIR::GenericId::None,
  1233. .first_param_node_id = Parse::NodeId::None,
  1234. .last_param_node_id = Parse::NodeId::None,
  1235. .pattern_block_id = pattern_block_id,
  1236. .implicit_param_patterns_id =
  1237. function_params_insts->implicit_param_patterns_id,
  1238. .param_patterns_id = function_params_insts->param_patterns_id,
  1239. .is_extern = false,
  1240. .extern_library_id = SemIR::LibraryNameId::None,
  1241. .non_owning_decl_id = SemIR::InstId::None,
  1242. .first_owning_decl_id = decl_id,
  1243. .definition_id = SemIR::InstId::None},
  1244. {.call_params_id = function_params_insts->call_params_id,
  1245. .return_type_inst_id = function_params_insts->return_type_inst_id,
  1246. .return_patterns_id = function_params_insts->return_patterns_id,
  1247. .virtual_modifier = virtual_modifier,
  1248. .virtual_index = virtual_index,
  1249. .self_param_id = FindSelfPattern(
  1250. context, function_params_insts->implicit_param_patterns_id),
  1251. .clang_decl_id = context.clang_decls().Add(
  1252. {.key = SemIR::ClangDeclKey::ForFunctionDecl(clang_decl, num_params),
  1253. .inst_id = decl_id})}};
  1254. function_decl.function_id = context.functions().Add(function_info);
  1255. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  1256. SemIR::SpecificId::None);
  1257. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  1258. return function_decl.function_id;
  1259. }
  1260. // Imports a C++ function, returning a corresponding Carbon function.
  1261. // `num_params` specifies how many parameters the corresponding Carbon function
  1262. // should have, which may be fewer than the number of parameters that the C++
  1263. // function has if default arguments are available for the trailing parameters.
  1264. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  1265. clang::FunctionDecl* clang_decl, int num_params)
  1266. -> SemIR::InstId {
  1267. auto key = SemIR::ClangDeclKey::ForFunctionDecl(clang_decl, num_params);
  1268. // Check if the declaration is already mapped.
  1269. if (SemIR::InstId existing_inst_id = LookupClangDeclInstId(context, key);
  1270. existing_inst_id.has_value()) {
  1271. return existing_inst_id;
  1272. }
  1273. if (clang_decl->isVariadic()) {
  1274. context.TODO(loc_id, "Unsupported: Variadic function");
  1275. MarkFailedDecl(context, key);
  1276. return SemIR::ErrorInst::InstId;
  1277. }
  1278. if (clang_decl->getTemplatedKind() ==
  1279. clang::FunctionDecl::TK_FunctionTemplate) {
  1280. context.TODO(loc_id, "Unsupported: Template function");
  1281. MarkFailedDecl(context, key);
  1282. return SemIR::ErrorInst::InstId;
  1283. }
  1284. CARBON_CHECK(clang_decl->getFunctionType()->isFunctionProtoType(),
  1285. "Not Prototype function (non-C++ code)");
  1286. auto function_id = ImportFunction(context, loc_id, clang_decl, num_params);
  1287. if (!function_id) {
  1288. MarkFailedDecl(context, key);
  1289. return SemIR::ErrorInst::InstId;
  1290. }
  1291. SemIR::Function& function_info = context.functions().Get(*function_id);
  1292. if (IsCppThunkRequired(context, function_info)) {
  1293. Diagnostics::AnnotationScope annotate_diagnostics(
  1294. &context.emitter(), [&](auto& builder) {
  1295. CARBON_DIAGNOSTIC(InCppThunk, Note,
  1296. "in thunk for C++ function used here");
  1297. builder.Note(loc_id, InCppThunk);
  1298. });
  1299. if (clang::FunctionDecl* thunk_clang_decl =
  1300. BuildCppThunk(context, function_info)) {
  1301. if (auto thunk_function_id =
  1302. ImportFunction(context, loc_id, thunk_clang_decl,
  1303. thunk_clang_decl->getNumParams())) {
  1304. SemIR::InstId thunk_function_decl_id =
  1305. context.functions().Get(*thunk_function_id).first_owning_decl_id;
  1306. function_info.SetHasCppThunk(thunk_function_decl_id);
  1307. }
  1308. }
  1309. } else {
  1310. // Inform Clang that the function has been referenced. This will trigger
  1311. // instantiation if needed.
  1312. context.clang_sema().MarkFunctionReferenced(GetCppLocation(context, loc_id),
  1313. clang_decl);
  1314. }
  1315. return function_info.first_owning_decl_id;
  1316. }
  1317. namespace {
  1318. // An item to be imported in an import worklist.
  1319. // TODO: If worklists ever become particularly large, consider changing this
  1320. // to use a `PointerIntPair`.
  1321. struct ImportItem {
  1322. // A declaration that we want to import.
  1323. SemIR::ClangDeclKey decl_key;
  1324. // Whether we have added `decl`'s dependencies to the worklist.
  1325. bool added_dependencies;
  1326. };
  1327. // A worklist of declarations to import.
  1328. using ImportWorklist = llvm::SmallVector<ImportItem>;
  1329. } // namespace
  1330. // Adds the given declaration to our list of declarations to import.
  1331. static auto AddDependentDecl(Context& context, SemIR::ClangDeclKey decl,
  1332. ImportWorklist& worklist) -> void {
  1333. if (!IsClangDeclImported(context, decl)) {
  1334. worklist.push_back({.decl_key = decl, .added_dependencies = false});
  1335. }
  1336. }
  1337. // Finds all decls that need to be imported before importing the given type and
  1338. // adds them to the given set.
  1339. static auto AddDependentUnimportedTypeDecls(Context& context,
  1340. clang::QualType type,
  1341. ImportWorklist& worklist) -> void {
  1342. while (true) {
  1343. if (type->isPointerType() || type->isReferenceType()) {
  1344. type = type->getPointeeType();
  1345. } else if (const clang::ArrayType* array_type =
  1346. type->getAsArrayTypeUnsafe()) {
  1347. type = array_type->getElementType();
  1348. } else {
  1349. break;
  1350. }
  1351. }
  1352. if (const auto* tag_type = type->getAs<clang::TagType>()) {
  1353. AddDependentDecl(context, SemIR::ClangDeclKey(tag_type->getDecl()),
  1354. worklist);
  1355. }
  1356. }
  1357. // Finds all decls that need to be imported before importing the given function
  1358. // and adds them to the given set.
  1359. static auto AddDependentUnimportedFunctionDecls(
  1360. Context& context, const clang::FunctionDecl& clang_decl, int num_params,
  1361. ImportWorklist& worklist) -> void {
  1362. const auto* function_type =
  1363. clang_decl.getType()->castAs<clang::FunctionProtoType>();
  1364. for (int i : llvm::seq(clang_decl.hasCXXExplicitFunctionObjectParameter() +
  1365. num_params)) {
  1366. AddDependentUnimportedTypeDecls(context, function_type->getParamType(i),
  1367. worklist);
  1368. }
  1369. AddDependentUnimportedTypeDecls(context, clang_decl.getReturnType(),
  1370. worklist);
  1371. }
  1372. // Finds all decls that need to be imported before importing the given
  1373. // declaration and adds them to the given set.
  1374. static auto AddDependentUnimportedDecls(Context& context,
  1375. SemIR::ClangDeclKey key,
  1376. ImportWorklist& worklist) -> void {
  1377. clang::Decl* clang_decl = key.decl;
  1378. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1379. AddDependentUnimportedFunctionDecls(context, *clang_function_decl,
  1380. key.num_params, worklist);
  1381. } else if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1382. if (!isa<clang::TagDecl>(clang_decl)) {
  1383. AddDependentUnimportedTypeDecls(
  1384. context, type_decl->getASTContext().getTypeDeclType(type_decl),
  1385. worklist);
  1386. }
  1387. }
  1388. auto* parent = GetParentDecl(clang_decl);
  1389. if (llvm::isa_and_nonnull<clang::TagDecl, clang::NamespaceDecl,
  1390. clang::TranslationUnitDecl>(parent)) {
  1391. AddDependentDecl(context, SemIR::ClangDeclKey::ForNonFunctionDecl(parent),
  1392. worklist);
  1393. }
  1394. }
  1395. static auto ImportVarDecl(Context& context, SemIR::LocId loc_id,
  1396. clang::VarDecl* var_decl) -> SemIR::InstId {
  1397. if (SemIR::InstId existing_inst_id =
  1398. LookupClangDeclInstId(context, SemIR::ClangDeclKey(var_decl));
  1399. existing_inst_id.has_value()) {
  1400. return existing_inst_id;
  1401. }
  1402. // Extract type and name.
  1403. clang::QualType var_type = var_decl->getType();
  1404. SemIR::TypeId var_type_id = MapType(context, loc_id, var_type).type_id;
  1405. if (!var_type_id.has_value()) {
  1406. context.TODO(loc_id, llvm::formatv("Unsupported: var type: {0}",
  1407. var_type.getAsString()));
  1408. return SemIR::ErrorInst::InstId;
  1409. }
  1410. SemIR::NameId var_name_id = AddIdentifierName(context, var_decl->getName());
  1411. SemIR::VarStorage var_storage{.type_id = var_type_id,
  1412. .pattern_id = SemIR::InstId::None};
  1413. // We can't use the convenience for `AddPlaceholderInstInNoBlock()` with typed
  1414. // nodes because it doesn't support insts with cleanup.
  1415. SemIR::InstId var_storage_inst_id =
  1416. AddPlaceholderImportedInstInNoBlock(context, {loc_id, var_storage});
  1417. auto clang_decl_id = context.clang_decls().Add(
  1418. {.key = SemIR::ClangDeclKey(var_decl), .inst_id = var_storage_inst_id});
  1419. // Entity name referring to a Clang decl for mangling.
  1420. SemIR::EntityNameId entity_name_id =
  1421. context.entity_names().AddSymbolicBindingName(
  1422. var_name_id, GetParentNameScopeId(context, var_decl),
  1423. SemIR::CompileTimeBindIndex::None, false);
  1424. context.cpp_global_names().Add({.key = {.entity_name_id = entity_name_id},
  1425. .clang_decl_id = clang_decl_id});
  1426. // Create `RefBindingPattern` and `VarPattern` in a `NameBindingDecl`.
  1427. context.pattern_block_stack().Push();
  1428. SemIR::TypeId pattern_type_id = GetPatternType(context, var_type_id);
  1429. SemIR::InstId binding_pattern_inst_id =
  1430. AddPatternInst<SemIR::RefBindingPattern>(
  1431. context, loc_id,
  1432. {.type_id = pattern_type_id, .entity_name_id = entity_name_id});
  1433. var_storage.pattern_id = AddPatternInst<SemIR::VarPattern>(
  1434. context, Parse::VariablePatternId::None,
  1435. {.type_id = pattern_type_id, .subpattern_id = binding_pattern_inst_id});
  1436. context.imports().push_back(AddInstInNoBlock<SemIR::NameBindingDecl>(
  1437. context, loc_id,
  1438. {.pattern_block_id = context.pattern_block_stack().Pop()}));
  1439. // Finalize the `VarStorage` instruction.
  1440. ReplaceInstBeforeConstantUse(context, var_storage_inst_id, var_storage);
  1441. return var_storage_inst_id;
  1442. }
  1443. // Imports a declaration from Clang to Carbon. Returns the instruction for the
  1444. // new Carbon declaration, which will be an ErrorInst on failure. Assumes all
  1445. // dependencies have already been imported.
  1446. static auto ImportDeclAfterDependencies(Context& context, SemIR::LocId loc_id,
  1447. SemIR::ClangDeclKey key)
  1448. -> SemIR::InstId {
  1449. clang::Decl* clang_decl = key.decl;
  1450. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1451. return ImportFunctionDecl(context, loc_id, clang_function_decl,
  1452. key.num_params);
  1453. }
  1454. if (auto* clang_namespace_decl = dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  1455. return ImportNamespaceDecl(context, clang_namespace_decl);
  1456. }
  1457. if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1458. auto type = clang_decl->getASTContext().getTypeDeclType(type_decl);
  1459. auto type_inst_id = MapType(context, loc_id, type).inst_id;
  1460. if (!type_inst_id.has_value()) {
  1461. context.TODO(AddImportIRInst(context.sem_ir(), type_decl->getLocation()),
  1462. llvm::formatv("Unsupported: Type declaration: {0}",
  1463. type.getAsString()));
  1464. return SemIR::ErrorInst::InstId;
  1465. }
  1466. context.clang_decls().Add({.key = key, .inst_id = type_inst_id});
  1467. return type_inst_id;
  1468. }
  1469. if (isa<clang::FieldDecl, clang::IndirectFieldDecl>(clang_decl)) {
  1470. // Usable fields get imported as a side effect of importing the class.
  1471. if (SemIR::InstId existing_inst_id = LookupClangDeclInstId(context, key);
  1472. existing_inst_id.has_value()) {
  1473. return existing_inst_id;
  1474. }
  1475. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1476. "Unsupported: field declaration has unhandled type or kind");
  1477. return SemIR::ErrorInst::InstId;
  1478. }
  1479. if (auto* enum_const_decl = dyn_cast<clang::EnumConstantDecl>(clang_decl)) {
  1480. return ImportEnumConstantDecl(context, enum_const_decl);
  1481. }
  1482. if (auto* var_decl = dyn_cast<clang::VarDecl>(clang_decl)) {
  1483. return ImportVarDecl(context, loc_id, var_decl);
  1484. }
  1485. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1486. llvm::formatv("Unsupported: Declaration type {0}",
  1487. clang_decl->getDeclKindName()));
  1488. return SemIR::ErrorInst::InstId;
  1489. }
  1490. // Attempts to import a set of declarations. Returns `false` if an error was
  1491. // produced, `true` otherwise.
  1492. static auto ImportDeclSet(Context& context, SemIR::LocId loc_id,
  1493. ImportWorklist& worklist) -> bool {
  1494. // Walk the dependency graph in depth-first order, and import declarations
  1495. // once we've imported all of their dependencies.
  1496. while (!worklist.empty()) {
  1497. auto& item = worklist.back();
  1498. if (!item.added_dependencies) {
  1499. // Skip items we've already imported. We checked this when initially
  1500. // adding the item to the worklist, but it might have been added to the
  1501. // worklist twice before the first time we visited it. For example, this
  1502. // happens for `fn F(a: Cpp.T, b: Cpp.T)`.
  1503. if (IsClangDeclImported(context, item.decl_key)) {
  1504. worklist.pop_back();
  1505. continue;
  1506. }
  1507. // First time visiting this declaration (preorder): add its dependencies
  1508. // to the work list.
  1509. item.added_dependencies = true;
  1510. AddDependentUnimportedDecls(context, item.decl_key, worklist);
  1511. } else {
  1512. // Second time visiting this declaration (postorder): its dependencies are
  1513. // already imported, so we can import it now.
  1514. auto decl_key = worklist.pop_back_val().decl_key;
  1515. auto inst_id = ImportDeclAfterDependencies(context, loc_id, decl_key);
  1516. CARBON_CHECK(inst_id.has_value());
  1517. if (inst_id == SemIR::ErrorInst::InstId) {
  1518. return false;
  1519. }
  1520. CARBON_CHECK(IsClangDeclImported(context, decl_key));
  1521. }
  1522. }
  1523. return true;
  1524. }
  1525. // Imports a declaration from Clang to Carbon. If successful, returns the
  1526. // instruction for the new Carbon declaration. All unimported dependencies are
  1527. // imported first.
  1528. static auto ImportDeclAndDependencies(Context& context, SemIR::LocId loc_id,
  1529. SemIR::ClangDeclKey key)
  1530. -> SemIR::InstId {
  1531. // Collect dependencies by walking the dependency graph in depth-first order.
  1532. ImportWorklist worklist;
  1533. AddDependentDecl(context, key, worklist);
  1534. if (!ImportDeclSet(context, loc_id, worklist)) {
  1535. return SemIR::ErrorInst::InstId;
  1536. }
  1537. return LookupClangDeclInstId(context, key);
  1538. }
  1539. // Imports a type from Clang to Carbon. If successful, returns the imported
  1540. // TypeId. All unimported dependencies are imported first.
  1541. static auto ImportTypeAndDependencies(Context& context, SemIR::LocId loc_id,
  1542. clang::QualType type) -> TypeExpr {
  1543. // Collect dependencies by walking the dependency graph in depth-first order.
  1544. ImportWorklist worklist;
  1545. AddDependentUnimportedTypeDecls(context, type, worklist);
  1546. if (!ImportDeclSet(context, loc_id, worklist)) {
  1547. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1548. .type_id = SemIR::ErrorInst::TypeId};
  1549. }
  1550. return MapType(context, loc_id, type);
  1551. }
  1552. auto ImportCppFunctionDecl(Context& context, SemIR::LocId loc_id,
  1553. clang::FunctionDecl* clang_decl, int num_params)
  1554. -> SemIR::InstId {
  1555. return ImportDeclAndDependencies(
  1556. context, loc_id,
  1557. SemIR::ClangDeclKey::ForFunctionDecl(clang_decl, num_params));
  1558. }
  1559. // Imports a Clang declaration into Carbon and adds that name into the
  1560. // `NameScope`.
  1561. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  1562. SemIR::NameScopeId scope_id,
  1563. SemIR::NameId name_id,
  1564. SemIR::ClangDeclKey key,
  1565. SemIR::AccessKind access_kind)
  1566. -> SemIR::ScopeLookupResult {
  1567. SemIR::InstId inst_id = ImportDeclAndDependencies(context, loc_id, key);
  1568. if (!inst_id.has_value()) {
  1569. return SemIR::ScopeLookupResult::MakeNotFound();
  1570. }
  1571. AddNameToScope(context, scope_id, name_id, access_kind, inst_id);
  1572. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  1573. access_kind);
  1574. }
  1575. // Returns true if the scope is the top `Cpp` scope.
  1576. static auto IsTopCppScope(Context& context, SemIR::NameScopeId scope_id)
  1577. -> bool {
  1578. const SemIR::NameScope& name_scope = context.name_scopes().Get(scope_id);
  1579. CARBON_CHECK(name_scope.is_cpp_scope());
  1580. return name_scope.parent_scope_id() == SemIR::NameScopeId::Package;
  1581. }
  1582. // For a builtin name like `Cpp.long`, returns the associated type.
  1583. static auto LookupBuiltinName(Context& context, SemIR::LocId loc_id,
  1584. SemIR::NameScopeId scope_id,
  1585. SemIR::NameId name_id) -> SemIR::InstId {
  1586. if (!IsTopCppScope(context, scope_id)) {
  1587. return SemIR::InstId::None;
  1588. }
  1589. auto name = context.names().GetAsStringIfIdentifier(name_id);
  1590. if (!name) {
  1591. return SemIR::InstId::None;
  1592. }
  1593. const clang::ASTContext& ast_context = context.ast_context();
  1594. // List of types based on
  1595. // https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p5448.md#details
  1596. auto builtin_type =
  1597. llvm::StringSwitch<clang::QualType>(*name)
  1598. .Case("signed_char", ast_context.SignedCharTy)
  1599. .Case("short", ast_context.ShortTy)
  1600. .Case("int", ast_context.IntTy)
  1601. .Case("long", ast_context.LongTy)
  1602. .Case("long_long", ast_context.LongLongTy)
  1603. .Case("unsigned_char", ast_context.UnsignedCharTy)
  1604. .Case("unsigned_short", ast_context.UnsignedShortTy)
  1605. .Case("unsigned_int", ast_context.UnsignedIntTy)
  1606. .Case("unsigned_long", ast_context.UnsignedLongTy)
  1607. .Case("unsigned_long_long", ast_context.UnsignedLongLongTy)
  1608. .Case("float", ast_context.FloatTy)
  1609. .Case("double", ast_context.DoubleTy)
  1610. .Case("long_double", ast_context.LongDoubleTy)
  1611. .Case("void", ast_context.VoidTy)
  1612. .Default(clang::QualType());
  1613. if (builtin_type.isNull()) {
  1614. if (*name == "nullptr") {
  1615. // Map `Cpp.nullptr` to an uninitialized value of type `Core.CppNullptrT`.
  1616. auto type_id = MapNullptrType(context, loc_id).type_id;
  1617. return GetOrAddInst<SemIR::UninitializedValue>(
  1618. context, SemIR::LocId::None, {.type_id = type_id});
  1619. }
  1620. return SemIR::InstId::None;
  1621. }
  1622. SemIR::InstId inst_id =
  1623. MapNonWrapperType(context, loc_id, builtin_type).inst_id;
  1624. if (!inst_id.has_value()) {
  1625. context.TODO(loc_id, llvm::formatv("Unsupported: builtin type: {0}",
  1626. builtin_type.getAsString()));
  1627. return SemIR::ErrorInst::InstId;
  1628. }
  1629. return inst_id;
  1630. }
  1631. auto ImportCppOverloadSet(
  1632. Context& context, SemIR::LocId loc_id, SemIR::NameScopeId scope_id,
  1633. SemIR::NameId name_id, clang::CXXRecordDecl* naming_class,
  1634. clang::UnresolvedSet<4>&& overload_set,
  1635. clang::OverloadCandidateSet::OperatorRewriteInfo operator_rewrite_info)
  1636. -> SemIR::InstId {
  1637. SemIR::CppOverloadSetId overload_set_id = context.cpp_overload_sets().Add(
  1638. SemIR::CppOverloadSet{.name_id = name_id,
  1639. .parent_scope_id = scope_id,
  1640. .naming_class = naming_class,
  1641. .candidate_functions = std::move(overload_set),
  1642. .operator_rewrite_info = operator_rewrite_info});
  1643. auto overload_set_inst_id = AddInstInNoBlock<SemIR::CppOverloadSetValue>(
  1644. context, loc_id,
  1645. {.type_id = GetCppOverloadSetType(context, overload_set_id,
  1646. SemIR::SpecificId::None),
  1647. .overload_set_id = overload_set_id});
  1648. context.imports().push_back(overload_set_inst_id);
  1649. return overload_set_inst_id;
  1650. }
  1651. // Gets the best access for an overloaded function set. This is the access that
  1652. // we use for the overload set as a whole. More fine-grained checking is done
  1653. // after overload resolution.
  1654. static auto GetOverloadSetAccess(const clang::UnresolvedSet<4>& overload_set)
  1655. -> SemIR::AccessKind {
  1656. SemIR::AccessKind access_kind = SemIR::AccessKind::Private;
  1657. for (clang::DeclAccessPair overload : overload_set.pairs()) {
  1658. access_kind = std::min(access_kind, MapCppAccess(overload));
  1659. if (access_kind == SemIR::AccessKind::Public) {
  1660. break;
  1661. }
  1662. }
  1663. return access_kind;
  1664. }
  1665. // Imports an overload set from Clang to Carbon and adds the name into the
  1666. // `NameScope`.
  1667. static auto ImportOverloadSetIntoScope(Context& context, SemIR::LocId loc_id,
  1668. SemIR::NameScopeId scope_id,
  1669. SemIR::NameId name_id,
  1670. clang::CXXRecordDecl* naming_class,
  1671. clang::UnresolvedSet<4>&& overload_set)
  1672. -> SemIR::ScopeLookupResult {
  1673. SemIR::AccessKind access_kind = GetOverloadSetAccess(overload_set);
  1674. SemIR::InstId inst_id = ImportCppOverloadSet(
  1675. context, loc_id, scope_id, name_id, naming_class, std::move(overload_set),
  1676. /*operator_rewrite_info=*/{});
  1677. AddNameToScope(context, scope_id, name_id, access_kind, inst_id);
  1678. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  1679. access_kind);
  1680. }
  1681. // Imports the constructors for a given class name. The found constructors are
  1682. // imported as part of an overload set into the scope. Currently copy/move
  1683. // constructors are not imported.
  1684. static auto ImportConstructorsIntoScope(Context& context, SemIR::LocId loc_id,
  1685. SemIR::NameScopeId scope_id,
  1686. SemIR::NameId name_id)
  1687. -> SemIR::ScopeLookupResult {
  1688. auto* naming_class =
  1689. cast<clang::CXXRecordDecl>(GetDeclContext(context, scope_id));
  1690. clang::DeclContextLookupResult constructors_lookup =
  1691. context.clang_sema().LookupConstructors(naming_class);
  1692. clang::UnresolvedSet<4> overload_set;
  1693. for (auto* decl : constructors_lookup) {
  1694. auto info = clang::getConstructorInfo(decl);
  1695. if (!info.Constructor || info.Constructor->isCopyOrMoveConstructor()) {
  1696. continue;
  1697. }
  1698. overload_set.addDecl(info.FoundDecl, info.FoundDecl.getAccess());
  1699. }
  1700. if (overload_set.empty()) {
  1701. return SemIR::ScopeLookupResult::MakeNotFound();
  1702. }
  1703. return ImportOverloadSetIntoScope(context, loc_id, scope_id, name_id,
  1704. naming_class, std::move(overload_set));
  1705. }
  1706. // Attempts to import a builtin name from Clang to Carbon and adds the name into
  1707. // the scope.
  1708. static auto ImportBuiltinNameIntoScope(Context& context, SemIR::LocId loc_id,
  1709. SemIR::NameScopeId scope_id,
  1710. SemIR::NameId name_id)
  1711. -> SemIR::ScopeLookupResult {
  1712. SemIR::InstId builtin_inst_id =
  1713. LookupBuiltinName(context, loc_id, scope_id, name_id);
  1714. if (builtin_inst_id.has_value()) {
  1715. AddNameToScope(context, scope_id, name_id, SemIR::AccessKind::Public,
  1716. builtin_inst_id);
  1717. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  1718. builtin_inst_id, SemIR::AccessKind::Public);
  1719. }
  1720. return SemIR::ScopeLookupResult::MakeNotFound();
  1721. }
  1722. // Checks if the name scope is a class that is not complete.
  1723. static auto IsIncompleteClass(Context& context, SemIR::NameScopeId scope_id)
  1724. -> bool {
  1725. auto class_decl = context.insts().TryGetAs<SemIR::ClassDecl>(
  1726. context.name_scopes().Get(scope_id).inst_id());
  1727. return class_decl.has_value() &&
  1728. !context.types().IsComplete(
  1729. context.classes().Get(class_decl->class_id).self_type_id);
  1730. }
  1731. // Maps a Clang literal expression to a Carbon constant.
  1732. // TODO: Add support for all constant types for which a C++ to Carbon type
  1733. // mapping exists.
  1734. static auto MapConstant(Context& context, SemIR::LocId loc_id,
  1735. clang::Expr* expr) -> SemIR::InstId {
  1736. CARBON_CHECK(expr, "empty expression");
  1737. if (auto* string_literal = dyn_cast<clang::StringLiteral>(expr)) {
  1738. if (!string_literal->isOrdinary() && !string_literal->isUTF8()) {
  1739. context.TODO(loc_id,
  1740. llvm::formatv("Unsupported: string literal type: {0}",
  1741. expr->getType()));
  1742. return SemIR::ErrorInst::InstId;
  1743. }
  1744. StringLiteralValueId string_id =
  1745. context.string_literal_values().Add(string_literal->getString());
  1746. auto inst_id =
  1747. MakeStringLiteral(context, Parse::StringLiteralId::None, string_id);
  1748. return inst_id;
  1749. } else if (isa<clang::CXXNullPtrLiteralExpr>(expr)) {
  1750. auto type_id = MapNullptrType(context, loc_id).type_id;
  1751. return GetOrAddInst<SemIR::UninitializedValue>(context, SemIR::LocId::None,
  1752. {.type_id = type_id});
  1753. }
  1754. SemIR::TypeId type_id = MapType(context, loc_id, expr->getType()).type_id;
  1755. if (!type_id.has_value()) {
  1756. context.TODO(loc_id, llvm::formatv("Unsupported: C++ literal's type `{0}` "
  1757. "could not be mapped to a Carbon type",
  1758. expr->getType().getAsString()));
  1759. return SemIR::ErrorInst::InstId;
  1760. }
  1761. SemIR::InstId inst_id = SemIR::InstId::None;
  1762. SemIR::ImportIRInstId imported_loc_id =
  1763. AddImportIRInst(context.sem_ir(), expr->getExprLoc());
  1764. if (auto* integer_literal = dyn_cast<clang::IntegerLiteral>(expr)) {
  1765. IntId int_id =
  1766. context.ints().Add(integer_literal->getValue().getSExtValue());
  1767. inst_id = AddInstInNoBlock(
  1768. context,
  1769. MakeImportedLocIdAndInst<SemIR::IntValue>(
  1770. context, imported_loc_id, {.type_id = type_id, .int_id = int_id}));
  1771. } else if (auto* bool_literal = dyn_cast<clang::CXXBoolLiteralExpr>(expr)) {
  1772. inst_id = AddInstInNoBlock(
  1773. context,
  1774. MakeImportedLocIdAndInst<SemIR::BoolLiteral>(
  1775. context, imported_loc_id,
  1776. {.type_id = type_id,
  1777. .value = SemIR::BoolValue::From(bool_literal->getValue())}));
  1778. } else if (auto* float_literal = dyn_cast<clang::FloatingLiteral>(expr)) {
  1779. FloatId float_id = context.floats().Add(float_literal->getValue());
  1780. inst_id = AddInstInNoBlock(context,
  1781. MakeImportedLocIdAndInst<SemIR::FloatValue>(
  1782. context, imported_loc_id,
  1783. {.type_id = type_id, .float_id = float_id}));
  1784. } else if (auto* character_literal =
  1785. dyn_cast<clang::CharacterLiteral>(expr)) {
  1786. inst_id = AddInstInNoBlock(
  1787. context, MakeImportedLocIdAndInst<SemIR::CharLiteralValue>(
  1788. context, imported_loc_id,
  1789. {.type_id = type_id,
  1790. .value = SemIR::CharId(character_literal->getValue())}));
  1791. } else {
  1792. context.TODO(loc_id, llvm::formatv(
  1793. "Unsupported: C++ constant expression type: '{0}'",
  1794. expr->getType().getAsString()));
  1795. return SemIR::ErrorInst::InstId;
  1796. }
  1797. context.imports().push_back(inst_id);
  1798. return inst_id;
  1799. }
  1800. // Imports a macro definition into the scope. Currently supports only simple
  1801. // object-like macros that expand to a constant integer value.
  1802. // TODO: Add support for other macro types and non-integer literal values.
  1803. static auto ImportMacro(Context& context, SemIR::LocId loc_id,
  1804. SemIR::NameScopeId scope_id, SemIR::NameId name_id,
  1805. clang::MacroInfo* macro_info)
  1806. -> SemIR::ScopeLookupResult {
  1807. clang::Expr* macro_expr =
  1808. TryEvaluateMacroToConstant(context, loc_id, name_id, macro_info);
  1809. if (!macro_expr) {
  1810. return SemIR::ScopeLookupResult::MakeNotFound();
  1811. }
  1812. auto inst_id = MapConstant(context, loc_id, macro_expr);
  1813. if (inst_id == SemIR::ErrorInst::InstId) {
  1814. return SemIR::ScopeLookupResult::MakeNotFound();
  1815. }
  1816. AddNameToScope(context, scope_id, name_id, SemIR::AccessKind::Public,
  1817. inst_id);
  1818. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  1819. inst_id, SemIR::AccessKind::Public);
  1820. }
  1821. // Looks up a macro definition in the top-level `Cpp` scope. Returns nullptr if
  1822. // the macro is not found or if it is a builtin macro, function-like macro or a
  1823. // macro used for header guards.
  1824. // TODO: Function-like and builtin macros are currently not supported and their
  1825. // support still needs to be clarified.
  1826. static auto LookupMacro(Context& context, SemIR::NameScopeId scope_id,
  1827. clang::IdentifierInfo* identifier_info)
  1828. -> clang::MacroInfo* {
  1829. if (!IsTopCppScope(context, scope_id)) {
  1830. return nullptr;
  1831. }
  1832. CARBON_CHECK(identifier_info, "Identifier info is empty");
  1833. clang::MacroInfo* macro_info =
  1834. context.clang_sema().getPreprocessor().getMacroInfo(identifier_info);
  1835. if (macro_info && !macro_info->isUsedForHeaderGuard() &&
  1836. !macro_info->isFunctionLike() && !macro_info->isBuiltinMacro()) {
  1837. return macro_info;
  1838. }
  1839. return nullptr;
  1840. }
  1841. // Gets the identifier info for a name. Returns `nullptr` if the name is not an
  1842. // identifier name.
  1843. static auto GetIdentifierInfo(Context& context, SemIR::NameId name_id)
  1844. -> clang::IdentifierInfo* {
  1845. std::optional<llvm::StringRef> string_name =
  1846. context.names().GetAsStringIfIdentifier(name_id);
  1847. if (!string_name) {
  1848. return nullptr;
  1849. }
  1850. clang::IdentifierInfo* identifier_info =
  1851. context.clang_sema().getPreprocessor().getIdentifierInfo(*string_name);
  1852. return identifier_info;
  1853. }
  1854. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  1855. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  1856. -> SemIR::ScopeLookupResult {
  1857. Diagnostics::AnnotationScope annotate_diagnostics(
  1858. &context.emitter(), [&](auto& builder) {
  1859. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  1860. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  1861. builder.Note(loc_id, InCppNameLookup, name_id);
  1862. });
  1863. if (IsIncompleteClass(context, scope_id)) {
  1864. return SemIR::ScopeLookupResult::MakeError();
  1865. }
  1866. clang::IdentifierInfo* identifier_info = GetIdentifierInfo(context, name_id);
  1867. if (!identifier_info) {
  1868. return SemIR::ScopeLookupResult::MakeNotFound();
  1869. }
  1870. if (clang::MacroInfo* macro_info =
  1871. LookupMacro(context, scope_id, identifier_info)) {
  1872. return ImportMacro(context, loc_id, scope_id, name_id, macro_info);
  1873. }
  1874. auto lookup = ClangLookupName(context, scope_id, identifier_info);
  1875. if (!lookup) {
  1876. return ImportBuiltinNameIntoScope(context, loc_id, scope_id, name_id);
  1877. }
  1878. // Access checks are performed separately by the Carbon name lookup logic.
  1879. lookup->suppressAccessDiagnostics();
  1880. if (lookup->isOverloadedResult() ||
  1881. (lookup->isSingleResult() &&
  1882. lookup->getFoundDecl()->isFunctionOrFunctionTemplate())) {
  1883. clang::UnresolvedSet<4> overload_set;
  1884. overload_set.append(lookup->begin(), lookup->end());
  1885. return ImportOverloadSetIntoScope(context, loc_id, scope_id, name_id,
  1886. lookup->getNamingClass(),
  1887. std::move(overload_set));
  1888. }
  1889. if (!lookup->isSingleResult()) {
  1890. // Clang will diagnose ambiguous lookup results for us.
  1891. if (!lookup->isAmbiguous()) {
  1892. context.TODO(loc_id,
  1893. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  1894. "find a single result; LookupResultKind: {0}",
  1895. static_cast<int>(lookup->getResultKind())));
  1896. }
  1897. context.name_scopes().AddRequiredName(scope_id, name_id,
  1898. SemIR::ErrorInst::InstId);
  1899. return SemIR::ScopeLookupResult::MakeError();
  1900. }
  1901. if (IsDeclInjectedClassName(context, scope_id, name_id,
  1902. lookup->getFoundDecl())) {
  1903. return ImportConstructorsIntoScope(context, loc_id, scope_id, name_id);
  1904. }
  1905. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(lookup->getFoundDecl());
  1906. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id, key,
  1907. MapCppAccess(lookup->begin().getPair()));
  1908. }
  1909. auto ImportClassDefinitionForClangDecl(Context& context, SemIR::LocId loc_id,
  1910. SemIR::ClassId class_id,
  1911. SemIR::ClangDeclId clang_decl_id)
  1912. -> bool {
  1913. SemIR::CppFile* cpp_file = context.sem_ir().cpp_file();
  1914. CARBON_CHECK(cpp_file);
  1915. auto* clang_decl =
  1916. cast<clang::TagDecl>(context.clang_decls().Get(clang_decl_id).key.decl);
  1917. auto class_inst_id = context.types().GetAsTypeInstId(
  1918. context.classes().Get(class_id).first_owning_decl_id);
  1919. // TODO: Map loc_id into a clang location and use it for diagnostics if
  1920. // instantiation fails, instead of annotating the diagnostic with another
  1921. // location.
  1922. clang::SourceLocation loc = clang_decl->getLocation();
  1923. Diagnostics::AnnotationScope annotate_diagnostics(
  1924. &context.emitter(), [&](auto& builder) {
  1925. CARBON_DIAGNOSTIC(InCppTypeCompletion, Note,
  1926. "while completing C++ type {0}", SemIR::TypeId);
  1927. builder.Note(loc_id, InCppTypeCompletion,
  1928. context.classes().Get(class_id).self_type_id);
  1929. });
  1930. // Ask Clang whether the type is complete. This triggers template
  1931. // instantiation if necessary.
  1932. clang::DiagnosticErrorTrap trap(cpp_file->diagnostics());
  1933. if (!context.cpp_context()->sema().isCompleteType(
  1934. loc, context.ast_context().getCanonicalTagType(clang_decl))) {
  1935. // Type is incomplete. Nothing more to do, but tell the caller if we
  1936. // produced an error.
  1937. return !trap.hasErrorOccurred();
  1938. }
  1939. auto import_ir_inst_id =
  1940. context.insts().GetCanonicalLocId(class_inst_id).import_ir_inst_id();
  1941. if (auto* class_decl = dyn_cast<clang::CXXRecordDecl>(clang_decl)) {
  1942. auto* class_def = class_decl->getDefinition();
  1943. CARBON_CHECK(class_def, "Complete type has no definition");
  1944. BuildClassDefinition(context, import_ir_inst_id, class_id, class_inst_id,
  1945. class_def);
  1946. } else if (auto* enum_decl = dyn_cast<clang::EnumDecl>(clang_decl)) {
  1947. BuildEnumDefinition(context, import_ir_inst_id, class_id, class_inst_id,
  1948. enum_decl);
  1949. }
  1950. return true;
  1951. }
  1952. } // namespace Carbon::Check