blob: 83152bd353363d4aa2266f571cf2bf4f359d35fd [file] [log] [blame]
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001//===--- FrontendAction.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/FrontendAction.h"
Sebastian Redl07a89a82010-07-30 00:29:29 +000011#include "clang/AST/ASTConsumer.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000012#include "clang/AST/ASTContext.h"
Nico Weber2992efa2011-01-25 20:34:14 +000013#include "clang/AST/DeclGroup.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000014#include "clang/Frontend/ASTUnit.h"
15#include "clang/Frontend/CompilerInstance.h"
16#include "clang/Frontend/FrontendDiagnostic.h"
Nico Weber2992efa2011-01-25 20:34:14 +000017#include "clang/Frontend/FrontendPluginRegistry.h"
Douglas Gregore9fc3772012-01-26 07:55:45 +000018#include "clang/Frontend/LayoutOverrideSource.h"
Nico Weber2992efa2011-01-25 20:34:14 +000019#include "clang/Frontend/MultiplexConsumer.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000020#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/HeaderSearch.h"
Taewook Oh06b1af52017-03-07 20:20:23 +000022#include "clang/Lex/LiteralSupport.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Lex/Preprocessor.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000024#include "clang/Lex/PreprocessorOptions.h"
John McCall8b0666c2010-08-20 18:27:03 +000025#include "clang/Parse/ParseAST.h"
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000026#include "clang/Serialization/ASTDeserializationListener.h"
Jonathan D. Turner0248f572011-08-05 22:17:03 +000027#include "clang/Serialization/ASTReader.h"
Douglas Gregor5e306b12013-01-23 22:38:11 +000028#include "clang/Serialization/GlobalModuleIndex.h"
David Blaikie9941da42018-11-17 18:04:13 +000029#include "llvm/Support/BuryPointer.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000030#include "llvm/Support/ErrorHandling.h"
Douglas Gregorfc9e7a22012-10-23 06:18:24 +000031#include "llvm/Support/FileSystem.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000032#include "llvm/Support/Path.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000033#include "llvm/Support/Timer.h"
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000034#include "llvm/Support/raw_ostream.h"
Rafael Espindola8a8e5542014-06-12 17:19:42 +000035#include <system_error>
Daniel Dunbara0ff58d2009-11-14 10:42:35 +000036using namespace clang;
37
John Brawn4d79ec72016-08-05 11:01:08 +000038LLVM_INSTANTIATE_REGISTRY(FrontendPluginRegistry)
NAKAMURA Takumiad4c06c2014-07-11 15:06:24 +000039
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000040namespace {
41
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000042class DelegatingDeserializationListener : public ASTDeserializationListener {
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000043 ASTDeserializationListener *Previous;
Nico Weber824285e2014-05-08 04:26:47 +000044 bool DeletePrevious;
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000045
46public:
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000047 explicit DelegatingDeserializationListener(
Nico Weber824285e2014-05-08 04:26:47 +000048 ASTDeserializationListener *Previous, bool DeletePrevious)
49 : Previous(Previous), DeletePrevious(DeletePrevious) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +000050 ~DelegatingDeserializationListener() override {
Nico Weber824285e2014-05-08 04:26:47 +000051 if (DeletePrevious)
52 delete Previous;
53 }
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000054
Craig Topperafa7cb32014-03-13 06:07:04 +000055 void ReaderInitialized(ASTReader *Reader) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000056 if (Previous)
57 Previous->ReaderInitialized(Reader);
58 }
Craig Topperafa7cb32014-03-13 06:07:04 +000059 void IdentifierRead(serialization::IdentID ID,
60 IdentifierInfo *II) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000061 if (Previous)
62 Previous->IdentifierRead(ID, II);
63 }
Craig Topperafa7cb32014-03-13 06:07:04 +000064 void TypeRead(serialization::TypeIdx Idx, QualType T) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000065 if (Previous)
66 Previous->TypeRead(Idx, T);
67 }
Craig Topperafa7cb32014-03-13 06:07:04 +000068 void DeclRead(serialization::DeclID ID, const Decl *D) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000069 if (Previous)
70 Previous->DeclRead(ID, D);
71 }
Craig Topperafa7cb32014-03-13 06:07:04 +000072 void SelectorRead(serialization::SelectorID ID, Selector Sel) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000073 if (Previous)
74 Previous->SelectorRead(ID, Sel);
75 }
Craig Topperafa7cb32014-03-13 06:07:04 +000076 void MacroDefinitionRead(serialization::PreprocessedEntityID PPID,
Richard Smith66a81862015-05-04 02:25:31 +000077 MacroDefinitionRecord *MD) override {
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000078 if (Previous)
79 Previous->MacroDefinitionRead(PPID, MD);
80 }
81};
82
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000083/// Dumps deserialized declarations.
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000084class DeserializedDeclsDumper : public DelegatingDeserializationListener {
85public:
Nico Weber824285e2014-05-08 04:26:47 +000086 explicit DeserializedDeclsDumper(ASTDeserializationListener *Previous,
87 bool DeletePrevious)
88 : DelegatingDeserializationListener(Previous, DeletePrevious) {}
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000089
Craig Topperafa7cb32014-03-13 06:07:04 +000090 void DeclRead(serialization::DeclID ID, const Decl *D) override {
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000091 llvm::outs() << "PCH DECL: " << D->getDeclKindName();
Vassil Vassilevda31c932018-05-20 09:38:52 +000092 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) {
93 llvm::outs() << " - ";
94 ND->printQualifiedName(llvm::outs());
95 }
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000096 llvm::outs() << "\n";
97
Argyrios Kyrtzidisb12986f2011-10-28 22:54:31 +000098 DelegatingDeserializationListener::DeclRead(ID, D);
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +000099 }
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +0000100};
101
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000102/// Checks deserialized declarations and emits error if a name
David Blaikie48b81282012-05-29 17:05:42 +0000103/// matches one given in command-line using -error-on-deserialized-decl.
104class DeserializedDeclsChecker : public DelegatingDeserializationListener {
105 ASTContext &Ctx;
106 std::set<std::string> NamesToCheck;
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000107
David Blaikie48b81282012-05-29 17:05:42 +0000108public:
109 DeserializedDeclsChecker(ASTContext &Ctx,
110 const std::set<std::string> &NamesToCheck,
Nico Weber824285e2014-05-08 04:26:47 +0000111 ASTDeserializationListener *Previous,
112 bool DeletePrevious)
113 : DelegatingDeserializationListener(Previous, DeletePrevious), Ctx(Ctx),
114 NamesToCheck(NamesToCheck) {}
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000115
Craig Topperafa7cb32014-03-13 06:07:04 +0000116 void DeclRead(serialization::DeclID ID, const Decl *D) override {
David Blaikie48b81282012-05-29 17:05:42 +0000117 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
118 if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) {
119 unsigned DiagID
120 = Ctx.getDiagnostics().getCustomDiagID(DiagnosticsEngine::Error,
121 "%0 was deserialized");
122 Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID)
123 << ND->getNameAsString();
124 }
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000125
David Blaikie48b81282012-05-29 17:05:42 +0000126 DelegatingDeserializationListener::DeclRead(ID, D);
127 }
Argyrios Kyrtzidis0427be92010-10-14 20:14:25 +0000128};
129
Argyrios Kyrtzidisa11aca42010-10-14 20:14:18 +0000130} // end anonymous namespace
131
Craig Topper49a27902014-05-22 04:46:25 +0000132FrontendAction::FrontendAction() : Instance(nullptr) {}
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000133
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000134FrontendAction::~FrontendAction() {}
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000135
Douglas Gregor32fbe312012-01-20 16:28:04 +0000136void FrontendAction::setCurrentInput(const FrontendInputFile &CurrentInput,
David Blaikief62d4e72014-08-10 17:03:42 +0000137 std::unique_ptr<ASTUnit> AST) {
Douglas Gregor32fbe312012-01-20 16:28:04 +0000138 this->CurrentInput = CurrentInput;
David Blaikief62d4e72014-08-10 17:03:42 +0000139 CurrentASTUnit = std::move(AST);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000140}
141
Richard Smith8128f332017-05-05 22:18:51 +0000142Module *FrontendAction::getCurrentModule() const {
143 CompilerInstance &CI = getCompilerInstance();
144 return CI.getPreprocessor().getHeaderSearchInfo().lookupModule(
145 CI.getLangOpts().CurrentModule, /*AllowSearch*/false);
146}
147
David Blaikie6beb6aa2014-08-10 19:56:51 +0000148std::unique_ptr<ASTConsumer>
149FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI,
150 StringRef InFile) {
151 std::unique_ptr<ASTConsumer> Consumer = CreateASTConsumer(CI, InFile);
Nico Weber2992efa2011-01-25 20:34:14 +0000152 if (!Consumer)
Craig Topper49a27902014-05-22 04:46:25 +0000153 return nullptr;
Nico Weber2992efa2011-01-25 20:34:14 +0000154
John Brawn6c789742016-03-15 12:51:40 +0000155 // If there are no registered plugins we don't need to wrap the consumer
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +0000156 if (FrontendPluginRegistry::begin() == FrontendPluginRegistry::end())
157 return Consumer;
158
Ivan Donchevskii270ef5b2018-05-17 09:21:07 +0000159 // If this is a code completion run, avoid invoking the plugin consumers
160 if (CI.hasCodeCompletionConsumer())
161 return Consumer;
162
Ivan Donchevskiif70d28b2018-05-17 09:15:22 +0000163 // Collect the list of plugins that go before the main action (in Consumers)
164 // or after it (in AfterConsumers)
165 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
John Brawn6c789742016-03-15 12:51:40 +0000166 std::vector<std::unique_ptr<ASTConsumer>> AfterConsumers;
167 for (FrontendPluginRegistry::iterator it = FrontendPluginRegistry::begin(),
168 ie = FrontendPluginRegistry::end();
169 it != ie; ++it) {
170 std::unique_ptr<PluginASTAction> P = it->instantiate();
171 PluginASTAction::ActionType ActionType = P->getActionType();
172 if (ActionType == PluginASTAction::Cmdline) {
173 // This is O(|plugins| * |add_plugins|), but since both numbers are
174 // way below 50 in practice, that's ok.
175 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size();
176 i != e; ++i) {
177 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) {
178 ActionType = PluginASTAction::AddAfterMainAction;
179 break;
180 }
181 }
Nico Weber2992efa2011-01-25 20:34:14 +0000182 }
John Brawn6c789742016-03-15 12:51:40 +0000183 if ((ActionType == PluginASTAction::AddBeforeMainAction ||
184 ActionType == PluginASTAction::AddAfterMainAction) &&
185 P->ParseArgs(CI, CI.getFrontendOpts().PluginArgs[it->getName()])) {
186 std::unique_ptr<ASTConsumer> PluginConsumer = P->CreateASTConsumer(CI, InFile);
187 if (ActionType == PluginASTAction::AddBeforeMainAction) {
188 Consumers.push_back(std::move(PluginConsumer));
189 } else {
190 AfterConsumers.push_back(std::move(PluginConsumer));
191 }
192 }
193 }
194
195 // Add to Consumers the main consumer, then all the plugins that go after it
196 Consumers.push_back(std::move(Consumer));
197 for (auto &C : AfterConsumers) {
198 Consumers.push_back(std::move(C));
Nico Weber2992efa2011-01-25 20:34:14 +0000199 }
200
David Blaikie6beb6aa2014-08-10 19:56:51 +0000201 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Nico Weber2992efa2011-01-25 20:34:14 +0000202}
203
Richard Smith8128f332017-05-05 22:18:51 +0000204/// For preprocessed files, if the first line is the linemarker and specifies
205/// the original source file name, use that name as the input file name.
206/// Returns the location of the first token after the line marker directive.
207///
208/// \param CI The compiler instance.
209/// \param InputFile Populated with the filename from the line marker.
Richard Smithf3f84612017-06-29 02:19:42 +0000210/// \param IsModuleMap If \c true, add a line note corresponding to this line
211/// directive. (We need to do this because the directive will not be
212/// visited by the preprocessor.)
Richard Smith8128f332017-05-05 22:18:51 +0000213static SourceLocation ReadOriginalFileName(CompilerInstance &CI,
214 std::string &InputFile,
Richard Smithf3f84612017-06-29 02:19:42 +0000215 bool IsModuleMap = false) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000216 auto &SourceMgr = CI.getSourceManager();
217 auto MainFileID = SourceMgr.getMainFileID();
Richard Smith8128f332017-05-05 22:18:51 +0000218
219 bool Invalid = false;
Taewook Oh06b1af52017-03-07 20:20:23 +0000220 const auto *MainFileBuf = SourceMgr.getBuffer(MainFileID, &Invalid);
221 if (Invalid)
Richard Smith8128f332017-05-05 22:18:51 +0000222 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000223
224 std::unique_ptr<Lexer> RawLexer(
225 new Lexer(MainFileID, MainFileBuf, SourceMgr, CI.getLangOpts()));
226
227 // If the first line has the syntax of
228 //
229 // # NUM "FILENAME"
230 //
231 // we use FILENAME as the input file name.
232 Token T;
233 if (RawLexer->LexFromRawLexer(T) || T.getKind() != tok::hash)
Richard Smith8128f332017-05-05 22:18:51 +0000234 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000235 if (RawLexer->LexFromRawLexer(T) || T.isAtStartOfLine() ||
236 T.getKind() != tok::numeric_constant)
Richard Smith8128f332017-05-05 22:18:51 +0000237 return SourceLocation();
238
239 unsigned LineNo;
240 SourceLocation LineNoLoc = T.getLocation();
Richard Smithf3f84612017-06-29 02:19:42 +0000241 if (IsModuleMap) {
Richard Smith8128f332017-05-05 22:18:51 +0000242 llvm::SmallString<16> Buffer;
243 if (Lexer::getSpelling(LineNoLoc, Buffer, SourceMgr, CI.getLangOpts())
244 .getAsInteger(10, LineNo))
245 return SourceLocation();
246 }
247
Taewook Oh06b1af52017-03-07 20:20:23 +0000248 RawLexer->LexFromRawLexer(T);
249 if (T.isAtStartOfLine() || T.getKind() != tok::string_literal)
Richard Smith8128f332017-05-05 22:18:51 +0000250 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000251
252 StringLiteralParser Literal(T, CI.getPreprocessor());
253 if (Literal.hadError)
Richard Smith8128f332017-05-05 22:18:51 +0000254 return SourceLocation();
255 RawLexer->LexFromRawLexer(T);
256 if (T.isNot(tok::eof) && !T.isAtStartOfLine())
257 return SourceLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000258 InputFile = Literal.GetString().str();
Richard Smith8128f332017-05-05 22:18:51 +0000259
Richard Smithf3f84612017-06-29 02:19:42 +0000260 if (IsModuleMap)
Richard Smith8128f332017-05-05 22:18:51 +0000261 CI.getSourceManager().AddLineNote(
Reid Klecknereb00ee02017-05-22 21:42:58 +0000262 LineNoLoc, LineNo, SourceMgr.getLineTableFilenameID(InputFile), false,
Richard Smithf3f84612017-06-29 02:19:42 +0000263 false, SrcMgr::C_User_ModuleMap);
Richard Smith8128f332017-05-05 22:18:51 +0000264
265 return T.getLocation();
Taewook Oh06b1af52017-03-07 20:20:23 +0000266}
267
Richard Smithf74d9462017-04-28 01:49:42 +0000268static SmallVectorImpl<char> &
269operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
270 Includes.append(RHS.begin(), RHS.end());
271 return Includes;
272}
273
274static void addHeaderInclude(StringRef HeaderName,
275 SmallVectorImpl<char> &Includes,
276 const LangOptions &LangOpts,
277 bool IsExternC) {
278 if (IsExternC && LangOpts.CPlusPlus)
279 Includes += "extern \"C\" {\n";
Erik Pilkingtonfa983902018-10-30 20:31:30 +0000280 if (LangOpts.ObjC)
Richard Smithf74d9462017-04-28 01:49:42 +0000281 Includes += "#import \"";
282 else
283 Includes += "#include \"";
284
285 Includes += HeaderName;
286
287 Includes += "\"\n";
288 if (IsExternC && LangOpts.CPlusPlus)
289 Includes += "}\n";
290}
291
Fangrui Song6907ce22018-07-30 19:24:48 +0000292/// Collect the set of header includes needed to construct the given
Richard Smithf74d9462017-04-28 01:49:42 +0000293/// module and update the TopHeaders file set of the module.
294///
295/// \param Module The module we're collecting includes from.
296///
297/// \param Includes Will be augmented with the set of \#includes or \#imports
298/// needed to load all of the named headers.
Richard Smith040e1262017-06-02 01:55:39 +0000299static std::error_code collectModuleHeaderIncludes(
300 const LangOptions &LangOpts, FileManager &FileMgr, DiagnosticsEngine &Diag,
301 ModuleMap &ModMap, clang::Module *Module, SmallVectorImpl<char> &Includes) {
Richard Smithf74d9462017-04-28 01:49:42 +0000302 // Don't collect any headers for unavailable modules.
303 if (!Module->isAvailable())
304 return std::error_code();
305
Richard Smith040e1262017-06-02 01:55:39 +0000306 // Resolve all lazy header directives to header files.
307 ModMap.resolveHeaderDirectives(Module);
308
309 // If any headers are missing, we can't build this module. In most cases,
310 // diagnostics for this should have already been produced; we only get here
311 // if explicit stat information was provided.
312 // FIXME: If the name resolves to a file with different stat information,
313 // produce a better diagnostic.
314 if (!Module->MissingHeaders.empty()) {
315 auto &MissingHeader = Module->MissingHeaders.front();
316 Diag.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
317 << MissingHeader.IsUmbrella << MissingHeader.FileName;
318 return std::error_code();
319 }
320
Richard Smithf74d9462017-04-28 01:49:42 +0000321 // Add includes for each of these headers.
322 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
323 for (Module::Header &H : Module->Headers[HK]) {
324 Module->addTopHeader(H.Entry);
325 // Use the path as specified in the module map file. We'll look for this
326 // file relative to the module build directory (the directory containing
327 // the module map file) so this will find the same file that we found
328 // while parsing the module map.
329 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
330 }
331 }
332 // Note that Module->PrivateHeaders will not be a TopHeader.
333
334 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
335 Module->addTopHeader(UmbrellaHeader.Entry);
336 if (Module->Parent)
337 // Include the umbrella header for submodules.
338 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
339 Module->IsExternC);
340 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
341 // Add all of the headers we find in this subdirectory.
342 std::error_code EC;
343 SmallString<128> DirNative;
344 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
345
Jonas Devliegherefc514902018-10-10 13:27:25 +0000346 llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
347 for (llvm::vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
Richard Smithf74d9462017-04-28 01:49:42 +0000348 Dir != End && !EC; Dir.increment(EC)) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000349 // Check whether this entry has an extension typically associated with
Richard Smithf74d9462017-04-28 01:49:42 +0000350 // headers.
Sam McCall0ae00562018-09-14 12:47:38 +0000351 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
352 .Cases(".h", ".H", ".hh", ".hpp", true)
353 .Default(false))
Richard Smithf74d9462017-04-28 01:49:42 +0000354 continue;
355
Sam McCall0ae00562018-09-14 12:47:38 +0000356 const FileEntry *Header = FileMgr.getFile(Dir->path());
Richard Smithf74d9462017-04-28 01:49:42 +0000357 // FIXME: This shouldn't happen unless there is a file system race. Is
358 // that worth diagnosing?
359 if (!Header)
360 continue;
361
Fangrui Song6907ce22018-07-30 19:24:48 +0000362 // If this header is marked 'unavailable' in this module, don't include
Richard Smithf74d9462017-04-28 01:49:42 +0000363 // it.
364 if (ModMap.isHeaderUnavailableInModule(Header, Module))
365 continue;
366
367 // Compute the relative path from the directory to this file.
368 SmallVector<StringRef, 16> Components;
Sam McCall0ae00562018-09-14 12:47:38 +0000369 auto PathIt = llvm::sys::path::rbegin(Dir->path());
Richard Smithf74d9462017-04-28 01:49:42 +0000370 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
371 Components.push_back(*PathIt);
372 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
373 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
374 ++It)
375 llvm::sys::path::append(RelativeHeader, *It);
376
377 // Include this header as part of the umbrella directory.
378 Module->addTopHeader(Header);
379 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
380 }
381
382 if (EC)
383 return EC;
384 }
385
386 // Recurse into submodules.
387 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
388 SubEnd = Module->submodule_end();
389 Sub != SubEnd; ++Sub)
390 if (std::error_code Err = collectModuleHeaderIncludes(
Richard Smith040e1262017-06-02 01:55:39 +0000391 LangOpts, FileMgr, Diag, ModMap, *Sub, Includes))
Richard Smithf74d9462017-04-28 01:49:42 +0000392 return Err;
393
394 return std::error_code();
395}
396
Richard Smithab755972017-06-05 18:10:11 +0000397static bool loadModuleMapForModuleBuild(CompilerInstance &CI, bool IsSystem,
Richard Smith8b706102017-05-31 20:56:55 +0000398 bool IsPreprocessed,
399 std::string &PresumedModuleMapFile,
400 unsigned &Offset) {
Richard Smith8128f332017-05-05 22:18:51 +0000401 auto &SrcMgr = CI.getSourceManager();
402 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
403
404 // Map the current input to a file.
405 FileID ModuleMapID = SrcMgr.getMainFileID();
406 const FileEntry *ModuleMap = SrcMgr.getFileEntryForID(ModuleMapID);
407
408 // If the module map is preprocessed, handle the initial line marker;
409 // line directives are not part of the module map syntax in general.
410 Offset = 0;
411 if (IsPreprocessed) {
Richard Smith8128f332017-05-05 22:18:51 +0000412 SourceLocation EndOfLineMarker =
Richard Smithf3f84612017-06-29 02:19:42 +0000413 ReadOriginalFileName(CI, PresumedModuleMapFile, /*IsModuleMap*/ true);
Richard Smith8128f332017-05-05 22:18:51 +0000414 if (EndOfLineMarker.isValid())
415 Offset = CI.getSourceManager().getDecomposedLoc(EndOfLineMarker).second;
Richard Smithf74d9462017-04-28 01:49:42 +0000416 }
417
Richard Smith8128f332017-05-05 22:18:51 +0000418 // Load the module map file.
Richard Smith8b706102017-05-31 20:56:55 +0000419 if (HS.loadModuleMapFile(ModuleMap, IsSystem, ModuleMapID, &Offset,
420 PresumedModuleMapFile))
Richard Smith8128f332017-05-05 22:18:51 +0000421 return true;
422
423 if (SrcMgr.getBuffer(ModuleMapID)->getBufferSize() == Offset)
424 Offset = 0;
425
426 return false;
427}
428
429static Module *prepareToBuildModule(CompilerInstance &CI,
430 StringRef ModuleMapFilename) {
Richard Smithf74d9462017-04-28 01:49:42 +0000431 if (CI.getLangOpts().CurrentModule.empty()) {
432 CI.getDiagnostics().Report(diag::err_missing_module_name);
Richard Smith8128f332017-05-05 22:18:51 +0000433
Richard Smithf74d9462017-04-28 01:49:42 +0000434 // FIXME: Eventually, we could consider asking whether there was just
Fangrui Song6907ce22018-07-30 19:24:48 +0000435 // a single module described in the module map, and use that as a
Richard Smithf74d9462017-04-28 01:49:42 +0000436 // default. Then it would be fairly trivial to just "compile" a module
437 // map with a single module (the common case).
438 return nullptr;
439 }
440
Richard Smithf74d9462017-04-28 01:49:42 +0000441 // Dig out the module definition.
Richard Smith8128f332017-05-05 22:18:51 +0000442 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Richard Smithf74d9462017-04-28 01:49:42 +0000443 Module *M = HS.lookupModule(CI.getLangOpts().CurrentModule,
444 /*AllowSearch=*/false);
445 if (!M) {
446 CI.getDiagnostics().Report(diag::err_missing_module)
Richard Smith8128f332017-05-05 22:18:51 +0000447 << CI.getLangOpts().CurrentModule << ModuleMapFilename;
448
Richard Smithf74d9462017-04-28 01:49:42 +0000449 return nullptr;
450 }
451
452 // Check whether we can build this module at all.
Richard Smith27e5aa02017-06-05 18:57:56 +0000453 if (Preprocessor::checkModuleIsAvailable(CI.getLangOpts(), CI.getTarget(),
454 CI.getDiagnostics(), M))
Richard Smithf74d9462017-04-28 01:49:42 +0000455 return nullptr;
Richard Smithf74d9462017-04-28 01:49:42 +0000456
Richard Smith8128f332017-05-05 22:18:51 +0000457 // Inform the preprocessor that includes from within the input buffer should
458 // be resolved relative to the build directory of the module map file.
459 CI.getPreprocessor().setMainFileDir(M->Directory);
460
461 // If the module was inferred from a different module map (via an expanded
462 // umbrella module definition), track that fact.
463 // FIXME: It would be preferable to fill this in as part of processing
464 // the module map, rather than adding it after the fact.
465 StringRef OriginalModuleMapName = CI.getFrontendOpts().OriginalModuleMap;
466 if (!OriginalModuleMapName.empty()) {
467 auto *OriginalModuleMap =
468 CI.getFileManager().getFile(OriginalModuleMapName,
469 /*openFile*/ true);
470 if (!OriginalModuleMap) {
471 CI.getDiagnostics().Report(diag::err_module_map_not_found)
472 << OriginalModuleMapName;
473 return nullptr;
474 }
475 if (OriginalModuleMap != CI.getSourceManager().getFileEntryForID(
476 CI.getSourceManager().getMainFileID())) {
477 M->IsInferred = true;
478 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap()
479 .setInferredModuleAllowedBy(M, OriginalModuleMap);
480 }
Richard Smithf74d9462017-04-28 01:49:42 +0000481 }
482
Richard Smith8128f332017-05-05 22:18:51 +0000483 // If we're being run from the command-line, the module build stack will not
484 // have been filled in yet, so complete it now in order to allow us to detect
485 // module cycles.
486 SourceManager &SourceMgr = CI.getSourceManager();
487 if (SourceMgr.getModuleBuildStack().empty())
488 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
489 FullSourceLoc(SourceLocation(), SourceMgr));
490 return M;
491}
492
493/// Compute the input buffer that should be used to build the specified module.
494static std::unique_ptr<llvm::MemoryBuffer>
495getInputBufferForModule(CompilerInstance &CI, Module *M) {
Richard Smithf74d9462017-04-28 01:49:42 +0000496 FileManager &FileMgr = CI.getFileManager();
497
498 // Collect the set of #includes we need to build the module.
499 SmallString<256> HeaderContents;
500 std::error_code Err = std::error_code();
501 if (Module::Header UmbrellaHeader = M->getUmbrellaHeader())
502 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
503 CI.getLangOpts(), M->IsExternC);
504 Err = collectModuleHeaderIncludes(
Richard Smith040e1262017-06-02 01:55:39 +0000505 CI.getLangOpts(), FileMgr, CI.getDiagnostics(),
Richard Smithf74d9462017-04-28 01:49:42 +0000506 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), M,
507 HeaderContents);
508
509 if (Err) {
510 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
511 << M->getFullModuleName() << Err.message();
512 return nullptr;
513 }
514
Richard Smithf74d9462017-04-28 01:49:42 +0000515 return llvm::MemoryBuffer::getMemBufferCopy(
516 HeaderContents, Module::getModuleInputBufferName());
517}
518
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000519bool FrontendAction::BeginSourceFile(CompilerInstance &CI,
Richard Smithab755972017-06-05 18:10:11 +0000520 const FrontendInputFile &RealInput) {
521 FrontendInputFile Input(RealInput);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000522 assert(!Instance && "Already processing a source file!");
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000523 assert(!Input.isEmpty() && "Unexpected empty filename!");
Douglas Gregor32fbe312012-01-20 16:28:04 +0000524 setCurrentInput(Input);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000525 setCompilerInstance(&CI);
526
Jordan Roseea762b02012-08-10 01:06:08 +0000527 bool HasBegunSourceFile = false;
Richard Smithab755972017-06-05 18:10:11 +0000528 bool ReplayASTFile = Input.getKind().getFormat() == InputKind::Precompiled &&
529 usesPreprocessorOnly();
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +0000530 if (!BeginInvocation(CI))
531 goto failure;
532
Richard Smithab755972017-06-05 18:10:11 +0000533 // If we're replaying the build of an AST file, import it and set up
534 // the initial state from its build.
535 if (ReplayASTFile) {
536 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
537
538 // The AST unit populates its own diagnostics engine rather than ours.
539 IntrusiveRefCntPtr<DiagnosticsEngine> ASTDiags(
540 new DiagnosticsEngine(Diags->getDiagnosticIDs(),
541 &Diags->getDiagnosticOptions()));
542 ASTDiags->setClient(Diags->getClient(), /*OwnsClient*/false);
543
Richard Smithd6509cf2018-09-15 01:21:15 +0000544 // FIXME: What if the input is a memory buffer?
545 StringRef InputFile = Input.getFile();
546
Richard Smithab755972017-06-05 18:10:11 +0000547 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000548 InputFile, CI.getPCHContainerReader(), ASTUnit::LoadPreprocessorOnly,
549 ASTDiags, CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
Richard Smithab755972017-06-05 18:10:11 +0000550 if (!AST)
551 goto failure;
552
553 // Options relating to how we treat the input (but not what we do with it)
554 // are inherited from the AST unit.
Richard Smith18934752017-06-06 00:32:01 +0000555 CI.getHeaderSearchOpts() = AST->getHeaderSearchOpts();
556 CI.getPreprocessorOpts() = AST->getPreprocessorOpts();
Richard Smithab755972017-06-05 18:10:11 +0000557 CI.getLangOpts() = AST->getLangOpts();
558
Richard Smithab755972017-06-05 18:10:11 +0000559 // Set the shared objects, these are reset when we finish processing the
560 // file, otherwise the CompilerInstance will happily destroy them.
561 CI.setFileManager(&AST->getFileManager());
562 CI.createSourceManager(CI.getFileManager());
563 CI.getSourceManager().initializeForReplay(AST->getSourceManager());
Richard Smithab755972017-06-05 18:10:11 +0000564
Richard Smithf3f84612017-06-29 02:19:42 +0000565 // Preload all the module files loaded transitively by the AST unit. Also
566 // load all module map files that were parsed as part of building the AST
567 // unit.
568 if (auto ASTReader = AST->getASTReader()) {
569 auto &MM = ASTReader->getModuleManager();
570 auto &PrimaryModule = MM.getPrimaryModule();
571
Sam McCall5da4d752018-10-12 12:21:29 +0000572 for (serialization::ModuleFile &MF : MM)
Richard Smithf3f84612017-06-29 02:19:42 +0000573 if (&MF != &PrimaryModule)
574 CI.getFrontendOpts().ModuleFiles.push_back(MF.FileName);
575
576 ASTReader->visitTopLevelModuleMaps(PrimaryModule,
577 [&](const FileEntry *FE) {
578 CI.getFrontendOpts().ModuleMapFiles.push_back(FE->getName());
579 });
580 }
581
Richard Smithab755972017-06-05 18:10:11 +0000582 // Set up the input file for replay purposes.
583 auto Kind = AST->getInputKind();
584 if (Kind.getFormat() == InputKind::ModuleMap) {
585 Module *ASTModule =
586 AST->getPreprocessor().getHeaderSearchInfo().lookupModule(
587 AST->getLangOpts().CurrentModule, /*AllowSearch*/ false);
Richard Smithdbafb6c2017-06-29 23:23:46 +0000588 assert(ASTModule && "module file does not define its own module");
Richard Smithab755972017-06-05 18:10:11 +0000589 Input = FrontendInputFile(ASTModule->PresumedModuleMapFile, Kind);
590 } else {
Richard Smith8b464f22018-09-15 01:21:18 +0000591 auto &OldSM = AST->getSourceManager();
592 FileID ID = OldSM.getMainFileID();
593 if (auto *File = OldSM.getFileEntryForID(ID))
Richard Smithab755972017-06-05 18:10:11 +0000594 Input = FrontendInputFile(File->getName(), Kind);
595 else
Richard Smith8b464f22018-09-15 01:21:18 +0000596 Input = FrontendInputFile(OldSM.getBuffer(ID), Kind);
Richard Smithab755972017-06-05 18:10:11 +0000597 }
598 setCurrentInput(Input, std::move(AST));
599 }
600
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000601 // AST files follow a very different path, since they share objects via the
602 // AST unit.
Richard Smith40c0efa2017-04-26 18:57:40 +0000603 if (Input.getKind().getFormat() == InputKind::Precompiled) {
Richard Smithab755972017-06-05 18:10:11 +0000604 assert(!usesPreprocessorOnly() && "this case was handled above");
Daniel Dunbarfa6214c2010-06-07 23:24:43 +0000605 assert(hasASTFileSupport() &&
606 "This action does not have AST file support!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000607
Dylan Noblesmithc95d8192012-02-20 14:00:23 +0000608 IntrusiveRefCntPtr<DiagnosticsEngine> Diags(&CI.getDiagnostics());
Alp Toker965f8822013-11-27 05:22:15 +0000609
Richard Smithd6509cf2018-09-15 01:21:15 +0000610 // FIXME: What if the input is a memory buffer?
611 StringRef InputFile = Input.getFile();
612
Adrian Prantl6b21ab22015-08-27 19:46:20 +0000613 std::unique_ptr<ASTUnit> AST = ASTUnit::LoadFromASTFile(
Richard Smithdbafb6c2017-06-29 23:23:46 +0000614 InputFile, CI.getPCHContainerReader(), ASTUnit::LoadEverything, Diags,
615 CI.getFileSystemOpts(), CI.getCodeGenOpts().DebugTypeExtRefs);
David Blaikief62d4e72014-08-10 17:03:42 +0000616
Daniel Dunbar59203002009-12-03 01:45:44 +0000617 if (!AST)
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000618 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000619
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000620 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000621 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Argyrios Kyrtzidisc00f43a2013-03-18 22:55:24 +0000622 HasBegunSourceFile = true;
623
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000624 // Set the shared objects, these are reset when we finish processing the
625 // file, otherwise the CompilerInstance will happily destroy them.
626 CI.setFileManager(&AST->getFileManager());
627 CI.setSourceManager(&AST->getSourceManager());
David Blaikie41565462017-01-05 19:48:07 +0000628 CI.setPreprocessor(AST->getPreprocessorPtr());
David Blaikieee123222017-02-08 20:51:11 +0000629 Preprocessor &PP = CI.getPreprocessor();
630 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
631 PP.getLangOpts());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000632 CI.setASTContext(&AST->getASTContext());
633
David Blaikief62d4e72014-08-10 17:03:42 +0000634 setCurrentInput(Input, std::move(AST));
635
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000636 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000637 if (!BeginSourceFileAction(CI))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000638 goto failure;
639
James Dennettf8317672013-01-23 00:45:44 +0000640 // Create the AST consumer.
Argyrios Kyrtzidis873c8582012-11-09 19:40:39 +0000641 CI.setASTConsumer(CreateWrappedASTConsumer(CI, InputFile));
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000642 if (!CI.hasASTConsumer())
643 goto failure;
644
645 return true;
646 }
647
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000648 // Set up the file and source managers, if needed.
Raphael Isemannabc3d042017-09-12 16:54:53 +0000649 if (!CI.hasFileManager()) {
650 if (!CI.createFileManager()) {
651 goto failure;
652 }
653 }
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000654 if (!CI.hasSourceManager())
Chris Lattner5159f612010-11-23 08:35:12 +0000655 CI.createSourceManager(CI.getFileManager());
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000656
Richard Smithf74d9462017-04-28 01:49:42 +0000657 // Set up embedding for any specified files. Do this before we load any
658 // source files, including the primary module map for the compilation.
659 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
660 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
661 CI.getSourceManager().setFileIsTransient(FE);
662 else
663 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
664 }
665 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
666 CI.getSourceManager().setAllFilesAreTransient(true);
667
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000668 // IR files bypass the rest of initialization.
Richard Smith40c0efa2017-04-26 18:57:40 +0000669 if (Input.getKind().getLanguage() == InputKind::LLVM_IR) {
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000670 assert(hasIRSupport() &&
671 "This action does not have IR file support!");
672
673 // Inform the diagnostic client we are processing a source file.
Craig Topper49a27902014-05-22 04:46:25 +0000674 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), nullptr);
Jordan Roseea762b02012-08-10 01:06:08 +0000675 HasBegunSourceFile = true;
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000676
677 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000678 if (!BeginSourceFileAction(CI))
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000679 goto failure;
680
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000681 // Initialize the main file entry.
682 if (!CI.InitializeSourceManager(CurrentInput))
683 goto failure;
684
Daniel Dunbar9507f9c2010-06-07 23:26:47 +0000685 return true;
686 }
687
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000688 // If the implicit PCH include is actually a directory, rather than
689 // a single file, search for a suitable PCH file in that directory.
690 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
691 FileManager &FileMgr = CI.getFileManager();
692 PreprocessorOptions &PPOpts = CI.getPreprocessorOpts();
693 StringRef PCHInclude = PPOpts.ImplicitPCHInclude;
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000694 std::string SpecificModuleCachePath = CI.getSpecificModuleCachePath();
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000695 if (const DirectoryEntry *PCHDir = FileMgr.getDirectory(PCHInclude)) {
Rafael Espindolac0809172014-06-12 14:02:15 +0000696 std::error_code EC;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000697 SmallString<128> DirNative;
698 llvm::sys::path::native(PCHDir->getName(), DirNative);
699 bool Found = false;
Jonas Devliegherefc514902018-10-10 13:27:25 +0000700 llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
701 for (llvm::vfs::directory_iterator Dir = FS.dir_begin(DirNative, EC),
702 DirEnd;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000703 Dir != DirEnd && !EC; Dir.increment(EC)) {
704 // Check whether this is an acceptable AST file.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000705 if (ASTReader::isAcceptableASTFile(
Sam McCall0ae00562018-09-14 12:47:38 +0000706 Dir->path(), FileMgr, CI.getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000707 CI.getLangOpts(), CI.getTargetOpts(), CI.getPreprocessorOpts(),
708 SpecificModuleCachePath)) {
Sam McCall0ae00562018-09-14 12:47:38 +0000709 PPOpts.ImplicitPCHInclude = Dir->path();
Argyrios Kyrtzidis48b72d82013-02-05 16:36:52 +0000710 Found = true;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000711 break;
712 }
713 }
714
715 if (!Found) {
716 CI.getDiagnostics().Report(diag::err_fe_no_pch_in_dir) << PCHInclude;
Richard Smith81c72482015-09-04 21:44:32 +0000717 goto failure;
Douglas Gregorfc9e7a22012-10-23 06:18:24 +0000718 }
719 }
720 }
721
Ted Kremenekeeccb302014-08-27 15:14:15 +0000722 // Set up the preprocessor if needed. When parsing model files the
723 // preprocessor of the original source is reused.
724 if (!isModelParsingAction())
725 CI.createPreprocessor(getTranslationUnitKind());
Daniel Dunbaraed46fc2010-06-07 23:23:50 +0000726
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000727 // Inform the diagnostic client we are processing a source file.
728 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(),
729 &CI.getPreprocessor());
Jordan Roseea762b02012-08-10 01:06:08 +0000730 HasBegunSourceFile = true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000731
Richard Smith8128f332017-05-05 22:18:51 +0000732 // Initialize the main file entry.
733 if (!CI.InitializeSourceManager(Input))
734 goto failure;
735
Richard Smithf74d9462017-04-28 01:49:42 +0000736 // For module map files, we first parse the module map and synthesize a
737 // "<module-includes>" buffer before more conventional processing.
738 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
739 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
740
Richard Smith8b706102017-05-31 20:56:55 +0000741 std::string PresumedModuleMapFile;
Richard Smith8128f332017-05-05 22:18:51 +0000742 unsigned OffsetToContents;
Richard Smithab755972017-06-05 18:10:11 +0000743 if (loadModuleMapForModuleBuild(CI, Input.isSystem(),
Richard Smith8b706102017-05-31 20:56:55 +0000744 Input.isPreprocessed(),
745 PresumedModuleMapFile, OffsetToContents))
Richard Smithf74d9462017-04-28 01:49:42 +0000746 goto failure;
747
Richard Smith8128f332017-05-05 22:18:51 +0000748 auto *CurrentModule = prepareToBuildModule(CI, Input.getFile());
749 if (!CurrentModule)
750 goto failure;
Richard Smithf74d9462017-04-28 01:49:42 +0000751
Richard Smith8b706102017-05-31 20:56:55 +0000752 CurrentModule->PresumedModuleMapFile = PresumedModuleMapFile;
753
Richard Smith8128f332017-05-05 22:18:51 +0000754 if (OffsetToContents)
755 // If the module contents are in the same file, skip to them.
756 CI.getPreprocessor().setSkipMainFilePreamble(OffsetToContents, true);
757 else {
758 // Otherwise, convert the module description to a suitable input buffer.
759 auto Buffer = getInputBufferForModule(CI, CurrentModule);
760 if (!Buffer)
761 goto failure;
762
763 // Reinitialize the main file entry to refer to the new input.
Richard Smith6d9bc272017-09-09 01:14:04 +0000764 auto Kind = CurrentModule->IsSystem ? SrcMgr::C_System : SrcMgr::C_User;
765 auto &SourceMgr = CI.getSourceManager();
766 auto BufferID = SourceMgr.createFileID(std::move(Buffer), Kind);
767 assert(BufferID.isValid() && "couldn't creaate module buffer ID");
768 SourceMgr.setMainFileID(BufferID);
Richard Smith8128f332017-05-05 22:18:51 +0000769 }
Richard Smithf74d9462017-04-28 01:49:42 +0000770 }
771
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000772 // Initialize the action.
Richard Smithd9259c22017-06-09 01:36:10 +0000773 if (!BeginSourceFileAction(CI))
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000774 goto failure;
775
Bruno Cardoso Lopes7315d2d2018-07-19 12:32:06 +0000776 // If we were asked to load any module map files, do so now.
777 for (const auto &Filename : CI.getFrontendOpts().ModuleMapFiles) {
778 if (auto *File = CI.getFileManager().getFile(Filename))
779 CI.getPreprocessor().getHeaderSearchInfo().loadModuleMapFile(
780 File, /*IsSystem*/false);
781 else
782 CI.getDiagnostics().Report(diag::err_module_map_not_found) << Filename;
783 }
784
785 // Add a module declaration scope so that modules from -fmodule-map-file
786 // arguments may shadow modules found implicitly in search paths.
787 CI.getPreprocessor()
788 .getHeaderSearchInfo()
789 .getModuleMap()
790 .finishModuleDeclarationScope();
791
James Dennettf8317672013-01-23 00:45:44 +0000792 // Create the AST context and consumer unless this is a preprocessor only
793 // action.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000794 if (!usesPreprocessorOnly()) {
Ted Kremenekeeccb302014-08-27 15:14:15 +0000795 // Parsing a model file should reuse the existing ASTContext.
796 if (!isModelParsingAction())
797 CI.createASTContext();
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000798
Taewook Oh06b1af52017-03-07 20:20:23 +0000799 // For preprocessed files, check if the first line specifies the original
800 // source file name with a linemarker.
Richard Smithd6509cf2018-09-15 01:21:15 +0000801 std::string PresumedInputFile = getCurrentFileOrBufferName();
Taewook Oh06b1af52017-03-07 20:20:23 +0000802 if (Input.isPreprocessed())
Richard Smith8128f332017-05-05 22:18:51 +0000803 ReadOriginalFileName(CI, PresumedInputFile);
Taewook Oh06b1af52017-03-07 20:20:23 +0000804
David Blaikie6beb6aa2014-08-10 19:56:51 +0000805 std::unique_ptr<ASTConsumer> Consumer =
Richard Smith8128f332017-05-05 22:18:51 +0000806 CreateWrappedASTConsumer(CI, PresumedInputFile);
Fariborz Jahanian2129ccf2010-10-29 19:49:13 +0000807 if (!Consumer)
808 goto failure;
Sebastian Redl07a89a82010-07-30 00:29:29 +0000809
Ted Kremenekeeccb302014-08-27 15:14:15 +0000810 // FIXME: should not overwrite ASTMutationListener when parsing model files?
811 if (!isModelParsingAction())
812 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener());
Richard Smithe842a472014-10-22 02:05:46 +0000813
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000814 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) {
815 // Convert headers to PCH and chain them.
Alp Toker9e0523d2014-07-07 11:07:10 +0000816 IntrusiveRefCntPtr<ExternalSemaSource> source, FinalReader;
817 source = createChainedIncludesSource(CI, FinalReader);
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000818 if (!source)
819 goto failure;
Alp Toker9e0523d2014-07-07 11:07:10 +0000820 CI.setModuleManager(static_cast<ASTReader *>(FinalReader.get()));
Argyrios Kyrtzidis35dcda72011-03-09 17:21:42 +0000821 CI.getASTContext().setExternalSource(source);
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000822 } else if (CI.getLangOpts().Modules ||
823 !CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
824 // Use PCM or PCH.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000825 assert(hasPCHSupport() && "This action does not have PCH support!");
Douglas Gregor925296b2011-07-19 16:10:42 +0000826 ASTDeserializationListener *DeserialListener =
827 Consumer->GetASTDeserializationListener();
Nico Weber824285e2014-05-08 04:26:47 +0000828 bool DeleteDeserialListener = false;
829 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) {
830 DeserialListener = new DeserializedDeclsDumper(DeserialListener,
831 DeleteDeserialListener);
832 DeleteDeserialListener = true;
833 }
834 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) {
835 DeserialListener = new DeserializedDeclsChecker(
836 CI.getASTContext(),
837 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn,
838 DeserialListener, DeleteDeserialListener);
839 DeleteDeserialListener = true;
840 }
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000841 if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) {
842 CI.createPCHExternalASTSource(
843 CI.getPreprocessorOpts().ImplicitPCHInclude,
844 CI.getPreprocessorOpts().DisablePCHValidation,
Nico Weber824285e2014-05-08 04:26:47 +0000845 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors, DeserialListener,
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000846 DeleteDeserialListener);
847 if (!CI.getASTContext().getExternalSource())
848 goto failure;
849 }
850 // If modules are enabled, create the module manager before creating
851 // any builtins, so that all declarations know that they might be
852 // extended by an external source.
853 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
854 !CI.getASTContext().getExternalSource()) {
855 CI.createModuleManager();
856 CI.getModuleManager()->setDeserializationListener(DeserialListener,
857 DeleteDeserialListener);
858 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000859 }
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000860
David Blaikie6beb6aa2014-08-10 19:56:51 +0000861 CI.setASTConsumer(std::move(Consumer));
Sebastian Redl4d3af3e2010-07-09 21:00:24 +0000862 if (!CI.hasASTConsumer())
863 goto failure;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000864 }
865
Jonathan D. Turner0248f572011-08-05 22:17:03 +0000866 // Initialize built-in info as long as we aren't using an external AST
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000867 // source.
Vassil Vassileva2c2d942017-02-07 21:49:41 +0000868 if (CI.getLangOpts().Modules || !CI.hasASTContext() ||
869 !CI.getASTContext().getExternalSource()) {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000870 Preprocessor &PP = CI.getPreprocessor();
Eric Christopher02d5d862015-08-06 01:01:12 +0000871 PP.getBuiltinInfo().initializeBuiltins(PP.getIdentifierTable(),
David Blaikiebbafb8a2012-03-11 07:00:24 +0000872 PP.getLangOpts());
Richard Smith053f6c62014-05-16 23:01:30 +0000873 } else {
874 // FIXME: If this is a problem, recover from it by creating a multiplex
875 // source.
876 assert((!CI.getLangOpts().Modules || CI.getModuleManager()) &&
877 "modules enabled but created an external source that "
878 "doesn't support modules");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000879 }
880
Richard Smithd4b230b2014-10-27 23:01:16 +0000881 // If we were asked to load any module files, do so now.
882 for (const auto &ModuleFile : CI.getFrontendOpts().ModuleFiles)
883 if (!CI.loadModuleFile(ModuleFile))
Richard Smithe842a472014-10-22 02:05:46 +0000884 goto failure;
Richard Smithe842a472014-10-22 02:05:46 +0000885
Douglas Gregore9fc3772012-01-26 07:55:45 +0000886 // If there is a layout overrides file, attach an external AST source that
887 // provides the layouts from that file.
Taewook Oh06b1af52017-03-07 20:20:23 +0000888 if (!CI.getFrontendOpts().OverrideRecordLayoutsFile.empty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +0000889 CI.hasASTContext() && !CI.getASTContext().getExternalSource()) {
Taewook Oh06b1af52017-03-07 20:20:23 +0000890 IntrusiveRefCntPtr<ExternalASTSource>
Douglas Gregore9fc3772012-01-26 07:55:45 +0000891 Override(new LayoutOverrideSource(
892 CI.getFrontendOpts().OverrideRecordLayoutsFile));
893 CI.getASTContext().setExternalSource(Override);
894 }
Richard Smith053f6c62014-05-16 23:01:30 +0000895
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000896 return true;
897
898 // If we failed, reset state since the client will not end up calling the
899 // matching EndSourceFile().
Richard Smithab755972017-06-05 18:10:11 +0000900failure:
Jordan Roseea762b02012-08-10 01:06:08 +0000901 if (HasBegunSourceFile)
902 CI.getDiagnosticClient().EndSourceFile();
Benjamin Kramer3c717b42012-10-14 19:21:21 +0000903 CI.clearOutputFiles(/*EraseFiles=*/true);
Richard Smithf74d9462017-04-28 01:49:42 +0000904 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000905 setCurrentInput(FrontendInputFile());
Craig Topper49a27902014-05-22 04:46:25 +0000906 setCompilerInstance(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000907 return false;
908}
909
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000910bool FrontendAction::Execute() {
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000911 CompilerInstance &CI = getCompilerInstance();
912
Kovarththanan Rajaratnam5505dff2009-11-29 09:57:35 +0000913 if (CI.hasFrontendTimer()) {
914 llvm::TimeRegion Timer(CI.getFrontendTimer());
915 ExecuteAction();
916 }
917 else ExecuteAction();
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000918
Douglas Gregor5e306b12013-01-23 22:38:11 +0000919 // If we are supposed to rebuild the global module index, do so now unless
Douglas Gregorc1bbec82013-01-25 00:45:27 +0000920 // there were any module-build failures.
921 if (CI.shouldBuildGlobalModuleIndex() && CI.hasFileManager() &&
922 CI.hasPreprocessor()) {
Richard Smith3938f0c2015-08-15 00:34:15 +0000923 StringRef Cache =
924 CI.getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
925 if (!Cache.empty())
926 GlobalModuleIndex::writeIndex(CI.getFileManager(),
927 CI.getPCHContainerReader(), Cache);
Douglas Gregor5e306b12013-01-23 22:38:11 +0000928 }
929
Argyrios Kyrtzidis1416e172012-06-08 05:48:06 +0000930 return true;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000931}
932
933void FrontendAction::EndSourceFile() {
934 CompilerInstance &CI = getCompilerInstance();
935
Douglas Gregor1388a892011-02-09 18:47:31 +0000936 // Inform the diagnostic client we are done with this source file.
937 CI.getDiagnosticClient().EndSourceFile();
938
Benjamin Kramer88d99e42014-08-07 20:51:16 +0000939 // Inform the preprocessor we are done.
940 if (CI.hasPreprocessor())
941 CI.getPreprocessor().EndSourceFile();
942
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000943 // Finalize the action.
944 EndSourceFileAction();
945
Nico Weber7de358e2014-04-24 02:42:04 +0000946 // Sema references the ast consumer, so reset sema first.
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000947 //
948 // FIXME: There is more per-file stuff we could just drop here?
Nico Weber7de358e2014-04-24 02:42:04 +0000949 bool DisableFree = CI.getFrontendOpts().DisableFree;
950 if (DisableFree) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000951 CI.resetAndLeakSema();
952 CI.resetAndLeakASTContext();
David Blaikie9941da42018-11-17 18:04:13 +0000953 llvm::BuryPointer(CI.takeASTConsumer().get());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000954 } else {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000955 CI.setSema(nullptr);
956 CI.setASTContext(nullptr);
Craig Topper49a27902014-05-22 04:46:25 +0000957 CI.setASTConsumer(nullptr);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000958 }
959
960 if (CI.getFrontendOpts().ShowStats) {
961 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n";
962 CI.getPreprocessor().PrintStats();
963 CI.getPreprocessor().getIdentifierTable().PrintStats();
964 CI.getPreprocessor().getHeaderSearchInfo().PrintStats();
965 CI.getSourceManager().PrintStats();
966 llvm::errs() << "\n";
967 }
968
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000969 // Cleanup the output streams, and erase the output files if instructed by the
970 // FrontendAction.
971 CI.clearOutputFiles(/*EraseFiles=*/shouldEraseOutputFiles());
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000972
Nico Weber1f29ccf2014-04-24 03:31:27 +0000973 if (isCurrentFileAST()) {
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000974 if (DisableFree) {
975 CI.resetAndLeakPreprocessor();
976 CI.resetAndLeakSourceManager();
977 CI.resetAndLeakFileManager();
David Blaikie9941da42018-11-17 18:04:13 +0000978 llvm::BuryPointer(std::move(CurrentASTUnit));
Duncan P. N. Exon Smith4a8212a2015-05-04 14:59:20 +0000979 } else {
980 CI.setPreprocessor(nullptr);
981 CI.setSourceManager(nullptr);
982 CI.setFileManager(nullptr);
983 }
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000984 }
985
Craig Topper49a27902014-05-22 04:46:25 +0000986 setCompilerInstance(nullptr);
Douglas Gregor32fbe312012-01-20 16:28:04 +0000987 setCurrentInput(FrontendInputFile());
Richard Smithf74d9462017-04-28 01:49:42 +0000988 CI.getLangOpts().setCompilingModule(LangOptions::CMK_None);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000989}
990
Argyrios Kyrtzidisf0168de2013-06-11 00:36:55 +0000991bool FrontendAction::shouldEraseOutputFiles() {
992 return getCompilerInstance().getDiagnostics().hasErrorOccurred();
993}
994
Daniel Dunbara0ff58d2009-11-14 10:42:35 +0000995//===----------------------------------------------------------------------===//
996// Utility Actions
997//===----------------------------------------------------------------------===//
998
999void ASTFrontendAction::ExecuteAction() {
1000 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola5150f2f2013-07-28 13:23:37 +00001001 if (!CI.hasPreprocessor())
1002 return;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001003
1004 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
1005 // here so the source manager would be initialized.
1006 if (hasCodeCompletionSupport() &&
1007 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
1008 CI.createCodeCompletionConsumer();
1009
1010 // Use a code completion consumer?
Craig Topper49a27902014-05-22 04:46:25 +00001011 CodeCompleteConsumer *CompletionConsumer = nullptr;
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001012 if (CI.hasCodeCompletionConsumer())
1013 CompletionConsumer = &CI.getCodeCompletionConsumer();
1014
Douglas Gregor0e93f012010-08-12 23:31:19 +00001015 if (!CI.hasSema())
Douglas Gregor69f74f82011-08-25 22:30:56 +00001016 CI.createSema(getTranslationUnitKind(), CompletionConsumer);
Douglas Gregor0e93f012010-08-12 23:31:19 +00001017
Erik Verbruggen6e922512012-04-12 10:11:59 +00001018 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats,
1019 CI.getFrontendOpts().SkipFunctionBodies);
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001020}
1021
David Blaikie68e081d2011-12-20 02:48:34 +00001022void PluginASTAction::anchor() { }
1023
David Blaikie6beb6aa2014-08-10 19:56:51 +00001024std::unique_ptr<ASTConsumer>
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001025PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001026 StringRef InFile) {
Jeffrey Yasskin1615d452009-12-12 05:05:38 +00001027 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!");
Daniel Dunbara0ff58d2009-11-14 10:42:35 +00001028}
Chandler Carruthb5703512011-06-16 16:17:05 +00001029
David Blaikie6beb6aa2014-08-10 19:56:51 +00001030std::unique_ptr<ASTConsumer>
1031WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI,
1032 StringRef InFile) {
Chandler Carruthb5703512011-06-16 16:17:05 +00001033 return WrappedAction->CreateASTConsumer(CI, InFile);
1034}
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +00001035bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) {
1036 return WrappedAction->BeginInvocation(CI);
1037}
Richard Smithd9259c22017-06-09 01:36:10 +00001038bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI) {
Douglas Gregor32fbe312012-01-20 16:28:04 +00001039 WrappedAction->setCurrentInput(getCurrentInput());
Argyrios Kyrtzidis90b6a2a2011-06-18 00:53:41 +00001040 WrappedAction->setCompilerInstance(&CI);
Richard Smithd9259c22017-06-09 01:36:10 +00001041 auto Ret = WrappedAction->BeginSourceFileAction(CI);
Argyrios Kyrtzidise89a1792016-02-16 05:39:33 +00001042 // BeginSourceFileAction may change CurrentInput, e.g. during module builds.
1043 setCurrentInput(WrappedAction->getCurrentInput());
1044 return Ret;
Chandler Carruthb5703512011-06-16 16:17:05 +00001045}
1046void WrapperFrontendAction::ExecuteAction() {
1047 WrappedAction->ExecuteAction();
1048}
1049void WrapperFrontendAction::EndSourceFileAction() {
1050 WrappedAction->EndSourceFileAction();
1051}
1052
1053bool WrapperFrontendAction::usesPreprocessorOnly() const {
1054 return WrappedAction->usesPreprocessorOnly();
1055}
Douglas Gregor69f74f82011-08-25 22:30:56 +00001056TranslationUnitKind WrapperFrontendAction::getTranslationUnitKind() {
1057 return WrappedAction->getTranslationUnitKind();
Chandler Carruthb5703512011-06-16 16:17:05 +00001058}
1059bool WrapperFrontendAction::hasPCHSupport() const {
1060 return WrappedAction->hasPCHSupport();
1061}
1062bool WrapperFrontendAction::hasASTFileSupport() const {
1063 return WrappedAction->hasASTFileSupport();
1064}
1065bool WrapperFrontendAction::hasIRSupport() const {
1066 return WrappedAction->hasIRSupport();
1067}
1068bool WrapperFrontendAction::hasCodeCompletionSupport() const {
1069 return WrappedAction->hasCodeCompletionSupport();
1070}
1071
Argyrios Kyrtzidisd35e98f2016-02-07 19:28:36 +00001072WrapperFrontendAction::WrapperFrontendAction(
1073 std::unique_ptr<FrontendAction> WrappedAction)
1074 : WrappedAction(std::move(WrappedAction)) {}
Chandler Carruthb5703512011-06-16 16:17:05 +00001075