import.cpp 92 KB

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