import.cpp 99 KB

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