import.cpp 96 KB

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