import_cpp.cpp 79 KB

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