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