Coverage Report

Created: 2022-01-25 06:29

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