blob: 4d47c768ad3c2532786e1f9e2ee2bdc42b81552a [file] [log] [blame]
Daniel Dunbar02bd2d72009-11-14 10:42:46 +00001//===--- FrontendActions.cpp ----------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Daniel Dunbar02bd2d72009-11-14 10:42:46 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "clang/Frontend/FrontendActions.h"
10#include "clang/AST/ASTConsumer.h"
11#include "clang/Basic/FileManager.h"
Rainer Orth09d890d2019-08-05 13:59:26 +000012#include "clang/Basic/LangStandard.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000013#include "clang/Frontend/ASTConsumers.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000014#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000015#include "clang/Frontend/FrontendDiagnostic.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000016#include "clang/Frontend/MultiplexConsumer.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000017#include "clang/Frontend/Utils.h"
Alex Lorenz6e2d36b2019-06-03 22:59:17 +000018#include "clang/Lex/DependencyDirectivesSourceMinimizer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Lex/HeaderSearch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Lex/Preprocessor.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000021#include "clang/Lex/PreprocessorOptions.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000022#include "clang/Sema/TemplateInstCallback.h"
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000023#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000024#include "clang/Serialization/ASTWriter.h"
Douglas Gregor524e33e2011-12-08 19:11:24 +000025#include "llvm/Support/FileSystem.h"
Douglas Gregoraf82e352010-07-20 20:18:03 +000026#include "llvm/Support/MemoryBuffer.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000027#include "llvm/Support/Path.h"
Gabor Horvath207e7b12018-02-10 14:04:45 +000028#include "llvm/Support/YAMLTraits.h"
Alex Lorenz6e2d36b2019-06-03 22:59:17 +000029#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000030#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000031#include <system_error>
Douglas Gregor52da28b2011-09-23 23:43:36 +000032
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000033using namespace clang;
34
Gabor Horvath207e7b12018-02-10 14:04:45 +000035namespace {
36CodeCompleteConsumer *GetCodeCompletionConsumer(CompilerInstance &CI) {
37 return CI.hasCodeCompletionConsumer() ? &CI.getCodeCompletionConsumer()
38 : nullptr;
39}
40
41void EnsureSemaIsCreated(CompilerInstance &CI, FrontendAction &Action) {
42 if (Action.hasCodeCompletionSupport() &&
43 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty())
44 CI.createCodeCompletionConsumer();
45
46 if (!CI.hasSema())
47 CI.createSema(Action.getTranslationUnitKind(),
48 GetCodeCompletionConsumer(CI));
49}
50} // namespace
51
Daniel Dunbar88357802009-11-14 10:42:57 +000052//===----------------------------------------------------------------------===//
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000053// Custom Actions
54//===----------------------------------------------------------------------===//
55
David Blaikie6beb6aa2014-08-10 19:56:51 +000056std::unique_ptr<ASTConsumer>
57InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +000058 return std::make_unique<ASTConsumer>();
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000059}
60
61void InitOnlyAction::ExecuteAction() {
62}
63
64//===----------------------------------------------------------------------===//
Daniel Dunbar88357802009-11-14 10:42:57 +000065// AST Consumer Actions
66//===----------------------------------------------------------------------===//
67
David Blaikie6beb6aa2014-08-10 19:56:51 +000068std::unique_ptr<ASTConsumer>
69ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Peter Collingbourne03f89072016-07-15 00:55:40 +000070 if (std::unique_ptr<raw_ostream> OS =
71 CI.createDefaultOutputFile(false, InFile))
72 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
Craig Topper49a27902014-05-22 04:46:25 +000073 return nullptr;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000074}
75
David Blaikie6beb6aa2014-08-10 19:56:51 +000076std::unique_ptr<ASTConsumer>
77ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Aaron Ballman2ce598a2019-05-13 21:39:55 +000078 const FrontendOptions &Opts = CI.getFrontendOpts();
79 return CreateASTDumper(nullptr /*Dump to stdout.*/, Opts.ASTDumpFilter,
80 Opts.ASTDumpDecls, Opts.ASTDumpAll,
81 Opts.ASTDumpLookups, Opts.ASTDumpFormat);
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000082}
83
David Blaikie6beb6aa2014-08-10 19:56:51 +000084std::unique_ptr<ASTConsumer>
85ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Alexander Kornienko4de03592012-07-31 09:37:40 +000086 return CreateASTDeclNodeLister();
87}
88
David Blaikie6beb6aa2014-08-10 19:56:51 +000089std::unique_ptr<ASTConsumer>
90ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000091 return CreateASTViewer();
92}
93
David Blaikie6beb6aa2014-08-10 19:56:51 +000094std::unique_ptr<ASTConsumer>
David Blaikie6beb6aa2014-08-10 19:56:51 +000095GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000096 std::string Sysroot;
Ilya Biryukov417085a2017-11-16 16:25:01 +000097 if (!ComputeASTConsumerArguments(CI, /*ref*/ Sysroot))
98 return nullptr;
99
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000100 std::string OutputFile;
Peter Collingbourne03f89072016-07-15 00:55:40 +0000101 std::unique_ptr<raw_pwrite_stream> OS =
Ilya Biryukov417085a2017-11-16 16:25:01 +0000102 CreateOutputFile(CI, InFile, /*ref*/ OutputFile);
Rafael Espindola47de1492015-04-10 12:54:53 +0000103 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000104 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000105
Douglas Gregorc567ba22011-07-22 16:35:34 +0000106 if (!CI.getFrontendOpts().RelocatablePCH)
107 Sysroot.clear();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000108
Hans Wennborg08c5a7b2018-06-25 13:23:49 +0000109 const auto &FrontendOpts = CI.getFrontendOpts();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000110 auto Buffer = std::make_shared<PCHBuffer>();
111 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000112 Consumers.push_back(std::make_unique<PCHGenerator>(
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000113 CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
114 FrontendOpts.ModuleFileExtensions,
115 CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +0000116 FrontendOpts.IncludeTimestamps, +CI.getLangOpts().CacheGeneratedPCH));
Adrian Prantl03914062015-09-18 22:10:59 +0000117 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000118 CI, InFile, OutputFile, std::move(OS), Buffer));
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000119
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000120 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000121}
122
Ilya Biryukov417085a2017-11-16 16:25:01 +0000123bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
124 std::string &Sysroot) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000125 Sysroot = CI.getHeaderSearchOpts().Sysroot;
126 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redlea68af42010-08-17 17:55:38 +0000127 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Ilya Biryukov417085a2017-11-16 16:25:01 +0000128 return false;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000129 }
130
Ilya Biryukov417085a2017-11-16 16:25:01 +0000131 return true;
132}
133
134std::unique_ptr<llvm::raw_pwrite_stream>
135GeneratePCHAction::CreateOutputFile(CompilerInstance &CI, StringRef InFile,
136 std::string &OutputFile) {
Daniel Dunbara2867c72011-01-31 22:00:44 +0000137 // We use createOutputFile here because this is exposed via libclang, and we
138 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000139 // We use a temporary to avoid race conditions.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000140 std::unique_ptr<raw_pwrite_stream> OS =
Rafael Espindola47de1492015-04-10 12:54:53 +0000141 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
142 /*RemoveFileOnSignal=*/false, InFile,
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000143 /*Extension=*/"", /*UseTemporary=*/true);
Daniel Dunbar75546992009-12-03 09:13:30 +0000144 if (!OS)
Rafael Espindola47de1492015-04-10 12:54:53 +0000145 return nullptr;
Daniel Dunbar75546992009-12-03 09:13:30 +0000146
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000147 OutputFile = CI.getFrontendOpts().OutputFile;
Rafael Espindola47de1492015-04-10 12:54:53 +0000148 return OS;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000149}
150
Argyrios Kyrtzidiscf486b22017-02-27 03:52:36 +0000151bool GeneratePCHAction::shouldEraseOutputFiles() {
152 if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
153 return false;
154 return ASTFrontendAction::shouldEraseOutputFiles();
155}
156
Richard Smithd9259c22017-06-09 01:36:10 +0000157bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI) {
Manman Renffd3e9d2017-01-09 19:20:18 +0000158 CI.getLangOpts().CompilingPCH = true;
159 return true;
160}
161
David Blaikie6beb6aa2014-08-10 19:56:51 +0000162std::unique_ptr<ASTConsumer>
163GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
164 StringRef InFile) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000165 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000166 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000167 return nullptr;
168
Richard Smithbbcc9f02016-08-26 00:14:38 +0000169 std::string OutputFile = CI.getFrontendOpts().OutputFile;
170 std::string Sysroot;
171
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000172 auto Buffer = std::make_shared<PCHBuffer>();
173 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000174
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000175 Consumers.push_back(std::make_unique<PCHGenerator>(
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000176 CI.getPreprocessor(), CI.getModuleCache(), OutputFile, Sysroot, Buffer,
177 CI.getFrontendOpts().ModuleFileExtensions,
178 /*AllowASTWithErrors=*/false,
179 /*IncludeTimestamps=*/
Duncan P. N. Exon Smith70d759b2019-03-12 18:38:04 +0000180 +CI.getFrontendOpts().BuildingImplicitModule,
181 /*ShouldCacheASTInMemory=*/
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000182 +CI.getFrontendOpts().BuildingImplicitModule));
Adrian Prantl03914062015-09-18 22:10:59 +0000183 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000184 CI, InFile, OutputFile, std::move(OS), Buffer));
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000185 return std::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000186}
187
Richard Smith1f2bd352017-07-06 21:05:56 +0000188bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
189 CompilerInstance &CI) {
190 if (!CI.getLangOpts().Modules) {
191 CI.getDiagnostics().Report(diag::err_module_build_requires_fmodules);
192 return false;
193 }
194
195 return GenerateModuleAction::BeginSourceFileAction(CI);
196}
197
Peter Collingbourne03f89072016-07-15 00:55:40 +0000198std::unique_ptr<raw_pwrite_stream>
Richard Smithbbcc9f02016-08-26 00:14:38 +0000199GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
200 StringRef InFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000201 // If no output file was provided, figure out where this module would go
202 // in the module cache.
203 if (CI.getFrontendOpts().OutputFile.empty()) {
Richard Smithf74d9462017-04-28 01:49:42 +0000204 StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
205 if (ModuleMapFile.empty())
206 ModuleMapFile = InFile;
207
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000208 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000209 CI.getFrontendOpts().OutputFile =
Boris Kolpackovd30446f2017-08-31 06:26:43 +0000210 HS.getCachedModuleFileName(CI.getLangOpts().CurrentModule,
211 ModuleMapFile);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000212 }
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000213
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000214 // We use createOutputFile here because this is exposed via libclang, and we
215 // must disable the RemoveFileOnSignal behavior.
216 // We use a temporary to avoid race conditions.
Richard Smithbbcc9f02016-08-26 00:14:38 +0000217 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
218 /*RemoveFileOnSignal=*/false, InFile,
Rui Ueyama49a3ad22019-07-16 04:46:31 +0000219 /*Extension=*/"", /*UseTemporary=*/true,
Richard Smithbbcc9f02016-08-26 00:14:38 +0000220 /*CreateMissingDirectories=*/true);
221}
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000222
Richard Smithd9259c22017-06-09 01:36:10 +0000223bool GenerateModuleInterfaceAction::BeginSourceFileAction(
224 CompilerInstance &CI) {
Richard Smithb1b580e2019-04-14 11:11:37 +0000225 if (!CI.getLangOpts().ModulesTS && !CI.getLangOpts().CPlusPlusModules) {
226 CI.getDiagnostics().Report(diag::err_module_interface_requires_cpp_modules);
Richard Smithbbcc9f02016-08-26 00:14:38 +0000227 return false;
228 }
229
230 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
231
Richard Smithd9259c22017-06-09 01:36:10 +0000232 return GenerateModuleAction::BeginSourceFileAction(CI);
Richard Smithbbcc9f02016-08-26 00:14:38 +0000233}
234
235std::unique_ptr<raw_pwrite_stream>
236GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
237 StringRef InFile) {
238 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000239}
240
Richard Smithd6509cf2018-09-15 01:21:15 +0000241bool GenerateHeaderModuleAction::PrepareToExecuteAction(
242 CompilerInstance &CI) {
Richard Smithb1b580e2019-04-14 11:11:37 +0000243 if (!CI.getLangOpts().Modules) {
Richard Smithd6509cf2018-09-15 01:21:15 +0000244 CI.getDiagnostics().Report(diag::err_header_module_requires_modules);
245 return false;
246 }
247
248 auto &Inputs = CI.getFrontendOpts().Inputs;
249 if (Inputs.empty())
250 return GenerateModuleAction::BeginInvocation(CI);
251
252 auto Kind = Inputs[0].getKind();
253
254 // Convert the header file inputs into a single module input buffer.
255 SmallString<256> HeaderContents;
256 ModuleHeaders.reserve(Inputs.size());
257 for (const FrontendInputFile &FIF : Inputs) {
258 // FIXME: We should support re-compiling from an AST file.
259 if (FIF.getKind().getFormat() != InputKind::Source || !FIF.isFile()) {
260 CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
261 << (FIF.isFile() ? FIF.getFile()
262 : FIF.getBuffer()->getBufferIdentifier());
263 return true;
264 }
265
266 HeaderContents += "#include \"";
267 HeaderContents += FIF.getFile();
268 HeaderContents += "\"\n";
269 ModuleHeaders.push_back(FIF.getFile());
270 }
271 Buffer = llvm::MemoryBuffer::getMemBufferCopy(
272 HeaderContents, Module::getModuleInputBufferName());
273
274 // Set that buffer up as our "real" input.
275 Inputs.clear();
276 Inputs.push_back(FrontendInputFile(Buffer.get(), Kind, /*IsSystem*/false));
277
278 return GenerateModuleAction::PrepareToExecuteAction(CI);
279}
280
281bool GenerateHeaderModuleAction::BeginSourceFileAction(
282 CompilerInstance &CI) {
283 CI.getLangOpts().setCompilingModule(LangOptions::CMK_HeaderModule);
284
285 // Synthesize a Module object for the given headers.
286 auto &HS = CI.getPreprocessor().getHeaderSearchInfo();
287 SmallVector<Module::Header, 16> Headers;
288 for (StringRef Name : ModuleHeaders) {
289 const DirectoryLookup *CurDir = nullptr;
Alex Lorenz4dc55732019-08-22 18:15:50 +0000290 Optional<FileEntryRef> FE = HS.LookupFile(
291 Name, SourceLocation(), /*Angled*/ false, nullptr, CurDir, None,
292 nullptr, nullptr, nullptr, nullptr, nullptr, nullptr);
Richard Smithd6509cf2018-09-15 01:21:15 +0000293 if (!FE) {
294 CI.getDiagnostics().Report(diag::err_module_header_file_not_found)
295 << Name;
296 continue;
297 }
Alex Lorenz4dc55732019-08-22 18:15:50 +0000298 Headers.push_back({Name, &FE->getFileEntry()});
Richard Smithd6509cf2018-09-15 01:21:15 +0000299 }
300 HS.getModuleMap().createHeaderModule(CI.getLangOpts().CurrentModule, Headers);
301
302 return GenerateModuleAction::BeginSourceFileAction(CI);
303}
304
305std::unique_ptr<raw_pwrite_stream>
306GenerateHeaderModuleAction::CreateOutputFile(CompilerInstance &CI,
307 StringRef InFile) {
308 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
309}
310
Etienne Bergeron98de8052016-05-12 19:51:18 +0000311SyntaxOnlyAction::~SyntaxOnlyAction() {
312}
313
David Blaikie6beb6aa2014-08-10 19:56:51 +0000314std::unique_ptr<ASTConsumer>
315SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000316 return std::make_unique<ASTConsumer>();
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000317}
318
David Blaikie6beb6aa2014-08-10 19:56:51 +0000319std::unique_ptr<ASTConsumer>
320DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
321 StringRef InFile) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000322 return std::make_unique<ASTConsumer>();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000323}
324
David Blaikie6beb6aa2014-08-10 19:56:51 +0000325std::unique_ptr<ASTConsumer>
326VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000327 return std::make_unique<ASTConsumer>();
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000328}
329
330void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000331 CompilerInstance &CI = getCompilerInstance();
332 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
333 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000334 std::unique_ptr<ASTReader> Reader(new ASTReader(
Duncan P. N. Exon Smith8bef5cd2019-03-09 17:33:56 +0000335 CI.getPreprocessor(), CI.getModuleCache(), &CI.getASTContext(),
336 CI.getPCHContainerReader(), CI.getFrontendOpts().ModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000337 Sysroot.empty() ? "" : Sysroot.c_str(),
338 /*DisableValidation*/ false,
339 /*AllowPCHWithCompilerErrors*/ false,
340 /*AllowConfigurationMismatch*/ true,
341 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000342
343 Reader->ReadAST(getCurrentFile(),
344 Preamble ? serialization::MK_Preamble
345 : serialization::MK_PCH,
346 SourceLocation(),
347 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000348}
349
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000350namespace {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000351struct TemplightEntry {
352 std::string Name;
353 std::string Kind;
354 std::string Event;
355 std::string DefinitionLocation;
356 std::string PointOfInstantiation;
357};
358} // namespace
359
360namespace llvm {
361namespace yaml {
362template <> struct MappingTraits<TemplightEntry> {
363 static void mapping(IO &io, TemplightEntry &fields) {
364 io.mapRequired("name", fields.Name);
365 io.mapRequired("kind", fields.Kind);
366 io.mapRequired("event", fields.Event);
367 io.mapRequired("orig", fields.DefinitionLocation);
368 io.mapRequired("poi", fields.PointOfInstantiation);
369 }
370};
371} // namespace yaml
372} // namespace llvm
373
374namespace {
375class DefaultTemplateInstCallback : public TemplateInstantiationCallback {
376 using CodeSynthesisContext = Sema::CodeSynthesisContext;
377
378public:
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000379 void initialize(const Sema &) override {}
Gabor Horvath207e7b12018-02-10 14:04:45 +0000380
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000381 void finalize(const Sema &) override {}
Gabor Horvath207e7b12018-02-10 14:04:45 +0000382
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000383 void atTemplateBegin(const Sema &TheSema,
384 const CodeSynthesisContext &Inst) override {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000385 displayTemplightEntry<true>(llvm::outs(), TheSema, Inst);
386 }
387
Gabor Horvath6e0dbb02018-02-10 14:26:53 +0000388 void atTemplateEnd(const Sema &TheSema,
389 const CodeSynthesisContext &Inst) override {
Gabor Horvath207e7b12018-02-10 14:04:45 +0000390 displayTemplightEntry<false>(llvm::outs(), TheSema, Inst);
391 }
392
393private:
394 static std::string toString(CodeSynthesisContext::SynthesisKind Kind) {
395 switch (Kind) {
396 case CodeSynthesisContext::TemplateInstantiation:
397 return "TemplateInstantiation";
398 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
399 return "DefaultTemplateArgumentInstantiation";
400 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
401 return "DefaultFunctionArgumentInstantiation";
402 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
403 return "ExplicitTemplateArgumentSubstitution";
404 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
405 return "DeducedTemplateArgumentSubstitution";
406 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
407 return "PriorTemplateArgumentSubstitution";
408 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
409 return "DefaultTemplateArgumentChecking";
Richard Smith5159bbad2018-09-05 22:30:37 +0000410 case CodeSynthesisContext::ExceptionSpecEvaluation:
411 return "ExceptionSpecEvaluation";
Gabor Horvath207e7b12018-02-10 14:04:45 +0000412 case CodeSynthesisContext::ExceptionSpecInstantiation:
413 return "ExceptionSpecInstantiation";
414 case CodeSynthesisContext::DeclaringSpecialMember:
415 return "DeclaringSpecialMember";
416 case CodeSynthesisContext::DefiningSynthesizedFunction:
417 return "DefiningSynthesizedFunction";
Richard Smith974c8b72019-10-19 00:04:43 +0000418 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
419 return "RewritingOperatorAsSpaceship";
Gabor Horvath207e7b12018-02-10 14:04:45 +0000420 case CodeSynthesisContext::Memoization:
421 return "Memoization";
Saar Raz5d98ba62019-10-15 15:24:26 +0000422 case CodeSynthesisContext::ConstraintsCheck:
423 return "ConstraintsCheck";
424 case CodeSynthesisContext::ConstraintSubstitution:
425 return "ConstraintSubstitution";
Gabor Horvath207e7b12018-02-10 14:04:45 +0000426 }
427 return "";
428 }
429
430 template <bool BeginInstantiation>
431 static void displayTemplightEntry(llvm::raw_ostream &Out, const Sema &TheSema,
432 const CodeSynthesisContext &Inst) {
433 std::string YAML;
434 {
435 llvm::raw_string_ostream OS(YAML);
436 llvm::yaml::Output YO(OS);
437 TemplightEntry Entry =
438 getTemplightEntry<BeginInstantiation>(TheSema, Inst);
439 llvm::yaml::EmptyContext Context;
440 llvm::yaml::yamlize(YO, Entry, true, Context);
441 }
442 Out << "---" << YAML << "\n";
443 }
444
445 template <bool BeginInstantiation>
446 static TemplightEntry getTemplightEntry(const Sema &TheSema,
447 const CodeSynthesisContext &Inst) {
448 TemplightEntry Entry;
449 Entry.Kind = toString(Inst.Kind);
450 Entry.Event = BeginInstantiation ? "Begin" : "End";
451 if (auto *NamedTemplate = dyn_cast_or_null<NamedDecl>(Inst.Entity)) {
452 llvm::raw_string_ostream OS(Entry.Name);
453 NamedTemplate->getNameForDiagnostic(OS, TheSema.getLangOpts(), true);
Fangrui Song6907ce22018-07-30 19:24:48 +0000454 const PresumedLoc DefLoc =
Gabor Horvath207e7b12018-02-10 14:04:45 +0000455 TheSema.getSourceManager().getPresumedLoc(Inst.Entity->getLocation());
456 if(!DefLoc.isInvalid())
457 Entry.DefinitionLocation = std::string(DefLoc.getFilename()) + ":" +
458 std::to_string(DefLoc.getLine()) + ":" +
459 std::to_string(DefLoc.getColumn());
460 }
461 const PresumedLoc PoiLoc =
462 TheSema.getSourceManager().getPresumedLoc(Inst.PointOfInstantiation);
463 if (!PoiLoc.isInvalid()) {
464 Entry.PointOfInstantiation = std::string(PoiLoc.getFilename()) + ":" +
465 std::to_string(PoiLoc.getLine()) + ":" +
466 std::to_string(PoiLoc.getColumn());
467 }
468 return Entry;
469 }
470};
471} // namespace
472
473std::unique_ptr<ASTConsumer>
474TemplightDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000475 return std::make_unique<ASTConsumer>();
Gabor Horvath207e7b12018-02-10 14:04:45 +0000476}
477
478void TemplightDumpAction::ExecuteAction() {
479 CompilerInstance &CI = getCompilerInstance();
480
481 // This part is normally done by ASTFrontEndAction, but needs to happen
482 // before Templight observers can be created
483 // FIXME: Move the truncation aspect of this into Sema, we delayed this till
484 // here so the source manager would be initialized.
485 EnsureSemaIsCreated(CI, *this);
486
487 CI.getSema().TemplateInstCallbacks.push_back(
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +0000488 std::make_unique<DefaultTemplateInstCallback>());
Gabor Horvath207e7b12018-02-10 14:04:45 +0000489 ASTFrontendAction::ExecuteAction();
490}
491
492namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// AST reader listener that dumps module information for a module
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000494 /// file.
495 class DumpModuleInfoListener : public ASTReaderListener {
496 llvm::raw_ostream &Out;
497
498 public:
499 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
500
501#define DUMP_BOOLEAN(Value, Text) \
502 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
503
Craig Topperafa7cb32014-03-13 06:07:04 +0000504 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000505 Out.indent(2)
506 << "Generated by "
507 << (FullVersion == getClangFullRepositoryVersion()? "this"
508 : "a different")
509 << " Clang: " << FullVersion << "\n";
510 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
511 }
512
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000513 void ReadModuleName(StringRef ModuleName) override {
514 Out.indent(2) << "Module name: " << ModuleName << "\n";
515 }
516 void ReadModuleMapFile(StringRef ModuleMapPath) override {
517 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
518 }
519
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000520 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
521 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000522 Out.indent(2) << "Language options:\n";
523#define LANGOPT(Name, Bits, Default, Description) \
524 DUMP_BOOLEAN(LangOpts.Name, Description);
525#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
526 Out.indent(4) << Description << ": " \
527 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
528#define VALUE_LANGOPT(Name, Bits, Default, Description) \
529 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
530#define BENIGN_LANGOPT(Name, Bits, Default, Description)
531#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
532#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +0000533
534 if (!LangOpts.ModuleFeatures.empty()) {
535 Out.indent(4) << "Module features:\n";
536 for (StringRef Feature : LangOpts.ModuleFeatures)
537 Out.indent(6) << Feature << "\n";
538 }
539
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000540 return false;
541 }
542
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000543 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
544 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000545 Out.indent(2) << "Target options:\n";
546 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
547 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
548 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000549
550 if (!TargetOpts.FeaturesAsWritten.empty()) {
551 Out.indent(4) << "Target features:\n";
552 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
553 I != N; ++I) {
554 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
555 }
556 }
557
558 return false;
559 }
560
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000561 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
562 bool Complain) override {
Ben Langmuirb92de022014-04-29 16:25:26 +0000563 Out.indent(2) << "Diagnostic options:\n";
564#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
565#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
566 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
567#define VALUE_DIAGOPT(Name, Bits, Default) \
568 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
569#include "clang/Basic/DiagnosticOptions.def"
570
Richard Smith3be1cb22014-08-07 00:24:21 +0000571 Out.indent(4) << "Diagnostic flags:\n";
572 for (const std::string &Warning : DiagOpts->Warnings)
Ben Langmuirb92de022014-04-29 16:25:26 +0000573 Out.indent(6) << "-W" << Warning << "\n";
Richard Smith3be1cb22014-08-07 00:24:21 +0000574 for (const std::string &Remark : DiagOpts->Remarks)
575 Out.indent(6) << "-R" << Remark << "\n";
Ben Langmuirb92de022014-04-29 16:25:26 +0000576
577 return false;
578 }
579
Craig Topperafa7cb32014-03-13 06:07:04 +0000580 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000581 StringRef SpecificModuleCachePath,
Craig Topperafa7cb32014-03-13 06:07:04 +0000582 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000583 Out.indent(2) << "Header search options:\n";
584 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
Argyrios Kyrtzidisbdff27d2017-02-25 18:14:31 +0000585 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000586 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000587 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
588 "Use builtin include directories [-nobuiltininc]");
589 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
590 "Use standard system include directories [-nostdinc]");
591 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
592 "Use standard C++ include directories [-nostdinc++]");
593 DUMP_BOOLEAN(HSOpts.UseLibcxx,
594 "Use libc++ (rather than libstdc++) [-stdlib=]");
595 return false;
596 }
597
Craig Topperafa7cb32014-03-13 06:07:04 +0000598 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
599 bool Complain,
600 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000601 Out.indent(2) << "Preprocessor options:\n";
602 DUMP_BOOLEAN(PPOpts.UsePredefines,
603 "Uses compiler/target-specific predefines [-undef]");
604 DUMP_BOOLEAN(PPOpts.DetailedRecord,
605 "Uses detailed preprocessing record (for indexing)");
606
607 if (!PPOpts.Macros.empty()) {
608 Out.indent(4) << "Predefined macros:\n";
609 }
610
611 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
612 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
613 I != IEnd; ++I) {
614 Out.indent(6);
615 if (I->second)
616 Out << "-U";
617 else
618 Out << "-D";
619 Out << I->first << "\n";
620 }
621 return false;
622 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000623
624 /// Indicates that a particular module file extension has been read.
625 void readModuleFileExtension(
626 const ModuleFileExtensionMetadata &Metadata) override {
627 Out.indent(2) << "Module file extension '"
628 << Metadata.BlockName << "' " << Metadata.MajorVersion
629 << "." << Metadata.MinorVersion;
630 if (!Metadata.UserInfo.empty()) {
631 Out << ": ";
632 Out.write_escaped(Metadata.UserInfo);
633 }
634
635 Out << "\n";
636 }
Vassil Vassilev33eb7292018-07-18 06:49:33 +0000637
638 /// Tells the \c ASTReaderListener that we want to receive the
639 /// input files of the AST file via \c visitInputFile.
640 bool needsInputFileVisitation() override { return true; }
641
642 /// Tells the \c ASTReaderListener that we want to receive the
643 /// input files of the AST file via \c visitInputFile.
644 bool needsSystemInputFileVisitation() override { return true; }
645
646 /// Indicates that the AST file contains particular input file.
647 ///
648 /// \returns true to continue receiving the next input file, false to stop.
649 bool visitInputFile(StringRef Filename, bool isSystem,
650 bool isOverridden, bool isExplicitModule) override {
651
652 Out.indent(2) << "Input file: " << Filename;
653
654 if (isSystem || isOverridden || isExplicitModule) {
655 Out << " [";
656 if (isSystem) {
657 Out << "System";
658 if (isOverridden || isExplicitModule)
659 Out << ", ";
660 }
661 if (isOverridden) {
662 Out << "Overridden";
663 if (isExplicitModule)
664 Out << ", ";
665 }
666 if (isExplicitModule)
667 Out << "ExplicitModule";
668
669 Out << "]";
670 }
671
672 Out << "\n";
673
674 return true;
675 }
Bruno Cardoso Lopes6fc8a562018-09-11 05:17:13 +0000676
677 /// Returns true if this \c ASTReaderListener wants to receive the
678 /// imports of the AST file via \c visitImport, false otherwise.
679 bool needsImportVisitation() const override { return true; }
680
681 /// If needsImportVisitation returns \c true, this is called for each
682 /// AST file imported by this AST file.
683 void visitImport(StringRef ModuleName, StringRef Filename) override {
684 Out.indent(2) << "Imports module '" << ModuleName
685 << "': " << Filename.str() << "\n";
686 }
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000687#undef DUMP_BOOLEAN
688 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000689}
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000690
Adrian Prantl576b2db2016-08-17 23:13:53 +0000691bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
692 // The Object file reader also supports raw ast files and there is no point in
693 // being strict about the module file format in -module-file-info mode.
694 CI.getHeaderSearchOpts().ModuleFormat = "obj";
695 return true;
696}
697
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000698void DumpModuleInfoAction::ExecuteAction() {
699 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000700 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000701 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
702 if (!OutputFileName.empty() && OutputFileName != "-") {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000703 std::error_code EC;
704 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
Fangrui Songd9b948b2019-08-05 05:43:48 +0000705 llvm::sys::fs::OF_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000706 }
707 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
708
709 Out << "Information for module file '" << getCurrentFile() << "':\n";
Adrian Prantl99e765b2016-08-17 23:14:00 +0000710 auto &FileMgr = getCompilerInstance().getFileManager();
711 auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
712 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
713 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
714 Magic[2] == 'C' && Magic[3] == 'H');
715 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
Adrian Prantl576b2db2016-08-17 23:13:53 +0000716
Manman Ren47a44452016-07-26 17:12:17 +0000717 Preprocessor &PP = getCompilerInstance().getPreprocessor();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000718 DumpModuleInfoListener Listener(Out);
Manman Ren47a44452016-07-26 17:12:17 +0000719 HeaderSearchOptions &HSOpts =
720 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000721 ASTReader::readASTFileControlBlock(
Adrian Prantl99e765b2016-08-17 23:14:00 +0000722 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
Manman Ren47a44452016-07-26 17:12:17 +0000723 /*FindModuleFileExtensions=*/true, Listener,
724 HSOpts.ModulesValidateDiagnosticOptions);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000725}
726
Daniel Dunbar88357802009-11-14 10:42:57 +0000727//===----------------------------------------------------------------------===//
728// Preprocessor Actions
729//===----------------------------------------------------------------------===//
730
731void DumpRawTokensAction::ExecuteAction() {
732 Preprocessor &PP = getCompilerInstance().getPreprocessor();
733 SourceManager &SM = PP.getSourceManager();
734
735 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000736 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000737 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000738 RawLex.SetKeepWhitespaceMode(true);
739
740 Token RawTok;
741 RawLex.LexFromRawLexer(RawTok);
742 while (RawTok.isNot(tok::eof)) {
743 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000744 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000745 RawLex.LexFromRawLexer(RawTok);
746 }
747}
748
749void DumpTokensAction::ExecuteAction() {
750 Preprocessor &PP = getCompilerInstance().getPreprocessor();
751 // Start preprocessing the specified input file.
752 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000753 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000754 do {
755 PP.Lex(Tok);
756 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000757 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000758 } while (Tok.isNot(tok::eof));
759}
760
Daniel Dunbar88357802009-11-14 10:42:57 +0000761void PreprocessOnlyAction::ExecuteAction() {
762 Preprocessor &PP = getCompilerInstance().getPreprocessor();
763
Daniel Dunbard839e772010-06-11 20:10:12 +0000764 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000765 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000766
Daniel Dunbar88357802009-11-14 10:42:57 +0000767 Token Tok;
768 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000769 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000770 do {
771 PP.Lex(Tok);
772 } while (Tok.isNot(tok::eof));
773}
774
Daniel Dunbar88357802009-11-14 10:42:57 +0000775void PrintPreprocessedAction::ExecuteAction() {
776 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000777 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000778 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000779 //
780 // Look to see what type of line endings the file uses. If there's a
781 // CRLF, then we won't open the file up in binary mode. If there is
782 // just an LF or CR, then we will open the file up in binary mode.
783 // In this fashion, the output format should match the input format, unless
784 // the input format has inconsistent line endings.
785 //
786 // This should be a relatively fast operation since most files won't have
Fangrui Song6907ce22018-07-30 19:24:48 +0000787 // all of their source code on a single line. However, that is still a
Douglas Gregor52da28b2011-09-23 23:43:36 +0000788 // concern, so if we scan for too long, we'll just assume the file should
789 // be opened in binary mode.
790 bool BinaryMode = true;
791 bool InvalidFile = false;
792 const SourceManager& SM = CI.getSourceManager();
Fangrui Song6907ce22018-07-30 19:24:48 +0000793 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
Douglas Gregor52da28b2011-09-23 23:43:36 +0000794 &InvalidFile);
795 if (!InvalidFile) {
796 const char *cur = Buffer->getBufferStart();
797 const char *end = Buffer->getBufferEnd();
798 const char *next = (cur != end) ? cur + 1 : end;
799
800 // Limit ourselves to only scanning 256 characters into the source
Fangrui Song6907ce22018-07-30 19:24:48 +0000801 // file. This is mostly a sanity check in case the file has no
Douglas Gregor52da28b2011-09-23 23:43:36 +0000802 // newlines whatsoever.
803 if (end - cur > 256) end = cur + 256;
Aaron Ballman4fc36ae2017-06-16 20:52:59 +0000804
Douglas Gregor52da28b2011-09-23 23:43:36 +0000805 while (next < end) {
806 if (*cur == 0x0D) { // CR
807 if (*next == 0x0A) // CRLF
808 BinaryMode = false;
809
810 break;
811 } else if (*cur == 0x0A) // LF
812 break;
813
Richard Trieucc3949d2016-02-18 22:34:54 +0000814 ++cur;
815 ++next;
Douglas Gregor52da28b2011-09-23 23:43:36 +0000816 }
817 }
818
Peter Collingbourne03f89072016-07-15 00:55:40 +0000819 std::unique_ptr<raw_ostream> OS =
Richard Smith8b464f22018-09-15 01:21:18 +0000820 CI.createDefaultOutputFile(BinaryMode, getCurrentFileOrBufferName());
Daniel Dunbar75546992009-12-03 09:13:30 +0000821 if (!OS) return;
822
Richard Smith8128f332017-05-05 22:18:51 +0000823 // If we're preprocessing a module map, start by dumping the contents of the
824 // module itself before switching to the input buffer.
825 auto &Input = getCurrentInput();
826 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
Richard Smithc784e962017-06-01 20:10:35 +0000827 if (Input.isFile()) {
828 (*OS) << "# 1 \"";
829 OS->write_escaped(Input.getFile());
830 (*OS) << "\"\n";
831 }
Richard Smith8128f332017-05-05 22:18:51 +0000832 getCurrentModule()->print(*OS);
833 (*OS) << "#pragma clang module contents\n";
834 }
835
Peter Collingbourne03f89072016-07-15 00:55:40 +0000836 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
Daniel Dunbar88357802009-11-14 10:42:57 +0000837 CI.getPreprocessorOutputOpts());
838}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000839
840void PrintPreambleAction::ExecuteAction() {
Richard Smith40c0efa2017-04-26 18:57:40 +0000841 switch (getCurrentFileKind().getLanguage()) {
Rainer Orth09d890d2019-08-05 13:59:26 +0000842 case Language::C:
843 case Language::CXX:
844 case Language::ObjC:
845 case Language::ObjCXX:
846 case Language::OpenCL:
847 case Language::CUDA:
848 case Language::HIP:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000849 break;
Fangrui Song6907ce22018-07-30 19:24:48 +0000850
Rainer Orth09d890d2019-08-05 13:59:26 +0000851 case Language::Unknown:
852 case Language::Asm:
853 case Language::LLVM_IR:
854 case Language::RenderScript:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000855 // We can't do anything with these.
856 return;
857 }
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000858
Richard Smith40c0efa2017-04-26 18:57:40 +0000859 // We don't expect to find any #include directives in a preprocessed input.
860 if (getCurrentFileKind().isPreprocessed())
861 return;
862
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000863 CompilerInstance &CI = getCompilerInstance();
Benjamin Kramera8857962014-10-26 22:44:13 +0000864 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
865 if (Buffer) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000866 unsigned Preamble =
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000867 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).Size;
Benjamin Kramera8857962014-10-26 22:44:13 +0000868 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
Douglas Gregoraf82e352010-07-20 20:18:03 +0000869 }
870}
Aaron Ballman16ed8dd2018-05-31 13:57:09 +0000871
872void DumpCompilerOptionsAction::ExecuteAction() {
873 CompilerInstance &CI = getCompilerInstance();
874 std::unique_ptr<raw_ostream> OSP =
875 CI.createDefaultOutputFile(false, getCurrentFile());
876 if (!OSP)
877 return;
878
879 raw_ostream &OS = *OSP;
880 const Preprocessor &PP = CI.getPreprocessor();
881 const LangOptions &LangOpts = PP.getLangOpts();
882
883 // FIXME: Rather than manually format the JSON (which is awkward due to
884 // needing to remove trailing commas), this should make use of a JSON library.
885 // FIXME: Instead of printing enums as an integral value and specifying the
886 // type as a separate field, use introspection to print the enumerator.
887
888 OS << "{\n";
889 OS << "\n\"features\" : [\n";
890 {
891 llvm::SmallString<128> Str;
892#define FEATURE(Name, Predicate) \
893 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
894 .toVector(Str);
895#include "clang/Basic/Features.def"
896#undef FEATURE
897 // Remove the newline and comma from the last entry to ensure this remains
898 // valid JSON.
899 OS << Str.substr(0, Str.size() - 2);
900 }
901 OS << "\n],\n";
902
903 OS << "\n\"extensions\" : [\n";
904 {
905 llvm::SmallString<128> Str;
906#define EXTENSION(Name, Predicate) \
907 ("\t{\"" #Name "\" : " + llvm::Twine(Predicate ? "true" : "false") + "},\n") \
908 .toVector(Str);
909#include "clang/Basic/Features.def"
910#undef EXTENSION
911 // Remove the newline and comma from the last entry to ensure this remains
912 // valid JSON.
913 OS << Str.substr(0, Str.size() - 2);
914 }
915 OS << "\n]\n";
916
917 OS << "}";
918}
Alex Lorenz6e2d36b2019-06-03 22:59:17 +0000919
920void PrintDependencyDirectivesSourceMinimizerAction::ExecuteAction() {
921 CompilerInstance &CI = getCompilerInstance();
922 SourceManager &SM = CI.getPreprocessor().getSourceManager();
923 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
924
925 llvm::SmallString<1024> Output;
926 llvm::SmallVector<minimize_source_to_dependency_directives::Token, 32> Toks;
927 if (minimizeSourceToDependencyDirectives(
928 FromFile->getBuffer(), Output, Toks, &CI.getDiagnostics(),
929 SM.getLocForStartOfFile(SM.getMainFileID()))) {
930 assert(CI.getDiagnostics().hasErrorOccurred() &&
931 "no errors reported for failure");
932
933 // Preprocess the source when verifying the diagnostics to capture the
934 // 'expected' comments.
935 if (CI.getDiagnosticOpts().VerifyDiagnostics) {
936 // Make sure we don't emit new diagnostics!
Dmitri Gribenko20f45ed2019-09-12 12:16:43 +0000937 CI.getDiagnostics().setSuppressAllDiagnostics(true);
Alex Lorenz6e2d36b2019-06-03 22:59:17 +0000938 Preprocessor &PP = getCompilerInstance().getPreprocessor();
939 PP.EnterMainSourceFile();
940 Token Tok;
941 do {
942 PP.Lex(Tok);
943 } while (Tok.isNot(tok::eof));
944 }
945 return;
946 }
947 llvm::outs() << Output;
948}