import_cpp.cpp 85 KB

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