Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/FrontendAction.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- FrontendAction.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/FrontendAction.h"
10
#include "clang/AST/ASTConsumer.h"
11
#include "clang/AST/ASTContext.h"
12
#include "clang/AST/DeclGroup.h"
13
#include "clang/Basic/Builtins.h"
14
#include "clang/Basic/LangStandard.h"
15
#include "clang/Frontend/ASTUnit.h"
16
#include "clang/Frontend/CompilerInstance.h"
17
#include "clang/Frontend/FrontendDiagnostic.h"
18
#include "clang/Frontend/FrontendPluginRegistry.h"
19
#include "clang/Frontend/LayoutOverrideSource.h"
20
#include "clang/Frontend/MultiplexConsumer.h"
21
#include "clang/Frontend/Utils.h"
22
#include "clang/Lex/HeaderSearch.h"
23
#include "clang/Lex/LiteralSupport.h"
24
#include "clang/Lex/Preprocessor.h"
25
#include "clang/Lex/PreprocessorOptions.h"
26
#include "clang/Parse/ParseAST.h"
27
#include "clang/Serialization/ASTDeserializationListener.h"
28
#include "clang/Serialization/ASTReader.h"
29
#include "clang/Serialization/GlobalModuleIndex.h"
30
#include "llvm/ADT/ScopeExit.h"
31
#include "llvm/Support/BuryPointer.h"
32
#include "llvm/Support/ErrorHandling.h"
33
#include "llvm/Support/FileSystem.h"
34
#include "llvm/Support/Path.h"
35
#include "llvm/Support/Timer.h"
36
#include "llvm/Support/raw_ostream.h"
37
#include <system_error>
38
using namespace clang;
39
40
LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
41
42
namespace {
43
44
class DelegatingDeserializationListener : public ASTDeserializationListener {
45
  ASTDeserializationListener *Previous;
46
  bool DeletePrevious;
47
48
public:
49
  explicit DelegatingDeserializationListener(
50
      ASTDeserializationListener *Previous, bool DeletePrevious)
51
106
      : Previous(Previous), DeletePrevious(DeletePrevious) {}
52
104
  ~DelegatingDeserializationListener() override {
53
104
    if (DeletePrevious)
54
0
      delete Previous;
55
104
  }
56
57
212
  void ReaderInitialized(ASTReader *Reader) override {
58
212
    if (Previous)
59
26
      Previous->ReaderInitialized(Reader);
60
212
  }
61
  void IdentifierRead(serialization::IdentID ID,
62
7.81k
                      IdentifierInfo *II) override {
63
7.81k
    if (Previous)
64
261
      Previous->IdentifierRead(ID, II);
65
7.81k
  }
66
1.13k
  void TypeRead(serialization::TypeIdx Idx, QualType T) override {
67
1.13k
    if (Previous)
68
28
      Previous->TypeRead(Idx, T);
69
1.13k
  }
70
1.27k
  void DeclRead(serialization::DeclID ID, const Decl *D) override {
71
1.27k
    if (Previous)
72
15
      Previous->DeclRead(ID, D);
73
1.27k
  }
74
0
  void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
75
0
    if (Previous)
76
0
      Previous->SelectorRead(ID, Sel);
77
0
  }
78
  void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
79
99
                           MacroDefinitionRecord *MD) override {
80
99
    if (Previous)
81
12
      Previous->MacroDefinitionRead(PPID, MD);
82
99
  }
83
};
84
85
/// Dumps deserialized declarations.
86
class DeserializedDeclsDumper : public DelegatingDeserializationListener {
87
public:
88
  explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
89
                                   bool DeletePrevious)
90
0
      : DelegatingDeserializationListener(Previous, DeletePrevious) {}
91
92
0
  void DeclRead(serialization::DeclID ID, const Decl *D) override {
93
0
    llvm::outs() << "PCH DECL: " << D->getDeclKindName();
94
0
    if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
95
0
      llvm::outs() << " - ";
96
0
      ND->printQualifiedName(llvm::outs());
97
0
    }
98
0
    llvm::outs() << "\n";
99
100
0
    DelegatingDeserializationListener::DeclRead(ID, D);
101
0
  }
102
};
103
104
/// Checks deserialized declarations and emits error if a name
105
/// matches one given in command-line using -error-on-deserialized-decl.
106
class DeserializedDeclsChecker : public DelegatingDeserializationListener {
107
  ASTContext &Ctx;
108
  std::set<std::string> NamesToCheck;
109
110
public:
111
  DeserializedDeclsChecker(ASTContext &Ctx,
112
                           const std::set<std::string> &NamesToCheck,
113
                           ASTDeserializationListener *Previous,
114
                           bool DeletePrevious)
115
      : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
116
106
        NamesToCheck(NamesToCheck) {}
117
118
1.27k
  void DeclRead(serialization::DeclID ID, const Decl *D) override {
119
1.27k
    if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
120
1.15k
      if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
121
2
        unsigned DiagID
122
2
          = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
123
2
                                                 "%0 was deserialized");
124
2
        Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
125
2
            << ND;
126
2
      }
127
128
1.27k
    DelegatingDeserializationListener::DeclRead(ID, D);
129
1.27k
  }
