1//===--- CompilerInstance.cpp ---------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "clang/Frontend/CompilerInstance.h"
10#include "clang/AST/ASTConsumer.h"
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Decl.h"
13#include "clang/Basic/CharInfo.h"
14#include "clang/Basic/Diagnostic.h"
15#include "clang/Basic/DiagnosticFrontend.h"
16#include "clang/Basic/DiagnosticOptions.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Basic/LangStandard.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/Stack.h"
21#include "clang/Basic/TargetInfo.h"
22#include "clang/Basic/Version.h"
23#include "clang/Config/config.h"
24#include "clang/Frontend/ChainedDiagnosticConsumer.h"
25#include "clang/Frontend/FrontendAction.h"
26#include "clang/Frontend/FrontendActions.h"
27#include "clang/Frontend/FrontendPluginRegistry.h"
28#include "clang/Frontend/LogDiagnosticPrinter.h"
29#include "clang/Frontend/SARIFDiagnosticPrinter.h"
30#include "clang/Frontend/SerializedDiagnosticPrinter.h"
31#include "clang/Frontend/TextDiagnosticPrinter.h"
32#include "clang/Frontend/Utils.h"
33#include "clang/Frontend/VerifyDiagnosticConsumer.h"
34#include "clang/Lex/HeaderSearch.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Lex/PreprocessorOptions.h"
37#include "clang/Sema/CodeCompleteConsumer.h"
38#include "clang/Sema/ParsedAttr.h"
39#include "clang/Sema/Sema.h"
40#include "clang/Serialization/ASTReader.h"
41#include "clang/Serialization/GlobalModuleIndex.h"
42#include "clang/Serialization/InMemoryModuleCache.h"
43#include "clang/Serialization/ModuleCache.h"
44#include "clang/Serialization/SerializationDiagnostic.h"
45#include "llvm/ADT/IntrusiveRefCntPtr.h"
46#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/ScopeExit.h"
48#include "llvm/ADT/Statistic.h"
49#include "llvm/Config/llvm-config.h"
50#include "llvm/Plugins/PassPlugin.h"
51#include "llvm/Support/AdvisoryLock.h"
52#include "llvm/Support/BuryPointer.h"
53#include "llvm/Support/CrashRecoveryContext.h"
54#include "llvm/Support/Errc.h"
55#include "llvm/Support/FileSystem.h"
56#include "llvm/Support/MemoryBuffer.h"
57#include "llvm/Support/Path.h"
58#include "llvm/Support/Signals.h"
59#include "llvm/Support/TimeProfiler.h"
60#include "llvm/Support/Timer.h"
61#include "llvm/Support/VirtualFileSystem.h"
62#include "llvm/Support/VirtualOutputBackends.h"
63#include "llvm/Support/VirtualOutputError.h"
64#include "llvm/Support/raw_ostream.h"
65#include "llvm/TargetParser/Host.h"
66#include <optional>
67#include <time.h>
68#include <utility>
69
70using namespace clang;
71
72CompilerInstance::CompilerInstance(
73 std::shared_ptr<CompilerInvocation> Invocation,
74 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
75 std::shared_ptr<ModuleCache> ModCache)
76 : ModuleLoader(/*BuildingModule=*/ModCache != nullptr),
77 Invocation(std::move(Invocation)),
78 ModCache(ModCache ? std::move(ModCache)
79 : createCrossProcessModuleCache()),
80 ThePCHContainerOperations(std::move(PCHContainerOps)) {
81 assert(this->Invocation && "Invocation must not be null");
82}
83
84CompilerInstance::~CompilerInstance() {
85 assert(OutputFiles.empty() && "Still output files in flight?");
86}
87
88bool CompilerInstance::shouldBuildGlobalModuleIndex() const {
89 return (BuildGlobalModuleIndex ||
90 (TheASTReader && TheASTReader->isGlobalIndexUnavailable() &&
91 getFrontendOpts().GenerateGlobalModuleIndex)) &&
92 !DisableGeneratingGlobalModuleIndex;
93}
94
95void CompilerInstance::setDiagnostics(
96 llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Value) {
97 Diagnostics = std::move(Value);
98}
99
100void CompilerInstance::setVerboseOutputStream(raw_ostream &Value) {
101 OwnedVerboseOutputStream.reset();
102 VerboseOutputStream = &Value;
103}
104
105void CompilerInstance::setVerboseOutputStream(std::unique_ptr<raw_ostream> Value) {
106 OwnedVerboseOutputStream.swap(u&: Value);
107 VerboseOutputStream = OwnedVerboseOutputStream.get();
108}
109
110void CompilerInstance::setTarget(TargetInfo *Value) { Target = Value; }
111void CompilerInstance::setAuxTarget(TargetInfo *Value) { AuxTarget = Value; }
112
113bool CompilerInstance::createTarget() {
114 // Create the target instance.
115 setTarget(TargetInfo::CreateTargetInfo(Diags&: getDiagnostics(),
116 Opts&: getInvocation().getTargetOpts()));
117 if (!hasTarget())
118 return false;
119
120 // Check whether AuxTarget exists, if not, then create TargetInfo for the
121 // other side of CUDA/OpenMP/SYCL compilation.
122 if (!getAuxTarget() &&
123 (getLangOpts().CUDA || getLangOpts().isTargetDevice()) &&
124 !getFrontendOpts().AuxTriple.empty()) {
125 auto &TO = AuxTargetOpts = std::make_unique<TargetOptions>();
126 TO->Triple = llvm::Triple::normalize(Str: getFrontendOpts().AuxTriple);
127 if (getFrontendOpts().AuxTargetCPU)
128 TO->CPU = *getFrontendOpts().AuxTargetCPU;
129 if (getFrontendOpts().AuxTargetFeatures)
130 TO->FeaturesAsWritten = *getFrontendOpts().AuxTargetFeatures;
131 TO->HostTriple = getTarget().getTriple().str();
132 setAuxTarget(TargetInfo::CreateTargetInfo(Diags&: getDiagnostics(), Opts&: *TO));
133 }
134
135 if (!getTarget().hasStrictFP() && !getLangOpts().ExpStrictFP) {
136 if (getLangOpts().RoundingMath) {
137 getDiagnostics().Report(DiagID: diag::warn_fe_backend_unsupported_fp_rounding);
138 getLangOpts().RoundingMath = false;
139 }
140 auto FPExc = getLangOpts().getFPExceptionMode();
141 if (FPExc != LangOptions::FPE_Default && FPExc != LangOptions::FPE_Ignore) {
142 getDiagnostics().Report(DiagID: diag::warn_fe_backend_unsupported_fp_exceptions);
143 getLangOpts().setFPExceptionMode(LangOptions::FPE_Ignore);
144 }
145 // FIXME: can we disable FEnvAccess?
146 }
147
148 // We should do it here because target knows nothing about
149 // language options when it's being created.
150 if (getLangOpts().OpenCL &&
151 !getTarget().validateOpenCLTarget(Opts: getLangOpts(), Diags&: getDiagnostics()))
152 return false;
153
154 // Inform the target of the language options.
155 // FIXME: We shouldn't need to do this, the target should be immutable once
156 // created. This complexity should be lifted elsewhere.
157 getTarget().adjust(Diags&: getDiagnostics(), Opts&: getLangOpts(), Aux: getAuxTarget());
158
159 if (auto *Aux = getAuxTarget())
160 getTarget().setAuxTarget(Aux);
161
162 return true;
163}
164
165void CompilerInstance::setFileManager(IntrusiveRefCntPtr<FileManager> Value) {
166 assert(Value == nullptr ||
167 getVirtualFileSystemPtr() == Value->getVirtualFileSystemPtr());
168 FileMgr = std::move(Value);
169}
170
171void CompilerInstance::setSourceManager(
172 llvm::IntrusiveRefCntPtr<SourceManager> Value) {
173 SourceMgr = std::move(Value);
174}
175
176void CompilerInstance::setPreprocessor(std::shared_ptr<Preprocessor> Value) {
177 PP = std::move(Value);
178}
179
180void CompilerInstance::setASTContext(
181 llvm::IntrusiveRefCntPtr<ASTContext> Value) {
182 Context = std::move(Value);
183
184 if (Context && Consumer)
185 getASTConsumer().Initialize(Context&: getASTContext());
186}
187
188void CompilerInstance::setSema(Sema *S) {
189 TheSema.reset(p: S);
190}
191
192void CompilerInstance::setASTConsumer(std::unique_ptr<ASTConsumer> Value) {
193 Consumer = std::move(Value);
194
195 if (Context && Consumer)
196 getASTConsumer().Initialize(Context&: getASTContext());
197}
198
199void CompilerInstance::setCodeCompletionConsumer(CodeCompleteConsumer *Value) {
200 CompletionConsumer.reset(p: Value);
201}
202
203std::unique_ptr<Sema> CompilerInstance::takeSema() {
204 return std::move(TheSema);
205}
206
207IntrusiveRefCntPtr<ASTReader> CompilerInstance::getASTReader() const {
208 return TheASTReader;
209}
210void CompilerInstance::setASTReader(IntrusiveRefCntPtr<ASTReader> Reader) {
211 assert(ModCache.get() == &Reader->getModuleManager().getModuleCache() &&
212 "Expected ASTReader to use the same PCM cache");
213 TheASTReader = std::move(Reader);
214}
215
216std::shared_ptr<ModuleDependencyCollector>
217CompilerInstance::getModuleDepCollector() const {
218 return ModuleDepCollector;
219}
220
221void CompilerInstance::setModuleDepCollector(
222 std::shared_ptr<ModuleDependencyCollector> Collector) {
223 ModuleDepCollector = std::move(Collector);
224}
225
226static void collectHeaderMaps(const HeaderSearch &HS,
227 std::shared_ptr<ModuleDependencyCollector> MDC) {
228 SmallVector<std::string, 4> HeaderMapFileNames;
229 HS.getHeaderMapFileNames(Names&: HeaderMapFileNames);
230 for (auto &Name : HeaderMapFileNames)
231 MDC->addFile(Filename: Name);
232}
233
234static void collectIncludePCH(CompilerInstance &CI,
235 std::shared_ptr<ModuleDependencyCollector> MDC) {
236 const PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
237 if (PPOpts.ImplicitPCHInclude.empty())
238 return;
239
240 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
241 FileManager &FileMgr = CI.getFileManager();
242 auto PCHDir = FileMgr.getOptionalDirectoryRef(DirName: PCHInclude);
243 if (!PCHDir) {
244 MDC->addFile(Filename: PCHInclude);
245 return;
246 }
247
248 std::error_code EC;
249 SmallString<128> DirNative;
250 llvm::sys::path::native(path: PCHDir->getName(), result&: DirNative);
251 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
252 SimpleASTReaderListener Validator(CI.getPreprocessor());
253 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(Dir: DirNative, EC), DirEnd;
254 Dir != DirEnd && !EC; Dir.increment(EC)) {
255 // Check whether this is an AST file. ASTReader::isAcceptableASTFile is not
256 // used here since we're not interested in validating the PCH at this time,
257 // but only to check whether this is a file containing an AST.
258 if (!ASTReader::readASTFileControlBlock(
259 Filename: Dir->path(), FileMgr, ModCache: CI.getModuleCache(),
260 PCHContainerRdr: CI.getPCHContainerReader(),
261 /*FindModuleFileExtensions=*/false, Listener&: Validator,
262 /*ValidateDiagnosticOptions=*/false))
263 MDC->addFile(Filename: Dir->path());
264 }
265}
266
267static void collectVFSEntries(CompilerInstance &CI,
268 std::shared_ptr<ModuleDependencyCollector> MDC) {
269 // Collect all VFS found.
270 SmallVector<llvm::vfs::YAMLVFSEntry, 16> VFSEntries;
271 CI.getVirtualFileSystem().visit(Callback: [&](llvm::vfs::FileSystem &VFS) {
272 if (auto *RedirectingVFS = dyn_cast<llvm::vfs::RedirectingFileSystem>(Val: &VFS))
273 llvm::vfs::collectVFSEntries(VFS&: *RedirectingVFS, CollectedEntries&: VFSEntries);
274 });
275
276 for (auto &E : VFSEntries)
277 MDC->addFile(Filename: E.VPath, FileDst: E.RPath);
278}
279
280void CompilerInstance::createVirtualFileSystem(
281 IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS, DiagnosticConsumer *DC) {
282 DiagnosticOptions DiagOpts;
283 DiagnosticsEngine Diags(DiagnosticIDs::create(), DiagOpts, DC,
284 /*ShouldOwnClient=*/false);
285
286 VFS = createVFSFromCompilerInvocation(CI: getInvocation(), Diags,
287 BaseFS: std::move(BaseFS));
288 // FIXME: Should this go into createVFSFromCompilerInvocation?
289 if (getFrontendOpts().ShowStats)
290 VFS =
291 llvm::makeIntrusiveRefCnt<llvm::vfs::TracingFileSystem>(A: std::move(VFS));
292}
293
294// Diagnostics
295static void SetUpDiagnosticLog(DiagnosticOptions &DiagOpts,
296 const CodeGenOptions *CodeGenOpts,
297 DiagnosticsEngine &Diags) {
298 std::error_code EC;
299 std::unique_ptr<raw_ostream> StreamOwner;
300 raw_ostream *OS = &llvm::errs();
301 if (DiagOpts.DiagnosticLogFile != "-") {
302 // Create the output stream.
303 auto FileOS = std::make_unique<llvm::raw_fd_ostream>(
304 args&: DiagOpts.DiagnosticLogFile, args&: EC,
305 args: llvm::sys::fs::OF_Append | llvm::sys::fs::OF_TextWithCRLF);
306 if (EC) {
307 Diags.Report(DiagID: diag::warn_fe_cc_log_diagnostics_failure)
308 << DiagOpts.DiagnosticLogFile << EC.message();
309 } else {
310 FileOS->SetUnbuffered();
311 OS = FileOS.get();
312 StreamOwner = std::move(FileOS);
313 }
314 }
315
316 // Chain in the diagnostic client which will log the diagnostics.
317 auto Logger = std::make_unique<LogDiagnosticPrinter>(args&: *OS, args&: DiagOpts,
318 args: std::move(StreamOwner));
319 if (CodeGenOpts)
320 Logger->setDwarfDebugFlags(CodeGenOpts->DwarfDebugFlags);
321 if (Diags.ownsClient()) {
322 Diags.setClient(
323 client: new ChainedDiagnosticConsumer(Diags.takeClient(), std::move(Logger)));
324 } else {
325 Diags.setClient(
326 client: new ChainedDiagnosticConsumer(Diags.getClient(), std::move(Logger)));
327 }
328}
329
330static void SetupSerializedDiagnostics(DiagnosticOptions &DiagOpts,
331 DiagnosticsEngine &Diags,
332 StringRef OutputFile) {
333 auto SerializedConsumer =
334 clang::serialized_diags::create(OutputFile, DiagOpts);
335
336 if (Diags.ownsClient()) {
337 Diags.setClient(client: new ChainedDiagnosticConsumer(
338 Diags.takeClient(), std::move(SerializedConsumer)));
339 } else {
340 Diags.setClient(client: new ChainedDiagnosticConsumer(
341 Diags.getClient(), std::move(SerializedConsumer)));
342 }
343}
344
345void CompilerInstance::createDiagnostics(DiagnosticConsumer *Client,
346 bool ShouldOwnClient) {
347 Diagnostics = createDiagnostics(VFS&: getVirtualFileSystem(), Opts&: getDiagnosticOpts(),
348 Client, ShouldOwnClient, CodeGenOpts: &getCodeGenOpts());
349}
350
351IntrusiveRefCntPtr<DiagnosticsEngine> CompilerInstance::createDiagnostics(
352 llvm::vfs::FileSystem &VFS, DiagnosticOptions &Opts,
353 DiagnosticConsumer *Client, bool ShouldOwnClient,
354 const CodeGenOptions *CodeGenOpts) {
355 auto Diags = llvm::makeIntrusiveRefCnt<DiagnosticsEngine>(
356 A: DiagnosticIDs::create(), A&: Opts);
357
358 // Create the diagnostic client for reporting errors or for
359 // implementing -verify.
360 if (Client) {
361 Diags->setClient(client: Client, ShouldOwnClient);
362 } else if (Opts.getFormat() == DiagnosticOptions::SARIF) {
363 Diags->setClient(client: new SARIFDiagnosticPrinter(llvm::errs(), Opts));
364 } else
365 Diags->setClient(client: new TextDiagnosticPrinter(llvm::errs(), Opts));
366
367 // Chain in -verify checker, if requested.
368 if (Opts.VerifyDiagnostics)
369 Diags->setClient(client: new VerifyDiagnosticConsumer(*Diags));
370
371 // Chain in -diagnostic-log-file dumper, if requested.
372 if (!Opts.DiagnosticLogFile.empty())
373 SetUpDiagnosticLog(DiagOpts&: Opts, CodeGenOpts, Diags&: *Diags);
374
375 if (!Opts.DiagnosticSerializationFile.empty())
376 SetupSerializedDiagnostics(DiagOpts&: Opts, Diags&: *Diags, OutputFile: Opts.DiagnosticSerializationFile);
377
378 // Configure our handling of diagnostics.
379 ProcessWarningOptions(Diags&: *Diags, Opts, VFS);
380
381 return Diags;
382}
383
384// File Manager
385
386void CompilerInstance::createFileManager() {
387 assert(VFS && "CompilerInstance needs a VFS for creating FileManager");
388 FileMgr = llvm::makeIntrusiveRefCnt<FileManager>(A&: getFileSystemOpts(), A&: VFS);
389}
390
391// Source Manager
392
393void CompilerInstance::createSourceManager() {
394 assert(Diagnostics && "DiagnosticsEngine needed for creating SourceManager");
395 assert(FileMgr && "FileManager needed for creating SourceManager");
396 SourceMgr = llvm::makeIntrusiveRefCnt<SourceManager>(A&: getDiagnostics(),
397 A&: getFileManager());
398}
399
400// Initialize the remapping of files to alternative contents, e.g.,
401// those specified through other files.
402static void InitializeFileRemapping(DiagnosticsEngine &Diags,
403 SourceManager &SourceMgr,
404 FileManager &FileMgr,
405 const PreprocessorOptions &InitOpts) {
406 // Remap files in the source manager (with buffers).
407 for (const auto &RB : InitOpts.RemappedFileBuffers) {
408 // Create the file entry for the file that we're mapping from.
409 FileEntryRef FromFile =
410 FileMgr.getVirtualFileRef(Filename: RB.first, Size: RB.second->getBufferSize(), ModificationTime: 0);
411
412 // Override the contents of the "from" file with the contents of the
413 // "to" file. If the caller owns the buffers, then pass a MemoryBufferRef;
414 // otherwise, pass as a std::unique_ptr<MemoryBuffer> to transfer ownership
415 // to the SourceManager.
416 if (InitOpts.RetainRemappedFileBuffers)
417 SourceMgr.overrideFileContents(SourceFile: FromFile, Buffer: RB.second->getMemBufferRef());
418 else
419 SourceMgr.overrideFileContents(
420 SourceFile: FromFile, Buffer: std::unique_ptr<llvm::MemoryBuffer>(RB.second));
421 }
422
423 // Remap files in the source manager (with other files).
424 for (const auto &RF : InitOpts.RemappedFiles) {
425 // Find the file that we're mapping to.
426 OptionalFileEntryRef ToFile = FileMgr.getOptionalFileRef(Filename: RF.second);
427 if (!ToFile) {
428 Diags.Report(DiagID: diag::err_fe_remap_missing_to_file) << RF.first << RF.second;
429 continue;
430 }
431
432 // Create the file entry for the file that we're mapping from.
433 FileEntryRef FromFile =
434 FileMgr.getVirtualFileRef(Filename: RF.first, Size: ToFile->getSize(), ModificationTime: 0);
435
436 // Override the contents of the "from" file with the contents of
437 // the "to" file.
438 SourceMgr.overrideFileContents(SourceFile: FromFile, NewFile: *ToFile);
439 }
440
441 SourceMgr.setOverridenFilesKeepOriginalName(
442 InitOpts.RemappedFilesKeepOriginalName);
443}
444
445// Preprocessor
446
447void CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
448 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
449
450 // The AST reader holds a reference to the old preprocessor (if any).
451 TheASTReader.reset();
452
453 // Create the Preprocessor.
454 HeaderSearch *HeaderInfo =
455 new HeaderSearch(getHeaderSearchOpts(), getSourceManager(),
456 getDiagnostics(), getLangOpts(), &getTarget());
457 PP = std::make_shared<Preprocessor>(args&: Invocation->getPreprocessorOpts(),
458 args&: getDiagnostics(), args&: getLangOpts(),
459 args&: getSourceManager(), args&: *HeaderInfo, args&: *this,
460 /*IdentifierInfoLookup=*/args: nullptr,
461 /*OwnsHeaderSearch=*/args: true, args&: TUKind);
462 getTarget().adjust(Diags&: getDiagnostics(), Opts&: getLangOpts(), Aux: getAuxTarget());
463 PP->Initialize(Target: getTarget(), AuxTarget: getAuxTarget());
464
465 if (PPOpts.DetailedRecord)
466 PP->createPreprocessingRecord();
467
468 // Apply remappings to the source manager.
469 InitializeFileRemapping(Diags&: PP->getDiagnostics(), SourceMgr&: PP->getSourceManager(),
470 FileMgr&: PP->getFileManager(), InitOpts: PPOpts);
471
472 // Predefine macros and configure the preprocessor.
473 InitializePreprocessor(PP&: *PP, PPOpts, PCHContainerRdr: getPCHContainerReader(),
474 FEOpts: getFrontendOpts(), CodeGenOpts: getCodeGenOpts());
475
476 // Initialize the header search object. In CUDA compilations, we use the aux
477 // triple (the host triple) to initialize our header search, since we need to
478 // find the host headers in order to compile the CUDA code.
479 const llvm::Triple *HeaderSearchTriple = &PP->getTargetInfo().getTriple();
480 if (PP->getTargetInfo().getTriple().getOS() == llvm::Triple::CUDA &&
481 PP->getAuxTargetInfo())
482 HeaderSearchTriple = &PP->getAuxTargetInfo()->getTriple();
483
484 ApplyHeaderSearchOptions(HS&: PP->getHeaderSearchInfo(), HSOpts: getHeaderSearchOpts(),
485 Lang: PP->getLangOpts(), triple: *HeaderSearchTriple);
486
487 PP->setPreprocessedOutput(getPreprocessorOutputOpts().ShowCPP);
488
489 if (PP->getLangOpts().Modules && PP->getLangOpts().ImplicitModules) {
490 // FIXME: We already might've computed the context hash and the specific
491 // module cache path in `FrontendAction::BeginSourceFile()` when turning
492 // "-include-pch <DIR>" into "-include-pch <DIR>/<FILE>". Reuse those here.
493 PP->getHeaderSearchInfo().initializeModuleCachePath(
494 ContextHash: getInvocation().computeContextHash());
495 }
496
497 // Handle generating dependencies, if requested.
498 const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
499 if (!DepOpts.OutputFile.empty())
500 addDependencyCollector(Listener: std::make_shared<DependencyFileGenerator>(args: DepOpts));
501 if (!DepOpts.DOTOutputFile.empty())
502 AttachDependencyGraphGen(PP&: *PP, OutputFile: DepOpts.DOTOutputFile,
503 SysRoot: getHeaderSearchOpts().Sysroot);
504
505 // If we don't have a collector, but we are collecting module dependencies,
506 // then we're the top level compiler instance and need to create one.
507 if (!ModuleDepCollector && !DepOpts.ModuleDependencyOutputDir.empty()) {
508 ModuleDepCollector = std::make_shared<ModuleDependencyCollector>(
509 args: DepOpts.ModuleDependencyOutputDir, args: getVirtualFileSystemPtr());
510 }
511
512 // If there is a module dep collector, register with other dep collectors
513 // and also (a) collect header maps and (b) TODO: input vfs overlay files.
514 if (ModuleDepCollector) {
515 addDependencyCollector(Listener: ModuleDepCollector);
516 collectHeaderMaps(HS: PP->getHeaderSearchInfo(), MDC: ModuleDepCollector);
517 collectIncludePCH(CI&: *this, MDC: ModuleDepCollector);
518 collectVFSEntries(CI&: *this, MDC: ModuleDepCollector);
519 }
520
521 // Modules need an output manager.
522 if (!hasOutputManager())
523 createOutputManager();
524
525 for (auto &Listener : DependencyCollectors)
526 Listener->attachToPreprocessor(PP&: *PP);
527
528 // Handle generating header include information, if requested.
529 if (DepOpts.ShowHeaderIncludes)
530 AttachHeaderIncludeGen(PP&: *PP, DepOpts);
531 if (!DepOpts.HeaderIncludeOutputFile.empty()) {
532 StringRef OutputPath = DepOpts.HeaderIncludeOutputFile;
533 if (OutputPath == "-")
534 OutputPath = "";
535 AttachHeaderIncludeGen(PP&: *PP, DepOpts,
536 /*ShowAllHeaders=*/true, OutputPath,
537 /*ShowDepth=*/false);
538 }
539
540 if (DepOpts.ShowIncludesDest != ShowIncludesDestination::None) {
541 AttachHeaderIncludeGen(PP&: *PP, DepOpts,
542 /*ShowAllHeaders=*/true, /*OutputPath=*/"",
543 /*ShowDepth=*/true, /*MSStyle=*/true);
544 }
545
546 if (GetDependencyDirectives)
547 PP->setDependencyDirectivesGetter(*GetDependencyDirectives);
548}
549
550// ASTContext
551
552void CompilerInstance::createASTContext() {
553 Preprocessor &PP = getPreprocessor();
554 auto Context = llvm::makeIntrusiveRefCnt<ASTContext>(
555 A&: getLangOpts(), A&: PP.getSourceManager(), A&: PP.getIdentifierTable(),
556 A&: PP.getSelectorTable(), A&: PP.getBuiltinInfo(), A: PP.TUKind);
557 Context->InitBuiltinTypes(Target: getTarget(), AuxTarget: getAuxTarget());
558 setASTContext(std::move(Context));
559}
560
561// ExternalASTSource
562
563namespace {
564// Helper to recursively read the module names for all modules we're adding.
565// We mark these as known and redirect any attempt to load that module to
566// the files we were handed.
567struct ReadModuleNames : ASTReaderListener {
568 Preprocessor &PP;
569 llvm::SmallVector<std::string, 8> LoadedModules;
570
571 ReadModuleNames(Preprocessor &PP) : PP(PP) {}
572
573 void ReadModuleName(StringRef ModuleName) override {
574 // Keep the module name as a string for now. It's not safe to create a new
575 // IdentifierInfo from an ASTReader callback.
576 LoadedModules.push_back(Elt: ModuleName.str());
577 }
578
579 void registerAll() {
580 ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
581 for (const std::string &LoadedModule : LoadedModules)
582 MM.cacheModuleLoad(II: *PP.getIdentifierInfo(Name: LoadedModule),
583 M: MM.findOrLoadModule(Name: LoadedModule));
584 LoadedModules.clear();
585 }
586
587 void markAllUnavailable() {
588 for (const std::string &LoadedModule : LoadedModules) {
589 if (Module *M = PP.getHeaderSearchInfo().getModuleMap().findOrLoadModule(
590 Name: LoadedModule)) {
591 M->HasIncompatibleModuleFile = true;
592
593 // Mark module as available if the only reason it was unavailable
594 // was missing headers.
595 SmallVector<Module *, 2> Stack;
596 Stack.push_back(Elt: M);
597 while (!Stack.empty()) {
598 Module *Current = Stack.pop_back_val();
599 if (Current->IsUnimportable) continue;
600 Current->IsAvailable = true;
601 auto SubmodulesRange = Current->submodules();
602 llvm::append_range(C&: Stack, R&: SubmodulesRange);
603 }
604 }
605 }
606 LoadedModules.clear();
607 }
608};
609} // namespace
610
611void CompilerInstance::createPCHExternalASTSource(
612 StringRef Path, DisableValidationForModuleKind DisableValidation,
613 bool AllowPCHWithCompilerErrors, void *DeserializationListener,
614 bool OwnDeserializationListener) {
615 bool Preamble = getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
616 TheASTReader = createPCHExternalASTSource(
617 Path, Sysroot: getHeaderSearchOpts().Sysroot, DisableValidation,
618 AllowPCHWithCompilerErrors, PP&: getPreprocessor(), ModCache&: getModuleCache(),
619 Context&: getASTContext(), PCHContainerRdr: getPCHContainerReader(), CodeGenOpts: getCodeGenOpts(),
620 Extensions: getFrontendOpts().ModuleFileExtensions, DependencyCollectors,
621 DeserializationListener, OwnDeserializationListener, Preamble,
622 UseGlobalModuleIndex: getFrontendOpts().UseGlobalModuleIndex);
623}
624
625IntrusiveRefCntPtr<ASTReader> CompilerInstance::createPCHExternalASTSource(
626 StringRef Path, StringRef Sysroot,
627 DisableValidationForModuleKind DisableValidation,
628 bool AllowPCHWithCompilerErrors, Preprocessor &PP, ModuleCache &ModCache,
629 ASTContext &Context, const PCHContainerReader &PCHContainerRdr,
630 const CodeGenOptions &CodeGenOpts,
631 ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
632 ArrayRef<std::shared_ptr<DependencyCollector>> DependencyCollectors,
633 void *DeserializationListener, bool OwnDeserializationListener,
634 bool Preamble, bool UseGlobalModuleIndex) {
635 const HeaderSearchOptions &HSOpts =
636 PP.getHeaderSearchInfo().getHeaderSearchOpts();
637
638 auto Reader = llvm::makeIntrusiveRefCnt<ASTReader>(
639 A&: PP, A&: ModCache, A: &Context, A: PCHContainerRdr, A: CodeGenOpts, A&: Extensions,
640 A: Sysroot.empty() ? "" : Sysroot.data(), A&: DisableValidation,
641 A&: AllowPCHWithCompilerErrors, /*AllowConfigurationMismatch*/ A: false,
642 A: HSOpts.ModulesValidateSystemHeaders,
643 A: HSOpts.ModulesForceValidateUserHeaders,
644 A: HSOpts.ValidateASTInputFilesContent, A&: UseGlobalModuleIndex);
645
646 // We need the external source to be set up before we read the AST, because
647 // eagerly-deserialized declarations may use it.
648 Context.setExternalSource(Reader);
649
650 Reader->setDeserializationListener(
651 Listener: static_cast<ASTDeserializationListener *>(DeserializationListener),
652 /*TakeOwnership=*/OwnDeserializationListener);
653
654 for (auto &Listener : DependencyCollectors)
655 Listener->attachToASTReader(R&: *Reader);
656
657 auto Listener = std::make_unique<ReadModuleNames>(args&: PP);
658 auto &ListenerRef = *Listener;
659 ASTReader::ListenerScope ReadModuleNamesListener(*Reader,
660 std::move(Listener));
661
662 switch (Reader->ReadAST(FileName: Path,
663 Type: Preamble ? serialization::MK_Preamble
664 : serialization::MK_PCH,
665 ImportLoc: SourceLocation(),
666 ClientLoadCapabilities: ASTReader::ARR_None)) {
667 case ASTReader::Success:
668 // Set the predefines buffer as suggested by the PCH reader. Typically, the
669 // predefines buffer will be empty.
670 PP.setPredefines(Reader->getSuggestedPredefines());
671 ListenerRef.registerAll();
672 return Reader;
673
674 case ASTReader::Failure:
675 // Unrecoverable failure: don't even try to process the input file.
676 break;
677
678 case ASTReader::Missing:
679 case ASTReader::OutOfDate:
680 case ASTReader::VersionMismatch:
681 case ASTReader::ConfigurationMismatch:
682 case ASTReader::HadErrors:
683 // No suitable PCH file could be found. Return an error.
684 break;
685 }
686
687 ListenerRef.markAllUnavailable();
688 Context.setExternalSource(nullptr);
689 return nullptr;
690}
691
692// Code Completion
693
694static bool EnableCodeCompletion(Preprocessor &PP,
695 StringRef Filename,
696 unsigned Line,
697 unsigned Column) {
698 // Tell the source manager to chop off the given file at a specific
699 // line and column.
700 auto Entry = PP.getFileManager().getOptionalFileRef(Filename);
701 if (!Entry) {
702 PP.getDiagnostics().Report(DiagID: diag::err_fe_invalid_code_complete_file)
703 << Filename;
704 return true;
705 }
706
707 // Truncate the named file at the given line/column.
708 PP.SetCodeCompletionPoint(File: *Entry, Line, Column);
709 return false;
710}
711
712void CompilerInstance::createCodeCompletionConsumer() {
713 const ParsedSourceLocation &Loc = getFrontendOpts().CodeCompletionAt;
714 if (!CompletionConsumer) {
715 setCodeCompletionConsumer(createCodeCompletionConsumer(
716 PP&: getPreprocessor(), Filename: Loc.FileName, Line: Loc.Line, Column: Loc.Column,
717 Opts: getFrontendOpts().CodeCompleteOpts, OS&: llvm::outs()));
718 return;
719 } else if (EnableCodeCompletion(PP&: getPreprocessor(), Filename: Loc.FileName,
720 Line: Loc.Line, Column: Loc.Column)) {
721 setCodeCompletionConsumer(nullptr);
722 return;
723 }
724}
725
726void CompilerInstance::createFrontendTimer() {
727 timerGroup.reset(p: new llvm::TimerGroup("clang", "Clang time report"));
728 FrontendTimer.reset(p: new llvm::Timer("frontend", "Front end", *timerGroup));
729}
730
731CodeCompleteConsumer *
732CompilerInstance::createCodeCompletionConsumer(Preprocessor &PP,
733 StringRef Filename,
734 unsigned Line,
735 unsigned Column,
736 const CodeCompleteOptions &Opts,
737 raw_ostream &OS) {
738 if (EnableCodeCompletion(PP, Filename, Line, Column))
739 return nullptr;
740
741 // Set up the creation routine for code-completion.
742 return new PrintingCodeCompleteConsumer(Opts, OS);
743}
744
745void CompilerInstance::createSema(TranslationUnitKind TUKind,
746 CodeCompleteConsumer *CompletionConsumer) {
747 TheSema.reset(p: new Sema(getPreprocessor(), getASTContext(), getASTConsumer(),
748 TUKind, CompletionConsumer));
749
750 // Set up API notes.
751 TheSema->APINotes.setSwiftVersion(getAPINotesOpts().SwiftVersion);
752
753 // Attach the external sema source if there is any.
754 if (ExternalSemaSrc) {
755 TheSema->addExternalSource(E: ExternalSemaSrc);
756 ExternalSemaSrc->InitializeSema(S&: *TheSema);
757 }
758
759 // If we're building a module and are supposed to load API notes,
760 // notify the API notes manager.
761 if (auto *currentModule = getPreprocessor().getCurrentModule()) {
762 (void)TheSema->APINotes.loadCurrentModuleAPINotes(
763 M: currentModule, LookInModule: getLangOpts().APINotesModules,
764 SearchPaths: getAPINotesOpts().ModuleSearchPaths);
765 }
766}
767
768// Output Files
769
770void CompilerInstance::clearOutputFiles(bool EraseFiles) {
771 // The ASTConsumer can own streams that write to the output files.
772 assert(!hasASTConsumer() && "ASTConsumer should be reset");
773 if (!EraseFiles) {
774 for (auto &O : OutputFiles)
775 llvm::handleAllErrors(
776 E: O.keep(),
777 Handlers: [&](const llvm::vfs::TempFileOutputError &E) {
778 getDiagnostics().Report(DiagID: diag::err_unable_to_rename_temp)
779 << E.getTempPath() << E.getOutputPath()
780 << E.convertToErrorCode().message();
781 },
782 Handlers: [&](const llvm::vfs::OutputError &E) {
783 getDiagnostics().Report(DiagID: diag::err_fe_unable_to_open_output)
784 << E.getOutputPath() << E.convertToErrorCode().message();
785 },
786 Handlers: [&](const llvm::ErrorInfoBase &EIB) { // Handle any remaining error
787 getDiagnostics().Report(DiagID: diag::err_fe_unable_to_open_output)
788 << O.getPath() << EIB.message();
789 });
790 }
791 OutputFiles.clear();
792 if (DeleteBuiltModules) {
793 for (auto &Module : BuiltModules)
794 llvm::sys::fs::remove(path: Module.second);
795 BuiltModules.clear();
796 }
797}
798
799std::unique_ptr<raw_pwrite_stream> CompilerInstance::createDefaultOutputFile(
800 bool Binary, StringRef InFile, StringRef Extension, bool RemoveFileOnSignal,
801 bool CreateMissingDirectories, bool ForceUseTemporary) {
802 StringRef OutputPath = getFrontendOpts().OutputFile;
803 std::optional<SmallString<128>> PathStorage;
804 if (OutputPath.empty()) {
805 if (InFile == "-" || Extension.empty()) {
806 OutputPath = "-";
807 } else {
808 PathStorage.emplace(args&: InFile);
809 llvm::sys::path::replace_extension(path&: *PathStorage, extension: Extension);
810 OutputPath = *PathStorage;
811 }
812 }
813
814 return createOutputFile(OutputPath, Binary, RemoveFileOnSignal,
815 UseTemporary: getFrontendOpts().UseTemporary || ForceUseTemporary,
816 CreateMissingDirectories);
817}
818
819std::unique_ptr<raw_pwrite_stream> CompilerInstance::createNullOutputFile() {
820 return std::make_unique<llvm::raw_null_ostream>();
821}
822
823// Output Manager
824
825void CompilerInstance::setOutputManager(
826 IntrusiveRefCntPtr<llvm::vfs::OutputBackend> NewOutputs) {
827 assert(!OutputMgr && "Already has an output manager");
828 OutputMgr = std::move(NewOutputs);
829}
830
831void CompilerInstance::createOutputManager() {
832 assert(!OutputMgr && "Already has an output manager");
833 OutputMgr = llvm::makeIntrusiveRefCnt<llvm::vfs::OnDiskOutputBackend>();
834}
835
836llvm::vfs::OutputBackend &CompilerInstance::getOutputManager() {
837 assert(OutputMgr);
838 return *OutputMgr;
839}
840
841llvm::vfs::OutputBackend &CompilerInstance::getOrCreateOutputManager() {
842 if (!hasOutputManager())
843 createOutputManager();
844 return getOutputManager();
845}
846
847std::unique_ptr<raw_pwrite_stream>
848CompilerInstance::createOutputFile(StringRef OutputPath, bool Binary,
849 bool RemoveFileOnSignal, bool UseTemporary,
850 bool CreateMissingDirectories) {
851 Expected<std::unique_ptr<raw_pwrite_stream>> OS =
852 createOutputFileImpl(OutputPath, Binary, RemoveFileOnSignal, UseTemporary,
853 CreateMissingDirectories);
854 if (OS)
855 return std::move(*OS);
856 getDiagnostics().Report(DiagID: diag::err_fe_unable_to_open_output)
857 << OutputPath << errorToErrorCode(Err: OS.takeError()).message();
858 return nullptr;
859}
860
861Expected<std::unique_ptr<llvm::raw_pwrite_stream>>
862CompilerInstance::createOutputFileImpl(StringRef OutputPath, bool Binary,
863 bool RemoveFileOnSignal,
864 bool UseTemporary,
865 bool CreateMissingDirectories) {
866 assert((!CreateMissingDirectories || UseTemporary) &&
867 "CreateMissingDirectories is only allowed when using temporary files");
868
869 // If '-working-directory' was passed, the output filename should be
870 // relative to that.
871 std::optional<SmallString<128>> AbsPath;
872 if (OutputPath != "-" && !llvm::sys::path::is_absolute(path: OutputPath)) {
873 assert(hasFileManager() &&
874 "File Manager is required to fix up relative path.\n");
875
876 AbsPath.emplace(args&: OutputPath);
877 FileManager::fixupRelativePath(FileSystemOpts: getFileSystemOpts(), Path&: *AbsPath);
878 OutputPath = *AbsPath;
879 }
880
881 using namespace llvm::vfs;
882 Expected<OutputFile> O = getOrCreateOutputManager().createFile(
883 Path: OutputPath,
884 Config: OutputConfig()
885 .setTextWithCRLF(!Binary)
886 .setDiscardOnSignal(RemoveFileOnSignal)
887 .setAtomicWrite(UseTemporary)
888 .setImplyCreateDirectories(UseTemporary && CreateMissingDirectories));
889 if (!O)
890 return O.takeError();
891
892 O->discardOnDestroy(Handler: [](llvm::Error E) { consumeError(Err: std::move(E)); });
893 OutputFiles.push_back(x: std::move(*O));
894 return OutputFiles.back().createProxy();
895}
896
897// Initialization Utilities
898
899bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input){
900 return InitializeSourceManager(Input, Diags&: getDiagnostics(), FileMgr&: getFileManager(),
901 SourceMgr&: getSourceManager());
902}
903
904// static
905bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
906 DiagnosticsEngine &Diags,
907 FileManager &FileMgr,
908 SourceManager &SourceMgr) {
909 SrcMgr::CharacteristicKind Kind =
910 Input.getKind().getFormat() == InputKind::ModuleMap
911 ? Input.isSystem() ? SrcMgr::C_System_ModuleMap
912 : SrcMgr::C_User_ModuleMap
913 : Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
914
915 if (Input.isBuffer()) {
916 SourceMgr.setMainFileID(SourceMgr.createFileID(Buffer: Input.getBuffer(), FileCharacter: Kind));
917 assert(SourceMgr.getMainFileID().isValid() &&
918 "Couldn't establish MainFileID!");
919 return true;
920 }
921
922 StringRef InputFile = Input.getFile();
923
924 // Figure out where to get and map in the main file.
925 auto FileOrErr = InputFile == "-"
926 ? FileMgr.getSTDIN()
927 : FileMgr.getFileRef(Filename: InputFile, /*OpenFile=*/true);
928 if (!FileOrErr) {
929 auto EC = llvm::errorToErrorCode(Err: FileOrErr.takeError());
930 if (InputFile != "-")
931 Diags.Report(DiagID: diag::err_fe_error_reading) << InputFile << EC.message();
932 else
933 Diags.Report(DiagID: diag::err_fe_error_reading_stdin) << EC.message();
934 return false;
935 }
936
937 SourceMgr.setMainFileID(
938 SourceMgr.createFileID(SourceFile: *FileOrErr, IncludePos: SourceLocation(), FileCharacter: Kind));
939
940 assert(SourceMgr.getMainFileID().isValid() &&
941 "Couldn't establish MainFileID!");
942 return true;
943}
944
945// High-Level Operations
946
947bool CompilerInstance::ExecuteAction(FrontendAction &Act) {
948 assert(hasDiagnostics() && "Diagnostics engine is not initialized!");
949 assert(!getFrontendOpts().ShowHelp && "Client must handle '-help'!");
950 assert(!getFrontendOpts().ShowVersion && "Client must handle '-version'!");
951
952 // Mark this point as the bottom of the stack if we don't have somewhere
953 // better. We generally expect frontend actions to be invoked with (nearly)
954 // DesiredStackSpace available.
955 noteBottomOfStack();
956
957 raw_ostream &OS = getVerboseOutputStream();
958
959 if (!Act.PrepareToExecute(CI&: *this))
960 return false;
961
962 if (!createTarget())
963 return false;
964
965 // rewriter project will change target built-in bool type from its default.
966 if (getFrontendOpts().ProgramAction == frontend::RewriteObjC)
967 getTarget().noSignedCharForObjCBool();
968
969 // Validate/process some options.
970 if (getHeaderSearchOpts().Verbose)
971 OS << "clang -cc1 version " CLANG_VERSION_STRING << " based upon LLVM "
972 << LLVM_VERSION_STRING << " default target "
973 << llvm::sys::getDefaultTargetTriple() << "\n";
974
975 if (getFrontendOpts().ShowStats || !getFrontendOpts().StatsFile.empty())
976 llvm::EnableStatistics(DoPrintOnExit: false);
977
978 // Sort vectors containing toc data and no toc data variables to facilitate
979 // binary search later.
980 llvm::sort(C&: getCodeGenOpts().TocDataVarsUserSpecified);
981 llvm::sort(C&: getCodeGenOpts().NoTocDataVars);
982
983 for (const FrontendInputFile &FIF : getFrontendOpts().Inputs) {
984 // Reset the ID tables if we are reusing the SourceManager and parsing
985 // regular files.
986 if (hasSourceManager() && !Act.isModelParsingAction())
987 getSourceManager().clearIDTables();
988
989 if (Act.BeginSourceFile(CI&: *this, Input: FIF)) {
990 if (llvm::Error Err = Act.Execute()) {
991 consumeError(Err: std::move(Err)); // FIXME this drops errors on the floor.
992 }
993 Act.EndSourceFile();
994 }
995 }
996
997 printDiagnosticStats();
998
999 if (getFrontendOpts().ShowStats) {
1000 if (hasFileManager()) {
1001 getFileManager().PrintStats();
1002 OS << '\n';
1003 }
1004 llvm::PrintStatistics(OS);
1005 }
1006 StringRef StatsFile = getFrontendOpts().StatsFile;
1007 if (!StatsFile.empty()) {
1008 llvm::sys::fs::OpenFlags FileFlags = llvm::sys::fs::OF_TextWithCRLF;
1009 if (getFrontendOpts().AppendStats)
1010 FileFlags |= llvm::sys::fs::OF_Append;
1011 std::error_code EC;
1012 auto StatS =
1013 std::make_unique<llvm::raw_fd_ostream>(args&: StatsFile, args&: EC, args&: FileFlags);
1014 if (EC) {
1015 getDiagnostics().Report(DiagID: diag::warn_fe_unable_to_open_stats_file)
1016 << StatsFile << EC.message();
1017 } else {
1018 llvm::PrintStatisticsJSON(OS&: *StatS);
1019 }
1020 }
1021
1022 return !getDiagnostics().getClient()->getNumErrors();
1023}
1024
1025void CompilerInstance::printDiagnosticStats() {
1026 if (!getDiagnosticOpts().ShowCarets)
1027 return;
1028
1029 raw_ostream &OS = getVerboseOutputStream();
1030
1031 // We can have multiple diagnostics sharing one diagnostic client.
1032 // Get the total number of warnings/errors from the client.
1033 unsigned NumWarnings = getDiagnostics().getClient()->getNumWarnings();
1034 unsigned NumErrors = getDiagnostics().getClient()->getNumErrors();
1035
1036 if (NumWarnings)
1037 OS << NumWarnings << " warning" << (NumWarnings == 1 ? "" : "s");
1038 if (NumWarnings && NumErrors)
1039 OS << " and ";
1040 if (NumErrors)
1041 OS << NumErrors << " error" << (NumErrors == 1 ? "" : "s");
1042 if (NumWarnings || NumErrors) {
1043 OS << " generated";
1044 if (getLangOpts().CUDA) {
1045 if (!getLangOpts().CUDAIsDevice) {
1046 OS << " when compiling for host";
1047 } else {
1048 OS << " when compiling for "
1049 << (!getTargetOpts().CPU.empty() ? getTargetOpts().CPU
1050 : getTarget().getTriple().str());
1051 }
1052 }
1053 OS << ".\n";
1054 }
1055}
1056
1057void CompilerInstance::LoadRequestedPlugins() {
1058 // Load any requested plugins.
1059 for (const std::string &Path : getFrontendOpts().Plugins) {
1060 std::string Error;
1061 if (llvm::sys::DynamicLibrary::LoadLibraryPermanently(Filename: Path.c_str(), ErrMsg: &Error))
1062 getDiagnostics().Report(DiagID: diag::err_fe_unable_to_load_plugin)
1063 << Path << Error;
1064 }
1065
1066 // Load and store pass plugins for the back-end.
1067 for (const std::string &Path : getCodeGenOpts().PassPlugins) {
1068 if (auto PassPlugin = llvm::PassPlugin::Load(Filename: Path)) {
1069 PassPlugins.emplace_back(args: std::make_unique<llvm::PassPlugin>(args&: *PassPlugin));
1070 } else {
1071 getDiagnostics().Report(DiagID: diag::err_fe_unable_to_load_plugin)
1072 << Path << toString(E: PassPlugin.takeError());
1073 }
1074 }
1075
1076 // Check if any of the loaded plugins replaces the main AST action
1077 for (const FrontendPluginRegistry::entry &Plugin :
1078 FrontendPluginRegistry::entries()) {
1079 std::unique_ptr<PluginASTAction> P(Plugin.instantiate());
1080 if (P->getActionType() == PluginASTAction::ReplaceAction) {
1081 getFrontendOpts().ProgramAction = clang::frontend::PluginAction;
1082 getFrontendOpts().ActionName = Plugin.getName().str();
1083 break;
1084 }
1085 }
1086}
1087
1088/// Determine the appropriate source input kind based on language
1089/// options.
1090static Language getLanguageFromOptions(const LangOptions &LangOpts) {
1091 if (LangOpts.OpenCL)
1092 return Language::OpenCL;
1093 if (LangOpts.CUDA)
1094 return Language::CUDA;
1095 if (LangOpts.ObjC)
1096 return LangOpts.CPlusPlus ? Language::ObjCXX : Language::ObjC;
1097 return LangOpts.CPlusPlus ? Language::CXX : Language::C;
1098}
1099
1100std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompileImpl(
1101 SourceLocation ImportLoc, StringRef ModuleName, FrontendInputFile Input,
1102 StringRef OriginalModuleMapFile, StringRef ModuleFileName,
1103 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1104 // Construct a compiler invocation for creating this module.
1105 auto Invocation = std::make_shared<CompilerInvocation>(args&: getInvocation());
1106
1107 PreprocessorOptions &PPOpts = Invocation->getPreprocessorOpts();
1108
1109 // For any options that aren't intended to affect how a module is built,
1110 // reset them to their default values.
1111 Invocation->resetNonModularOptions();
1112
1113 // Remove any macro definitions that are explicitly ignored by the module.
1114 // They aren't supposed to affect how the module is built anyway.
1115 HeaderSearchOptions &HSOpts = Invocation->getHeaderSearchOpts();
1116 llvm::erase_if(C&: PPOpts.Macros,
1117 P: [&HSOpts](const std::pair<std::string, bool> &def) {
1118 StringRef MacroDef = def.first;
1119 return HSOpts.ModulesIgnoreMacros.contains(
1120 key: llvm::CachedHashString(MacroDef.split(Separator: '=').first));
1121 });
1122
1123 // If the original compiler invocation had -fmodule-name, pass it through.
1124 Invocation->getLangOpts().ModuleName =
1125 getInvocation().getLangOpts().ModuleName;
1126
1127 // Note the name of the module we're building.
1128 Invocation->getLangOpts().CurrentModule = std::string(ModuleName);
1129
1130 // If there is a module map file, build the module using the module map.
1131 // Set up the inputs/outputs so that we build the module from its umbrella
1132 // header.
1133 FrontendOptions &FrontendOpts = Invocation->getFrontendOpts();
1134 FrontendOpts.OutputFile = ModuleFileName.str();
1135 FrontendOpts.DisableFree = false;
1136 FrontendOpts.GenerateGlobalModuleIndex = false;
1137 FrontendOpts.BuildingImplicitModule = true;
1138 FrontendOpts.OriginalModuleMap = std::string(OriginalModuleMapFile);
1139 // Force implicitly-built modules to hash the content of the module file.
1140 HSOpts.ModulesHashContent = true;
1141 FrontendOpts.Inputs = {std::move(Input)};
1142
1143 // Don't free the remapped file buffers; they are owned by our caller.
1144 PPOpts.RetainRemappedFileBuffers = true;
1145
1146 DiagnosticOptions &DiagOpts = Invocation->getDiagnosticOpts();
1147
1148 DiagOpts.VerifyDiagnostics = 0;
1149 assert(getInvocation().computeContextHash() ==
1150 Invocation->computeContextHash() &&
1151 "Module hash mismatch!");
1152
1153 std::shared_ptr<ModuleCache> ModCache;
1154 if (ThreadSafeConfig) {
1155 ModCache = ThreadSafeConfig->getModuleCache();
1156 } else {
1157 ModCache = this->ModCache;
1158 }
1159
1160 // Construct a compiler instance that will be used to create the module.
1161 auto InstancePtr = std::make_unique<CompilerInstance>(
1162 args: std::move(Invocation), args: getPCHContainerOperations(), args: std::move(ModCache));
1163 auto &Instance = *InstancePtr;
1164
1165 auto &Inv = Instance.getInvocation();
1166
1167 if (ThreadSafeConfig) {
1168 Instance.setVirtualFileSystem(ThreadSafeConfig->getVFS());
1169 Instance.createFileManager();
1170 } else if (FrontendOpts.ModulesShareFileManager) {
1171 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1172 Instance.setFileManager(getFileManagerPtr());
1173 } else {
1174 Instance.setVirtualFileSystem(getVirtualFileSystemPtr());
1175 Instance.createFileManager();
1176 }
1177
1178 if (ThreadSafeConfig) {
1179 Instance.createDiagnostics(Client: &ThreadSafeConfig->getDiagConsumer(),
1180 /*ShouldOwnClient=*/false);
1181 } else {
1182 Instance.createDiagnostics(
1183 Client: new ForwardingDiagnosticConsumer(getDiagnosticClient()),
1184 /*ShouldOwnClient=*/true);
1185 }
1186 if (llvm::is_contained(Range&: DiagOpts.SystemHeaderWarningsModules, Element: ModuleName))
1187 Instance.getDiagnostics().setSuppressSystemWarnings(false);
1188
1189 Instance.createSourceManager();
1190 SourceManager &SourceMgr = Instance.getSourceManager();
1191
1192 if (ThreadSafeConfig) {
1193 // Detecting cycles in the module graph is responsibility of the client.
1194 } else {
1195 // Note that this module is part of the module build stack, so that we
1196 // can detect cycles in the module graph.
1197 SourceMgr.setModuleBuildStack(getSourceManager().getModuleBuildStack());
1198 SourceMgr.pushModuleBuildStack(
1199 moduleName: ModuleName, importLoc: FullSourceLoc(ImportLoc, getSourceManager()));
1200 }
1201
1202 // Make a copy for the new instance.
1203 Instance.FailedModules = FailedModules;
1204
1205 // Pass along the GenModuleActionWrapper callback.
1206 Instance.setGenModuleActionWrapper(getGenModuleActionWrapper());
1207
1208 if (GetDependencyDirectives)
1209 Instance.GetDependencyDirectives =
1210 GetDependencyDirectives->cloneFor(FileMgr&: Instance.getFileManager());
1211
1212 if (ThreadSafeConfig) {
1213 Instance.setModuleDepCollector(ThreadSafeConfig->getModuleDepCollector());
1214 } else {
1215 // If we're collecting module dependencies, we need to share a collector
1216 // between all of the module CompilerInstances. Other than that, we don't
1217 // want to produce any dependency output from the module build.
1218 Instance.setModuleDepCollector(getModuleDepCollector());
1219 }
1220 Inv.getDependencyOutputOpts() = DependencyOutputOptions();
1221
1222 return InstancePtr;
1223}
1224
1225namespace {
1226class PrettyStackTraceBuildModule : public llvm::PrettyStackTraceEntry {
1227 StringRef ModuleName;
1228 StringRef ModuleFileName;
1229
1230public:
1231 PrettyStackTraceBuildModule(StringRef ModuleName, StringRef ModuleFileName)
1232 : ModuleName(ModuleName), ModuleFileName(ModuleFileName) {}
1233 void print(raw_ostream &OS) const override {
1234 OS << "Building module '" << ModuleName << "' as '" << ModuleFileName
1235 << "'\n";
1236 }
1237};
1238} // namespace
1239
1240bool CompilerInstance::compileModule(SourceLocation ImportLoc,
1241 StringRef ModuleName,
1242 StringRef ModuleFileName,
1243 CompilerInstance &Instance) {
1244 PrettyStackTraceBuildModule CrashInfo(ModuleName, ModuleFileName);
1245 llvm::TimeTraceScope TimeScope("Module Compile", ModuleName);
1246
1247 // Never compile a module that's already finalized - this would cause the
1248 // existing module to be freed, causing crashes if it is later referenced
1249 if (getModuleCache().getInMemoryModuleCache().isPCMFinal(Filename: ModuleFileName)) {
1250 getDiagnostics().Report(Loc: ImportLoc, DiagID: diag::err_module_rebuild_finalized)
1251 << ModuleName;
1252 return false;
1253 }
1254
1255 getDiagnostics().Report(Loc: ImportLoc, DiagID: diag::remark_module_build)
1256 << ModuleName << ModuleFileName;
1257
1258 // Execute the action to actually build the module in-place. Use a separate
1259 // thread so that we get a stack large enough.
1260 bool Crashed = !llvm::CrashRecoveryContext().RunSafelyOnNewStack(
1261 [&]() {
1262 std::unique_ptr<FrontendAction> Action =
1263 std::make_unique<GenerateModuleFromModuleMapAction>();
1264
1265 if (auto WrapGenModuleAction = Instance.getGenModuleActionWrapper())
1266 Action = WrapGenModuleAction(Instance.getFrontendOpts(),
1267 std::move(Action));
1268
1269 Instance.ExecuteAction(Act&: *Action);
1270 },
1271 RequestedStackSize: DesiredStackSize);
1272
1273 getDiagnostics().Report(Loc: ImportLoc, DiagID: diag::remark_module_build_done)
1274 << ModuleName;
1275
1276 // Propagate the statistics to the parent FileManager.
1277 if (!getFrontendOpts().ModulesShareFileManager)
1278 getFileManager().AddStats(Other: Instance.getFileManager());
1279
1280 // Propagate the failed modules to the parent instance.
1281 FailedModules = std::move(Instance.FailedModules);
1282
1283 if (Crashed) {
1284 // Clear the ASTConsumer if it hasn't been already, in case it owns streams
1285 // that must be closed before clearing output files.
1286 Instance.setSema(nullptr);
1287 Instance.setASTConsumer(nullptr);
1288
1289 // Delete any remaining temporary files related to Instance.
1290 Instance.clearOutputFiles(/*EraseFiles=*/true);
1291 }
1292
1293 // We've rebuilt a module. If we're allowed to generate or update the global
1294 // module index, record that fact in the importing compiler instance.
1295 if (getFrontendOpts().GenerateGlobalModuleIndex) {
1296 setBuildGlobalModuleIndex(true);
1297 }
1298
1299 // If \p AllowPCMWithCompilerErrors is set return 'success' even if errors
1300 // occurred.
1301 return !Instance.getDiagnostics().hasErrorOccurred() ||
1302 Instance.getFrontendOpts().AllowPCMWithCompilerErrors;
1303}
1304
1305static OptionalFileEntryRef getPublicModuleMap(FileEntryRef File,
1306 FileManager &FileMgr) {
1307 StringRef Filename = llvm::sys::path::filename(path: File.getName());
1308 SmallString<128> PublicFilename(File.getDir().getName());
1309 if (Filename == "module_private.map")
1310 llvm::sys::path::append(path&: PublicFilename, a: "module.map");
1311 else if (Filename == "module.private.modulemap")
1312 llvm::sys::path::append(path&: PublicFilename, a: "module.modulemap");
1313 else
1314 return std::nullopt;
1315 return FileMgr.getOptionalFileRef(Filename: PublicFilename);
1316}
1317
1318std::unique_ptr<CompilerInstance> CompilerInstance::cloneForModuleCompile(
1319 SourceLocation ImportLoc, const Module *Module, StringRef ModuleFileName,
1320 std::optional<ThreadSafeCloneConfig> ThreadSafeConfig) {
1321 StringRef ModuleName = Module->getTopLevelModuleName();
1322
1323 InputKind IK(getLanguageFromOptions(LangOpts: getLangOpts()), InputKind::ModuleMap);
1324
1325 // Get or create the module map that we'll use to build this module.
1326 ModuleMap &ModMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1327 SourceManager &SourceMgr = getSourceManager();
1328
1329 if (FileID ModuleMapFID = ModMap.getContainingModuleMapFileID(Module);
1330 ModuleMapFID.isValid()) {
1331 // We want to use the top-level module map. If we don't, the compiling
1332 // instance may think the containing module map is a top-level one, while
1333 // the importing instance knows it's included from a parent module map via
1334 // the extern directive. This mismatch could bite us later.
1335 SourceLocation Loc = SourceMgr.getIncludeLoc(FID: ModuleMapFID);
1336 while (Loc.isValid() && isModuleMap(CK: SourceMgr.getFileCharacteristic(Loc))) {
1337 ModuleMapFID = SourceMgr.getFileID(SpellingLoc: Loc);
1338 Loc = SourceMgr.getIncludeLoc(FID: ModuleMapFID);
1339 }
1340
1341 OptionalFileEntryRef ModuleMapFile =
1342 SourceMgr.getFileEntryRefForID(FID: ModuleMapFID);
1343 assert(ModuleMapFile && "Top-level module map with no FileID");
1344
1345 // Canonicalize compilation to start with the public module map. This is
1346 // vital for submodules declarations in the private module maps to be
1347 // correctly parsed when depending on a top level module in the public one.
1348 if (OptionalFileEntryRef PublicMMFile =
1349 getPublicModuleMap(File: *ModuleMapFile, FileMgr&: getFileManager()))
1350 ModuleMapFile = PublicMMFile;
1351
1352 StringRef ModuleMapFilePath = ModuleMapFile->getNameAsRequested();
1353
1354 // Use the systemness of the module map as parsed instead of using the
1355 // IsSystem attribute of the module. If the module has [system] but the
1356 // module map is not in a system path, then this would incorrectly parse
1357 // any other modules in that module map as system too.
1358 const SrcMgr::SLocEntry &SLoc = SourceMgr.getSLocEntry(FID: ModuleMapFID);
1359 bool IsSystem = isSystem(CK: SLoc.getFile().getFileCharacteristic());
1360
1361 // Use the module map where this module resides.
1362 return cloneForModuleCompileImpl(
1363 ImportLoc, ModuleName,
1364 Input: FrontendInputFile(ModuleMapFilePath, IK, IsSystem),
1365 OriginalModuleMapFile: ModMap.getModuleMapFileForUniquing(M: Module)->getName(), ModuleFileName,
1366 ThreadSafeConfig: std::move(ThreadSafeConfig));
1367 }
1368
1369 // FIXME: We only need to fake up an input file here as a way of
1370 // transporting the module's directory to the module map parser. We should
1371 // be able to do that more directly, and parse from a memory buffer without
1372 // inventing this file.
1373 SmallString<128> FakeModuleMapFile(Module->Directory->getName());
1374 llvm::sys::path::append(path&: FakeModuleMapFile, a: "__inferred_module.map");
1375
1376 std::string InferredModuleMapContent;
1377 llvm::raw_string_ostream OS(InferredModuleMapContent);
1378 Module->print(OS);
1379
1380 auto Instance = cloneForModuleCompileImpl(
1381 ImportLoc, ModuleName,
1382 Input: FrontendInputFile(FakeModuleMapFile, IK, +Module->IsSystem),
1383 OriginalModuleMapFile: ModMap.getModuleMapFileForUniquing(M: Module)->getName(), ModuleFileName,
1384 ThreadSafeConfig: std::move(ThreadSafeConfig));
1385
1386 std::unique_ptr<llvm::MemoryBuffer> ModuleMapBuffer =
1387 llvm::MemoryBuffer::getMemBufferCopy(InputData: InferredModuleMapContent);
1388 FileEntryRef ModuleMapFile = Instance->getFileManager().getVirtualFileRef(
1389 Filename: FakeModuleMapFile, Size: InferredModuleMapContent.size(), ModificationTime: 0);
1390 Instance->getSourceManager().overrideFileContents(SourceFile: ModuleMapFile,
1391 Buffer: std::move(ModuleMapBuffer));
1392
1393 return Instance;
1394}
1395
1396/// Read the AST right after compiling the module.
1397/// Returns true on success, false on failure.
1398static bool readASTAfterCompileModule(CompilerInstance &ImportingInstance,
1399 SourceLocation ImportLoc,
1400 SourceLocation ModuleNameLoc,
1401 Module *Module, StringRef ModuleFileName,
1402 bool *OutOfDate, bool *Missing) {
1403 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1404
1405 unsigned ModuleLoadCapabilities = ASTReader::ARR_Missing;
1406 if (OutOfDate)
1407 ModuleLoadCapabilities |= ASTReader::ARR_OutOfDate;
1408
1409 // Try to read the module file, now that we've compiled it.
1410 ASTReader::ASTReadResult ReadResult =
1411 ImportingInstance.getASTReader()->ReadAST(
1412 FileName: ModuleFileName, Type: serialization::MK_ImplicitModule, ImportLoc,
1413 ClientLoadCapabilities: ModuleLoadCapabilities);
1414 if (ReadResult == ASTReader::Success)
1415 return true;
1416
1417 // The caller wants to handle out-of-date failures.
1418 if (OutOfDate && ReadResult == ASTReader::OutOfDate) {
1419 *OutOfDate = true;
1420 return false;
1421 }
1422
1423 // The caller wants to handle missing module files.
1424 if (Missing && ReadResult == ASTReader::Missing) {
1425 *Missing = true;
1426 return false;
1427 }
1428
1429 // The ASTReader didn't diagnose the error, so conservatively report it.
1430 if (ReadResult == ASTReader::Missing || !Diags.hasErrorOccurred())
1431 Diags.Report(Loc: ModuleNameLoc, DiagID: diag::err_module_not_built)
1432 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1433
1434 return false;
1435}
1436
1437/// Compile a module in a separate compiler instance.
1438/// Returns true on success, false on failure.
1439static bool compileModuleImpl(CompilerInstance &ImportingInstance,
1440 SourceLocation ImportLoc,
1441 SourceLocation ModuleNameLoc, Module *Module,
1442 StringRef ModuleFileName) {
1443 {
1444 auto Instance = ImportingInstance.cloneForModuleCompile(
1445 ImportLoc: ModuleNameLoc, Module, ModuleFileName);
1446
1447 if (!ImportingInstance.compileModule(ImportLoc: ModuleNameLoc,
1448 ModuleName: Module->getTopLevelModuleName(),
1449 ModuleFileName, Instance&: *Instance)) {
1450 ImportingInstance.getDiagnostics().Report(Loc: ModuleNameLoc,
1451 DiagID: diag::err_module_not_built)
1452 << Module->Name << SourceRange(ImportLoc, ModuleNameLoc);
1453 return false;
1454 }
1455 }
1456
1457 // The module is built successfully, we can update its timestamp now.
1458 if (ImportingInstance.getPreprocessor()
1459 .getHeaderSearchInfo()
1460 .getHeaderSearchOpts()
1461 .ModulesValidateOncePerBuildSession) {
1462 ImportingInstance.getModuleCache().updateModuleTimestamp(ModuleFilename: ModuleFileName);
1463 }
1464
1465 return true;
1466}
1467
1468/// The result of `compileModuleBehindLockOrRead()`.
1469enum class CompileOrReadResult : uint8_t {
1470 /// We failed to compile the module.
1471 FailedToCompile,
1472 /// We successfully compiled the module and we still need to read it.
1473 Compiled,
1474 /// We failed to read the module file compiled by another instance.
1475 FailedToRead,
1476 /// We read a module file compiled by another instance.
1477 Read,
1478};
1479
1480/// Attempt to compile the module in a separate compiler instance behind a lock
1481/// (to avoid building the same module in multiple compiler instances), or read
1482/// the AST produced by another compiler instance.
1483static CompileOrReadResult compileModuleBehindLockOrRead(
1484 CompilerInstance &ImportingInstance, SourceLocation ImportLoc,
1485 SourceLocation ModuleNameLoc, Module *Module, StringRef ModuleFileName) {
1486 DiagnosticsEngine &Diags = ImportingInstance.getDiagnostics();
1487
1488 Diags.Report(Loc: ModuleNameLoc, DiagID: diag::remark_module_lock)
1489 << ModuleFileName << Module->Name;
1490
1491 auto &ModuleCache = ImportingInstance.getModuleCache();
1492 ModuleCache.prepareForGetLock(ModuleFilename: ModuleFileName);
1493
1494 while (true) {
1495 auto Lock = ModuleCache.getLock(ModuleFilename: ModuleFileName);
1496 bool Owned;
1497 if (llvm::Error Err = Lock->tryLock().moveInto(Value&: Owned)) {
1498 // ModuleCache takes care of correctness and locks are only necessary for
1499 // performance. Fallback to building the module in case of any lock
1500 // related errors.
1501 Diags.Report(Loc: ModuleNameLoc, DiagID: diag::remark_module_lock_failure)
1502 << Module->Name << toString(E: std::move(Err));
1503 if (!compileModuleImpl(ImportingInstance, ImportLoc, ModuleNameLoc,
1504 Module, ModuleFileName))
1505 return CompileOrReadResult::FailedToCompile;
1506 return CompileOrReadResult::Compiled;
1507 }
1508 if (Owned) {
1509 // We're responsible for building the module ourselves.
1510 if (!compileModuleImpl(ImportingInstance, ImportLoc, ModuleNameLoc,
1511 Module, ModuleFileName))
1512 return CompileOrReadResult::FailedToCompile;
1513 return CompileOrReadResult::Compiled;
1514 }
1515
1516 // Someone else is responsible for building the module. Wait for them to
1517 // finish.
1518 unsigned Timeout =
1519 ImportingInstance.getFrontendOpts().ImplicitModulesLockTimeoutSeconds;
1520 switch (Lock->waitForUnlockFor(MaxSeconds: std::chrono::seconds(Timeout))) {
1521 case llvm::WaitForUnlockResult::Success:
1522 break; // The interesting case.
1523 case llvm::WaitForUnlockResult::OwnerDied:
1524 continue; // try again to get the lock.
1525 case llvm::WaitForUnlockResult::Timeout:
1526 // Since the InMemoryModuleCache takes care of correctness, we try waiting
1527 // for someone else to complete the build so that it does not happen
1528 // twice. In case of timeout, try to build it ourselves again.
1529 Diags.Report(Loc: ModuleNameLoc, DiagID: diag::remark_module_lock_timeout)
1530 << Module->Name;
1531 // Clear the lock file so that future invocations can make progress.
1532 Lock->unsafeUnlock();
1533 continue;
1534 }
1535
1536 // Read the module that was just written by someone else.
1537 bool OutOfDate = false;
1538 bool Missing = false;
1539 if (readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1540 Module, ModuleFileName, OutOfDate: &OutOfDate, Missing: &Missing))
1541 return CompileOrReadResult::Read;
1542 if (!OutOfDate && !Missing)
1543 return CompileOrReadResult::FailedToRead;
1544
1545 // The module may be missing or out of date in the presence of file system
1546 // races. It may also be out of date if one of its imports depends on header
1547 // search paths that are not consistent with this ImportingInstance.
1548 // Try again...
1549 }
1550}
1551
1552/// Compile a module in a separate compiler instance and read the AST,
1553/// returning true if the module compiles without errors, potentially using a
1554/// lock manager to avoid building the same module in multiple compiler
1555/// instances.
1556static bool compileModuleAndReadAST(CompilerInstance &ImportingInstance,
1557 SourceLocation ImportLoc,
1558 SourceLocation ModuleNameLoc,
1559 Module *Module, StringRef ModuleFileName) {
1560 if (ImportingInstance.getInvocation()
1561 .getFrontendOpts()
1562 .BuildingImplicitModuleUsesLock) {
1563 switch (compileModuleBehindLockOrRead(
1564 ImportingInstance, ImportLoc, ModuleNameLoc, Module, ModuleFileName)) {
1565 case CompileOrReadResult::FailedToRead:
1566 case CompileOrReadResult::FailedToCompile:
1567 return false;
1568 case CompileOrReadResult::Read:
1569 return true;
1570 case CompileOrReadResult::Compiled:
1571 // We successfully compiled the module under a lock. Let's read it from
1572 // the in-memory module cache now.
1573 break;
1574 }
1575 } else {
1576 if (!compileModuleImpl(ImportingInstance, ImportLoc, ModuleNameLoc, Module,
1577 ModuleFileName))
1578 return false;
1579 }
1580
1581 return readASTAfterCompileModule(ImportingInstance, ImportLoc, ModuleNameLoc,
1582 Module, ModuleFileName,
1583 /*OutOfDate=*/nullptr, /*Missing=*/nullptr);
1584}
1585
1586/// Diagnose differences between the current definition of the given
1587/// configuration macro and the definition provided on the command line.
1588static void checkConfigMacro(Preprocessor &PP, StringRef ConfigMacro,
1589 Module *Mod, SourceLocation ImportLoc) {
1590 IdentifierInfo *Id = PP.getIdentifierInfo(Name: ConfigMacro);
1591 SourceManager &SourceMgr = PP.getSourceManager();
1592
1593 // If this identifier has never had a macro definition, then it could
1594 // not have changed.
1595 if (!Id->hadMacroDefinition())
1596 return;
1597 auto *LatestLocalMD = PP.getLocalMacroDirectiveHistory(II: Id);
1598
1599 // Find the macro definition from the command line.
1600 MacroInfo *CmdLineDefinition = nullptr;
1601 for (auto *MD = LatestLocalMD; MD; MD = MD->getPrevious()) {
1602 SourceLocation MDLoc = MD->getLocation();
1603 FileID FID = SourceMgr.getFileID(SpellingLoc: MDLoc);
1604 if (FID.isInvalid())
1605 continue;
1606 // We only care about the predefines buffer, or if the macro is defined
1607 // over the command line transitively through a PCH.
1608 if (FID != PP.getPredefinesFileID() &&
1609 !SourceMgr.isWrittenInCommandLineFile(Loc: MDLoc))
1610 continue;
1611 if (auto *DMD = dyn_cast<DefMacroDirective>(Val: MD))
1612 CmdLineDefinition = DMD->getMacroInfo();
1613 break;
1614 }
1615
1616 auto *CurrentDefinition = PP.getMacroInfo(II: Id);
1617 if (CurrentDefinition == CmdLineDefinition) {
1618 // Macro matches. Nothing to do.
1619 } else if (!CurrentDefinition) {
1620 // This macro was defined on the command line, then #undef'd later.
1621 // Complain.
1622 PP.Diag(Loc: ImportLoc, DiagID: diag::warn_module_config_macro_undef)
1623 << true << ConfigMacro << Mod->getFullModuleName();
1624 auto LatestDef = LatestLocalMD->getDefinition();
1625 assert(LatestDef.isUndefined() &&
1626 "predefined macro went away with no #undef?");
1627 PP.Diag(Loc: LatestDef.getUndefLocation(), DiagID: diag::note_module_def_undef_here)
1628 << true;
1629 return;
1630 } else if (!CmdLineDefinition) {
1631 // There was no definition for this macro in the command line,
1632 // but there was a local definition. Complain.
1633 PP.Diag(Loc: ImportLoc, DiagID: diag::warn_module_config_macro_undef)
1634 << false << ConfigMacro << Mod->getFullModuleName();
1635 PP.Diag(Loc: CurrentDefinition->getDefinitionLoc(),
1636 DiagID: diag::note_module_def_undef_here)
1637 << false;
1638 } else if (!CurrentDefinition->isIdenticalTo(Other: *CmdLineDefinition, PP,
1639 /*Syntactically=*/true)) {
1640 // The macro definitions differ.
1641 PP.Diag(Loc: ImportLoc, DiagID: diag::warn_module_config_macro_undef)
1642 << false << ConfigMacro << Mod->getFullModuleName();
1643 PP.Diag(Loc: CurrentDefinition->getDefinitionLoc(),
1644 DiagID: diag::note_module_def_undef_here)
1645 << false;
1646 }
1647}
1648
1649static void checkConfigMacros(Preprocessor &PP, Module *M,
1650 SourceLocation ImportLoc) {
1651 clang::Module *TopModule = M->getTopLevelModule();
1652 for (const StringRef ConMacro : TopModule->ConfigMacros) {
1653 checkConfigMacro(PP, ConfigMacro: ConMacro, Mod: M, ImportLoc);
1654 }
1655}
1656
1657void CompilerInstance::createASTReader() {
1658 if (TheASTReader)
1659 return;
1660
1661 if (!hasASTContext())
1662 createASTContext();
1663
1664 // If we're implicitly building modules but not currently recursively
1665 // building a module, check whether we need to prune the module cache.
1666 if (getSourceManager().getModuleBuildStack().empty() &&
1667 !getPreprocessor()
1668 .getHeaderSearchInfo()
1669 .getSpecificModuleCachePath()
1670 .empty())
1671 ModCache->maybePrune(Path: getHeaderSearchOpts().ModuleCachePath,
1672 PruneInterval: getHeaderSearchOpts().ModuleCachePruneInterval,
1673 PruneAfter: getHeaderSearchOpts().ModuleCachePruneAfter);
1674
1675 HeaderSearchOptions &HSOpts = getHeaderSearchOpts();
1676 std::string Sysroot = HSOpts.Sysroot;
1677 const PreprocessorOptions &PPOpts = getPreprocessorOpts();
1678 const FrontendOptions &FEOpts = getFrontendOpts();
1679 std::unique_ptr<llvm::Timer> ReadTimer;
1680
1681 if (timerGroup)
1682 ReadTimer = std::make_unique<llvm::Timer>(args: "reading_modules",
1683 args: "Reading modules", args&: *timerGroup);
1684 TheASTReader = llvm::makeIntrusiveRefCnt<ASTReader>(
1685 A&: getPreprocessor(), A&: getModuleCache(), A: &getASTContext(),
1686 A: getPCHContainerReader(), A&: getCodeGenOpts(),
1687 A&: getFrontendOpts().ModuleFileExtensions,
1688 A: Sysroot.empty() ? "" : Sysroot.c_str(),
1689 A: PPOpts.DisablePCHOrModuleValidation,
1690 /*AllowASTWithCompilerErrors=*/A: FEOpts.AllowPCMWithCompilerErrors,
1691 /*AllowConfigurationMismatch=*/A: false,
1692 A: +HSOpts.ModulesValidateSystemHeaders,
1693 A: +HSOpts.ModulesForceValidateUserHeaders,
1694 A: +HSOpts.ValidateASTInputFilesContent,
1695 A: +getFrontendOpts().UseGlobalModuleIndex, A: std::move(ReadTimer));
1696 if (hasASTConsumer()) {
1697 TheASTReader->setDeserializationListener(
1698 Listener: getASTConsumer().GetASTDeserializationListener());
1699 getASTContext().setASTMutationListener(
1700 getASTConsumer().GetASTMutationListener());
1701 }
1702 getASTContext().setExternalSource(TheASTReader);
1703 if (hasSema())
1704 TheASTReader->InitializeSema(S&: getSema());
1705 if (hasASTConsumer())
1706 TheASTReader->StartTranslationUnit(Consumer: &getASTConsumer());
1707
1708 for (auto &Listener : DependencyCollectors)
1709 Listener->attachToASTReader(R&: *TheASTReader);
1710}
1711
1712bool CompilerInstance::loadModuleFile(
1713 StringRef FileName, serialization::ModuleFile *&LoadedModuleFile) {
1714 llvm::Timer Timer;
1715 if (timerGroup)
1716 Timer.init(TimerName: "preloading." + FileName.str(), TimerDescription: "Preloading " + FileName.str(),
1717 tg&: *timerGroup);
1718 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1719
1720 // If we don't already have an ASTReader, create one now.
1721 if (!TheASTReader)
1722 createASTReader();
1723
1724 // If -Wmodule-file-config-mismatch is mapped as an error or worse, allow the
1725 // ASTReader to diagnose it, since it can produce better errors that we can.
1726 bool ConfigMismatchIsRecoverable =
1727 getDiagnostics().getDiagnosticLevel(DiagID: diag::warn_ast_file_config_mismatch,
1728 Loc: SourceLocation()) <=
1729 DiagnosticsEngine::Warning;
1730
1731 auto Listener = std::make_unique<ReadModuleNames>(args&: *PP);
1732 auto &ListenerRef = *Listener;
1733 ASTReader::ListenerScope ReadModuleNamesListener(*TheASTReader,
1734 std::move(Listener));
1735
1736 // Try to load the module file.
1737 switch (TheASTReader->ReadAST(
1738 FileName, Type: serialization::MK_ExplicitModule, ImportLoc: SourceLocation(),
1739 ClientLoadCapabilities: ConfigMismatchIsRecoverable ? ASTReader::ARR_ConfigurationMismatch : 0,
1740 NewLoadedModuleFile: &LoadedModuleFile)) {
1741 case ASTReader::Success:
1742 // We successfully loaded the module file; remember the set of provided
1743 // modules so that we don't try to load implicit modules for them.
1744 ListenerRef.registerAll();
1745 return true;
1746
1747 case ASTReader::ConfigurationMismatch:
1748 // Ignore unusable module files.
1749 getDiagnostics().Report(Loc: SourceLocation(),
1750 DiagID: diag::warn_ast_file_config_mismatch)
1751 << FileName;
1752 // All modules provided by any files we tried and failed to load are now
1753 // unavailable; includes of those modules should now be handled textually.
1754 ListenerRef.markAllUnavailable();
1755 return true;
1756
1757 default:
1758 return false;
1759 }
1760}
1761
1762namespace {
1763enum ModuleSource {
1764 MS_ModuleNotFound,
1765 MS_ModuleCache,
1766 MS_PrebuiltModulePath,
1767 MS_ModuleBuildPragma
1768};
1769} // end namespace
1770
1771/// Select a source for loading the named module and compute the filename to
1772/// load it from.
1773static ModuleSource selectModuleSource(
1774 Module *M, StringRef ModuleName, std::string &ModuleFilename,
1775 const std::map<std::string, std::string, std::less<>> &BuiltModules,
1776 HeaderSearch &HS) {
1777 assert(ModuleFilename.empty() && "Already has a module source?");
1778
1779 // Check to see if the module has been built as part of this compilation
1780 // via a module build pragma.
1781 auto BuiltModuleIt = BuiltModules.find(x: ModuleName);
1782 if (BuiltModuleIt != BuiltModules.end()) {
1783 ModuleFilename = BuiltModuleIt->second;
1784 return MS_ModuleBuildPragma;
1785 }
1786
1787 // Try to load the module from the prebuilt module path.
1788 const HeaderSearchOptions &HSOpts = HS.getHeaderSearchOpts();
1789 if (!HSOpts.PrebuiltModuleFiles.empty() ||
1790 !HSOpts.PrebuiltModulePaths.empty()) {
1791 ModuleFilename = HS.getPrebuiltModuleFileName(ModuleName);
1792 if (HSOpts.EnablePrebuiltImplicitModules && ModuleFilename.empty())
1793 ModuleFilename = HS.getPrebuiltImplicitModuleFileName(Module: M);
1794 if (!ModuleFilename.empty())
1795 return MS_PrebuiltModulePath;
1796 }
1797
1798 // Try to load the module from the module cache.
1799 if (M) {
1800 ModuleFilename = HS.getCachedModuleFileName(Module: M);
1801 return MS_ModuleCache;
1802 }
1803
1804 return MS_ModuleNotFound;
1805}
1806
1807ModuleLoadResult CompilerInstance::findOrCompileModuleAndReadAST(
1808 StringRef ModuleName, SourceLocation ImportLoc, SourceRange ModuleNameRange,
1809 bool IsInclusionDirective) {
1810 // Search for a module with the given name.
1811 HeaderSearch &HS = PP->getHeaderSearchInfo();
1812 Module *M =
1813 HS.lookupModule(ModuleName, ImportLoc, AllowSearch: true, AllowExtraModuleMapSearch: !IsInclusionDirective);
1814
1815 // Check for any configuration macros that have changed. This is done
1816 // immediately before potentially building a module in case this module
1817 // depends on having one of its configuration macros defined to successfully
1818 // build. If this is not done the user will never see the warning.
1819 if (M)
1820 checkConfigMacros(PP&: getPreprocessor(), M, ImportLoc);
1821
1822 // Select the source and filename for loading the named module.
1823 std::string ModuleFilename;
1824 ModuleSource Source =
1825 selectModuleSource(M, ModuleName, ModuleFilename, BuiltModules, HS);
1826 SourceLocation ModuleNameLoc = ModuleNameRange.getBegin();
1827 if (Source == MS_ModuleNotFound) {
1828 // We can't find a module, error out here.
1829 getDiagnostics().Report(Loc: ModuleNameLoc, DiagID: diag::err_module_not_found)
1830 << ModuleName << ModuleNameRange;
1831 return nullptr;
1832 }
1833 if (ModuleFilename.empty()) {
1834 if (M && M->HasIncompatibleModuleFile) {
1835 // We tried and failed to load a module file for this module. Fall
1836 // back to textual inclusion for its headers.
1837 return ModuleLoadResult::ConfigMismatch;
1838 }
1839
1840 getDiagnostics().Report(Loc: ModuleNameLoc, DiagID: diag::err_module_build_disabled)
1841 << ModuleName;
1842 return nullptr;
1843 }
1844
1845 // Create an ASTReader on demand.
1846 if (!getASTReader())
1847 createASTReader();
1848
1849 // Time how long it takes to load the module.
1850 llvm::Timer Timer;
1851 if (timerGroup)
1852 Timer.init(TimerName: "loading." + ModuleFilename, TimerDescription: "Loading " + ModuleFilename,
1853 tg&: *timerGroup);
1854 llvm::TimeRegion TimeLoading(timerGroup ? &Timer : nullptr);
1855 llvm::TimeTraceScope TimeScope("Module Load", ModuleName);
1856
1857 // Try to load the module file. If we are not trying to load from the
1858 // module cache, we don't know how to rebuild modules.
1859 unsigned ARRFlags = Source == MS_ModuleCache
1860 ? ASTReader::ARR_OutOfDate | ASTReader::ARR_Missing |
1861 ASTReader::ARR_TreatModuleWithErrorsAsOutOfDate
1862 : Source == MS_PrebuiltModulePath
1863 ? 0
1864 : ASTReader::ARR_ConfigurationMismatch;
1865 switch (getASTReader()->ReadAST(FileName: ModuleFilename,
1866 Type: Source == MS_PrebuiltModulePath
1867 ? serialization::MK_PrebuiltModule
1868 : Source == MS_ModuleBuildPragma
1869 ? serialization::MK_ExplicitModule
1870 : serialization::MK_ImplicitModule,
1871 ImportLoc, ClientLoadCapabilities: ARRFlags)) {
1872 case ASTReader::Success: {
1873 if (M)
1874 return M;
1875 assert(Source != MS_ModuleCache &&
1876 "missing module, but file loaded from cache");
1877
1878 // A prebuilt module is indexed as a ModuleFile; the Module does not exist
1879 // until the first call to ReadAST. Look it up now.
1880 M = HS.lookupModule(ModuleName, ImportLoc, AllowSearch: true, AllowExtraModuleMapSearch: !IsInclusionDirective);
1881
1882 // Check whether M refers to the file in the prebuilt module path.
1883 if (M && M->getASTFile())
1884 if (auto ModuleFile = FileMgr->getOptionalFileRef(Filename: ModuleFilename))
1885 if (*ModuleFile == M->getASTFile())
1886 return M;
1887
1888 getDiagnostics().Report(Loc: ModuleNameLoc, DiagID: diag::err_module_prebuilt)
1889 << ModuleName;
1890 return ModuleLoadResult();
1891 }
1892
1893 case ASTReader::OutOfDate:
1894 case ASTReader::Missing:
1895 // The most interesting case.
1896 break;
1897
1898 case ASTReader::ConfigurationMismatch:
1899 if (Source == MS_PrebuiltModulePath)
1900 // FIXME: We shouldn't be setting HadFatalFailure below if we only
1901 // produce a warning here!
1902 getDiagnostics().Report(Loc: SourceLocation(),
1903 DiagID: diag::warn_ast_file_config_mismatch)
1904 << ModuleFilename;
1905 // Fall through to error out.
1906 [[fallthrough]];
1907 case ASTReader::VersionMismatch:
1908 case ASTReader::HadErrors:
1909 ModuleLoader::HadFatalFailure = true;
1910 // FIXME: The ASTReader will already have complained, but can we shoehorn
1911 // that diagnostic information into a more useful form?
1912 return ModuleLoadResult();
1913
1914 case ASTReader::Failure:
1915 ModuleLoader::HadFatalFailure = true;
1916 return ModuleLoadResult();
1917 }
1918
1919 // ReadAST returned Missing or OutOfDate.
1920 if (Source != MS_ModuleCache) {
1921 // We don't know the desired configuration for this module and don't
1922 // necessarily even have a module map. Since ReadAST already produces
1923 // diagnostics for these two cases, we simply error out here.
1924 return ModuleLoadResult();
1925 }
1926
1927 // The module file is missing or out-of-date. Build it.
1928 assert(M && "missing module, but trying to compile for cache");
1929
1930 // Check whether there is a cycle in the module graph.
1931 ModuleBuildStack ModPath = getSourceManager().getModuleBuildStack();
1932 ModuleBuildStack::iterator Pos = ModPath.begin(), PosEnd = ModPath.end();
1933 for (; Pos != PosEnd; ++Pos) {
1934 if (Pos->first == ModuleName)
1935 break;
1936 }
1937
1938 if (Pos != PosEnd) {
1939 SmallString<256> CyclePath;
1940 for (; Pos != PosEnd; ++Pos) {
1941 CyclePath += Pos->first;
1942 CyclePath += " -> ";
1943 }
1944 CyclePath += ModuleName;
1945
1946 getDiagnostics().Report(Loc: ModuleNameLoc, DiagID: diag::err_module_cycle)
1947 << ModuleName << CyclePath;
1948 return nullptr;
1949 }
1950
1951 // Check whether we have already attempted to build this module (but failed).
1952 if (FailedModules.contains(key: ModuleName)) {
1953 getDiagnostics().Report(Loc: ModuleNameLoc, DiagID: diag::err_module_not_built)
1954 << ModuleName << SourceRange(ImportLoc, ModuleNameLoc);
1955 return nullptr;
1956 }
1957
1958 // Try to compile and then read the AST.
1959 if (!compileModuleAndReadAST(ImportingInstance&: *this, ImportLoc, ModuleNameLoc, Module: M,
1960 ModuleFileName: ModuleFilename)) {
1961 assert(getDiagnostics().hasErrorOccurred() &&
1962 "undiagnosed error in compileModuleAndReadAST");
1963 FailedModules.insert(key: ModuleName);
1964 return nullptr;
1965 }
1966
1967 // Okay, we've rebuilt and now loaded the module.
1968 return M;
1969}
1970
1971ModuleLoadResult
1972CompilerInstance::loadModule(SourceLocation ImportLoc,
1973 ModuleIdPath Path,
1974 Module::NameVisibilityKind Visibility,
1975 bool IsInclusionDirective) {
1976 // Determine what file we're searching from.
1977 StringRef ModuleName = Path[0].getIdentifierInfo()->getName();
1978 SourceLocation ModuleNameLoc = Path[0].getLoc();
1979
1980 // If we've already handled this import, just return the cached result.
1981 // This one-element cache is important to eliminate redundant diagnostics
1982 // when both the preprocessor and parser see the same import declaration.
1983 if (ImportLoc.isValid() && LastModuleImportLoc == ImportLoc) {
1984 // Make the named module visible.
1985 if (LastModuleImportResult && ModuleName != getLangOpts().CurrentModule)
1986 TheASTReader->makeModuleVisible(Mod: LastModuleImportResult, NameVisibility: Visibility,
1987 ImportLoc);
1988 return LastModuleImportResult;
1989 }
1990
1991 // If we don't already have information on this module, load the module now.
1992 Module *Module = nullptr;
1993 ModuleMap &MM = getPreprocessor().getHeaderSearchInfo().getModuleMap();
1994 if (auto MaybeModule = MM.getCachedModuleLoad(II: *Path[0].getIdentifierInfo())) {
1995 // Use the cached result, which may be nullptr.
1996 Module = *MaybeModule;
1997 // Config macros are already checked before building a module, but they need
1998 // to be checked at each import location in case any of the config macros
1999 // have a new value at the current `ImportLoc`.
2000 if (Module)
2001 checkConfigMacros(PP&: getPreprocessor(), M: Module, ImportLoc);
2002 } else if (ModuleName == getLangOpts().CurrentModule) {
2003 // This is the module we're building.
2004 Module = PP->getHeaderSearchInfo().lookupModule(
2005 ModuleName, ImportLoc, /*AllowSearch*/ true,
2006 /*AllowExtraModuleMapSearch*/ !IsInclusionDirective);
2007
2008 // Config macros do not need to be checked here for two reasons.
2009 // * This will always be textual inclusion, and thus the config macros
2010 // actually do impact the content of the header.
2011 // * `Preprocessor::HandleHeaderIncludeOrImport` will never call this
2012 // function as the `#include` or `#import` is textual.
2013
2014 MM.cacheModuleLoad(II: *Path[0].getIdentifierInfo(), M: Module);
2015 } else if (getPreprocessorOpts().SingleModuleParseMode) {
2016 // This mimics how findOrCompileModuleAndReadAST() finds the module.
2017 Module = getPreprocessor().getHeaderSearchInfo().lookupModule(
2018 ModuleName, ImportLoc, AllowSearch: true, AllowExtraModuleMapSearch: !IsInclusionDirective);
2019 if (Module) {
2020 if (PPCallbacks *PPCb = getPreprocessor().getPPCallbacks())
2021 PPCb->moduleLoadSkipped(Skipped: Module);
2022 // Mark the module and its submodules as if they were loaded from a PCM.
2023 // This prevents emission of the "missing submodule" diagnostic below.
2024 std::vector<clang::Module *> Worklist{Module};
2025 while (!Worklist.empty()) {
2026 clang::Module *M = Worklist.back();
2027 Worklist.pop_back();
2028 M->IsFromModuleFile = true;
2029 for (auto *SubM : M->submodules())
2030 Worklist.push_back(x: SubM);
2031 }
2032 }
2033 MM.cacheModuleLoad(II: *Path[0].getIdentifierInfo(), M: Module);
2034 } else {
2035 SourceLocation ModuleNameEndLoc = Path.back().getLoc().getLocWithOffset(
2036 Offset: Path.back().getIdentifierInfo()->getLength());
2037 ModuleLoadResult Result = findOrCompileModuleAndReadAST(
2038 ModuleName, ImportLoc, ModuleNameRange: SourceRange{ModuleNameLoc, ModuleNameEndLoc},
2039 IsInclusionDirective);
2040 if (!Result.isNormal())
2041 return Result;
2042 if (!Result)
2043 DisableGeneratingGlobalModuleIndex = true;
2044 Module = Result;
2045 MM.cacheModuleLoad(II: *Path[0].getIdentifierInfo(), M: Module);
2046 }
2047
2048 // If we never found the module, fail. Otherwise, verify the module and link
2049 // it up.
2050 if (!Module)
2051 return ModuleLoadResult();
2052
2053 // Verify that the rest of the module path actually corresponds to
2054 // a submodule.
2055 bool MapPrivateSubModToTopLevel = false;
2056 for (unsigned I = 1, N = Path.size(); I != N; ++I) {
2057 StringRef Name = Path[I].getIdentifierInfo()->getName();
2058 clang::Module *Sub = Module->findSubmodule(Name);
2059
2060 // If the user is requesting Foo.Private and it doesn't exist, try to
2061 // match Foo_Private and emit a warning asking for the user to write
2062 // @import Foo_Private instead. FIXME: remove this when existing clients
2063 // migrate off of Foo.Private syntax.
2064 if (!Sub && Name == "Private" && Module == Module->getTopLevelModule()) {
2065 SmallString<128> PrivateModule(Module->Name);
2066 PrivateModule.append(RHS: "_Private");
2067
2068 SmallVector<IdentifierLoc, 2> PrivPath;
2069 auto &II = PP->getIdentifierTable().get(
2070 Name: PrivateModule, TokenCode: PP->getIdentifierInfo(Name: Module->Name)->getTokenID());
2071 PrivPath.emplace_back(Args: Path[0].getLoc(), Args: &II);
2072
2073 std::string FileName;
2074 // If there is a modulemap module or prebuilt module, load it.
2075 if (PP->getHeaderSearchInfo().lookupModule(ModuleName: PrivateModule, ImportLoc, AllowSearch: true,
2076 AllowExtraModuleMapSearch: !IsInclusionDirective) ||
2077 selectModuleSource(M: nullptr, ModuleName: PrivateModule, ModuleFilename&: FileName, BuiltModules,
2078 HS&: PP->getHeaderSearchInfo()) != MS_ModuleNotFound)
2079 Sub = loadModule(ImportLoc, Path: PrivPath, Visibility, IsInclusionDirective);
2080 if (Sub) {
2081 MapPrivateSubModToTopLevel = true;
2082 PP->markClangModuleAsAffecting(M: Module);
2083 if (!getDiagnostics().isIgnored(
2084 DiagID: diag::warn_no_priv_submodule_use_toplevel, Loc: ImportLoc)) {
2085 getDiagnostics().Report(Loc: Path[I].getLoc(),
2086 DiagID: diag::warn_no_priv_submodule_use_toplevel)
2087 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2088 << PrivateModule
2089 << SourceRange(Path[0].getLoc(), Path[I].getLoc())
2090 << FixItHint::CreateReplacement(RemoveRange: SourceRange(Path[0].getLoc()),
2091 Code: PrivateModule);
2092 getDiagnostics().Report(Loc: Sub->DefinitionLoc,
2093 DiagID: diag::note_private_top_level_defined);
2094 }
2095 }
2096 }
2097
2098 if (!Sub) {
2099 // Attempt to perform typo correction to find a module name that works.
2100 SmallVector<StringRef, 2> Best;
2101 unsigned BestEditDistance = (std::numeric_limits<unsigned>::max)();
2102
2103 for (class Module *SubModule : Module->submodules()) {
2104 unsigned ED =
2105 Name.edit_distance(Other: SubModule->Name,
2106 /*AllowReplacements=*/true, MaxEditDistance: BestEditDistance);
2107 if (ED <= BestEditDistance) {
2108 if (ED < BestEditDistance) {
2109 Best.clear();
2110 BestEditDistance = ED;
2111 }
2112
2113 Best.push_back(Elt: SubModule->Name);
2114 }
2115 }
2116
2117 // If there was a clear winner, user it.
2118 if (Best.size() == 1) {
2119 getDiagnostics().Report(Loc: Path[I].getLoc(),
2120 DiagID: diag::err_no_submodule_suggest)
2121 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2122 << Best[0] << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc())
2123 << FixItHint::CreateReplacement(RemoveRange: SourceRange(Path[I].getLoc()),
2124 Code: Best[0]);
2125
2126 Sub = Module->findSubmodule(Name: Best[0]);
2127 }
2128 }
2129
2130 if (!Sub) {
2131 // No submodule by this name. Complain, and don't look for further
2132 // submodules.
2133 getDiagnostics().Report(Loc: Path[I].getLoc(), DiagID: diag::err_no_submodule)
2134 << Path[I].getIdentifierInfo() << Module->getFullModuleName()
2135 << SourceRange(Path[0].getLoc(), Path[I - 1].getLoc());
2136 break;
2137 }
2138
2139 Module = Sub;
2140 }
2141
2142 // Make the named module visible, if it's not already part of the module
2143 // we are parsing.
2144 if (ModuleName != getLangOpts().CurrentModule) {
2145 if (!Module->IsFromModuleFile && !MapPrivateSubModToTopLevel) {
2146 // We have an umbrella header or directory that doesn't actually include
2147 // all of the headers within the directory it covers. Complain about
2148 // this missing submodule and recover by forgetting that we ever saw
2149 // this submodule.
2150 // FIXME: Should we detect this at module load time? It seems fairly
2151 // expensive (and rare).
2152 getDiagnostics().Report(Loc: ImportLoc, DiagID: diag::warn_missing_submodule)
2153 << Module->getFullModuleName()
2154 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2155
2156 return ModuleLoadResult(Module, ModuleLoadResult::MissingExpected);
2157 }
2158
2159 // Check whether this module is available.
2160 if (Preprocessor::checkModuleIsAvailable(LangOpts: getLangOpts(), TargetInfo: getTarget(),
2161 M: *Module, Diags&: getDiagnostics())) {
2162 getDiagnostics().Report(Loc: ImportLoc, DiagID: diag::note_module_import_here)
2163 << SourceRange(Path.front().getLoc(), Path.back().getLoc());
2164 LastModuleImportLoc = ImportLoc;
2165 LastModuleImportResult = ModuleLoadResult();
2166 return ModuleLoadResult();
2167 }
2168
2169 TheASTReader->makeModuleVisible(Mod: Module, NameVisibility: Visibility, ImportLoc);
2170 }
2171
2172 // Resolve any remaining module using export_as for this one.
2173 getPreprocessor()
2174 .getHeaderSearchInfo()
2175 .getModuleMap()
2176 .resolveLinkAsDependencies(Mod: Module->getTopLevelModule());
2177
2178 LastModuleImportLoc = ImportLoc;
2179 LastModuleImportResult = ModuleLoadResult(Module);
2180 return LastModuleImportResult;
2181}
2182
2183void CompilerInstance::createModuleFromSource(SourceLocation ImportLoc,
2184 StringRef ModuleName,
2185 StringRef Source) {
2186 // Avoid creating filenames with special characters.
2187 SmallString<128> CleanModuleName(ModuleName);
2188 for (auto &C : CleanModuleName)
2189 if (!isAlphanumeric(c: C))
2190 C = '_';
2191
2192 // FIXME: Using a randomized filename here means that our intermediate .pcm
2193 // output is nondeterministic (as .pcm files refer to each other by name).
2194 // Can this affect the output in any way?
2195 SmallString<128> ModuleFileName;
2196 if (std::error_code EC = llvm::sys::fs::createTemporaryFile(
2197 Prefix: CleanModuleName, Suffix: "pcm", ResultPath&: ModuleFileName)) {
2198 getDiagnostics().Report(Loc: ImportLoc, DiagID: diag::err_fe_unable_to_open_output)
2199 << ModuleFileName << EC.message();
2200 return;
2201 }
2202 std::string ModuleMapFileName = (CleanModuleName + ".map").str();
2203
2204 FrontendInputFile Input(
2205 ModuleMapFileName,
2206 InputKind(getLanguageFromOptions(LangOpts: Invocation->getLangOpts()),
2207 InputKind::ModuleMap, /*Preprocessed*/true));
2208
2209 std::string NullTerminatedSource(Source.str());
2210
2211 auto Other = cloneForModuleCompileImpl(ImportLoc, ModuleName, Input,
2212 OriginalModuleMapFile: StringRef(), ModuleFileName);
2213
2214 // Create a virtual file containing our desired source.
2215 // FIXME: We shouldn't need to do this.
2216 FileEntryRef ModuleMapFile = Other->getFileManager().getVirtualFileRef(
2217 Filename: ModuleMapFileName, Size: NullTerminatedSource.size(), ModificationTime: 0);
2218 Other->getSourceManager().overrideFileContents(
2219 SourceFile: ModuleMapFile, Buffer: llvm::MemoryBuffer::getMemBuffer(InputData: NullTerminatedSource));
2220
2221 Other->BuiltModules = std::move(BuiltModules);
2222 Other->DeleteBuiltModules = false;
2223
2224 // Build the module, inheriting any modules that we've built locally.
2225 bool Success = compileModule(ImportLoc, ModuleName, ModuleFileName, Instance&: *Other);
2226
2227 BuiltModules = std::move(Other->BuiltModules);
2228
2229 if (Success) {
2230 BuiltModules[std::string(ModuleName)] = std::string(ModuleFileName);
2231 llvm::sys::RemoveFileOnSignal(Filename: ModuleFileName);
2232 }
2233}
2234
2235void CompilerInstance::makeModuleVisible(Module *Mod,
2236 Module::NameVisibilityKind Visibility,
2237 SourceLocation ImportLoc) {
2238 if (!TheASTReader)
2239 createASTReader();
2240 if (!TheASTReader)
2241 return;
2242
2243 TheASTReader->makeModuleVisible(Mod, NameVisibility: Visibility, ImportLoc);
2244}
2245
2246GlobalModuleIndex *CompilerInstance::loadGlobalModuleIndex(
2247 SourceLocation TriggerLoc) {
2248 if (getPreprocessor()
2249 .getHeaderSearchInfo()
2250 .getSpecificModuleCachePath()
2251 .empty())
2252 return nullptr;
2253 if (!TheASTReader)
2254 createASTReader();
2255 // Can't do anything if we don't have the module manager.
2256 if (!TheASTReader)
2257 return nullptr;
2258 // Get an existing global index. This loads it if not already
2259 // loaded.
2260 TheASTReader->loadGlobalIndex();
2261 GlobalModuleIndex *GlobalIndex = TheASTReader->getGlobalIndex();
2262 // If the global index doesn't exist, create it.
2263 if (!GlobalIndex && shouldBuildGlobalModuleIndex() && hasFileManager() &&
2264 hasPreprocessor()) {
2265 llvm::sys::fs::create_directories(
2266 path: getPreprocessor().getHeaderSearchInfo().getSpecificModuleCachePath());
2267 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2268 FileMgr&: getFileManager(), PCHContainerRdr: getPCHContainerReader(),
2269 Path: getPreprocessor()
2270 .getHeaderSearchInfo()
2271 .getSpecificModuleCachePath())) {
2272 // FIXME this drops the error on the floor. This code is only used for
2273 // typo correction and drops more than just this one source of errors
2274 // (such as the directory creation failure above). It should handle the
2275 // error.
2276 consumeError(Err: std::move(Err));
2277 return nullptr;
2278 }
2279 TheASTReader->resetForReload();
2280 TheASTReader->loadGlobalIndex();
2281 GlobalIndex = TheASTReader->getGlobalIndex();
2282 }
2283 // For finding modules needing to be imported for fixit messages,
2284 // we need to make the global index cover all modules, so we do that here.
2285 if (!HaveFullGlobalModuleIndex && GlobalIndex && !buildingModule()) {
2286 ModuleMap &MMap = getPreprocessor().getHeaderSearchInfo().getModuleMap();
2287
2288 // Load modules that were parsed from module maps but not loaded yet.
2289 MMap.loadAllParsedModules();
2290
2291 bool RecreateIndex = false;
2292 for (ModuleMap::module_iterator I = MMap.module_begin(),
2293 E = MMap.module_end(); I != E; ++I) {
2294 Module *TheModule = I->second;
2295 OptionalFileEntryRef Entry = TheModule->getASTFile();
2296 if (!Entry) {
2297 SmallVector<IdentifierLoc, 2> Path;
2298 Path.emplace_back(Args&: TriggerLoc,
2299 Args: getPreprocessor().getIdentifierInfo(Name: TheModule->Name));
2300 std::reverse(first: Path.begin(), last: Path.end());
2301 // Load a module as hidden. This also adds it to the global index.
2302 loadModule(ImportLoc: TheModule->DefinitionLoc, Path, Visibility: Module::Hidden, IsInclusionDirective: false);
2303 RecreateIndex = true;
2304 }
2305 }
2306 if (RecreateIndex) {
2307 if (llvm::Error Err = GlobalModuleIndex::writeIndex(
2308 FileMgr&: getFileManager(), PCHContainerRdr: getPCHContainerReader(),
2309 Path: getPreprocessor()
2310 .getHeaderSearchInfo()
2311 .getSpecificModuleCachePath())) {
2312 // FIXME As above, this drops the error on the floor.
2313 consumeError(Err: std::move(Err));
2314 return nullptr;
2315 }
2316 TheASTReader->resetForReload();
2317 TheASTReader->loadGlobalIndex();
2318 GlobalIndex = TheASTReader->getGlobalIndex();
2319 }
2320 HaveFullGlobalModuleIndex = true;
2321 }
2322 return GlobalIndex;
2323}
2324
2325// Check global module index for missing imports.
2326bool
2327CompilerInstance::lookupMissingImports(StringRef Name,
2328 SourceLocation TriggerLoc) {
2329 // Look for the symbol in non-imported modules, but only if an error
2330 // actually occurred.
2331 if (!buildingModule()) {
2332 // Load global module index, or retrieve a previously loaded one.
2333 GlobalModuleIndex *GlobalIndex = loadGlobalModuleIndex(
2334 TriggerLoc);
2335
2336 // Only if we have a global index.
2337 if (GlobalIndex) {
2338 GlobalModuleIndex::HitSet FoundModules;
2339
2340 // Find the modules that reference the identifier.
2341 // Note that this only finds top-level modules.
2342 // We'll let diagnoseTypo find the actual declaration module.
2343 if (GlobalIndex->lookupIdentifier(Name, Hits&: FoundModules))
2344 return true;
2345 }
2346 }
2347
2348 return false;
2349}
2350void CompilerInstance::resetAndLeakSema() { llvm::BuryPointer(Ptr: takeSema()); }
2351
2352void CompilerInstance::setExternalSemaSource(
2353 IntrusiveRefCntPtr<ExternalSemaSource> ESS) {
2354 ExternalSemaSrc = std::move(ESS);
2355}
2356