import.cpp 103 KB

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