import.cpp 90 KB

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