import_cpp.cpp 78 KB

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