130
};
131
132
} // end anonymous namespace
133
134
72.4k
FrontendAction::FrontendAction() : Instance(nullptr) {}
135
136
66.8k
FrontendAction::~FrontendAction() {}
137
138
void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
139
143k
                                     std::unique_ptr<ASTUnit> AST) {
140
143k
  this->CurrentInput = CurrentInput;
141
143k
  CurrentASTUnit = std::move(AST);
142
143k
}
143
144
19
Module *FrontendAction::getCurrentModule() const {
145
19
  CompilerInstance &CI = getCompilerInstance();
146
19
  return CI.getPreprocessor().getHeaderSearchInfo().lookupModule(
147
19
      CI.getLangOpts().CurrentModule, SourceLocation(), /*AllowSearch*/false);
148
19
}
149
150
std::unique_ptr<ASTConsumer>
151
FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
152
70.0k
                                         StringRef InFile) {
153
70.0k
  std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
154
70.0k
  if (!Consumer)
155
3
    return nullptr;
156
157
  // Validate -add-plugin args.
158
70.0k
  bool FoundAllPlugins = true;
159
70.0k
  for (const std::string &Arg : CI.getFrontendOpts().AddPluginActions) {
160
1
    bool Found = false;
161
1
    for (const FrontendPluginRegistry::entry &Plugin :
162
1
         FrontendPluginRegistry::entries()) {
163
0
      if (Plugin.getName() == Arg)
164
0
        Found = true;
165
0
    }
166
1
    if (!Found) {
167
1
      CI.getDiagnostics().Report(diag::err_fe_invalid_plugin_name) << Arg;
168
1
      FoundAllPlugins = false;
169
1
    }
170
1
  }
171
70.0k
  if (!FoundAllPlugins)
172
1
    return nullptr;
173
174
  // If there are no registered plugins we don't need to wrap the consumer
175
70.0k
  if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
176
70.0k
    return Consumer;
177
178
  // If this is a code completion run, avoid invoking the plugin consumers
179
0
  if (CI.hasCodeCompletionConsumer())
180
0
    return Consumer;
181
182
  // Collect the list of plugins that go before the main action (in Consumers)
183
  // or after it (in AfterConsumers)
184
0
  std::vector<std::unique_ptr<ASTConsumer>> Consumers;
185
0
  std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
186
0
  for (const FrontendPluginRegistry::entry &Plugin :
187
0
       FrontendPluginRegistry::entries()) {
188
0
    std::unique_ptr<PluginASTAction> P = Plugin.instantiate();
189
0
    PluginASTAction::ActionType ActionType = P->getActionType();
190
0
    if (ActionType == PluginASTAction::CmdlineAfterMainAction ||
191
0
        ActionType == PluginASTAction::CmdlineBeforeMainAction) {
192
      // This is O(|plugins| * |add_plugins|), but since both numbers are
193
      // way below 50 in practice, that's ok.
194
0
      if (llvm::any_of(CI.getFrontendOpts().AddPluginActions,
195
0
                       [&](const std::string &PluginAction) {
196
0
                         return PluginAction == Plugin.getName();
197
0
                       })) {
198
0
        if (ActionType == PluginASTAction::CmdlineBeforeMainAction)
199
0
          ActionType = PluginASTAction::AddBeforeMainAction;
200
0
        else
201
0
          ActionType = PluginASTAction::AddAfterMainAction;
202
0
      }
203
0
    }
204
0
    if ((ActionType == PluginASTAction::AddBeforeMainAction ||
205
0
         ActionType == PluginASTAction::AddAfterMainAction) &&
206
0
        P->ParseArgs(
207
0
            CI,
208
0
            CI.getFrontendOpts().PluginArgs[std::string(Plugin.getName())])) {
209
0
      std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
210
0
      if (ActionType == PluginASTAction::AddBeforeMainAction) {
211
0
        Consumers.push_back(std::move(PluginConsumer));
212
0
      } else {
213
0
        AfterConsumers.push_back(std::move(PluginConsumer));
214
0
      }
215
0
    }
216
0
  }
217
218
  // Add to Consumers the main consumer, then all the plugins that go after it
219
0
  Consumers.push_back(std::move(Consumer));
220
0
  if (!AfterConsumers.empty()) {
221
    // If we have plugins after the main consumer, which may be the codegen
222
    // action, they likely will need the ASTContext, so don't clear it in the
223
    // codegen action.
224
0
    CI.getCodeGenOpts().ClearASTBeforeBackend = false;
225
0
    for (auto &C : AfterConsumers)
226
0
      Consumers.push_back(std::move(C));
227
0
  }
228
229
0
  return std::make_unique<MultiplexConsumer>(std::move(Consumers));
230
0
}
231
232
/// For preprocessed files, if the first line is the linemarker and specifies
233
/// the original source file name, use that name as the input file name.
234
/// Returns the location of the first token after the line marker directive.
235
///
236
/// \param CI The compiler instance.
237
/// \param InputFile Populated with the filename from the line marker.
238
/// \param IsModuleMap If \c true, add a line note corresponding to this line
239
///        directive. (We need to do this because the directive will not be
240
///        visited by the preprocessor.)
241
static SourceLocation ReadOriginalFileName(CompilerInstance &CI,
242
                                           std::string &InputFile,
243
176
                                           bool IsModuleMap = false) {
244
176
  auto &SourceMgr = CI.getSourceManager();
245
176
  auto MainFileID = SourceMgr.getMainFileID();
246
247
176
  auto MainFileBuf = SourceMgr.getBufferOrNone(MainFileID);
248
176
  if (!MainFileBuf)
249
0
    return SourceLocation();
250
251
176
  std::unique_ptr<Lexer> RawLexer(
252
176
      new Lexer(MainFileID, *MainFileBuf, SourceMgr, CI.getLangOpts()));
253
254
  // If the first line has the syntax of
255
  //
256
  // # NUM "FILENAME"
257
  //
258
  // we use FILENAME as the input file name.
259
176
  Token T;
260
176
  if (RawLexer->LexFromRawLexer(T) || 
T.getKind() != tok::hash174
)
261
137
    return SourceLocation();
262
39
  if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
263
39
      T.getKind() != tok::numeric_constant)
264
4
    return SourceLocation();
265
266
35
  unsigned LineNo;
267
35
  SourceLocation LineNoLoc = T.getLocation();
268
35
  if (IsModuleMap) {
269
16
    llvm::SmallString<16> Buffer;
270
16
    if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
271
16
            .getAsInteger(10, LineNo))
272
0
      return SourceLocation();
273
16
  }
274
275
35
  RawLexer->LexFromRawLexer(T);
276
35
  if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
277
0
    return SourceLocation();
278
279
35
  StringLiteralParser Literal(T, CI.getPreprocessor());
280
35
  if (Literal.hadError)
281
0
    return SourceLocation();
282
35
  RawLexer->LexFromRawLexer(T);
283
35
  if (T.isNot(tok::eof) && !T.isAtStartOfLine())
284
0
    return SourceLocation();
285
35
  InputFile = Literal.GetString().str();
286
287
35
  if (IsModuleMap)
288
16
    CI.getSourceManager().AddLineNote(
289
16
        LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
290
16
        false, SrcMgr::C_User_ModuleMap);
291
292
35
  return T.getLocation();
