import.cpp 102 KB

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