import.cpp 98 KB

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