import.cpp 100 KB

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