293
35
}
294
295
static SmallVectorImpl<char> &
296
68.4k
operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
297
68.4k
  Includes.append(RHS.begin(), RHS.end());
298
68.4k
  return Includes;
299
68.4k
}
300
301
static void addHeaderInclude(StringRef HeaderName,
302
                             SmallVectorImpl<char> &Includes,
303
                             const LangOptions &LangOpts,
304
18.7k
                             bool IsExternC) {
305
18.7k
  if (IsExternC && 
LangOpts.CPlusPlus11.5k
)
306
6.08k
    Includes += "extern \"C\" {\n";
307
18.7k
  if (LangOpts.ObjC)
308
6.37k
    Includes += "#import \"";
309
12.3k
  else
310
12.3k
    Includes += "#include \"";
311
312
18.7k
  Includes += HeaderName;
313
314
18.7k
  Includes += "\"\n";
315
18.7k
  if (IsExternC && 
LangOpts.CPlusPlus11.5k
)
316
6.08k
    Includes += "}\n";
317
18.7k
}
318
319
/// Collect the set of header includes needed to construct the given
320
/// module and update the TopHeaders file set of the module.
321
///
322
/// \param Module The module we're collecting includes from.
323
///
324
/// \param Includes Will be augmented with the set of \#includes or \#imports
325
/// needed to load all of the named headers.
326
static std::error_code collectModuleHeaderIncludes(
327
    const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
328
16.5k
    ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
329
  // Don't collect any headers for unavailable modules.
330
16.5k
  if (!Module->isAvailable())
331
401
    return std::error_code();
332
333
  // Resolve all lazy header directives to header files.
334
16.1k
  ModMap.resolveHeaderDirectives(Module);
335
336
  // If any headers are missing, we can't build this module. In most cases,
337
  // diagnostics for this should have already been produced; we only get here
338
  // if explicit stat information was provided.
339
  // FIXME: If the name resolves to a file with different stat information,
340
  // produce a better diagnostic.
341
16.1k
  if (!Module->MissingHeaders.empty()) {
342
1
    auto &MissingHeader = Module->MissingHeaders.front();
343
1
    Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
344
1
      << MissingHeader.IsUmbrella << MissingHeader.FileName;
345
1
    return std::error_code();
346
1
  }
347
348
  // Add includes for each of these headers.
349
32.3k
  
for (auto HK : {Module::HK_Normal, Module::HK_Private})16.1k
{
350
32.3k
    for (Module::Header &H : Module->Headers[HK]) {
351
15.0k
      Module->addTopHeader(H.Entry);
352
      // Use the path as specified in the module map file. We'll look for this
353
      // file relative to the module build directory (the directory containing
354
      // the module map file) so this will find the same file that we found
355
      // while parsing the module map.
356
15.0k
      addHeaderInclude(H.PathRelativeToRootModuleDirectory, Includes, LangOpts,
357
15.0k
                       Module->IsExternC);
358
15.0k
    }
359
32.3k
  }
360
  // Note that Module->PrivateHeaders will not be a TopHeader.
361
362
16.1k
  if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
363
490
    Module->addTopHeader(UmbrellaHeader.Entry);
364
490
    if (Module->Parent)
365
      // Include the umbrella header for submodules.
366
224
      addHeaderInclude(UmbrellaHeader.PathRelativeToRootModuleDirectory,
367
224
                       Includes, LangOpts, Module->IsExternC);
368
15.6k
  } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
369
    // Add all of the headers we find in this subdirectory.
370
201
    std::error_code EC;
371
201
    SmallString<128> DirNative;
372
201
    llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
373
374
201
    llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
375
201
    SmallVector<std::pair<std::string, const FileEntry *>, 8> Headers;
376
201
    for (llvm::vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
377
3.52k
         Dir != End && 
!EC3.32k
;
Dir.increment(EC)3.32k
) {
378
      // Check whether this entry has an extension typically associated with
379
      // headers.
380
3.32k
      if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
381
3.32k
               .Cases(".h", ".H", ".hh", ".hpp", true)
382
3.32k
               .Default(false))
383
40
        continue;
384
385
3.28k
      auto Header = FileMgr.getFile(Dir->path());
386
      // FIXME: This shouldn't happen unless there is a file system race. Is
387
      // that worth diagnosing?
388
3.28k
      if (!Header)
389
1
        continue;
390
391
      // If this header is marked 'unavailable' in this module, don't include
392
      // it.
393
3.28k
      if (ModMap.isHeaderUnavailableInModule(*Header, Module))
394
8
        continue;
395
396
      // Compute the relative path from the directory to this file.
397
3.27k
      SmallVector<StringRef, 16> Components;
398
3.27k
      auto PathIt = llvm::sys::path::rbegin(Dir->path());
399
6.55k
      for (int I = 0; I != Dir.level() + 1; 
++I, ++PathIt3.27k
)
400
3.27k
        Components.push_back(*PathIt);
401
3.27k
      SmallString<128> RelativeHeader(
402
3.27k
          UmbrellaDir.PathRelativeToRootModuleDirectory);
403
6.55k
      for (auto It = Components.rbegin(), End = Components.rend(); It != End;
404
3.27k
           ++It)
405
3.27k
        llvm::sys::path::append(RelativeHeader, *It);
406
407
3.27k
      std::string RelName = RelativeHeader.c_str();
408
3.27k
      Headers.push_back(std::make_pair(RelName, *Header));
409
3.27k
    }
410
411
201
    if (EC)
412
0
      return EC;
413
414
    // Sort header paths and make the header inclusion order deterministic
415
    // across different OSs and filesystems.
416
201
    llvm::sort(Headers.begin(), Headers.end(), [](
417
201
      const std::pair<std::string, const FileEntry *> &LHS,
418
16.4k
      const std::pair<std::string, const FileEntry *> &RHS) {
419
16.4k
        return LHS.first < RHS.first;
420
16.4k
    });
421
3.27k
    for (auto &H : Headers) {
422
      // Include this header as part of the umbrella directory.
423
3.27k
      Module->addTopHeader(H.second);
424
3.27k
      addHeaderInclude(H.first, Includes, LangOpts, Module->IsExternC);
425
3.27k
    }
426
201
  }
427
428
  // Recurse into submodules.
429
16.1k
  for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
