Coverage Report

Created: 2024-01-17 10:31

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