import.cpp 94 KB

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