430
16.1k
                                      SubEnd = Module->submodule_end();
431
30.8k
       Sub != SubEnd; 
++Sub14.6k
)
432
14.6k
    if (std::error_code Err = collectModuleHeaderIncludes(
433
14.6k
            LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
434
0
      return Err;
435
436
16.1k
  return std::error_code();
437
16.1k
}
438
439
static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
440
                                        bool IsPreprocessed,
441
                                        std::string &PresumedModuleMapFile,
442
1.97k
                                        unsigned &Offset) {
443
1.97k
  auto &SrcMgr = CI.getSourceManager();
444
1.97k
  HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
445
446
  // Map the current input to a file.
447
1.97k
  FileID ModuleMapID = SrcMgr.getMainFileID();
448
1.97k
  const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
449
450
  // If the module map is preprocessed, handle the initial line marker;
451
  // line directives are not part of the module map syntax in general.
452
1.97k
  Offset = 0;
453
1.97k
  if (IsPreprocessed) {
454
82
    SourceLocation EndOfLineMarker =
455
82
        ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
456
82
    if (EndOfLineMarker.isValid())
457
16
      Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
458
82
  }
459
460
  // Load the module map file.
461
1.97k
  if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
462
1.97k
                           PresumedModuleMapFile))
463
0
    return true;
464
465
1.97k
  if (SrcMgr.getBufferOrFake(ModuleMapID).getBufferSize() == Offset)
466
1.88k
    Offset = 0;
467
468
1.97k
  return false;
469
1.97k
}
470
471
static Module *prepareToBuildModule(CompilerInstance &CI,
472
1.97k
                                    StringRef ModuleMapFilename) {
473
1.97k
  if (CI.getLangOpts().CurrentModule.empty()) {
474
0
    CI.getDiagnostics().Report(diag::err_missing_module_name);
475
476
    // FIXME: Eventually, we could consider asking whether there was just
477
    // a single module described in the module map, and use that as a
478
    // default. Then it would be fairly trivial to just "compile" a module
479
    // map with a single module (the common case).
480
0
    return nullptr;
481
0
  }
482
483
  // Dig out the module definition.
484
1.97k
  HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
485
1.97k
  Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule, SourceLocation(),
486
1.97k
                              /*AllowSearch=*/true);
487
1.97k
  if (!M) {
488
2
    CI.getDiagnostics().Report(diag::err_missing_module)
489
2
      << CI.getLangOpts().CurrentModule << ModuleMapFilename;
490
491
2
    return nullptr;
492
2
  }
493
494
  // Check whether we can build this module at all.
495
1.97k
  if (Preprocessor::checkModuleIsAvailable(CI.getLangOpts(), CI.getTarget(),
496
1.97k
                                           CI.getDiagnostics(), M))
497
3
    return nullptr;
498
499
  // Inform the preprocessor that includes from within the input buffer should
500
  // be resolved relative to the build directory of the module map file.
501
1.96k
  CI.getPreprocessor().setMainFileDir(M->Directory);
502
503
  // If the module was inferred from a different module map (via an expanded
504
  // umbrella module definition), track that fact.
505
  // FIXME: It would be preferable to fill this in as part of processing
506
  // the module map, rather than adding it after the fact.
507
1.96k
  StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
508
1.96k
  if (!OriginalModuleMapName.empty()) {
509
1.65k
    auto OriginalModuleMap =
510
1.65k
        CI.getFileManager().getFile(OriginalModuleMapName,
511
1.65k
                                    /*openFile*/ true);
512
1.65k
    if (!OriginalModuleMap) {
513
0
      CI.getDiagnostics().Report(diag::err_module_map_not_found)
514
0
        << OriginalModuleMapName;
515
0
      return nullptr;
516
0
    }
517
1.65k
    if (*OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
518
1.65k
                                 CI.getSourceManager().getMainFileID())) {
519
109
      M->IsInferred = true;
520
109
      CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
521
109
        .setInferredModuleAllowedBy(M, *OriginalModuleMap);
522
109
    }
523
1.65k
  }
524
525
  // If we're being run from the command-line, the module build stack will not
526
  // have been filled in yet, so complete it now in order to allow us to detect
527
  // module cycles.
528
1.96k
  SourceManager &SourceMgr = CI.getSourceManager();
529
1.96k
  if (SourceMgr.getModuleBuildStack().empty())
530
242
    SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
531
242
                                   FullSourceLoc(SourceLocation(), SourceMgr));
532
1.96k
  return M;
