import_cpp.cpp 74 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852
  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/import_cpp.h"
  5. #include <memory>
  6. #include <optional>
  7. #include <string>
  8. #include <tuple>
  9. #include <utility>
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/AST/RecordLayout.h"
  12. #include "clang/Basic/FileManager.h"
  13. #include "clang/Frontend/ASTUnit.h"
  14. #include "clang/Frontend/CompilerInstance.h"
  15. #include "clang/Frontend/CompilerInvocation.h"
  16. #include "clang/Frontend/TextDiagnostic.h"
  17. #include "clang/Lex/PreprocessorOptions.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "common/check.h"
  20. #include "common/ostream.h"
  21. #include "common/raw_string_ostream.h"
  22. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include "toolchain/base/kind_switch.h"
  26. #include "toolchain/check/class.h"
  27. #include "toolchain/check/context.h"
  28. #include "toolchain/check/convert.h"
  29. #include "toolchain/check/cpp_thunk.h"
  30. #include "toolchain/check/diagnostic_helpers.h"
  31. #include "toolchain/check/eval.h"
  32. #include "toolchain/check/function.h"
  33. #include "toolchain/check/import.h"
  34. #include "toolchain/check/inst.h"
  35. #include "toolchain/check/literal.h"
  36. #include "toolchain/check/pattern.h"
  37. #include "toolchain/check/pattern_match.h"
  38. #include "toolchain/check/type.h"
  39. #include "toolchain/check/type_completion.h"
  40. #include "toolchain/diagnostics/diagnostic.h"
  41. #include "toolchain/diagnostics/diagnostic_emitter.h"
  42. #include "toolchain/diagnostics/format_providers.h"
  43. #include "toolchain/parse/node_ids.h"
  44. #include "toolchain/sem_ir/clang_decl.h"
  45. #include "toolchain/sem_ir/class.h"
  46. #include "toolchain/sem_ir/function.h"
  47. #include "toolchain/sem_ir/ids.h"
  48. #include "toolchain/sem_ir/inst.h"
  49. #include "toolchain/sem_ir/name_scope.h"
  50. #include "toolchain/sem_ir/typed_insts.h"
  51. namespace Carbon::Check {
  52. // Add a line marker directive pointing at the location of the `import Cpp`
  53. // declaration in the Carbon source file. This will cause Clang's diagnostics
  54. // machinery to track and report the location in Carbon code where the import
  55. // was written.
  56. static auto GenerateLineMarker(Context& context, llvm::raw_ostream& out,
  57. int line) {
  58. out << "# " << line << " \""
  59. << FormatEscaped(context.tokens().source().filename()) << "\"\n";
  60. }
  61. // Generates C++ file contents to #include all requested imports.
  62. static auto GenerateCppIncludesHeaderCode(
  63. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  64. -> std::string {
  65. std::string code;
  66. llvm::raw_string_ostream code_stream(code);
  67. for (const Parse::Tree::PackagingNames& import : imports) {
  68. if (import.inline_body_id.has_value()) {
  69. // Expand `import Cpp inline "code";` directly into the specified code.
  70. auto code_token = context.parse_tree().node_token(import.inline_body_id);
  71. // Compute the line number on which the C++ code starts. Usually the code
  72. // is specified as a block string literal and starts on the line after the
  73. // start of the string token.
  74. // TODO: Determine if this is a block string literal without calling
  75. // `GetTokenText`, which re-lexes the string.
  76. int line = context.tokens().GetLineNumber(code_token);
  77. if (context.tokens().GetTokenText(code_token).contains('\n')) {
  78. ++line;
  79. }
  80. GenerateLineMarker(context, code_stream, line);
  81. code_stream << context.string_literal_values().Get(
  82. context.tokens().GetStringLiteralValue(code_token))
  83. << "\n";
  84. // TODO: Inject a clang pragma here to produce an error if there are
  85. // unclosed scopes at the end of this inline C++ fragment.
  86. } else {
  87. // Translate `import Cpp library "foo.h";` into `#include "foo.h"`.
  88. GenerateLineMarker(context, code_stream,
  89. context.tokens().GetLineNumber(
  90. context.parse_tree().node_token(import.node_id)));
  91. code_stream << "#include \""
  92. << FormatEscaped(
  93. context.string_literal_values().Get(import.library_id))
  94. << "\"\n";
  95. }
  96. }
  97. // Inject a declaration of placement operator new, because the code we
  98. // generate in thunks depends on it for placement new expressions. Clang has
  99. // special-case logic for lowering a new-expression using this, so a
  100. // definition is not required.
  101. // TODO: This is a hack. We should be able to directly generate Clang AST to
  102. // construct objects in-place without this.
  103. // TODO: Once we can rely on libc++ being available, consider including
  104. // `<__new/placement_new_delete.h>` instead.
  105. code_stream << R"(# 1 "<carbon-internal>"
  106. #undef constexpr
  107. #if __cplusplus > 202302L
  108. constexpr
  109. #endif
  110. #undef void
  111. #undef operator
  112. #undef new
  113. void* operator new(__SIZE_TYPE__, void*)
  114. #if __cplusplus < 201103L
  115. #undef throw
  116. throw()
  117. #else
  118. #undef noexcept
  119. noexcept
  120. #endif
  121. ;
  122. )";
  123. return code;
  124. }
  125. // Adds the name to the scope with the given `access_kind` and `inst_id`.
  126. // `inst_id` must have a value.
  127. static auto AddNameToScope(Context& context, SemIR::NameScopeId scope_id,
  128. SemIR::NameId name_id, SemIR::AccessKind access_kind,
  129. SemIR::InstId inst_id) -> void {
  130. CARBON_CHECK(inst_id.has_value());
  131. context.name_scopes().Get(scope_id).AddRequired(
  132. {.name_id = name_id,
  133. .result = SemIR::ScopeLookupResult::MakeFound(inst_id, access_kind)});
  134. }
  135. // Maps a Clang name to a Carbon `NameId`.
  136. static auto AddIdentifierName(Context& context, llvm::StringRef name)
  137. -> SemIR::NameId {
  138. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  139. }
  140. // Adds the given source location and an `ImportIRInst` referring to it in
  141. // `ImportIRId::Cpp`.
  142. static auto AddImportIRInst(SemIR::File& file,
  143. clang::SourceLocation clang_source_loc)
  144. -> SemIR::ImportIRInstId {
  145. SemIR::ClangSourceLocId clang_source_loc_id =
  146. file.clang_source_locs().Add(clang_source_loc);
  147. return file.import_ir_insts().Add(SemIR::ImportIRInst(clang_source_loc_id));
  148. }
  149. namespace {
  150. // Used to convert Clang diagnostics to Carbon diagnostics.
  151. //
  152. // Handling of Clang notes is a little subtle: as far as Clang is concerned,
  153. // notes are separate diagnostics, not connected to the error or warning that
  154. // precedes them. But in Carbon's diagnostics system, notes are part of the
  155. // enclosing diagnostic. To handle this, we buffer Clang diagnostics until we
  156. // reach a point where we know we're not in the middle of a diagnostic, and then
  157. // emit a diagnostic along with all of its notes. This is triggered when adding
  158. // or removing a Carbon context note, which could otherwise get attached to the
  159. // wrong C++ diagnostics, and at the end of the Carbon program.
  160. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  161. public:
  162. // Creates an instance with the location that triggers calling Clang. The
  163. // `context` is not stored here, and the diagnostics consumer is expected to
  164. // outlive it.
  165. explicit CarbonClangDiagnosticConsumer(
  166. Context& context, std::shared_ptr<clang::CompilerInvocation> invocation)
  167. : sem_ir_(&context.sem_ir()),
  168. emitter_(&context.emitter()),
  169. invocation_(std::move(invocation)) {
  170. emitter_->AddFlushFn([this] { EmitDiagnostics(); });
  171. }
  172. ~CarbonClangDiagnosticConsumer() override {
  173. // Do not inspect `emitter_` here; it's typically destroyed before the
  174. // consumer is.
  175. // TODO: If Clang produces diagnostics after check finishes, they'll get
  176. // added to the list of pending diagnostics and never emitted.
  177. CARBON_CHECK(diagnostic_infos_.empty(),
  178. "Missing flush before destroying diagnostic consumer");
  179. }
  180. // Generates a Carbon warning for each Clang warning and a Carbon error for
  181. // each Clang error or fatal.
  182. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  183. const clang::Diagnostic& info) -> void override {
  184. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  185. SemIR::ImportIRInstId clang_import_ir_inst_id =
  186. AddImportIRInst(*sem_ir_, info.getLocation());
  187. llvm::SmallString<256> message;
  188. info.FormatDiagnostic(message);
  189. // Render a code snippet including any highlighted ranges and fixit hints.
  190. // TODO: Also include the #include stack and macro expansion stack in the
  191. // diagnostic output in some way.
  192. RawStringOstream snippet_stream;
  193. if (!info.hasSourceManager()) {
  194. // If we don't have a source manager, this is an error from early in the
  195. // frontend. Don't produce a snippet.
  196. CARBON_CHECK(info.getLocation().isInvalid());
  197. } else {
  198. CodeContextRenderer(snippet_stream, invocation_->getLangOpts(),
  199. invocation_->getDiagnosticOpts())
  200. .emitDiagnostic(
  201. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  202. diag_level, message, info.getRanges(), info.getFixItHints());
  203. }
  204. diagnostic_infos_.push_back({.level = diag_level,
  205. .import_ir_inst_id = clang_import_ir_inst_id,
  206. .message = message.str().str(),
  207. .snippet = snippet_stream.TakeStr()});
  208. }
  209. // Returns the diagnostic to use for a given Clang diagnostic level.
  210. static auto GetDiagnostic(clang::DiagnosticsEngine::Level level)
  211. -> const Diagnostics::DiagnosticBase<std::string>& {
  212. switch (level) {
  213. case clang::DiagnosticsEngine::Ignored: {
  214. CARBON_FATAL("Emitting an ignored diagnostic");
  215. break;
  216. }
  217. case clang::DiagnosticsEngine::Note: {
  218. CARBON_DIAGNOSTIC(CppInteropParseNote, Note, "{0}", std::string);
  219. return CppInteropParseNote;
  220. }
  221. case clang::DiagnosticsEngine::Remark:
  222. case clang::DiagnosticsEngine::Warning: {
  223. // TODO: Add a distinct Remark level to Carbon diagnostics, and stop
  224. // mapping remarks to warnings.
  225. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "{0}", std::string);
  226. return CppInteropParseWarning;
  227. }
  228. case clang::DiagnosticsEngine::Error:
  229. case clang::DiagnosticsEngine::Fatal: {
  230. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "{0}", std::string);
  231. return CppInteropParseError;
  232. }
  233. }
  234. }
  235. // Outputs Carbon diagnostics based on the collected Clang diagnostics. Must
  236. // be called after the AST is set in the context.
  237. auto EmitDiagnostics() -> void {
  238. CARBON_CHECK(sem_ir_->clang_ast_unit(),
  239. "Attempted to emit diagnostics before the AST Unit is loaded");
  240. for (size_t i = 0; i != diagnostic_infos_.size(); ++i) {
  241. const ClangDiagnosticInfo& info = diagnostic_infos_[i];
  242. auto builder = emitter_->Build(SemIR::LocId(info.import_ir_inst_id),
  243. GetDiagnostic(info.level), info.message);
  244. builder.OverrideSnippet(info.snippet);
  245. for (; i + 1 < diagnostic_infos_.size() &&
  246. diagnostic_infos_[i + 1].level == clang::DiagnosticsEngine::Note;
  247. ++i) {
  248. const ClangDiagnosticInfo& note_info = diagnostic_infos_[i + 1];
  249. builder
  250. .Note(SemIR::LocId(note_info.import_ir_inst_id),
  251. GetDiagnostic(note_info.level), note_info.message)
  252. .OverrideSnippet(note_info.snippet);
  253. }
  254. // TODO: This will apply all current Carbon annotation functions. We
  255. // should instead track how Clang's context notes and Carbon's annotation
  256. // functions are interleaved, and interleave the notes in the same order.
  257. builder.Emit();
  258. }
  259. diagnostic_infos_.clear();
  260. }
  261. private:
  262. // A diagnostics renderer based on clang's TextDiagnostic that captures just
  263. // the code context (the snippet).
  264. class CodeContextRenderer : public clang::TextDiagnostic {
  265. public:
  266. using TextDiagnostic::TextDiagnostic;
  267. void emitDiagnosticMessage(
  268. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  269. clang::DiagnosticsEngine::Level /*level*/, llvm::StringRef /*message*/,
  270. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/,
  271. clang::DiagOrStoredDiag /*info*/) override {}
  272. void emitDiagnosticLoc(
  273. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  274. clang::DiagnosticsEngine::Level /*level*/,
  275. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/) override {}
  276. // emitCodeContext is inherited from clang::TextDiagnostic.
  277. void emitIncludeLocation(clang::FullSourceLoc /*loc*/,
  278. clang::PresumedLoc /*ploc*/) override {}
  279. void emitImportLocation(clang::FullSourceLoc /*loc*/,
  280. clang::PresumedLoc /*ploc*/,
  281. llvm::StringRef /*module_name*/) override {}
  282. void emitBuildingModuleLocation(clang::FullSourceLoc /*loc*/,
  283. clang::PresumedLoc /*ploc*/,
  284. llvm::StringRef /*module_name*/) override {}
  285. // beginDiagnostic and endDiagnostic are inherited from
  286. // clang::TextDiagnostic in case it wants to do any setup / teardown work.
  287. };
  288. // Information on a Clang diagnostic that can be converted to a Carbon
  289. // diagnostic.
  290. struct ClangDiagnosticInfo {
  291. // The Clang diagnostic level.
  292. clang::DiagnosticsEngine::Level level;
  293. // The ID of the ImportIR instruction referring to the Clang source
  294. // location.
  295. SemIR::ImportIRInstId import_ir_inst_id;
  296. // The Clang diagnostic textual message.
  297. std::string message;
  298. // The code snippet produced by clang.
  299. std::string snippet;
  300. };
  301. // The Carbon file that this C++ compilation is attached to.
  302. SemIR::File* sem_ir_;
  303. // The diagnostic emitter that we're emitting diagnostics into.
  304. DiagnosticEmitterBase* emitter_;
  305. // The compiler invocation that is producing the diagnostics.
  306. std::shared_ptr<clang::CompilerInvocation> invocation_;
  307. // Collects the information for all Clang diagnostics to be converted to
  308. // Carbon diagnostics after the context has been initialized with the Clang
  309. // AST.
  310. llvm::SmallVector<ClangDiagnosticInfo> diagnostic_infos_;
  311. };
  312. // A wrapper around a clang::CompilerInvocation that allows us to make a shallow
  313. // copy of most of the invocation and only make a deep copy of the parts that we
  314. // want to change.
  315. //
  316. // clang::CowCompilerInvocation almost allows this, but doesn't derive from
  317. // CompilerInvocation or support shallow copies from a CompilerInvocation, so is
  318. // not useful to us as we can't build an ASTUnit from it.
  319. class ShallowCopyCompilerInvocation : public clang::CompilerInvocation {
  320. public:
  321. explicit ShallowCopyCompilerInvocation(
  322. const clang::CompilerInvocation& invocation) {
  323. shallow_copy_assign(invocation);
  324. // The preprocessor options are modified to hold a replacement includes
  325. // buffer, so make our own version of those options.
  326. PPOpts = std::make_shared<clang::PreprocessorOptions>(*PPOpts);
  327. }
  328. };
  329. } // namespace
  330. // Returns an AST for the C++ imports and a bool that represents whether
  331. // compilation errors where encountered or the generated AST is null due to an
  332. // error. Sets the AST in the context's `sem_ir`.
  333. // TODO: Consider to always have a (non-null) AST.
  334. static auto GenerateAst(
  335. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  336. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  337. std::shared_ptr<clang::CompilerInvocation> base_invocation)
  338. -> std::pair<std::unique_ptr<clang::ASTUnit>, bool> {
  339. auto invocation =
  340. std::make_shared<ShallowCopyCompilerInvocation>(*base_invocation);
  341. // Build a diagnostics engine.
  342. llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diags(
  343. clang::CompilerInstance::createDiagnostics(
  344. *fs, invocation->getDiagnosticOpts(),
  345. new CarbonClangDiagnosticConsumer(context, invocation),
  346. /*ShouldOwnClient=*/true));
  347. // Extract the input from the frontend invocation and make sure it makes
  348. // sense.
  349. const auto& inputs = invocation->getFrontendOpts().Inputs;
  350. CARBON_CHECK(inputs.size() == 1 &&
  351. inputs[0].getKind().getLanguage() == clang::Language::CXX &&
  352. inputs[0].getKind().getFormat() == clang::InputKind::Source);
  353. llvm::StringRef file_name = inputs[0].getFile();
  354. // Remap the imports file name to the corresponding `#include`s.
  355. // TODO: Modify the frontend options to specify this memory buffer as input
  356. // instead of remapping the file.
  357. std::string includes = GenerateCppIncludesHeaderCode(context, imports);
  358. auto includes_buffer =
  359. llvm::MemoryBuffer::getMemBufferCopy(includes, file_name);
  360. invocation->getPreprocessorOpts().addRemappedFile(file_name,
  361. includes_buffer.release());
  362. clang::DiagnosticErrorTrap trap(*diags);
  363. // Create the AST unit.
  364. auto ast = clang::ASTUnit::LoadFromCompilerInvocation(
  365. invocation, std::make_shared<clang::PCHContainerOperations>(), nullptr,
  366. diags, new clang::FileManager(invocation->getFileSystemOpts(), fs));
  367. // Attach the AST to SemIR. This needs to be done before we can emit any
  368. // diagnostics, so their locations can be properly interpreted by our
  369. // diagnostics machinery.
  370. context.sem_ir().set_clang_ast_unit(ast.get());
  371. // Emit any diagnostics we queued up while building the AST.
  372. context.emitter().Flush();
  373. return {std::move(ast), !ast || trap.hasErrorOccurred()};
  374. }
  375. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  376. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  377. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  378. -> SemIR::NameScopeId {
  379. auto& import_cpps = context.sem_ir().import_cpps();
  380. import_cpps.Reserve(imports.size());
  381. for (const Parse::Tree::PackagingNames& import : imports) {
  382. import_cpps.Add({.node_id = context.parse_tree().As<Parse::ImportDeclId>(
  383. import.node_id),
  384. .library_id = import.library_id});
  385. }
  386. return AddImportNamespaceToScope(
  387. context,
  388. GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  389. SemIR::NameId::ForPackageName(cpp_package_id),
  390. SemIR::NameScopeId::Package,
  391. /*diagnose_duplicate_namespace=*/false,
  392. [&]() {
  393. return AddInst<SemIR::ImportCppDecl>(
  394. context,
  395. context.parse_tree().As<Parse::ImportDeclId>(
  396. imports.front().node_id),
  397. {});
  398. })
  399. .add_result.name_scope_id;
  400. }
  401. auto ImportCppFiles(Context& context,
  402. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  403. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  404. std::shared_ptr<clang::CompilerInvocation> invocation)
  405. -> std::unique_ptr<clang::ASTUnit> {
  406. if (imports.empty()) {
  407. return nullptr;
  408. }
  409. CARBON_CHECK(!context.sem_ir().clang_ast_unit());
  410. PackageNameId package_id = imports.front().package_id;
  411. CARBON_CHECK(
  412. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  413. return import.package_id == package_id;
  414. }));
  415. auto name_scope_id = AddNamespace(context, package_id, imports);
  416. auto [generated_ast, ast_has_error] =
  417. GenerateAst(context, imports, fs, std::move(invocation));
  418. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  419. name_scope.set_is_closed_import(true);
  420. name_scope.set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  421. {.decl = generated_ast->getASTContext().getTranslationUnitDecl(),
  422. .inst_id = name_scope.inst_id()}));
  423. if (ast_has_error) {
  424. name_scope.set_has_error();
  425. }
  426. return std::move(generated_ast);
  427. }
  428. // Looks up the given name in the Clang AST in a specific scope. Returns the
  429. // lookup result if lookup was successful.
  430. static auto ClangLookupName(Context& context, SemIR::NameScopeId scope_id,
  431. SemIR::NameId name_id)
  432. -> std::optional<clang::LookupResult> {
  433. std::optional<llvm::StringRef> name =
  434. context.names().GetAsStringIfIdentifier(name_id);
  435. if (!name) {
  436. // Special names never exist in C++ code.
  437. return std::nullopt;
  438. }
  439. clang::ASTUnit* ast = context.sem_ir().clang_ast_unit();
  440. CARBON_CHECK(ast);
  441. clang::Sema& sema = ast->getSema();
  442. // TODO: Map the LocId of the lookup to a clang SourceLocation and provide it
  443. // here so that clang's diagnostics can point into the carbon code that uses
  444. // the name.
  445. clang::LookupResult lookup(
  446. sema,
  447. clang::DeclarationNameInfo(
  448. clang::DeclarationName(
  449. sema.getPreprocessor().getIdentifierInfo(*name)),
  450. clang::SourceLocation()),
  451. clang::Sema::LookupNameKind::LookupOrdinaryName);
  452. auto scope_clang_decl_context_id =
  453. context.name_scopes().Get(scope_id).clang_decl_context_id();
  454. bool found = sema.LookupQualifiedName(
  455. lookup, dyn_cast<clang::DeclContext>(context.sem_ir()
  456. .clang_decls()
  457. .Get(scope_clang_decl_context_id)
  458. .decl));
  459. if (!found) {
  460. return std::nullopt;
  461. }
  462. return lookup;
  463. }
  464. // Looks up for constructors in the class scope and returns the lookup result.
  465. static auto ClangConstructorLookup(const Context& context,
  466. SemIR::NameScopeId scope_id)
  467. -> clang::DeclContextLookupResult {
  468. const SemIR::NameScope& scope = context.sem_ir().name_scopes().Get(scope_id);
  469. clang::Sema& sema = context.sem_ir().clang_ast_unit()->getSema();
  470. clang::Decl* decl =
  471. context.sem_ir().clang_decls().Get(scope.clang_decl_context_id()).decl;
  472. return sema.LookupConstructors(cast<clang::CXXRecordDecl>(decl));
  473. }
  474. // Returns true if the given Clang declaration is the implicit injected class
  475. // name within the class.
  476. static auto IsDeclInjectedClassName(const Context& context,
  477. SemIR::NameScopeId scope_id,
  478. SemIR::NameId name_id,
  479. const clang::NamedDecl* named_decl)
  480. -> bool {
  481. if (!named_decl->isImplicit()) {
  482. return false;
  483. }
  484. const auto* record_decl = dyn_cast<clang::CXXRecordDecl>(named_decl);
  485. if (!record_decl) {
  486. return false;
  487. }
  488. const SemIR::ClangDecl& clang_decl = context.sem_ir().clang_decls().Get(
  489. context.sem_ir().name_scopes().Get(scope_id).clang_decl_context_id());
  490. const auto* scope_record_decl = cast<clang::CXXRecordDecl>(clang_decl.decl);
  491. const clang::ASTContext& ast_context =
  492. context.sem_ir().clang_ast_unit()->getASTContext();
  493. CARBON_CHECK(
  494. ast_context.getCanonicalType(
  495. ast_context.getRecordType(scope_record_decl)) ==
  496. ast_context.getCanonicalType(ast_context.getRecordType(record_decl)));
  497. auto class_decl =
  498. context.sem_ir().insts().GetAs<SemIR::ClassDecl>(clang_decl.inst_id);
  499. CARBON_CHECK(name_id ==
  500. context.sem_ir().classes().Get(class_decl.class_id).name_id);
  501. return true;
  502. }
  503. // Looks up the given name in the Clang AST in a specific scope, and returns the
  504. // found declaration and its access. If the found declaration is the injected
  505. // class name, looks up constructors instead. If not found, returns `nullopt`.
  506. // If there's not a single result, returns `nullptr` and default access.
  507. // Otherwise, returns the single declaration and its access.
  508. static auto ClangLookup(Context& context, SemIR::LocId loc_id,
  509. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  510. -> std::optional<std::tuple<clang::NamedDecl*, clang::AccessSpecifier>> {
  511. auto lookup = ClangLookupName(context, scope_id, name_id);
  512. if (!lookup) {
  513. return std::nullopt;
  514. }
  515. std::tuple<clang::NamedDecl*, clang::AccessSpecifier> result{
  516. nullptr, clang::AccessSpecifier::AS_none};
  517. // Access checks are performed separately by the Carbon name lookup logic.
  518. lookup->suppressAccessDiagnostics();
  519. if (!lookup->isSingleResult()) {
  520. // Clang will diagnose ambiguous lookup results for us.
  521. if (!lookup->isAmbiguous()) {
  522. context.TODO(loc_id,
  523. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  524. "find a single result; LookupResultKind: {0}",
  525. static_cast<int>(lookup->getResultKind())));
  526. }
  527. return result;
  528. }
  529. if (!IsDeclInjectedClassName(context, scope_id, name_id,
  530. lookup->getFoundDecl())) {
  531. result = {lookup->getFoundDecl(), lookup->begin().getAccess()};
  532. return result;
  533. }
  534. clang::DeclContextLookupResult constructors_lookup =
  535. ClangConstructorLookup(context, scope_id);
  536. llvm::SmallVector<clang::CXXConstructorDecl*> constructors;
  537. for (clang::Decl* decl : constructors_lookup) {
  538. auto* constructor = cast<clang::CXXConstructorDecl>(decl);
  539. if (constructor->isDeleted() || constructor->isCopyOrMoveConstructor()) {
  540. continue;
  541. }
  542. constructors.push_back(constructor);
  543. }
  544. if (constructors.size() != 1) {
  545. context.TODO(
  546. loc_id,
  547. llvm::formatv("Unsupported: Constructors lookup succeeded but couldn't "
  548. "find a single result; Found {0} constructors",
  549. constructors.size()));
  550. return result;
  551. }
  552. result = {constructors[0], constructors[0]->getAccess()};
  553. return result;
  554. }
  555. // Returns whether `decl` already mapped to an instruction.
  556. static auto IsClangDeclImported(const Context& context, clang::Decl* decl)
  557. -> bool {
  558. return context.sem_ir()
  559. .clang_decls()
  560. .Lookup(decl->getCanonicalDecl())
  561. .has_value();
  562. }
  563. // If `decl` already mapped to an instruction, returns that instruction.
  564. // Otherwise returns `None`.
  565. static auto LookupClangDeclInstId(const Context& context, clang::Decl* decl)
  566. -> SemIR::InstId {
  567. const auto& clang_decls = context.sem_ir().clang_decls();
  568. if (auto context_clang_decl_id = clang_decls.Lookup(decl->getCanonicalDecl());
  569. context_clang_decl_id.has_value()) {
  570. return clang_decls.Get(context_clang_decl_id).inst_id;
  571. }
  572. return SemIR::InstId::None;
  573. }
  574. // Returns the parent of the given declaration. Skips declaration types we
  575. // ignore.
  576. static auto GetParentDecl(clang::Decl* clang_decl) -> clang::Decl* {
  577. return cast<clang::Decl>(
  578. clang_decl->getDeclContext()->getNonTransparentContext());
  579. }
  580. // Returns the given declaration's parent scope. Assumes the parent declaration
  581. // was already imported.
  582. static auto GetParentNameScopeId(Context& context, clang::Decl* clang_decl)
  583. -> SemIR::NameScopeId {
  584. SemIR::InstId parent_inst_id =
  585. LookupClangDeclInstId(context, GetParentDecl(clang_decl));
  586. CARBON_CHECK(parent_inst_id.has_value());
  587. CARBON_KIND_SWITCH(context.insts().Get(parent_inst_id)) {
  588. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  589. return context.classes().Get(class_decl.class_id).scope_id;
  590. }
  591. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  592. return context.interfaces().Get(interface_decl.interface_id).scope_id;
  593. }
  594. case CARBON_KIND(SemIR::Namespace namespace_inst): {
  595. return namespace_inst.name_scope_id;
  596. }
  597. default: {
  598. CARBON_FATAL("Unexpected parent instruction kind");
  599. }
  600. }
  601. }
  602. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  603. // the new Carbon namespace declaration `InstId`. If the declaration was already
  604. // imported, returns the mapped instruction.
  605. static auto ImportNamespaceDecl(Context& context,
  606. clang::NamespaceDecl* clang_decl)
  607. -> SemIR::InstId {
  608. // Check if the declaration is already mapped.
  609. if (SemIR::InstId existing_inst_id =
  610. LookupClangDeclInstId(context, clang_decl);
  611. existing_inst_id.has_value()) {
  612. return existing_inst_id;
  613. }
  614. auto result = AddImportNamespace(
  615. context, GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  616. AddIdentifierName(context, clang_decl->getName()),
  617. GetParentNameScopeId(context, clang_decl),
  618. /*import_id=*/SemIR::InstId::None);
  619. context.name_scopes()
  620. .Get(result.name_scope_id)
  621. .set_clang_decl_context_id(context.sem_ir().clang_decls().Add(
  622. {.decl = clang_decl->getCanonicalDecl(), .inst_id = result.inst_id}));
  623. return result.inst_id;
  624. }
  625. static auto ImportTypeAndDependencies(Context& context, SemIR::LocId loc_id,
  626. clang::QualType type) -> TypeExpr;
  627. // Creates a class declaration for the given class name in the given scope.
  628. // Returns the `InstId` for the declaration.
  629. static auto BuildClassDecl(Context& context,
  630. SemIR::ImportIRInstId import_ir_inst_id,
  631. SemIR::NameScopeId parent_scope_id,
  632. SemIR::NameId name_id)
  633. -> std::tuple<SemIR::ClassId, SemIR::TypeInstId> {
  634. // Add the class declaration.
  635. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeType::TypeId,
  636. .class_id = SemIR::ClassId::None,
  637. .decl_block_id = SemIR::InstBlockId::None};
  638. auto class_decl_id = AddPlaceholderInstInNoBlock(
  639. context,
  640. SemIR::LocIdAndInst::UncheckedLoc(import_ir_inst_id, class_decl));
  641. context.imports().push_back(class_decl_id);
  642. SemIR::Class class_info = {
  643. {.name_id = name_id,
  644. .parent_scope_id = parent_scope_id,
  645. .generic_id = SemIR::GenericId::None,
  646. .first_param_node_id = Parse::NodeId::None,
  647. .last_param_node_id = Parse::NodeId::None,
  648. .pattern_block_id = SemIR::InstBlockId::None,
  649. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  650. .param_patterns_id = SemIR::InstBlockId::None,
  651. .is_extern = false,
  652. .extern_library_id = SemIR::LibraryNameId::None,
  653. .non_owning_decl_id = SemIR::InstId::None,
  654. .first_owning_decl_id = class_decl_id},
  655. {// `.self_type_id` depends on the ClassType, so is set below.
  656. .self_type_id = SemIR::TypeId::None,
  657. // TODO: Support Dynamic classes.
  658. // TODO: Support Final classes.
  659. .inheritance_kind = SemIR::Class::Base}};
  660. class_decl.class_id = context.classes().Add(class_info);
  661. // Write the class ID into the ClassDecl.
  662. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  663. SetClassSelfType(context, class_decl.class_id);
  664. return {class_decl.class_id, context.types().GetAsTypeInstId(class_decl_id)};
  665. }
  666. // Imports a record declaration from Clang to Carbon. If successful, returns
  667. // the new Carbon class declaration `InstId`.
  668. static auto ImportCXXRecordDecl(Context& context,
  669. clang::CXXRecordDecl* clang_decl)
  670. -> SemIR::InstId {
  671. auto import_ir_inst_id =
  672. AddImportIRInst(context.sem_ir(), clang_decl->getLocation());
  673. auto [class_id, class_inst_id] = BuildClassDecl(
  674. context, import_ir_inst_id, GetParentNameScopeId(context, clang_decl),
  675. AddIdentifierName(context, clang_decl->getName()));
  676. // TODO: The caller does the same lookup. Avoid doing it twice.
  677. auto clang_decl_id = context.sem_ir().clang_decls().Add(
  678. {.decl = clang_decl->getCanonicalDecl(), .inst_id = class_inst_id});
  679. // Name lookup into the Carbon class looks in the C++ class definition.
  680. auto& class_info = context.classes().Get(class_id);
  681. class_info.scope_id = context.name_scopes().Add(
  682. class_inst_id, SemIR::NameId::None, class_info.parent_scope_id);
  683. context.name_scopes()
  684. .Get(class_info.scope_id)
  685. .set_clang_decl_context_id(clang_decl_id);
  686. return class_inst_id;
  687. }
  688. // Determines the Carbon inheritance kind to use for a C++ class definition.
  689. static auto GetInheritanceKind(clang::CXXRecordDecl* class_def)
  690. -> SemIR::Class::InheritanceKind {
  691. if (class_def->isUnion()) {
  692. // Treat all unions as final classes to match their C++ semantics. While we
  693. // could support this, the author of a C++ union has no way to mark their
  694. // type as `final` to prevent it, and so we assume the intent was to
  695. // disallow inheritance.
  696. return SemIR::Class::Final;
  697. }
  698. if (class_def->hasAttr<clang::FinalAttr>()) {
  699. // The class is final in C++; don't allow Carbon types to derive from it.
  700. // Note that such a type might also be abstract in C++; we treat final as
  701. // taking precedence.
  702. //
  703. // We could also treat classes with a final destructor as being final, as
  704. // Clang does when determining whether a class is "effectively final", but
  705. // to keep our rules simpler we do not.
  706. return SemIR::Class::Final;
  707. }
  708. if (class_def->isAbstract()) {
  709. // If the class has any abstract members, it's abstract.
  710. return SemIR::Class::Abstract;
  711. }
  712. // Allow inheritance from any other C++ class type.
  713. return SemIR::Class::Base;
  714. }
  715. // Checks that the specified finished class definition is valid and builds and
  716. // returns a corresponding complete type witness instruction.
  717. static auto ImportClassObjectRepr(Context& context, SemIR::ClassId class_id,
  718. SemIR::ImportIRInstId import_ir_inst_id,
  719. SemIR::TypeInstId class_type_inst_id,
  720. const clang::CXXRecordDecl* clang_def)
  721. -> SemIR::TypeInstId {
  722. // For now, if the class is empty, produce an empty struct as the object
  723. // representation. This allows our tests to continue to pass while we don't
  724. // properly support initializing imported C++ classes.
  725. // TODO: Remove this.
  726. if (clang_def->isEmpty() && !clang_def->getNumBases()) {
  727. return context.types().GetAsTypeInstId(AddInst(
  728. context,
  729. MakeImportedLocIdAndInst(
  730. context, import_ir_inst_id,
  731. SemIR::StructType{.type_id = SemIR::TypeType::TypeId,
  732. .fields_id = SemIR::StructTypeFieldsId::Empty})));
  733. }
  734. const auto& clang_layout =
  735. context.ast_context().getASTRecordLayout(clang_def);
  736. llvm::SmallVector<uint64_t> layout;
  737. llvm::SmallVector<SemIR::StructTypeField> fields;
  738. static_assert(SemIR::CustomLayoutId::SizeIndex == 0);
  739. layout.push_back(clang_layout.getSize().getQuantity());
  740. static_assert(SemIR::CustomLayoutId::AlignIndex == 1);
  741. layout.push_back(clang_layout.getAlignment().getQuantity());
  742. static_assert(SemIR::CustomLayoutId::FirstFieldIndex == 2);
  743. // TODO: Import vptr(s).
  744. // Import bases.
  745. for (const auto& base : clang_def->bases()) {
  746. CARBON_CHECK(!base.isVirtual(),
  747. "Should not import definition for class with a virtual base");
  748. auto [base_type_inst_id, base_type_id] =
  749. ImportTypeAndDependencies(context, import_ir_inst_id, base.getType());
  750. if (!base_type_id.has_value()) {
  751. // TODO: If the base class's type can't be mapped, skip it.
  752. continue;
  753. }
  754. auto base_decl_id = AddInst(
  755. context,
  756. MakeImportedLocIdAndInst(
  757. context, import_ir_inst_id,
  758. SemIR::BaseDecl{.type_id = GetUnboundElementType(
  759. context, class_type_inst_id, base_type_inst_id),
  760. .base_type_inst_id = base_type_inst_id,
  761. .index = SemIR::ElementIndex(fields.size())}));
  762. // If there's exactly one base class, treat it as a Carbon base class too.
  763. // TODO: Improve handling for the case where the class has multiple base
  764. // classes.
  765. if (clang_def->getNumBases() == 1) {
  766. auto& class_info = context.classes().Get(class_id);
  767. CARBON_CHECK(!class_info.base_id.has_value());
  768. class_info.base_id = base_decl_id;
  769. }
  770. auto* base_class = base.getType()->getAsCXXRecordDecl();
  771. CARBON_CHECK(base_class, "Base class {0} is not a class",
  772. base.getType().getAsString());
  773. auto base_offset = base.isVirtual()
  774. ? clang_layout.getVBaseClassOffset(base_class)
  775. : clang_layout.getBaseClassOffset(base_class);
  776. layout.push_back(base_offset.getQuantity());
  777. fields.push_back(
  778. {.name_id = SemIR::NameId::Base, .type_inst_id = base_type_inst_id});
  779. }
  780. // Import fields.
  781. for (auto* decl : clang_def->decls()) {
  782. auto* field = dyn_cast<clang::FieldDecl>(decl);
  783. // Track the chain of fields from the class to this field. This chain is
  784. // only one element long unless the field is a member of an anonymous struct
  785. // or union.
  786. clang::NamedDecl* single_field_chain[1] = {field};
  787. llvm::ArrayRef<clang::NamedDecl*> chain = single_field_chain;
  788. // If this isn't a field, it might be an indirect field in an anonymous
  789. // struct or union.
  790. if (!field) {
  791. auto* indirect_field = dyn_cast<clang::IndirectFieldDecl>(decl);
  792. if (!indirect_field) {
  793. continue;
  794. }
  795. chain = indirect_field->chain();
  796. field = indirect_field->getAnonField();
  797. }
  798. if (field->isBitField()) {
  799. // TODO: Add a representation for named bitfield members.
  800. continue;
  801. }
  802. if (field->isAnonymousStructOrUnion()) {
  803. // Fields within an anonymous structure or union will be added via their
  804. // IndirectFieldDecls.
  805. continue;
  806. }
  807. auto field_name_id = AddIdentifierName(context, field->getName());
  808. auto [field_type_inst_id, field_type_id] =
  809. ImportTypeAndDependencies(context, import_ir_inst_id, field->getType());
  810. if (!field_type_inst_id.has_value()) {
  811. // TODO: For now, just skip over fields whose types we can't map.
  812. continue;
  813. }
  814. // Create a field now, as we know the index to use.
  815. // TODO: Consider doing this lazily instead.
  816. auto field_decl_id = AddInst(
  817. context, MakeImportedLocIdAndInst(
  818. context, import_ir_inst_id,
  819. SemIR::FieldDecl{
  820. .type_id = GetUnboundElementType(
  821. context, class_type_inst_id, field_type_inst_id),
  822. .name_id = field_name_id,
  823. .index = SemIR::ElementIndex(fields.size())}));
  824. context.sem_ir().clang_decls().Add(
  825. {.decl = decl->getCanonicalDecl(), .inst_id = field_decl_id});
  826. // Compute the offset to the field that appears directly in the class.
  827. uint64_t offset = clang_layout.getFieldOffset(
  828. cast<clang::FieldDecl>(chain.front())->getFieldIndex());
  829. // If this is an indirect field, walk the path and accumulate the offset to
  830. // the named field.
  831. for (auto* inner_decl : chain.drop_front()) {
  832. auto* inner_field = cast<clang::FieldDecl>(inner_decl);
  833. const auto& inner_layout =
  834. context.ast_context().getASTRecordLayout(inner_field->getParent());
  835. offset += inner_layout.getFieldOffset(inner_field->getFieldIndex());
  836. }
  837. layout.push_back(
  838. context.ast_context().toCharUnitsFromBits(offset).getQuantity());
  839. fields.push_back(
  840. {.name_id = field_name_id, .type_inst_id = field_type_inst_id});
  841. }
  842. // TODO: Add a field to prevent tail padding reuse if necessary.
  843. return AddTypeInst<SemIR::CustomLayoutType>(
  844. context, import_ir_inst_id,
  845. {.type_id = SemIR::TypeType::TypeId,
  846. .fields_id = context.struct_type_fields().Add(fields),
  847. .layout_id = context.custom_layouts().Add(layout)});
  848. }
  849. // Creates a class definition based on the information in the given Clang
  850. // declaration, which is assumed to be for a class definition.
  851. static auto BuildClassDefinition(Context& context,
  852. SemIR::ImportIRInstId import_ir_inst_id,
  853. SemIR::ClassId class_id,
  854. SemIR::TypeInstId class_inst_id,
  855. clang::CXXRecordDecl* clang_def) -> void {
  856. auto& class_info = context.classes().Get(class_id);
  857. CARBON_CHECK(!class_info.has_definition_started());
  858. class_info.definition_id = class_inst_id;
  859. context.inst_block_stack().Push();
  860. class_info.inheritance_kind = GetInheritanceKind(clang_def);
  861. // Compute the class's object representation.
  862. auto object_repr_id = ImportClassObjectRepr(
  863. context, class_id, import_ir_inst_id, class_inst_id, clang_def);
  864. class_info.complete_type_witness_id = AddInst<SemIR::CompleteTypeWitness>(
  865. context, import_ir_inst_id,
  866. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  867. .object_repr_type_inst_id = object_repr_id});
  868. class_info.body_block_id = context.inst_block_stack().Pop();
  869. }
  870. auto ImportCppClassDefinition(Context& context, SemIR::LocId loc_id,
  871. SemIR::ClassId class_id,
  872. SemIR::ClangDeclId clang_decl_id) -> bool {
  873. clang::ASTUnit* ast = context.sem_ir().clang_ast_unit();
  874. CARBON_CHECK(ast);
  875. auto* clang_decl = cast<clang::CXXRecordDecl>(
  876. context.sem_ir().clang_decls().Get(clang_decl_id).decl);
  877. auto class_inst_id = context.types().GetAsTypeInstId(
  878. context.classes().Get(class_id).first_owning_decl_id);
  879. // TODO: Map loc_id into a clang location and use it for diagnostics if
  880. // instantiation fails, instead of annotating the diagnostic with another
  881. // location.
  882. clang::SourceLocation loc = clang_decl->getLocation();
  883. Diagnostics::AnnotationScope annotate_diagnostics(
  884. &context.emitter(), [&](auto& builder) {
  885. CARBON_DIAGNOSTIC(InCppTypeCompletion, Note,
  886. "while completing C++ class type {0}", SemIR::TypeId);
  887. builder.Note(loc_id, InCppTypeCompletion,
  888. context.classes().Get(class_id).self_type_id);
  889. });
  890. // Ask Clang whether the type is complete. This triggers template
  891. // instantiation if necessary.
  892. clang::DiagnosticErrorTrap trap(ast->getDiagnostics());
  893. if (!ast->getSema().isCompleteType(
  894. loc, context.ast_context().getRecordType(clang_decl))) {
  895. // Type is incomplete. Nothing more to do, but tell the caller if we
  896. // produced an error.
  897. return !trap.hasErrorOccurred();
  898. }
  899. clang::CXXRecordDecl* clang_def = clang_decl->getDefinition();
  900. CARBON_CHECK(clang_def, "Complete type has no definition");
  901. if (clang_def->getNumVBases()) {
  902. // TODO: Handle virtual bases. We don't actually know where they go in the
  903. // layout. We may also want to use a different size in the layout for
  904. // `partial C`, excluding the virtual base. It's also not entirely safe to
  905. // just skip over the virtual base, as the type we would construct would
  906. // have a misleading size. For now, treat a C++ class with vbases as
  907. // incomplete in Carbon.
  908. context.TODO(loc_id, "class with virtual bases");
  909. return false;
  910. }
  911. auto import_ir_inst_id =
  912. context.insts().GetCanonicalLocId(class_inst_id).import_ir_inst_id();
  913. BuildClassDefinition(context, import_ir_inst_id, class_id, class_inst_id,
  914. clang_def);
  915. return true;
  916. }
  917. // Mark the given `Decl` as failed in `clang_decls`.
  918. static auto MarkFailedDecl(Context& context, clang::Decl* clang_decl) {
  919. context.sem_ir().clang_decls().Add({.decl = clang_decl->getCanonicalDecl(),
  920. .inst_id = SemIR::ErrorInst::InstId});
  921. }
  922. // Creates an integer type of the given size.
  923. static auto MakeIntType(Context& context, IntId size_id, bool is_signed)
  924. -> TypeExpr {
  925. auto type_inst_id = MakeIntTypeLiteral(
  926. context, Parse::NodeId::None,
  927. is_signed ? SemIR::IntKind::Signed : SemIR::IntKind::Unsigned, size_id);
  928. return ExprAsType(context, Parse::NodeId::None, type_inst_id);
  929. }
  930. // Maps a C++ builtin type to a Carbon type.
  931. // TODO: Support more builtin types.
  932. static auto MapBuiltinType(Context& context, SemIR::LocId loc_id,
  933. clang::QualType qual_type,
  934. const clang::BuiltinType& type) -> TypeExpr {
  935. clang::ASTContext& ast_context = context.ast_context();
  936. if (type.isBooleanType()) {
  937. CARBON_CHECK(ast_context.hasSameType(qual_type, ast_context.BoolTy));
  938. return ExprAsType(context, Parse::NodeId::None,
  939. context.types().GetInstId(GetSingletonType(
  940. context, SemIR::BoolType::TypeInstId)));
  941. }
  942. if (type.isInteger()) {
  943. unsigned width = context.ast_context().getIntWidth(qual_type);
  944. bool is_signed = type.isSignedInteger();
  945. auto int_n_type =
  946. context.ast_context().getIntTypeForBitwidth(width, is_signed);
  947. if (context.ast_context().hasSameType(qual_type, int_n_type)) {
  948. TypeExpr type_expr =
  949. MakeIntType(context, context.ints().Add(width), is_signed);
  950. // Try to make sure signed integer of 32 or 64 bits are complete so we can
  951. // check against them when deciding whether we need to generate a thunk.
  952. if (width == 32 || width == 64) {
  953. SemIR::TypeId type_id = type_expr.type_id;
  954. if (!context.types().IsComplete(type_id)) {
  955. TryToCompleteType(context, type_id, loc_id);
  956. }
  957. }
  958. return type_expr;
  959. }
  960. // TODO: Handle integer types that map to named aliases.
  961. } else if (type.isFloatingPoint()) {
  962. if (type.isFloat16Type() || type.isFloat32Type() || type.isDoubleType() ||
  963. type.isFloat128Type()) {
  964. return ExprAsType(
  965. context, Parse::NodeId::None,
  966. MakeFloatTypeLiteral(
  967. context, Parse::NodeId::None,
  968. context.ints().Add(ast_context.getTypeSize(qual_type))));
  969. }
  970. // TODO: Handle floating-point types that map to named aliases.
  971. }
  972. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  973. }
  974. // Maps a C++ record type to a Carbon type.
  975. static auto MapRecordType(Context& context, const clang::RecordType& type)
  976. -> TypeExpr {
  977. auto* record_decl = dyn_cast<clang::CXXRecordDecl>(type.getDecl());
  978. if (!record_decl) {
  979. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  980. }
  981. // Check if the declaration is already mapped.
  982. SemIR::InstId record_inst_id = LookupClangDeclInstId(context, record_decl);
  983. if (!record_inst_id.has_value()) {
  984. record_inst_id = ImportCXXRecordDecl(context, record_decl);
  985. }
  986. SemIR::TypeInstId record_type_inst_id =
  987. context.types().GetAsTypeInstId(record_inst_id);
  988. return {
  989. .inst_id = record_type_inst_id,
  990. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  991. }
  992. // Maps a C++ type that is not a wrapper type such as a pointer to a Carbon
  993. // type.
  994. // TODO: Support more types.
  995. static auto MapNonWrapperType(Context& context, SemIR::LocId loc_id,
  996. clang::QualType type) -> TypeExpr {
  997. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  998. return MapBuiltinType(context, loc_id, type, *builtin_type);
  999. }
  1000. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  1001. return MapRecordType(context, *record_type);
  1002. }
  1003. CARBON_CHECK(!type.hasQualifiers() && !type->isPointerType(),
  1004. "Should not see wrapper types here");
  1005. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  1006. }
  1007. // Maps a qualified C++ type to a Carbon type.
  1008. static auto MapQualifiedType(Context& context, clang::QualType type,
  1009. TypeExpr type_expr) -> TypeExpr {
  1010. auto quals = type.getQualifiers();
  1011. if (quals.hasConst()) {
  1012. auto type_id = GetConstType(context, type_expr.inst_id);
  1013. type_expr = {.inst_id = context.types().GetInstId(type_id),
  1014. .type_id = type_id};
  1015. quals.removeConst();
  1016. }
  1017. // TODO: Support other qualifiers.
  1018. if (!quals.empty()) {
  1019. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  1020. }
  1021. return type_expr;
  1022. }
  1023. // Maps a C++ pointer type to a Carbon pointer type.
  1024. static auto MapPointerType(Context& context, clang::QualType type,
  1025. TypeExpr pointee_type_expr) -> TypeExpr {
  1026. CARBON_CHECK(type->isPointerType());
  1027. if (auto nullability = type->getNullability();
  1028. !nullability.has_value() ||
  1029. *nullability != clang::NullabilityKind::NonNull) {
  1030. // TODO: Support nullable pointers.
  1031. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  1032. }
  1033. SemIR::TypeId pointer_type_id =
  1034. GetPointerType(context, pointee_type_expr.inst_id);
  1035. return {.inst_id = context.types().GetInstId(pointer_type_id),
  1036. .type_id = pointer_type_id};
  1037. }
  1038. // Maps a C++ type to a Carbon type. `type` should not be canonicalized because
  1039. // we check for pointer nullability and nullability will be lost by
  1040. // canonicalization.
  1041. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  1042. -> TypeExpr {
  1043. // Unwrap any type modifiers and wrappers.
  1044. llvm::SmallVector<clang::QualType> wrapper_types;
  1045. while (true) {
  1046. clang::QualType orig_type = type;
  1047. if (type.hasQualifiers()) {
  1048. type = type.getUnqualifiedType();
  1049. } else if (type->isPointerType()) {
  1050. type = type->getPointeeType();
  1051. } else {
  1052. break;
  1053. }
  1054. wrapper_types.push_back(orig_type);
  1055. }
  1056. auto mapped = MapNonWrapperType(context, loc_id, type);
  1057. for (auto wrapper : llvm::reverse(wrapper_types)) {
  1058. if (!mapped.inst_id.has_value() ||
  1059. mapped.type_id == SemIR::ErrorInst::TypeId) {
  1060. break;
  1061. }
  1062. if (wrapper.hasQualifiers()) {
  1063. mapped = MapQualifiedType(context, wrapper, mapped);
  1064. } else if (wrapper->isPointerType()) {
  1065. mapped = MapPointerType(context, wrapper, mapped);
  1066. } else {
  1067. CARBON_FATAL("Unexpected wrapper type {0}", wrapper.getAsString());
  1068. }
  1069. }
  1070. return mapped;
  1071. }
  1072. // Returns a block for the implicit parameters of the given function
  1073. // declaration. Because function templates are not yet supported, this currently
  1074. // only contains the `self` parameter. On error, produces a diagnostic and
  1075. // returns None.
  1076. static auto MakeImplicitParamPatternsBlockId(
  1077. Context& context, SemIR::LocId loc_id,
  1078. const clang::FunctionDecl& clang_decl) -> SemIR::InstBlockId {
  1079. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(&clang_decl);
  1080. if (!method_decl || method_decl->isStatic() ||
  1081. isa<clang::CXXConstructorDecl>(clang_decl)) {
  1082. return SemIR::InstBlockId::Empty;
  1083. }
  1084. // Build a `self` parameter from the object parameter.
  1085. BeginSubpattern(context);
  1086. // Perform some special-case mapping for the object parameter:
  1087. //
  1088. // - If it's a const reference to T, produce a by-value `self: T` parameter.
  1089. // - If it's a non-const reference to T, produce an `addr self: T*`
  1090. // parameter.
  1091. // - Otherwise, map it directly, which will currently fail for `&&`-qualified
  1092. // methods.
  1093. //
  1094. // TODO: Some of this mapping should be performed for all parameters.
  1095. clang::QualType param_type =
  1096. method_decl->getFunctionObjectParameterReferenceType();
  1097. bool addr_self = false;
  1098. if (param_type->isLValueReferenceType()) {
  1099. param_type = param_type.getNonReferenceType();
  1100. if (param_type.isConstQualified()) {
  1101. // TODO: Consider only doing this if `const` is the only qualifier. For
  1102. // now, any other qualifier will fail when mapping the type.
  1103. auto split_type = param_type.getSplitUnqualifiedType();
  1104. split_type.Quals.removeConst();
  1105. param_type = method_decl->getASTContext().getQualifiedType(split_type);
  1106. } else {
  1107. addr_self = true;
  1108. }
  1109. }
  1110. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  1111. SemIR::ExprRegionId type_expr_region_id =
  1112. EndSubpatternAsExpr(context, type_inst_id);
  1113. if (!type_id.has_value()) {
  1114. context.TODO(loc_id,
  1115. llvm::formatv("Unsupported: object parameter type: {0}",
  1116. param_type.getAsString()));
  1117. return SemIR::InstBlockId::None;
  1118. }
  1119. // TODO: Fill in a location once available.
  1120. auto pattern_id =
  1121. addr_self ? AddAddrSelfParamPattern(context, SemIR::LocId::None,
  1122. type_expr_region_id, type_inst_id)
  1123. : AddSelfParamPattern(context, SemIR::LocId::None,
  1124. type_expr_region_id, type_id);
  1125. return context.inst_blocks().Add({pattern_id});
  1126. }
  1127. // Returns a block id for the explicit parameters of the given function
  1128. // declaration. If the function declaration has no parameters, it returns
  1129. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  1130. // produces an error and returns `SemIR::InstBlockId::None`.
  1131. // TODO: Consider refactoring to extract and reuse more logic from
  1132. // `HandleAnyBindingPattern()`.
  1133. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  1134. const clang::FunctionDecl& clang_decl)
  1135. -> SemIR::InstBlockId {
  1136. if (clang_decl.parameters().empty()) {
  1137. return SemIR::InstBlockId::Empty;
  1138. }
  1139. llvm::SmallVector<SemIR::InstId> params;
  1140. params.reserve(clang_decl.getNumNonObjectParams());
  1141. for (unsigned i : llvm::seq(clang_decl.getNumNonObjectParams())) {
  1142. const auto* param = clang_decl.getNonObjectParameter(i);
  1143. // TODO: Get the parameter type from the function, not from the
  1144. // `ParmVarDecl`. The type of the `ParmVarDecl` is the type within the
  1145. // function, and isn't in general the same as the type that's exposed to
  1146. // callers. In particular, the parameter type exposed to callers will never
  1147. // be cv-qualified.
  1148. clang::QualType param_type = param->getType();
  1149. // Mark the start of a region of insts, needed for the type expression
  1150. // created later with the call of `EndSubpatternAsExpr()`.
  1151. BeginSubpattern(context);
  1152. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  1153. // Type expression of the binding pattern - a single-entry/single-exit
  1154. // region that allows control flow in the type expression e.g. fn F(x: if C
  1155. // then i32 else i64).
  1156. SemIR::ExprRegionId type_expr_region_id =
  1157. EndSubpatternAsExpr(context, type_inst_id);
  1158. if (!type_id.has_value()) {
  1159. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  1160. param_type.getAsString()));
  1161. return SemIR::InstBlockId::None;
  1162. }
  1163. llvm::StringRef param_name = param->getName();
  1164. SemIR::NameId name_id =
  1165. param_name.empty()
  1166. // Translate an unnamed parameter to an underscore to
  1167. // match Carbon's naming of unnamed/unused function params.
  1168. ? SemIR::NameId::Underscore
  1169. : AddIdentifierName(context, param_name);
  1170. // TODO: Fix this once templates are supported.
  1171. bool is_template = false;
  1172. // TODO: Fix this once generics are supported.
  1173. bool is_generic = false;
  1174. SemIR::InstId binding_pattern_id =
  1175. // TODO: Fill in a location once available.
  1176. AddBindingPattern(context, SemIR::LocId::None, name_id, type_id,
  1177. type_expr_region_id, is_generic, is_template)
  1178. .pattern_id;
  1179. SemIR::InstId var_pattern_id = AddPatternInst(
  1180. context,
  1181. // TODO: Fill in a location once available.
  1182. SemIR::LocIdAndInst::NoLoc(SemIR::ValueParamPattern(
  1183. {.type_id = context.insts().Get(binding_pattern_id).type_id(),
  1184. .subpattern_id = binding_pattern_id,
  1185. .index = SemIR::CallParamIndex::None})));
  1186. params.push_back(var_pattern_id);
  1187. }
  1188. return context.inst_blocks().Add(params);
  1189. }
  1190. // Returns the return `TypeExpr` of the given function declaration. In case of
  1191. // an unsupported return type, returns `SemIR::ErrorInst::InstId`. Constructors
  1192. // are treated as returning a class instance.
  1193. // TODO: Support more return types.
  1194. static auto GetReturnTypeExpr(Context& context, SemIR::LocId loc_id,
  1195. clang::FunctionDecl* clang_decl) -> TypeExpr {
  1196. clang::QualType ret_type = clang_decl->getReturnType();
  1197. if (!ret_type->isVoidType()) {
  1198. TypeExpr mapped_type = MapType(context, loc_id, ret_type);
  1199. if (!mapped_type.inst_id.has_value()) {
  1200. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1201. .type_id = SemIR::ErrorInst::TypeId};
  1202. }
  1203. return mapped_type;
  1204. }
  1205. if (!isa<clang::CXXConstructorDecl>(clang_decl)) {
  1206. // void.
  1207. return {.inst_id = SemIR::TypeInstId::None, .type_id = SemIR::TypeId::None};
  1208. }
  1209. // TODO: Make this a `PartialType`.
  1210. SemIR::TypeInstId record_type_inst_id = context.types().GetAsTypeInstId(
  1211. context.sem_ir()
  1212. .clang_decls()
  1213. .Get(context.sem_ir().clang_decls().Lookup(
  1214. cast<clang::Decl>(clang_decl->getParent())))
  1215. .inst_id);
  1216. return {
  1217. .inst_id = record_type_inst_id,
  1218. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  1219. }
  1220. // Returns the return pattern of the given function declaration. In case of an
  1221. // unsupported return type, it produces a diagnostic and returns
  1222. // `SemIR::ErrorInst::InstId`. Constructors are treated as returning a class
  1223. // instance.
  1224. static auto GetReturnPattern(Context& context, SemIR::LocId loc_id,
  1225. clang::FunctionDecl* clang_decl) -> SemIR::InstId {
  1226. auto [type_inst_id, type_id] = GetReturnTypeExpr(context, loc_id, clang_decl);
  1227. if (!type_inst_id.has_value()) {
  1228. // void.
  1229. return SemIR::InstId::None;
  1230. }
  1231. if (type_inst_id == SemIR::ErrorInst::TypeInstId) {
  1232. context.TODO(loc_id,
  1233. llvm::formatv("Unsupported: return type: {0}",
  1234. clang_decl->getReturnType().getAsString()));
  1235. return SemIR::ErrorInst::InstId;
  1236. }
  1237. auto pattern_type_id = GetPatternType(context, type_id);
  1238. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  1239. // TODO: Fill in a location for the return type once available.
  1240. context,
  1241. SemIR::LocIdAndInst::NoLoc(SemIR::ReturnSlotPattern(
  1242. {.type_id = pattern_type_id, .type_inst_id = type_inst_id})));
  1243. SemIR::InstId param_pattern_id = AddPatternInst(
  1244. // TODO: Fill in a location for the return type once available.
  1245. context, SemIR::LocIdAndInst::NoLoc(SemIR::OutParamPattern(
  1246. {.type_id = pattern_type_id,
  1247. .subpattern_id = return_slot_pattern_id,
  1248. .index = SemIR::CallParamIndex::None})));
  1249. return param_pattern_id;
  1250. }
  1251. namespace {
  1252. // Represents the parameter patterns block id, the return slot pattern id and
  1253. // the call parameters block id for a function declaration.
  1254. struct FunctionParamsInsts {
  1255. SemIR::InstBlockId implicit_param_patterns_id;
  1256. SemIR::InstBlockId param_patterns_id;
  1257. SemIR::InstId return_slot_pattern_id;
  1258. SemIR::InstBlockId call_params_id;
  1259. };
  1260. } // namespace
  1261. // Creates a block containing the parameter pattern instructions for the
  1262. // explicit parameters, a parameter pattern instruction for the return type and
  1263. // a block containing the call parameters of the function. Emits a callee
  1264. // pattern-match for the explicit parameter patterns and the return slot pattern
  1265. // to create the Call parameters instructions block. Currently the implicit
  1266. // parameter patterns are not taken into account. Returns the parameter patterns
  1267. // block id, the return slot pattern id, and the call parameters block id.
  1268. // Produces a diagnostic and returns `std::nullopt` if the function declaration
  1269. // has an unsupported parameter type.
  1270. static auto CreateFunctionParamsInsts(Context& context, SemIR::LocId loc_id,
  1271. clang::FunctionDecl* clang_decl)
  1272. -> std::optional<FunctionParamsInsts> {
  1273. if (isa<clang::CXXDestructorDecl>(clang_decl)) {
  1274. context.TODO(loc_id, "Unsupported: Destructor");
  1275. return std::nullopt;
  1276. }
  1277. auto implicit_param_patterns_id =
  1278. MakeImplicitParamPatternsBlockId(context, loc_id, *clang_decl);
  1279. if (!implicit_param_patterns_id.has_value()) {
  1280. return std::nullopt;
  1281. }
  1282. auto param_patterns_id =
  1283. MakeParamPatternsBlockId(context, loc_id, *clang_decl);
  1284. if (!param_patterns_id.has_value()) {
  1285. return std::nullopt;
  1286. }
  1287. auto return_slot_pattern_id = GetReturnPattern(context, loc_id, clang_decl);
  1288. if (SemIR::ErrorInst::InstId == return_slot_pattern_id) {
  1289. return std::nullopt;
  1290. }
  1291. auto call_params_id =
  1292. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  1293. return_slot_pattern_id);
  1294. return {{.implicit_param_patterns_id = implicit_param_patterns_id,
  1295. .param_patterns_id = param_patterns_id,
  1296. .return_slot_pattern_id = return_slot_pattern_id,
  1297. .call_params_id = call_params_id}};
  1298. }
  1299. // Creates a `FunctionDecl` and a `Function` without C++ thunk information.
  1300. // Returns std::nullopt on failure. The given Clang declaration is assumed to:
  1301. // * Have not been imported before.
  1302. // * Be of supported type (ignoring parameters).
  1303. static auto ImportFunction(Context& context, SemIR::LocId loc_id,
  1304. clang::FunctionDecl* clang_decl)
  1305. -> std::optional<SemIR::FunctionId> {
  1306. context.scope_stack().PushForDeclName();
  1307. context.inst_block_stack().Push();
  1308. context.pattern_block_stack().Push();
  1309. auto function_params_insts =
  1310. CreateFunctionParamsInsts(context, loc_id, clang_decl);
  1311. auto pattern_block_id = context.pattern_block_stack().Pop();
  1312. auto decl_block_id = context.inst_block_stack().Pop();
  1313. context.scope_stack().Pop();
  1314. if (!function_params_insts.has_value()) {
  1315. return std::nullopt;
  1316. }
  1317. auto function_decl = SemIR::FunctionDecl{
  1318. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  1319. auto decl_id =
  1320. AddPlaceholderInstInNoBlock(context, Parse::NodeId::None, function_decl);
  1321. context.imports().push_back(decl_id);
  1322. SemIR::NameId function_name_id =
  1323. isa<clang::CXXConstructorDecl>(clang_decl)
  1324. ? context.classes()
  1325. .Get(context.insts()
  1326. .GetAs<SemIR::ClassDecl>(LookupClangDeclInstId(
  1327. context,
  1328. cast<clang::Decl>(clang_decl->getParent())))
  1329. .class_id)
  1330. .name_id
  1331. : AddIdentifierName(context, clang_decl->getName());
  1332. auto function_info = SemIR::Function{
  1333. {.name_id = function_name_id,
  1334. .parent_scope_id = GetParentNameScopeId(context, clang_decl),
  1335. .generic_id = SemIR::GenericId::None,
  1336. .first_param_node_id = Parse::NodeId::None,
  1337. .last_param_node_id = Parse::NodeId::None,
  1338. .pattern_block_id = pattern_block_id,
  1339. .implicit_param_patterns_id =
  1340. function_params_insts->implicit_param_patterns_id,
  1341. .param_patterns_id = function_params_insts->param_patterns_id,
  1342. .is_extern = false,
  1343. .extern_library_id = SemIR::LibraryNameId::None,
  1344. .non_owning_decl_id = SemIR::InstId::None,
  1345. .first_owning_decl_id = decl_id,
  1346. .definition_id = SemIR::InstId::None},
  1347. {.call_params_id = function_params_insts->call_params_id,
  1348. .return_slot_pattern_id = function_params_insts->return_slot_pattern_id,
  1349. .virtual_modifier = SemIR::FunctionFields::VirtualModifier::None,
  1350. .self_param_id = FindSelfPattern(
  1351. context, function_params_insts->implicit_param_patterns_id),
  1352. .clang_decl_id = context.sem_ir().clang_decls().Add(
  1353. {.decl = clang_decl, .inst_id = decl_id})}};
  1354. function_decl.function_id = context.functions().Add(function_info);
  1355. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  1356. SemIR::SpecificId::None);
  1357. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  1358. return function_decl.function_id;
  1359. }
  1360. // Imports a function declaration from Clang to Carbon. If successful, returns
  1361. // the new Carbon function declaration `InstId`. If the declaration was already
  1362. // imported, returns the mapped instruction.
  1363. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  1364. clang::FunctionDecl* clang_decl)
  1365. -> SemIR::InstId {
  1366. // Check if the declaration is already mapped.
  1367. if (SemIR::InstId existing_inst_id =
  1368. LookupClangDeclInstId(context, clang_decl);
  1369. existing_inst_id.has_value()) {
  1370. return existing_inst_id;
  1371. }
  1372. if (clang_decl->isVariadic()) {
  1373. context.TODO(loc_id, "Unsupported: Variadic function");
  1374. MarkFailedDecl(context, clang_decl);
  1375. return SemIR::ErrorInst::InstId;
  1376. }
  1377. if (clang_decl->getTemplatedKind() ==
  1378. clang::FunctionDecl::TK_FunctionTemplate) {
  1379. context.TODO(loc_id, "Unsupported: Template function");
  1380. MarkFailedDecl(context, clang_decl);
  1381. return SemIR::ErrorInst::InstId;
  1382. }
  1383. if (auto* method_decl = dyn_cast<clang::CXXMethodDecl>(clang_decl)) {
  1384. if (method_decl->isVirtual()) {
  1385. context.TODO(loc_id, "Unsupported: Virtual function");
  1386. MarkFailedDecl(context, clang_decl);
  1387. return SemIR::ErrorInst::InstId;
  1388. }
  1389. }
  1390. CARBON_CHECK(clang_decl->getFunctionType()->isFunctionProtoType(),
  1391. "Not Prototype function (non-C++ code)");
  1392. auto function_id = ImportFunction(context, loc_id, clang_decl);
  1393. if (!function_id) {
  1394. MarkFailedDecl(context, clang_decl);
  1395. return SemIR::ErrorInst::InstId;
  1396. }
  1397. SemIR::Function& function_info = context.functions().Get(*function_id);
  1398. if (IsCppThunkRequired(context, function_info)) {
  1399. clang::FunctionDecl* thunk_clang_decl =
  1400. BuildCppThunk(context, function_info);
  1401. if (thunk_clang_decl) {
  1402. SemIR::FunctionId thunk_function_id =
  1403. *ImportFunction(context, loc_id, thunk_clang_decl);
  1404. SemIR::InstId thunk_function_decl_id =
  1405. context.functions().Get(thunk_function_id).first_owning_decl_id;
  1406. function_info.SetHasCppThunk(thunk_function_decl_id);
  1407. }
  1408. }
  1409. return function_info.first_owning_decl_id;
  1410. }
  1411. namespace {
  1412. // An item to be imported in an import worklist.
  1413. // TODO: If worklists ever become particularly large, consider changing this
  1414. // to use a `PointerIntPair`.
  1415. struct ImportItem {
  1416. // A declaration that we want to import.
  1417. clang::Decl* decl;
  1418. // Whether we have added `decl`'s dependencies to the worklist.
  1419. bool added_dependencies;
  1420. };
  1421. // A worklist of declarations to import.
  1422. using ImportWorklist = llvm::SmallVector<ImportItem>;
  1423. } // namespace
  1424. // Adds the given declaration to our list of declarations to import.
  1425. static auto AddDependentDecl(const Context& context, clang::Decl* decl,
  1426. ImportWorklist& worklist) -> void {
  1427. if (!IsClangDeclImported(context, decl)) {
  1428. worklist.push_back({.decl = decl, .added_dependencies = false});
  1429. }
  1430. }
  1431. // Finds all decls that need to be imported before importing the given type and
  1432. // adds them to the given set.
  1433. static auto AddDependentUnimportedTypeDecls(const Context& context,
  1434. clang::QualType type,
  1435. ImportWorklist& worklist) -> void {
  1436. while (true) {
  1437. if (type->isPointerType() || type->isReferenceType()) {
  1438. type = type->getPointeeType();
  1439. } else if (const clang::ArrayType* array_type =
  1440. type->getAsArrayTypeUnsafe()) {
  1441. type = array_type->getElementType();
  1442. } else {
  1443. break;
  1444. }
  1445. }
  1446. if (const auto* record_type = type->getAs<clang::RecordType>()) {
  1447. AddDependentDecl(context, record_type->getDecl(), worklist);
  1448. }
  1449. }
  1450. // Finds all decls that need to be imported before importing the given function
  1451. // and adds them to the given set.
  1452. static auto AddDependentUnimportedFunctionDecls(
  1453. const Context& context, const clang::FunctionDecl& clang_decl,
  1454. ImportWorklist& worklist) -> void {
  1455. for (const auto* param : clang_decl.parameters()) {
  1456. AddDependentUnimportedTypeDecls(context, param->getType(), worklist);
  1457. }
  1458. AddDependentUnimportedTypeDecls(context, clang_decl.getReturnType(),
  1459. worklist);
  1460. }
  1461. // Finds all decls that need to be imported before importing the given
  1462. // declaration and adds them to the given set.
  1463. static auto AddDependentUnimportedDecls(const Context& context,
  1464. clang::Decl* clang_decl,
  1465. ImportWorklist& worklist) -> void {
  1466. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1467. AddDependentUnimportedFunctionDecls(context, *clang_function_decl,
  1468. worklist);
  1469. } else if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1470. if (!isa<clang::RecordDecl>(clang_decl)) {
  1471. AddDependentUnimportedTypeDecls(
  1472. context, type_decl->getASTContext().getTypeDeclType(type_decl),
  1473. worklist);
  1474. }
  1475. }
  1476. if (!isa<clang::TranslationUnitDecl>(clang_decl)) {
  1477. AddDependentDecl(context, GetParentDecl(clang_decl), worklist);
  1478. }
  1479. }
  1480. // Imports a declaration from Clang to Carbon. Returns the instruction for the
  1481. // new Carbon declaration, which will be an ErrorInst on failure. Assumes all
  1482. // dependencies have already been imported.
  1483. static auto ImportDeclAfterDependencies(Context& context, SemIR::LocId loc_id,
  1484. clang::Decl* clang_decl)
  1485. -> SemIR::InstId {
  1486. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1487. return ImportFunctionDecl(context, loc_id, clang_function_decl);
  1488. }
  1489. if (auto* clang_namespace_decl = dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  1490. return ImportNamespaceDecl(context, clang_namespace_decl);
  1491. }
  1492. if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1493. auto type = clang_decl->getASTContext().getTypeDeclType(type_decl);
  1494. auto type_inst_id = MapType(context, loc_id, type).inst_id;
  1495. if (!type_inst_id.has_value()) {
  1496. context.TODO(AddImportIRInst(context.sem_ir(), type_decl->getLocation()),
  1497. llvm::formatv("Unsupported: Type declaration: {0}",
  1498. type.getAsString()));
  1499. return SemIR::ErrorInst::InstId;
  1500. }
  1501. context.sem_ir().clang_decls().Add(
  1502. {.decl = clang_decl, .inst_id = type_inst_id});
  1503. return type_inst_id;
  1504. }
  1505. if (isa<clang::FieldDecl, clang::IndirectFieldDecl>(clang_decl)) {
  1506. // Usable fields get imported as a side effect of importing the class.
  1507. if (SemIR::InstId existing_inst_id =
  1508. LookupClangDeclInstId(context, clang_decl);
  1509. existing_inst_id.has_value()) {
  1510. return existing_inst_id;
  1511. }
  1512. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1513. "Unsupported: field declaration has unhandled type or kind");
  1514. return SemIR::ErrorInst::InstId;
  1515. }
  1516. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1517. llvm::formatv("Unsupported: Declaration type {0}",
  1518. clang_decl->getDeclKindName()));
  1519. return SemIR::ErrorInst::InstId;
  1520. }
  1521. // Attempts to import a set of declarations. Returns `false` if an error was
  1522. // produced, `true` otherwise.
  1523. static auto ImportDeclSet(Context& context, SemIR::LocId loc_id,
  1524. ImportWorklist& worklist) -> bool {
  1525. // Walk the dependency graph in depth-first order, and import declarations
  1526. // once we've imported all of their dependencies.
  1527. while (!worklist.empty()) {
  1528. auto& item = worklist.back();
  1529. if (!item.added_dependencies) {
  1530. // Skip items we've already imported. We checked this when initially
  1531. // adding the item to the worklist, but it might have been added to the
  1532. // worklist twice before the first time we visited it. For example, this
  1533. // happens for `fn F(a: Cpp.T, b: Cpp.T)`.
  1534. if (IsClangDeclImported(context, item.decl)) {
  1535. worklist.pop_back();
  1536. continue;
  1537. }
  1538. // First time visiting this declaration (preorder): add its dependencies
  1539. // to the work list.
  1540. item.added_dependencies = true;
  1541. AddDependentUnimportedDecls(context, item.decl, worklist);
  1542. } else {
  1543. // Second time visiting this declaration (postorder): its dependencies are
  1544. // already imported, so we can import it now.
  1545. auto* decl = worklist.pop_back_val().decl;
  1546. auto inst_id = ImportDeclAfterDependencies(context, loc_id, decl);
  1547. CARBON_CHECK(inst_id.has_value());
  1548. if (inst_id == SemIR::ErrorInst::InstId) {
  1549. return false;
  1550. }
  1551. CARBON_CHECK(IsClangDeclImported(context, decl));
  1552. }
  1553. }
  1554. return true;
  1555. }
  1556. // Imports a declaration from Clang to Carbon. If successful, returns the
  1557. // instruction for the new Carbon declaration. All unimported dependencies are
  1558. // imported first.
  1559. static auto ImportDeclAndDependencies(Context& context, SemIR::LocId loc_id,
  1560. clang::Decl* clang_decl)
  1561. -> SemIR::InstId {
  1562. // Collect dependencies by walking the dependency graph in depth-first order.
  1563. ImportWorklist worklist;
  1564. AddDependentDecl(context, clang_decl, worklist);
  1565. if (!ImportDeclSet(context, loc_id, worklist)) {
  1566. return SemIR::ErrorInst::InstId;
  1567. }
  1568. return LookupClangDeclInstId(context, clang_decl);
  1569. }
  1570. // Imports a type from Clang to Carbon. If successful, returns the imported
  1571. // TypeId. All unimported dependencies are imported first.
  1572. static auto ImportTypeAndDependencies(Context& context, SemIR::LocId loc_id,
  1573. clang::QualType type) -> TypeExpr {
  1574. // Collect dependencies by walking the dependency graph in depth-first order.
  1575. ImportWorklist worklist;
  1576. AddDependentUnimportedTypeDecls(context, type, worklist);
  1577. if (!ImportDeclSet(context, loc_id, worklist)) {
  1578. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1579. .type_id = SemIR::ErrorInst::TypeId};
  1580. }
  1581. return MapType(context, loc_id, type);
  1582. }
  1583. // Maps `clang::AccessSpecifier` to `SemIR::AccessKind`.
  1584. static auto MapAccess(clang::AccessSpecifier access_specifier)
  1585. -> SemIR::AccessKind {
  1586. switch (access_specifier) {
  1587. case clang::AS_public:
  1588. case clang::AS_none:
  1589. return SemIR::AccessKind::Public;
  1590. case clang::AS_protected:
  1591. return SemIR::AccessKind::Protected;
  1592. case clang::AS_private:
  1593. return SemIR::AccessKind::Private;
  1594. }
  1595. }
  1596. // Imports a `clang::NamedDecl` into Carbon and adds that name into the
  1597. // `NameScope`.
  1598. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  1599. SemIR::NameScopeId scope_id,
  1600. SemIR::NameId name_id,
  1601. clang::NamedDecl* clang_decl,
  1602. clang::AccessSpecifier access)
  1603. -> SemIR::ScopeLookupResult {
  1604. SemIR::InstId inst_id =
  1605. ImportDeclAndDependencies(context, loc_id, clang_decl);
  1606. if (!inst_id.has_value()) {
  1607. return SemIR::ScopeLookupResult::MakeNotFound();
  1608. }
  1609. SemIR::AccessKind access_kind = MapAccess(access);
  1610. AddNameToScope(context, scope_id, name_id, access_kind, inst_id);
  1611. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  1612. access_kind);
  1613. }
  1614. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  1615. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  1616. -> SemIR::ScopeLookupResult {
  1617. Diagnostics::AnnotationScope annotate_diagnostics(
  1618. &context.emitter(), [&](auto& builder) {
  1619. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  1620. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  1621. builder.Note(loc_id, InCppNameLookup, name_id);
  1622. });
  1623. auto decl_and_access = ClangLookup(context, loc_id, scope_id, name_id);
  1624. if (!decl_and_access) {
  1625. return SemIR::ScopeLookupResult::MakeNotFound();
  1626. }
  1627. auto [decl, access] = *decl_and_access;
  1628. if (!decl) {
  1629. context.name_scopes().AddRequiredName(scope_id, name_id,
  1630. SemIR::ErrorInst::InstId);
  1631. return SemIR::ScopeLookupResult::MakeError();
  1632. }
  1633. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id, decl,
  1634. access);
  1635. }
  1636. } // namespace Carbon::Check