Coverage Report

Created: 2020-02-25 14:32

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