533
1.96k
}
534
535
/// Compute the input buffer that should be used to build the specified module.
536
static std::unique_ptr<llvm::MemoryBuffer>
537
1.88k
getInputBufferForModule(CompilerInstance &CI, Module *M) {
538
1.88k
  FileManager &FileMgr = CI.getFileManager();
539
540
  // Collect the set of #includes we need to build the module.
541
1.88k
  SmallString<256> HeaderContents;
542
1.88k
  std::error_code Err = std::error_code();
543
1.88k
  if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
544
266
    addHeaderInclude(UmbrellaHeader.PathRelativeToRootModuleDirectory,
545
266
                     HeaderContents, CI.getLangOpts(), M->IsExternC);
546
1.88k
  Err = collectModuleHeaderIncludes(
547
1.88k
      CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
548
1.88k
      CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
549
1.88k
      HeaderContents);
550
551
1.88k
  if (Err) {
552
0
    CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
553
0
      << M->getFullModuleName() << Err.message();
554
0
    return nullptr;
555
0
  }
556
557
1.88k
  return llvm::MemoryBuffer::getMemBufferCopy(
558
1.88k
      HeaderContents, Module::getModuleInputBufferName());
559
1.88k
}
560
561
bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
562
72.2k
                                     const FrontendInputFile &RealInput) {
563
72.2k
  FrontendInputFile Input(RealInput);
564
72.2k
  assert(!Instance && "Already processing a source file!");
565
0
  assert(!Input.isEmpty() && "Unexpected empty filename!");
566
0
  setCurrentInput(Input);
567
72.2k
  setCompilerInstance(&CI);
568
569
72.2k
  bool HasBegunSourceFile = false;
570
72.2k
  bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
571
72.2k
                       
usesPreprocessorOnly()50
;
572
573
  // If we fail, reset state since the client will not end up calling the
574
  // matching EndSourceFile(). All paths that return true should release this.
575
72.2k
  auto FailureCleanup = llvm::make_scope_exit([&]() {
576
68
    if (HasBegunSourceFile)
577
53
      CI.getDiagnosticClient().EndSourceFile();
578
68
    CI.clearOutputFiles(/*EraseFiles=*/true);
579
68
    CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
580
68
    setCurrentInput(FrontendInputFile());
581
68
    setCompilerInstance(nullptr);
582
68
  });
583
584
72.2k
  if (!BeginInvocation(CI))
585
12
    return false;
586
587
  // If we're replaying the build of an AST file, import it and set up
588
  // the initial state from its build.
589
72.2k
  if (ReplayASTFile) {
590
15
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
591
592
    // The AST unit populates its own diagnostics engine rather than ours.
593
15
    IntrusiveRefCntPtr<DiagnosticsEngine> ASTDiags(
594
15
        new DiagnosticsEngine(Diags->getDiagnosticIDs(),
595
15
                              &Diags->getDiagnosticOptions()));
596
15
    ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
597
598
    // FIXME: What if the input is a memory buffer?
599
15
    StringRef InputFile = Input.getFile();
600
601
15
    std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
602
15
        std::string(InputFile), CI.getPCHContainerReader(),
603
15
        ASTUnit::LoadPreprocessorOnly, ASTDiags, CI.getFileSystemOpts(),
604
15
        CI.getCodeGenOpts().DebugTypeExtRefs);
605
15
    if (!AST)
606
0
      return false;
607
608
    // Options relating to how we treat the input (but not what we do with it)
609
    // are inherited from the AST unit.
610
15
    CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
611
15
    CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
612
15
    CI.getLangOpts() = AST->getLangOpts();
613
614
    // Set the shared objects, these are reset when we finish processing the
615
    // file, otherwise the CompilerInstance will happily destroy them.
616
15
    CI.setFileManager(&AST->getFileManager());
617
15
    CI.createSourceManager(CI.getFileManager());
618
15
    CI.getSourceManager().initializeForReplay(AST->getSourceManager());
619
620
    // Preload all the module files loaded transitively by the AST unit. Also
621
    // load all module map files that were parsed as part of building the AST
622
    // unit.
623
15
    if (auto ASTReader = AST->getASTReader()) {
624
15
      auto &MM = ASTReader->getModuleManager();
625
15
      auto &PrimaryModule = MM.getPrimaryModule();
626
627
15
      for (serialization::ModuleFile &MF : MM)
628
25
        if (&MF != &PrimaryModule)
629
10
          CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
630
631
15
      ASTReader->visitTopLevelModuleMaps(
632
15
          PrimaryModule, [&](const FileEntry *FE) {
633
14
            CI.getFrontendOpts().ModuleMapFiles.push_back(
634
14
                std::string(FE->getName()));
635
14
          });
636
15
    }
637
638
    // Set up the input file for replay purposes.
639
15
    auto Kind = AST->getInputKind();
640
15
    if (Kind.getFormat() == InputKind::ModuleMap) {
641
13
      Module *ASTModule =
642
13
          AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
643
13
              AST->getLangOpts().CurrentModule, SourceLocation(),
644
13
              /*AllowSearch*/ false);
645
13
      assert(ASTModule && "module file does not define its own module");
646
0
      Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
647
13
    } else {
648
2
      auto &OldSM = AST->getSourceManager();
649
2
      FileID ID = OldSM.getMainFileID();
650
2
      if (auto *File = OldSM.getFileEntryForID(ID))
651
0
        Input = FrontendInputFile(File->getName(), Kind);
652
2
      else
653
2
        Input = FrontendInputFile(OldSM.getBufferOrFake(ID), Kind);
654
2
    }
655
0
    setCurrentInput(Input, std::move(AST));
656
15
  }
657
658
  // AST files follow a very different path, since they share objects via the
659
  // AST unit.
660
72.2k
  if (Input.getKind().getFormat() == InputKind::Precompiled) {
661
35
    assert(!usesPreprocessorOnly() && "this case was handled above");
662
0
    assert(hasASTFileSupport() &&
663
35
           "This action does not have AST file support!");
664
665
0
    IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
666
667
    // FIXME: What if the input is a memory buffer?
668
35
    StringRef InputFile = Input.getFile();
669
670
35
    std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
671
35
        std::string(InputFile), CI.getPCHContainerReader(),
672
35
        ASTUnit::LoadEverything, Diags, CI.getFileSystemOpts(),
673
35
        CI.getCodeGenOpts().DebugTypeExtRefs);
674
675
35
    if (!AST)
676
0
      return false;
677
678
    // Inform the diagnostic client we are processing a source file.
679
35
    CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
680
35
    HasBegunSourceFile = true;
681
682
    // Set the shared objects, these are reset when we finish processing the
683
    // file, otherwise the CompilerInstance will happily destroy them.
684
35
    CI.setFileManager(&AST->getFileManager());
685
35
    CI.setSourceManager(&AST->getSourceManager());
686
35
    CI.setPreprocessor(AST->getPreprocessorPtr());
687
35
    Preprocessor &PP = CI.getPreprocessor();
688
35
    PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
689
35
                                           PP.getLangOpts());
690
35
    CI.setASTContext(&AST->getASTContext());
691
692
35
    setCurrentInput(Input, std::move(AST));
693
694
    // Initialize the action.
695
35
    if (!BeginSourceFileAction(CI))
696
0
      return false;
697
698
    // Create the AST consumer.
699
35
    CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
700
35
    if (!CI.hasASTConsumer())
701
0
      return false;
702
703
35
    FailureCleanup.release();
704
35
    return true;
705
35
  }
706
707
  // Set up the file and source managers, if needed.
708
72.2k
  if (!CI.hasFileManager()) {
709
39.4k
    if (!CI.createFileManager()) {
710
0
      return false;
711
0
    }
712
39.4k
  }
713
72.2k
  if (!CI.hasSourceManager())
714
40.8k
    CI.createSourceManager(CI.getFileManager());
715
716
  // Set up embedding for any specified files. Do this before we load any
717
  // source files, including the primary module map for the compilation.
718
72.2k
  for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
