import_cpp.cpp 73 KB

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