import.cpp 96 KB

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