719
3
    if (auto FE = CI.getFileManager().getFile(F, /*openFile*/true))
720
2
      CI.getSourceManager().setFileIsTransient(*FE);
721
1
    else
722
1
      CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
723
3
  }
724
72.2k
  if (CI.getFrontendOpts().ModulesEmbedAllFiles)
725
10
    CI.getSourceManager().setAllFilesAreTransient(true);
726
727
  // IR files bypass the rest of initialization.
728
72.2k
  if (Input.getKind().getLanguage() == Language::LLVM_IR) {
729
113
    assert(hasIRSupport() &&
730
113
           "This action does not have IR file support!");
731
732
    // Inform the diagnostic client we are processing a source file.
733
0
    CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
734
113
    HasBegunSourceFile = true;
735
736
    // Initialize the action.
737
113
    if (!BeginSourceFileAction(CI))
738
0
      return false;
739
740
    // Initialize the main file entry.
741
113
    if (!CI.InitializeSourceManager(CurrentInput))
742
0
      return false;
743
744
113
    FailureCleanup.release();
745
113
    return true;
746
113
  }
747
748
  // If the implicit PCH include is actually a directory, rather than
749
  // a single file, search for a suitable PCH file in that directory.
750
72.0k
  if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
751
3.66k
    FileManager &FileMgr = CI.getFileManager();
752
3.66k
    PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
753
3.66k
    StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
754
3.66k
    std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
755
3.66k
    if (auto PCHDir = FileMgr.getDirectory(PCHInclude)) {
756
6
      std::error_code EC;
757
6
      SmallString<128> DirNative;
758
6
      llvm::sys::path::native((*PCHDir)->getName(), DirNative);
759
6
      bool Found = false;
760
6
      llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
761
6
      for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
762
6
                                         DirEnd;
763
16
           Dir != DirEnd && 
!EC13
;
Dir.increment(EC)10
) {
764
        // Check whether this is an acceptable AST file.
765
13
        if (ASTReader::isAcceptableASTFile(
766
13
                Dir->path(), FileMgr, CI.getPCHContainerReader(),
767
13
                CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
768
13
                SpecificModuleCachePath)) {
769
3
          PPOpts.ImplicitPCHInclude = std::string(Dir->path());
770
3
          Found = true;
771
3
          break;
772
3
        }
773
13
      }
774
775
6
      if (!Found) {
776
3
        CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
777
3
        return false;
778
3
      }
779
6
    }
780
3.66k
  }
781
782
  // Set up the preprocessor if needed. When parsing model files the
783
  // preprocessor of the original source is reused.
784
72.0k
  if (!isModelParsingAction())
785
72.0k
    CI.createPreprocessor(getTranslationUnitKind());
786
787
  // Inform the diagnostic client we are processing a source file.
788
72.0k
  CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
789
72.0k
                                           &CI.getPreprocessor());
790
72.0k
  HasBegunSourceFile = true;
791
792
  // Initialize the main file entry.
793
72.0k
  if (!CI.InitializeSourceManager(Input))
794
4
    return false;
795
796
  // For module map files, we first parse the module map and synthesize a
797
  // "<module-includes>" buffer before more conventional processing.
798
72.0k
  if (Input.getKind().getFormat() == InputKind::ModuleMap) {
799
1.97k
    CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
800
801
1.97k
    std::string PresumedModuleMapFile;
802
1.97k
    unsigned OffsetToContents;
803
1.97k
    if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
804
1.97k
                                    Input.isPreprocessed(),
805
1.97k
                                    PresumedModuleMapFile, OffsetToContents))
806
0
      return false;
807
808
1.97k
    auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
809
1.97k
    if (!CurrentModule)
810
5
      return false;
811
812
1.96k
    CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
813
814
1.96k
    if (OffsetToContents)
815
      // If the module contents are in the same file, skip to them.
816
87
      CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
817
1.88k
    else {
818
      // Otherwise, convert the module description to a suitable input buffer.
819
1.88k
      auto Buffer = getInputBufferForModule(CI, CurrentModule);
820
1.88k
      if (!Buffer)
821
0
        return false;
822
823
      // Reinitialize the main file entry to refer to the new input.
824
1.88k
      auto Kind = CurrentModule->IsSystem ? 
SrcMgr::C_System331
:
SrcMgr::C_User1.55k
;
825
1.88k
      auto &SourceMgr = CI.getSourceManager();
826
1.88k
      auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
827
1.88k
      assert(BufferID.isValid() && "couldn't create module buffer ID");
828
0
      SourceMgr.setMainFileID(BufferID);
829
1.88k
    }
830
1.96k
  }
831
832
  // Initialize the action.
833
72.0k
  if (!BeginSourceFileAction(CI))
834
1
    return false;
835
836
  // If we were asked to load any module map files, do so now.
837
72.0k
  for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
838
286
    if (auto File = CI.getFileManager().getFile(Filename))
839
285
      CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
840
285
          *File, /*IsSystem*/false);
841
1
    else
842
1
      CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
843
286
  }
844
845
  // Add a module declaration scope so that modules from -fmodule-map-file
846
  // arguments may shadow modules found implicitly in search paths.
847
72.0k
  CI.getPreprocessor()
848
72.0k
      .getHeaderSearchInfo()
849
72.0k
      .getModuleMap()
850
72.0k
      .finishModuleDeclarationScope();
851
852
  // Create the AST context and consumer unless this is a preprocessor only
853
  // action.
