Coverage Report

Created: 2020-09-19 12:23

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