blob: eb91940cbbfc8078ad05eecf314ec8edbe62a144 [file] [log] [blame]
Daniel Dunbar02bd2d72009-11-14 10:42:46 +00001//===--- FrontendActions.cpp ----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/FrontendActions.h"
11#include "clang/AST/ASTConsumer.h"
12#include "clang/Basic/FileManager.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"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/HeaderSearch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Lex/Preprocessor.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000020#include "clang/Lex/PreprocessorOptions.h"
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000021#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000022#include "clang/Serialization/ASTWriter.h"
Douglas Gregor524e33e2011-12-08 19:11:24 +000023#include "llvm/Support/FileSystem.h"
Douglas Gregoraf82e352010-07-20 20:18:03 +000024#include "llvm/Support/MemoryBuffer.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000025#include "llvm/Support/Path.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000026#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000027#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000028#include <system_error>
Douglas Gregor52da28b2011-09-23 23:43:36 +000029
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000030using namespace clang;
31
Daniel Dunbar88357802009-11-14 10:42:57 +000032//===----------------------------------------------------------------------===//
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000033// Custom Actions
34//===----------------------------------------------------------------------===//
35
David Blaikie6beb6aa2014-08-10 19:56:51 +000036std::unique_ptr<ASTConsumer>
37InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
38 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000039}
40
41void InitOnlyAction::ExecuteAction() {
42}
43
44//===----------------------------------------------------------------------===//
Daniel Dunbar88357802009-11-14 10:42:57 +000045// AST Consumer Actions
46//===----------------------------------------------------------------------===//
47
David Blaikie6beb6aa2014-08-10 19:56:51 +000048std::unique_ptr<ASTConsumer>
49ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Peter Collingbourne03f89072016-07-15 00:55:40 +000050 if (std::unique_ptr<raw_ostream> OS =
51 CI.createDefaultOutputFile(false, InFile))
52 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
Craig Topper49a27902014-05-22 04:46:25 +000053 return nullptr;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000054}
55
David Blaikie6beb6aa2014-08-10 19:56:51 +000056std::unique_ptr<ASTConsumer>
57ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Richard Smith6ea05822013-06-24 01:45:33 +000058 return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter,
Richard Smith35f986d2014-08-11 22:11:07 +000059 CI.getFrontendOpts().ASTDumpDecls,
Richard Smith6ea05822013-06-24 01:45:33 +000060 CI.getFrontendOpts().ASTDumpLookups);
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000061}
62
David Blaikie6beb6aa2014-08-10 19:56:51 +000063std::unique_ptr<ASTConsumer>
64ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Alexander Kornienko4de03592012-07-31 09:37:40 +000065 return CreateASTDeclNodeLister();
66}
67
David Blaikie6beb6aa2014-08-10 19:56:51 +000068std::unique_ptr<ASTConsumer>
69ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000070 return CreateASTViewer();
71}
72
David Blaikie6beb6aa2014-08-10 19:56:51 +000073std::unique_ptr<ASTConsumer>
74DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
75 StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000076 return CreateDeclContextPrinter();
77}
78
David Blaikie6beb6aa2014-08-10 19:56:51 +000079std::unique_ptr<ASTConsumer>
80GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000081 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +000082 std::string OutputFile;
Peter Collingbourne03f89072016-07-15 00:55:40 +000083 std::unique_ptr<raw_pwrite_stream> OS =
Rafael Espindola47de1492015-04-10 12:54:53 +000084 ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
85 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +000086 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +000087
Douglas Gregorc567ba22011-07-22 16:35:34 +000088 if (!CI.getFrontendOpts().RelocatablePCH)
89 Sysroot.clear();
Adrian Prantlbb165fb2015-06-20 18:53:08 +000090
91 auto Buffer = std::make_shared<PCHBuffer>();
92 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
93 Consumers.push_back(llvm::make_unique<PCHGenerator>(
Richard Smithbd97f352016-08-25 18:26:30 +000094 CI.getPreprocessor(), OutputFile, Sysroot,
Pierre Gousseau533a8932016-07-13 14:21:11 +000095 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
96 /*AllowASTWithErrors*/false,
97 /*IncludeTimestamps*/
98 +CI.getFrontendOpts().IncludeTimestamps));
Adrian Prantl03914062015-09-18 22:10:59 +000099 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000100 CI, InFile, OutputFile, std::move(OS), Buffer));
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000101
102 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000103}
104
Peter Collingbourne03f89072016-07-15 00:55:40 +0000105std::unique_ptr<raw_pwrite_stream>
106GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
107 StringRef InFile,
108 std::string &Sysroot,
109 std::string &OutputFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000110 Sysroot = CI.getHeaderSearchOpts().Sysroot;
111 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redlea68af42010-08-17 17:55:38 +0000112 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Rafael Espindola47de1492015-04-10 12:54:53 +0000113 return nullptr;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000114 }
115
Daniel Dunbara2867c72011-01-31 22:00:44 +0000116 // We use createOutputFile here because this is exposed via libclang, and we
117 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000118 // We use a temporary to avoid race conditions.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000119 std::unique_ptr<raw_pwrite_stream> OS =
Rafael Espindola47de1492015-04-10 12:54:53 +0000120 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
121 /*RemoveFileOnSignal=*/false, InFile,
122 /*Extension=*/"", /*useTemporary=*/true);
Daniel Dunbar75546992009-12-03 09:13:30 +0000123 if (!OS)
Rafael Espindola47de1492015-04-10 12:54:53 +0000124 return nullptr;
Daniel Dunbar75546992009-12-03 09:13:30 +0000125
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000126 OutputFile = CI.getFrontendOpts().OutputFile;
Rafael Espindola47de1492015-04-10 12:54:53 +0000127 return OS;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000128}
129
David Blaikie6beb6aa2014-08-10 19:56:51 +0000130std::unique_ptr<ASTConsumer>
131GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
132 StringRef InFile) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000133 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000134 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000135 return nullptr;
136
Richard Smithbbcc9f02016-08-26 00:14:38 +0000137 std::string OutputFile = CI.getFrontendOpts().OutputFile;
138 std::string Sysroot;
139
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000140 auto Buffer = std::make_shared<PCHBuffer>();
141 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000142
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000143 Consumers.push_back(llvm::make_unique<PCHGenerator>(
Richard Smithbd97f352016-08-25 18:26:30 +0000144 CI.getPreprocessor(), OutputFile, Sysroot,
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000145 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
146 /*AllowASTWithErrors=*/false,
147 /*IncludeTimestamps=*/
148 +CI.getFrontendOpts().BuildingImplicitModule));
Adrian Prantl03914062015-09-18 22:10:59 +0000149 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000150 CI, InFile, OutputFile, std::move(OS), Buffer));
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000151 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000152}
153
Richard Smithbbcc9f02016-08-26 00:14:38 +0000154bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
155 StringRef Filename) {
156 // Set up embedding for any specified files. Do this before we load any
157 // source files, including the primary module map for the compilation.
158 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
159 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
160 CI.getSourceManager().setFileIsTransient(FE);
161 else
162 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
163 }
164 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
165 CI.getSourceManager().setAllFilesAreTransient(true);
166
167 return true;
168}
169
170
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000171static SmallVectorImpl<char> &
172operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
173 Includes.append(RHS.begin(), RHS.end());
174 return Includes;
175}
176
Davide Italiano75df8212016-03-02 06:09:18 +0000177static void addHeaderInclude(StringRef HeaderName,
178 SmallVectorImpl<char> &Includes,
179 const LangOptions &LangOpts,
180 bool IsExternC) {
Richard Smith9bca2982014-03-08 00:03:56 +0000181 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000182 Includes += "extern \"C\" {\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000183 if (LangOpts.ObjC1)
184 Includes += "#import \"";
185 else
186 Includes += "#include \"";
Richard Smith3c1a41a2014-12-02 00:08:08 +0000187
188 Includes += HeaderName;
189
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000190 Includes += "\"\n";
Richard Smith9bca2982014-03-08 00:03:56 +0000191 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000192 Includes += "}\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000193}
194
Douglas Gregor4332b322011-11-16 17:04:00 +0000195/// \brief Collect the set of header includes needed to construct the given
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000196/// module and update the TopHeaders file set of the module.
Douglas Gregor4332b322011-11-16 17:04:00 +0000197///
198/// \param Module The module we're collecting includes from.
Douglas Gregore5626c42011-12-06 17:15:11 +0000199///
James Dennettc423c532012-06-15 21:48:19 +0000200/// \param Includes Will be augmented with the set of \#includes or \#imports
Douglas Gregore5626c42011-12-06 17:15:11 +0000201/// needed to load all of the named headers.
Rafael Espindolac0809172014-06-12 14:02:15 +0000202static std::error_code
Richard Smith723928c2014-03-11 02:02:47 +0000203collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
204 ModuleMap &ModMap, clang::Module *Module,
205 SmallVectorImpl<char> &Includes) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000206 // Don't collect any headers for unavailable modules.
207 if (!Module->isAvailable())
Rafael Espindolac0809172014-06-12 14:02:15 +0000208 return std::error_code();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000209
Douglas Gregore5626c42011-12-06 17:15:11 +0000210 // Add includes for each of these headers.
Richard Smithf7aeda12016-01-08 22:36:45 +0000211 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
212 for (Module::Header &H : Module->Headers[HK]) {
213 Module->addTopHeader(H.Entry);
214 // Use the path as specified in the module map file. We'll look for this
215 // file relative to the module build directory (the directory containing
216 // the module map file) so this will find the same file that we found
217 // while parsing the module map.
Davide Italiano75df8212016-03-02 06:09:18 +0000218 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
Richard Smithf7aeda12016-01-08 22:36:45 +0000219 }
Douglas Gregor3ec66632012-02-02 18:42:48 +0000220 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000221 // Note that Module->PrivateHeaders will not be a TopHeader.
Douglas Gregore5626c42011-12-06 17:15:11 +0000222
Richard Smith2b63d152015-05-16 02:28:53 +0000223 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
224 Module->addTopHeader(UmbrellaHeader.Entry);
Davide Italiano75df8212016-03-02 06:09:18 +0000225 if (Module->Parent)
Douglas Gregor3ec66632012-02-02 18:42:48 +0000226 // Include the umbrella header for submodules.
Davide Italiano75df8212016-03-02 06:09:18 +0000227 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
228 Module->IsExternC);
Richard Smith2b63d152015-05-16 02:28:53 +0000229 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000230 // Add all of the headers we find in this subdirectory.
Rafael Espindolac0809172014-06-12 14:02:15 +0000231 std::error_code EC;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000232 SmallString<128> DirNative;
Richard Smith2b63d152015-05-16 02:28:53 +0000233 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +0000234
235 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
236 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
237 Dir != End && !EC; Dir.increment(EC)) {
Douglas Gregor524e33e2011-12-08 19:11:24 +0000238 // Check whether this entry has an extension typically associated with
239 // headers.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +0000240 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
Douglas Gregor524e33e2011-12-08 19:11:24 +0000241 .Cases(".h", ".H", ".hh", ".hpp", true)
242 .Default(false))
243 continue;
Richard Smith3c1a41a2014-12-02 00:08:08 +0000244
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +0000245 const FileEntry *Header = FileMgr.getFile(Dir->getName());
Richard Smith3c1a41a2014-12-02 00:08:08 +0000246 // FIXME: This shouldn't happen unless there is a file system race. Is
247 // that worth diagnosing?
248 if (!Header)
249 continue;
250
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000251 // If this header is marked 'unavailable' in this module, don't include
252 // it.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000253 if (ModMap.isHeaderUnavailableInModule(Header, Module))
254 continue;
255
Richard Smith2b63d152015-05-16 02:28:53 +0000256 // Compute the relative path from the directory to this file.
257 SmallVector<StringRef, 16> Components;
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +0000258 auto PathIt = llvm::sys::path::rbegin(Dir->getName());
Richard Smith2b63d152015-05-16 02:28:53 +0000259 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
260 Components.push_back(*PathIt);
261 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
262 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
263 ++It)
264 llvm::sys::path::append(RelativeHeader, *It);
265
Richard Smith723928c2014-03-11 02:02:47 +0000266 // Include this header as part of the umbrella directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000267 Module->addTopHeader(Header);
Davide Italiano75df8212016-03-02 06:09:18 +0000268 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
Douglas Gregor524e33e2011-12-08 19:11:24 +0000269 }
Richard Smith723928c2014-03-11 02:02:47 +0000270
271 if (EC)
272 return EC;
Douglas Gregor4332b322011-11-16 17:04:00 +0000273 }
Richard Smith3c1a41a2014-12-02 00:08:08 +0000274
Douglas Gregor4332b322011-11-16 17:04:00 +0000275 // Recurse into submodules.
Douglas Gregoreb90e832012-01-04 23:32:19 +0000276 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
277 SubEnd = Module->submodule_end();
Douglas Gregore5626c42011-12-06 17:15:11 +0000278 Sub != SubEnd; ++Sub)
Rafael Espindolac0809172014-06-12 14:02:15 +0000279 if (std::error_code Err = collectModuleHeaderIncludes(
Richard Smith723928c2014-03-11 02:02:47 +0000280 LangOpts, FileMgr, ModMap, *Sub, Includes))
281 return Err;
282
Rafael Espindolac0809172014-06-12 14:02:15 +0000283 return std::error_code();
Douglas Gregor4332b322011-11-16 17:04:00 +0000284}
285
Richard Smithbbcc9f02016-08-26 00:14:38 +0000286bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
287 CompilerInstance &CI, StringRef Filename) {
288 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
289
290 if (!GenerateModuleAction::BeginSourceFileAction(CI, Filename))
291 return false;
Richard Smith7e82e012016-02-19 22:25:36 +0000292
Richard Smithfb1e7f72015-08-14 05:02:58 +0000293 // Find the module map file.
294 const FileEntry *ModuleMap =
295 CI.getFileManager().getFile(Filename, /*openFile*/true);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000296 if (!ModuleMap) {
297 CI.getDiagnostics().Report(diag::err_module_map_not_found)
298 << Filename;
299 return false;
300 }
301
302 // Parse the module map file.
303 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Douglas Gregor963c5532013-06-21 16:28:10 +0000304 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000305 return false;
306
307 if (CI.getLangOpts().CurrentModule.empty()) {
308 CI.getDiagnostics().Report(diag::err_missing_module_name);
309
310 // FIXME: Eventually, we could consider asking whether there was just
311 // a single module described in the module map, and use that as a
312 // default. Then it would be fairly trivial to just "compile" a module
313 // map with a single module (the common case).
314 return false;
315 }
Richard Smith7bea1d42014-03-05 20:55:36 +0000316
317 // If we're being run from the command-line, the module build stack will not
318 // have been filled in yet, so complete it now in order to allow us to detect
319 // module cycles.
320 SourceManager &SourceMgr = CI.getSourceManager();
321 if (SourceMgr.getModuleBuildStack().empty())
322 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
323 FullSourceLoc(SourceLocation(), SourceMgr));
324
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000325 // Dig out the module definition.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000326 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
327 /*AllowSearch=*/false);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000328 if (!Module) {
329 CI.getDiagnostics().Report(diag::err_missing_module)
330 << CI.getLangOpts().CurrentModule << Filename;
331
332 return false;
333 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000334
335 // Check whether we can build this module at all.
Richard Smitha3feee22013-10-28 22:18:19 +0000336 clang::Module::Requirement Requirement;
Richard Smith3c1a41a2014-12-02 00:08:08 +0000337 clang::Module::UnresolvedHeaderDirective MissingHeader;
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000338 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
339 MissingHeader)) {
340 if (MissingHeader.FileNameLoc.isValid()) {
Ben Langmuirec8c9752014-04-18 22:07:31 +0000341 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
342 diag::err_module_header_missing)
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000343 << MissingHeader.IsUmbrella << MissingHeader.FileName;
344 } else {
345 CI.getDiagnostics().Report(diag::err_module_unavailable)
346 << Module->getFullModuleName()
347 << Requirement.second << Requirement.first;
348 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000349
350 return false;
351 }
352
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000353 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
354 Module->IsInferred = true;
355 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
356 } else {
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000357 ModuleMapForUniquing = ModuleMap;
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000358 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000359
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000360 FileManager &FileMgr = CI.getFileManager();
361
Douglas Gregor4332b322011-11-16 17:04:00 +0000362 // Collect the set of #includes we need to build the module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000363 SmallString<256> HeaderContents;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000364 std::error_code Err = std::error_code();
Richard Smith2b63d152015-05-16 02:28:53 +0000365 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader())
Davide Italiano75df8212016-03-02 06:09:18 +0000366 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
367 CI.getLangOpts(), Module->IsExternC);
368 Err = collectModuleHeaderIncludes(
Richard Smith723928c2014-03-11 02:02:47 +0000369 CI.getLangOpts(), FileMgr,
370 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
371 HeaderContents);
372
373 if (Err) {
374 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
375 << Module->getFullModuleName() << Err.message();
376 return false;
377 }
Douglas Gregor4332b322011-11-16 17:04:00 +0000378
Richard Smith3c1a41a2014-12-02 00:08:08 +0000379 // Inform the preprocessor that includes from within the input buffer should
380 // be resolved relative to the build directory of the module map file.
381 CI.getPreprocessor().setMainFileDir(Module->Directory);
382
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000383 std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000384 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
385 Module::getModuleInputBufferName());
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000386 // Ownership of InputBuffer will be transferred to the SourceManager.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000387 setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
Douglas Gregora686e1b2012-01-27 19:52:33 +0000388 Module->IsSystem));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000389 return true;
390}
391
Peter Collingbourne03f89072016-07-15 00:55:40 +0000392std::unique_ptr<raw_pwrite_stream>
Richard Smithbbcc9f02016-08-26 00:14:38 +0000393GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
394 StringRef InFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000395 // If no output file was provided, figure out where this module would go
396 // in the module cache.
397 if (CI.getFrontendOpts().OutputFile.empty()) {
398 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000399 CI.getFrontendOpts().OutputFile =
400 HS.getModuleFileName(CI.getLangOpts().CurrentModule,
Manman Ren11f2a472016-08-18 17:42:15 +0000401 ModuleMapForUniquing->getName(),
402 /*UsePrebuiltPath=*/false);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000403 }
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000404
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000405 // We use createOutputFile here because this is exposed via libclang, and we
406 // must disable the RemoveFileOnSignal behavior.
407 // We use a temporary to avoid race conditions.
Richard Smithbbcc9f02016-08-26 00:14:38 +0000408 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
409 /*RemoveFileOnSignal=*/false, InFile,
410 /*Extension=*/"", /*useTemporary=*/true,
411 /*CreateMissingDirectories=*/true);
412}
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000413
Richard Smithbbcc9f02016-08-26 00:14:38 +0000414bool GenerateModuleInterfaceAction::BeginSourceFileAction(CompilerInstance &CI,
415 StringRef Filename) {
416 if (!CI.getLangOpts().ModulesTS) {
417 CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
418 return false;
419 }
420
421 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
422
423 return GenerateModuleAction::BeginSourceFileAction(CI, Filename);
424}
425
426std::unique_ptr<raw_pwrite_stream>
427GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
428 StringRef InFile) {
429 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000430}
431
Etienne Bergeron98de8052016-05-12 19:51:18 +0000432SyntaxOnlyAction::~SyntaxOnlyAction() {
433}
434
David Blaikie6beb6aa2014-08-10 19:56:51 +0000435std::unique_ptr<ASTConsumer>
436SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
437 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000438}
439
David Blaikie6beb6aa2014-08-10 19:56:51 +0000440std::unique_ptr<ASTConsumer>
441DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
442 StringRef InFile) {
443 return llvm::make_unique<ASTConsumer>();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000444}
445
David Blaikie6beb6aa2014-08-10 19:56:51 +0000446std::unique_ptr<ASTConsumer>
447VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
448 return llvm::make_unique<ASTConsumer>();
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000449}
450
451void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000452 CompilerInstance &CI = getCompilerInstance();
453 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
454 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000455 std::unique_ptr<ASTReader> Reader(new ASTReader(
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000456 CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000457 CI.getFrontendOpts().ModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000458 Sysroot.empty() ? "" : Sysroot.c_str(),
459 /*DisableValidation*/ false,
460 /*AllowPCHWithCompilerErrors*/ false,
461 /*AllowConfigurationMismatch*/ true,
462 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000463
464 Reader->ReadAST(getCurrentFile(),
465 Preamble ? serialization::MK_Preamble
466 : serialization::MK_PCH,
467 SourceLocation(),
468 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000469}
470
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000471namespace {
472 /// \brief AST reader listener that dumps module information for a module
473 /// file.
474 class DumpModuleInfoListener : public ASTReaderListener {
475 llvm::raw_ostream &Out;
476
477 public:
478 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
479
480#define DUMP_BOOLEAN(Value, Text) \
481 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
482
Craig Topperafa7cb32014-03-13 06:07:04 +0000483 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000484 Out.indent(2)
485 << "Generated by "
486 << (FullVersion == getClangFullRepositoryVersion()? "this"
487 : "a different")
488 << " Clang: " << FullVersion << "\n";
489 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
490 }
491
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000492 void ReadModuleName(StringRef ModuleName) override {
493 Out.indent(2) << "Module name: " << ModuleName << "\n";
494 }
495 void ReadModuleMapFile(StringRef ModuleMapPath) override {
496 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
497 }
498
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000499 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
500 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000501 Out.indent(2) << "Language options:\n";
502#define LANGOPT(Name, Bits, Default, Description) \
503 DUMP_BOOLEAN(LangOpts.Name, Description);
504#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
505 Out.indent(4) << Description << ": " \
506 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
507#define VALUE_LANGOPT(Name, Bits, Default, Description) \
508 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
509#define BENIGN_LANGOPT(Name, Bits, Default, Description)
510#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
511#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +0000512
513 if (!LangOpts.ModuleFeatures.empty()) {
514 Out.indent(4) << "Module features:\n";
515 for (StringRef Feature : LangOpts.ModuleFeatures)
516 Out.indent(6) << Feature << "\n";
517 }
518
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000519 return false;
520 }
521
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000522 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
523 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000524 Out.indent(2) << "Target options:\n";
525 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
526 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
527 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000528
529 if (!TargetOpts.FeaturesAsWritten.empty()) {
530 Out.indent(4) << "Target features:\n";
531 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
532 I != N; ++I) {
533 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
534 }
535 }
536
537 return false;
538 }
539
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000540 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
541 bool Complain) override {
Ben Langmuirb92de022014-04-29 16:25:26 +0000542 Out.indent(2) << "Diagnostic options:\n";
543#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
544#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
545 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
546#define VALUE_DIAGOPT(Name, Bits, Default) \
547 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
548#include "clang/Basic/DiagnosticOptions.def"
549
Richard Smith3be1cb22014-08-07 00:24:21 +0000550 Out.indent(4) << "Diagnostic flags:\n";
551 for (const std::string &Warning : DiagOpts->Warnings)
Ben Langmuirb92de022014-04-29 16:25:26 +0000552 Out.indent(6) << "-W" << Warning << "\n";
Richard Smith3be1cb22014-08-07 00:24:21 +0000553 for (const std::string &Remark : DiagOpts->Remarks)
554 Out.indent(6) << "-R" << Remark << "\n";
Ben Langmuirb92de022014-04-29 16:25:26 +0000555
556 return false;
557 }
558
Craig Topperafa7cb32014-03-13 06:07:04 +0000559 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000560 StringRef SpecificModuleCachePath,
Craig Topperafa7cb32014-03-13 06:07:04 +0000561 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000562 Out.indent(2) << "Header search options:\n";
563 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000564 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000565 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
566 "Use builtin include directories [-nobuiltininc]");
567 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
568 "Use standard system include directories [-nostdinc]");
569 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
570 "Use standard C++ include directories [-nostdinc++]");
571 DUMP_BOOLEAN(HSOpts.UseLibcxx,
572 "Use libc++ (rather than libstdc++) [-stdlib=]");
573 return false;
574 }
575
Craig Topperafa7cb32014-03-13 06:07:04 +0000576 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
577 bool Complain,
578 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000579 Out.indent(2) << "Preprocessor options:\n";
580 DUMP_BOOLEAN(PPOpts.UsePredefines,
581 "Uses compiler/target-specific predefines [-undef]");
582 DUMP_BOOLEAN(PPOpts.DetailedRecord,
583 "Uses detailed preprocessing record (for indexing)");
584
585 if (!PPOpts.Macros.empty()) {
586 Out.indent(4) << "Predefined macros:\n";
587 }
588
589 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
590 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
591 I != IEnd; ++I) {
592 Out.indent(6);
593 if (I->second)
594 Out << "-U";
595 else
596 Out << "-D";
597 Out << I->first << "\n";
598 }
599 return false;
600 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000601
602 /// Indicates that a particular module file extension has been read.
603 void readModuleFileExtension(
604 const ModuleFileExtensionMetadata &Metadata) override {
605 Out.indent(2) << "Module file extension '"
606 << Metadata.BlockName << "' " << Metadata.MajorVersion
607 << "." << Metadata.MinorVersion;
608 if (!Metadata.UserInfo.empty()) {
609 Out << ": ";
610 Out.write_escaped(Metadata.UserInfo);
611 }
612
613 Out << "\n";
614 }
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000615#undef DUMP_BOOLEAN
616 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000617}
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000618
Adrian Prantl576b2db2016-08-17 23:13:53 +0000619bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
620 // The Object file reader also supports raw ast files and there is no point in
621 // being strict about the module file format in -module-file-info mode.
622 CI.getHeaderSearchOpts().ModuleFormat = "obj";
623 return true;
624}
625
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000626void DumpModuleInfoAction::ExecuteAction() {
627 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000628 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000629 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
630 if (!OutputFileName.empty() && OutputFileName != "-") {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000631 std::error_code EC;
632 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
633 llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000634 }
635 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
636
637 Out << "Information for module file '" << getCurrentFile() << "':\n";
Adrian Prantl99e765b2016-08-17 23:14:00 +0000638 auto &FileMgr = getCompilerInstance().getFileManager();
639 auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
640 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
641 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
642 Magic[2] == 'C' && Magic[3] == 'H');
643 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
Adrian Prantl576b2db2016-08-17 23:13:53 +0000644
Manman Ren47a44452016-07-26 17:12:17 +0000645 Preprocessor &PP = getCompilerInstance().getPreprocessor();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000646 DumpModuleInfoListener Listener(Out);
Manman Ren47a44452016-07-26 17:12:17 +0000647 HeaderSearchOptions &HSOpts =
648 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000649 ASTReader::readASTFileControlBlock(
Adrian Prantl99e765b2016-08-17 23:14:00 +0000650 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
Manman Ren47a44452016-07-26 17:12:17 +0000651 /*FindModuleFileExtensions=*/true, Listener,
652 HSOpts.ModulesValidateDiagnosticOptions);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000653}
654
Daniel Dunbar88357802009-11-14 10:42:57 +0000655//===----------------------------------------------------------------------===//
656// Preprocessor Actions
657//===----------------------------------------------------------------------===//
658
659void DumpRawTokensAction::ExecuteAction() {
660 Preprocessor &PP = getCompilerInstance().getPreprocessor();
661 SourceManager &SM = PP.getSourceManager();
662
663 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000664 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000665 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000666 RawLex.SetKeepWhitespaceMode(true);
667
668 Token RawTok;
669 RawLex.LexFromRawLexer(RawTok);
670 while (RawTok.isNot(tok::eof)) {
671 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000672 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000673 RawLex.LexFromRawLexer(RawTok);
674 }
675}
676
677void DumpTokensAction::ExecuteAction() {
678 Preprocessor &PP = getCompilerInstance().getPreprocessor();
679 // Start preprocessing the specified input file.
680 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000681 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000682 do {
683 PP.Lex(Tok);
684 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000685 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000686 } while (Tok.isNot(tok::eof));
687}
688
689void GeneratePTHAction::ExecuteAction() {
690 CompilerInstance &CI = getCompilerInstance();
Peter Collingbourne03f89072016-07-15 00:55:40 +0000691 std::unique_ptr<raw_pwrite_stream> OS =
692 CI.createDefaultOutputFile(true, getCurrentFile());
NAKAMURA Takumi5594d792015-04-13 08:43:40 +0000693 if (!OS)
694 return;
Daniel Dunbar75546992009-12-03 09:13:30 +0000695
Peter Collingbourne03f89072016-07-15 00:55:40 +0000696 CacheTokens(CI.getPreprocessor(), OS.get());
Daniel Dunbar88357802009-11-14 10:42:57 +0000697}
698
Daniel Dunbar88357802009-11-14 10:42:57 +0000699void PreprocessOnlyAction::ExecuteAction() {
700 Preprocessor &PP = getCompilerInstance().getPreprocessor();
701
Daniel Dunbard839e772010-06-11 20:10:12 +0000702 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000703 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000704
Daniel Dunbar88357802009-11-14 10:42:57 +0000705 Token Tok;
706 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000707 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000708 do {
709 PP.Lex(Tok);
710 } while (Tok.isNot(tok::eof));
711}
712
Daniel Dunbar88357802009-11-14 10:42:57 +0000713void PrintPreprocessedAction::ExecuteAction() {
714 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000715 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000716 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000717 //
718 // Look to see what type of line endings the file uses. If there's a
719 // CRLF, then we won't open the file up in binary mode. If there is
720 // just an LF or CR, then we will open the file up in binary mode.
721 // In this fashion, the output format should match the input format, unless
722 // the input format has inconsistent line endings.
723 //
724 // This should be a relatively fast operation since most files won't have
725 // all of their source code on a single line. However, that is still a
726 // concern, so if we scan for too long, we'll just assume the file should
727 // be opened in binary mode.
728 bool BinaryMode = true;
729 bool InvalidFile = false;
730 const SourceManager& SM = CI.getSourceManager();
731 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
732 &InvalidFile);
733 if (!InvalidFile) {
734 const char *cur = Buffer->getBufferStart();
735 const char *end = Buffer->getBufferEnd();
736 const char *next = (cur != end) ? cur + 1 : end;
737
738 // Limit ourselves to only scanning 256 characters into the source
739 // file. This is mostly a sanity check in case the file has no
740 // newlines whatsoever.
741 if (end - cur > 256) end = cur + 256;
742
743 while (next < end) {
744 if (*cur == 0x0D) { // CR
745 if (*next == 0x0A) // CRLF
746 BinaryMode = false;
747
748 break;
749 } else if (*cur == 0x0A) // LF
750 break;
751
Richard Trieucc3949d2016-02-18 22:34:54 +0000752 ++cur;
753 ++next;
Douglas Gregor52da28b2011-09-23 23:43:36 +0000754 }
755 }
756
Peter Collingbourne03f89072016-07-15 00:55:40 +0000757 std::unique_ptr<raw_ostream> OS =
758 CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000759 if (!OS) return;
760
Peter Collingbourne03f89072016-07-15 00:55:40 +0000761 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
Daniel Dunbar88357802009-11-14 10:42:57 +0000762 CI.getPreprocessorOutputOpts());
763}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000764
765void PrintPreambleAction::ExecuteAction() {
766 switch (getCurrentFileKind()) {
767 case IK_C:
768 case IK_CXX:
769 case IK_ObjC:
770 case IK_ObjCXX:
771 case IK_OpenCL:
Peter Collingbourne62089b82010-12-01 03:15:20 +0000772 case IK_CUDA:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000773 break;
774
775 case IK_None:
776 case IK_Asm:
777 case IK_PreprocessedC:
Artem Belevich83a6dcc2015-03-19 17:32:06 +0000778 case IK_PreprocessedCuda:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000779 case IK_PreprocessedCXX:
780 case IK_PreprocessedObjC:
781 case IK_PreprocessedObjCXX:
782 case IK_AST:
783 case IK_LLVM_IR:
Pirama Arumuga Nainar8b788d02016-06-09 23:34:20 +0000784 case IK_RenderScript:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000785 // We can't do anything with these.
786 return;
787 }
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000788
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000789 CompilerInstance &CI = getCompilerInstance();
Benjamin Kramera8857962014-10-26 22:44:13 +0000790 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
791 if (Buffer) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000792 unsigned Preamble =
Benjamin Kramera8857962014-10-26 22:44:13 +0000793 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
794 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
Douglas Gregoraf82e352010-07-20 20:18:03 +0000795 }
796}