854
72.0k
  if (!usesPreprocessorOnly()) {
855
    // Parsing a model file should reuse the existing ASTContext.
856
70.0k
    if (!isModelParsingAction())
857
70.0k
      CI.createASTContext();
858
859
    // For preprocessed files, check if the first line specifies the original
860
    // source file name with a linemarker.
861
70.0k
    std::string PresumedInputFile = std::string(getCurrentFileOrBufferName());
862
70.0k
    if (Input.isPreprocessed())
863
94
      ReadOriginalFileName(CI, PresumedInputFile);
864
865
70.0k
    std::unique_ptr<ASTConsumer> Consumer =
866
70.0k
        CreateWrappedASTConsumer(CI, PresumedInputFile);
867
70.0k
    if (!Consumer)
868
4
      return false;
869
870
    // FIXME: should not overwrite ASTMutationListener when parsing model files?
871
70.0k
    if (!isModelParsingAction())
872
70.0k
      CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
873
874
70.0k
    if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
875
      // Convert headers to PCH and chain them.
876
27
      IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
877
27
      source = createChainedIncludesSource(CI, FinalReader);
878
27
      if (!source)
879
0
        return false;
880
27
      CI.setASTReader(static_cast<ASTReader *>(FinalReader.get()));
881
27
      CI.getASTContext().setExternalSource(source);
882
70.0k
    } else if (CI.getLangOpts().Modules ||
883
70.0k
               
!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()60.9k
) {
884
      // Use PCM or PCH.
885
12.6k
      assert(hasPCHSupport() && "This action does not have PCH support!");
886
0
      ASTDeserializationListener *DeserialListener =
887
12.6k
          Consumer->GetASTDeserializationListener();
888
12.6k
      bool DeleteDeserialListener = false;
889
12.6k
      if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
890
0
        DeserialListener = new DeserializedDeclsDumper(DeserialListener,
891
0
                                                       DeleteDeserialListener);
892
0
        DeleteDeserialListener = true;
893
0
      }
894
12.6k
      if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
895
106
        DeserialListener = new DeserializedDeclsChecker(
896
106
            CI.getASTContext(),
897
106
            CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
898
106
            DeserialListener, DeleteDeserialListener);
899
106
        DeleteDeserialListener = true;
900
106
      }
901
12.6k
      if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
902
3.65k
        CI.createPCHExternalASTSource(
903
3.65k
            CI.getPreprocessorOpts().ImplicitPCHInclude,
904
3.65k
            CI.getPreprocessorOpts().DisablePCHOrModuleValidation,
905
3.65k
            CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
906
3.65k
            DeserialListener, DeleteDeserialListener);
907
3.65k
        if (!CI.getASTContext().getExternalSource())
908
28
          return false;
909
3.65k
      }
910
      // If modules are enabled, create the AST reader before creating
911
      // any builtins, so that all declarations know that they might be
912
      // extended by an external source.
913
12.5k
      if (CI.getLangOpts().Modules || 
!CI.hasASTContext()3.52k
||
914
12.5k
          
!CI.getASTContext().getExternalSource()3.52k
) {
915
9.04k
        CI.createASTReader();
916
9.04k
        CI.getASTReader()->setDeserializationListener(DeserialListener,
917
9.04k
                                                      DeleteDeserialListener);
918
9.04k
      }
919
12.5k
    }
920
921
70.0k
    CI.setASTConsumer(std::move(Consumer));
922
70.0k
    if (!CI.hasASTConsumer())
923
0
      return false;
924
70.0k
  }
925
926
  // Initialize built-in info as long as we aren't using an external AST
927
  // source.
928
72.0k
  if (CI.getLangOpts().Modules || 
!CI.hasASTContext()62.9k
||
929
72.0k
      
!CI.getASTContext().getExternalSource()60.9k
) {
930
68.5k
    Preprocessor &PP = CI.getPreprocessor();
931
68.5k
    PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
932
68.5k
                                           PP.getLangOpts());
933
68.5k
  } else {
934
    // FIXME: If this is a problem, recover from it by creating a multiplex
935
    // source.
936
3.54k
    assert((!CI.getLangOpts().Modules || CI.getASTReader()) &&
937
3.54k
           "modules enabled but created an external source that "
938
3.54k
           "doesn't support modules");
939
3.54k
  }
940
941
  // If we were asked to load any module files, do so now.
942
0
  for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
943
435
    if (!CI.loadModuleFile(ModuleFile))
944
11
      return false;
945
946
  // If there is a layout overrides file, attach an external AST source that
947
  // provides the layouts from that file.
948
72.0k
  if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
949
72.0k
      
CI.hasASTContext()6
&&
!CI.getASTContext().getExternalSource()6
) {
950
6
    IntrusiveRefCntPtr<ExternalASTSource>
951
6
      Override(new LayoutOverrideSource(
952
6
                     CI.getFrontendOpts().OverrideRecordLayoutsFile));
953
6
    CI.getASTContext().setExternalSource(Override);
954
6
  }
955
956
72.0k
  FailureCleanup.release();
957
72.0k
  return true;
