import.cpp 102 KB

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