import.cpp 95 KB

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