958
72.0k
}
959
960
70.8k
llvm::Error FrontendAction::Execute() {
961
70.8k
  CompilerInstance &CI = getCompilerInstance();
962
963
70.8k
  if (CI.hasFrontendTimer()) {
964
18
    llvm::TimeRegion Timer(CI.getFrontendTimer());
965
18
    ExecuteAction();
966
18
  }
967
70.7k
  else ExecuteAction();
968
969
  // If we are supposed to rebuild the global module index, do so now unless
970
  // there were any module-build failures.
971
70.8k
  if (CI.shouldBuildGlobalModuleIndex() && 
CI.hasFileManager()892
&&
972
70.8k
      
CI.hasPreprocessor()892
) {
973
892
    StringRef Cache =
974
892
        CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
975
892
    if (!Cache.empty()) {
976
802
      if (llvm::Error Err = GlobalModuleIndex::writeIndex(
977
802
              CI.getFileManager(), CI.getPCHContainerReader(), Cache)) {
978
        // FIXME this drops the error on the floor, but
979
        // Index/pch-from-libclang.c seems to rely on dropping at least some of
980
        // the error conditions!
981
26
        consumeError(std::move(Err));
982
26
      }
983
802
    }
984
892
  }
985
986
70.8k
  return llvm::Error::success();
987
70.8k
}
988
989
70.7k
void FrontendAction::EndSourceFile() {
990
70.7k
  CompilerInstance &CI = getCompilerInstance();
991
992
  // Inform the diagnostic client we are done with this source file.
993
70.7k
  CI.getDiagnosticClient().EndSourceFile();
994
995
  // Inform the preprocessor we are done.
996
70.7k
  if (CI.hasPreprocessor())
997
70.6k
    CI.getPreprocessor().EndSourceFile();
998
999
  // Finalize the action.
1000
70.7k
  EndSourceFileAction();
1001
1002
  // Sema references the ast consumer, so reset sema first.
1003
  //
1004
  // FIXME: There is more per-file stuff we could just drop here?
1005
70.7k
  bool DisableFree = CI.getFrontendOpts().DisableFree;
1006
70.7k
  if (DisableFree) {
1007
5.48k
    CI.resetAndLeakSema();
1008
5.48k
    CI.resetAndLeakASTContext();
1009
5.48k
    llvm::BuryPointer(CI.takeASTConsumer().get());
1010
65.2k
  } else {
1011
65.2k
    CI.setSema(nullptr);
1012
65.2k
    CI.setASTContext(nullptr);
1013
65.2k
    CI.setASTConsumer(nullptr);
1014
65.2k
  }
1015
1016
70.7k
  if (CI.getFrontendOpts().ShowStats) {
1017
4
    llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
1018
4
    CI.getPreprocessor().PrintStats();
1019
4
    CI.getPreprocessor().getIdentifierTable().PrintStats();
1020
4
    CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
1021
4
    CI.getSourceManager().PrintStats();
1022
4
    llvm::errs() << "\n";
1023
4
  }
1024
1025
  // Cleanup the output streams, and erase the output files if instructed by the
1026
  // FrontendAction.
1027
70.7k
  CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
1028
1029
70.7k
  if (isCurrentFileAST()) {
1030
50
    if (DisableFree) {
1031
9
      CI.resetAndLeakPreprocessor();
1032
9
      CI.resetAndLeakSourceManager();
1033
9
      CI.resetAndLeakFileManager();
1034
9
      llvm::BuryPointer(std::move(CurrentASTUnit));
1035
41
    } else {
1036
41
      CI.setPreprocessor(nullptr);
1037
41
      CI.setSourceManager(nullptr);
1038
41
      CI.setFileManager(nullptr);
1039
41
    }
1040
50
  }
1041
1042
70.7k
  setCompilerInstance(nullptr);
1043
70.7k
  setCurrentInput(FrontendInputFile());
1044
70.7k
  CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
1045
70.7k
}
1046
1047
70.6k
bool FrontendAction::shouldEraseOutputFiles() {
1048
70.6k
  return getCompilerInstance().getDiagnostics().hasErrorOccurred();
1049
70.6k
}
1050
1051
//===----------------------------------------------------------------------===//
1052
// Utility Actions
1053
//===----------------------------------------------------------------------===//
1054
1055
68.4k
void ASTFrontendAction::ExecuteAction() {
1056
68.4k
  CompilerInstance &CI = getCompilerInstance();
1057
68.4k
  if (!CI.hasPreprocessor())
1058
0
    return;
1059
1060
  // FIXME: Move the truncation aspect of this into Sema, we delayed this till
1061
  // here so the source manager would be initialized.
1062
68.4k
  if (hasCodeCompletionSupport() &&
1063
68.4k
      
!CI.getFrontendOpts().CodeCompletionAt.FileName.empty()12.5k
)
1064
1.21k
    CI.createCodeCompletionConsumer();
1065
1066
  // Use a code completion consumer?
1067
68.4k
  CodeCompleteConsumer *CompletionConsumer = nullptr;
1068
68.4k
  if (CI.hasCodeCompletionConsumer())
1069
1.21k
    CompletionConsumer = &CI.getCodeCompletionConsumer();
1070
1071
68.4k
  if (!CI.hasSema())
1072
68.4k
    CI.createSema(getTranslationUnitKind(), CompletionConsumer);
1073
1074
68.4k
  ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
1075
68.4k
           CI.getFrontendOpts().SkipFunctionBodies);
1076
68.4k
}
1077
1078
0
void PluginASTAction::anchor() { }
1079
1080
std::unique_ptr<ASTConsumer>
1081
PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1082
0
                                              StringRef InFile) {
1083
0
  llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
1084
0
}
1085
1086
62
bool WrapperFrontendAction::PrepareToExecuteAction(CompilerInstance &CI) {
1087
62
  return WrappedAction->PrepareToExecuteAction(CI);
1088
62
}
1089
std::unique_ptr<ASTConsumer>
1090
WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1091
47
                                         StringRef InFile) {
1092
47
  return WrappedAction->CreateASTConsumer(CI, InFile);
1093
47
}
1094
11
bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
1095
11
  return WrappedAction->BeginInvocation(CI);
1096
11
}
1097
49
bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI) {
1098
49
  WrappedAction->setCurrentInput(getCurrentInput());
1099
49
  WrappedAction->setCompilerInstance(&CI);
1100
49
  auto Ret = WrappedAction->BeginSourceFileAction(CI);
1101
  // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1102
49
  setCurrentInput(WrappedAction->getCurrentInput());
1103
49
  return Ret;
1104
49
}
1105
38
void WrapperFrontendAction::ExecuteAction() {
1106
38
  WrappedAction->ExecuteAction();
1107
38
}
1108
49
void WrapperFrontendAction::EndSourceFile() { WrappedAction->EndSourceFile(); }
1109
0
void WrapperFrontendAction::EndSourceFileAction() {
1110
0
  WrappedAction->EndSourceFileAction();
1111
0
}
1112
0
bool WrapperFrontendAction::shouldEraseOutputFiles() {
1113
0
  return WrappedAction->shouldEraseOutputFiles();
1114
0
}
1115
1116
49
bool WrapperFrontendAction::usesPreprocessorOnly() const {
1117
49
  return WrappedAction->usesPreprocessorOnly();
1118
49
}
1119
39
TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
1120
39
  return WrappedAction->getTranslationUnitKind();
1121
39
}
1122
4
bool WrapperFrontendAction::hasPCHSupport() const {
1123
4
  return WrappedAction->hasPCHSupport();
1124
4
}
1125
0
bool WrapperFrontendAction::hasASTFileSupport() const {
1126
0
  return WrappedAction->hasASTFileSupport();
1127
0
}
1128
0
bool WrapperFrontendAction::hasIRSupport() const {
1129
0
  return WrappedAction->hasIRSupport();
1130
0
}
1131
11
bool WrapperFrontendAction::hasCodeCompletionSupport() const {
1132
11
  return WrappedAction->hasCodeCompletionSupport();
1133
11
}
1134
1135
WrapperFrontendAction::WrapperFrontendAction(
1136
    std::unique_ptr<FrontendAction> WrappedAction)
1137
62
  : WrappedAction(std::move(WrappedAction)) {}
1138