blob: 1fce1e596bf18f393683494c9050f136f6df1eff [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 Smith3a36ac12017-03-09 22:00:01 +000060 CI.getFrontendOpts().ASTDumpAll,
Richard Smith6ea05822013-06-24 01:45:33 +000061 CI.getFrontendOpts().ASTDumpLookups);
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000062}
63
David Blaikie6beb6aa2014-08-10 19:56:51 +000064std::unique_ptr<ASTConsumer>
65ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Alexander Kornienko4de03592012-07-31 09:37:40 +000066 return CreateASTDeclNodeLister();
67}
68
David Blaikie6beb6aa2014-08-10 19:56:51 +000069std::unique_ptr<ASTConsumer>
70ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000071 return CreateASTViewer();
72}
73
David Blaikie6beb6aa2014-08-10 19:56:51 +000074std::unique_ptr<ASTConsumer>
75DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
76 StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000077 return CreateDeclContextPrinter();
78}
79
David Blaikie6beb6aa2014-08-10 19:56:51 +000080std::unique_ptr<ASTConsumer>
81GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000082 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +000083 std::string OutputFile;
Peter Collingbourne03f89072016-07-15 00:55:40 +000084 std::unique_ptr<raw_pwrite_stream> OS =
Rafael Espindola47de1492015-04-10 12:54:53 +000085 ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
86 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +000087 return nullptr;
Douglas Gregor48c8cd32010-08-03 08:14:03 +000088
Douglas Gregorc567ba22011-07-22 16:35:34 +000089 if (!CI.getFrontendOpts().RelocatablePCH)
90 Sysroot.clear();
Adrian Prantlbb165fb2015-06-20 18:53:08 +000091
92 auto Buffer = std::make_shared<PCHBuffer>();
93 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
94 Consumers.push_back(llvm::make_unique<PCHGenerator>(
Richard Smithbd97f352016-08-25 18:26:30 +000095 CI.getPreprocessor(), OutputFile, Sysroot,
Pierre Gousseau533a8932016-07-13 14:21:11 +000096 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
Argyrios Kyrtzidiscf486b22017-02-27 03:52:36 +000097 /*AllowASTWithErrors*/CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
Pierre Gousseau533a8932016-07-13 14:21:11 +000098 /*IncludeTimestamps*/
99 +CI.getFrontendOpts().IncludeTimestamps));
Adrian Prantl03914062015-09-18 22:10:59 +0000100 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000101 CI, InFile, OutputFile, std::move(OS), Buffer));
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000102
103 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000104}
105
Peter Collingbourne03f89072016-07-15 00:55:40 +0000106std::unique_ptr<raw_pwrite_stream>
107GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
108 StringRef InFile,
109 std::string &Sysroot,
110 std::string &OutputFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000111 Sysroot = CI.getHeaderSearchOpts().Sysroot;
112 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redlea68af42010-08-17 17:55:38 +0000113 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Rafael Espindola47de1492015-04-10 12:54:53 +0000114 return nullptr;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000115 }
116
Daniel Dunbara2867c72011-01-31 22:00:44 +0000117 // We use createOutputFile here because this is exposed via libclang, and we
118 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000119 // We use a temporary to avoid race conditions.
Peter Collingbourne03f89072016-07-15 00:55:40 +0000120 std::unique_ptr<raw_pwrite_stream> OS =
Rafael Espindola47de1492015-04-10 12:54:53 +0000121 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
122 /*RemoveFileOnSignal=*/false, InFile,
123 /*Extension=*/"", /*useTemporary=*/true);
Daniel Dunbar75546992009-12-03 09:13:30 +0000124 if (!OS)
Rafael Espindola47de1492015-04-10 12:54:53 +0000125 return nullptr;
Daniel Dunbar75546992009-12-03 09:13:30 +0000126
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000127 OutputFile = CI.getFrontendOpts().OutputFile;
Rafael Espindola47de1492015-04-10 12:54:53 +0000128 return OS;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000129}
130
Argyrios Kyrtzidiscf486b22017-02-27 03:52:36 +0000131bool GeneratePCHAction::shouldEraseOutputFiles() {
132 if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
133 return false;
134 return ASTFrontendAction::shouldEraseOutputFiles();
135}
136
Manman Renffd3e9d2017-01-09 19:20:18 +0000137bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI,
138 StringRef Filename) {
139 CI.getLangOpts().CompilingPCH = true;
140 return true;
141}
142
David Blaikie6beb6aa2014-08-10 19:56:51 +0000143std::unique_ptr<ASTConsumer>
144GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
145 StringRef InFile) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000146 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000147 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000148 return nullptr;
149
Richard Smithbbcc9f02016-08-26 00:14:38 +0000150 std::string OutputFile = CI.getFrontendOpts().OutputFile;
151 std::string Sysroot;
152
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000153 auto Buffer = std::make_shared<PCHBuffer>();
154 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000155
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000156 Consumers.push_back(llvm::make_unique<PCHGenerator>(
Richard Smithbd97f352016-08-25 18:26:30 +0000157 CI.getPreprocessor(), OutputFile, Sysroot,
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000158 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
159 /*AllowASTWithErrors=*/false,
160 /*IncludeTimestamps=*/
161 +CI.getFrontendOpts().BuildingImplicitModule));
Adrian Prantl03914062015-09-18 22:10:59 +0000162 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Peter Collingbourne03f89072016-07-15 00:55:40 +0000163 CI, InFile, OutputFile, std::move(OS), Buffer));
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000164 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000165}
166
Richard Smithbbcc9f02016-08-26 00:14:38 +0000167bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
168 StringRef Filename) {
169 // Set up embedding for any specified files. Do this before we load any
170 // source files, including the primary module map for the compilation.
171 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
172 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
173 CI.getSourceManager().setFileIsTransient(FE);
174 else
175 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
176 }
177 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
178 CI.getSourceManager().setAllFilesAreTransient(true);
179
180 return true;
181}
182
183
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000184static SmallVectorImpl<char> &
185operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
186 Includes.append(RHS.begin(), RHS.end());
187 return Includes;
188}
189
Davide Italiano75df8212016-03-02 06:09:18 +0000190static void addHeaderInclude(StringRef HeaderName,
191 SmallVectorImpl<char> &Includes,
192 const LangOptions &LangOpts,
193 bool IsExternC) {
Richard Smith9bca2982014-03-08 00:03:56 +0000194 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000195 Includes += "extern \"C\" {\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000196 if (LangOpts.ObjC1)
197 Includes += "#import \"";
198 else
199 Includes += "#include \"";
Richard Smith3c1a41a2014-12-02 00:08:08 +0000200
201 Includes += HeaderName;
202
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000203 Includes += "\"\n";
Richard Smith9bca2982014-03-08 00:03:56 +0000204 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000205 Includes += "}\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000206}
207
Douglas Gregor4332b322011-11-16 17:04:00 +0000208/// \brief Collect the set of header includes needed to construct the given
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000209/// module and update the TopHeaders file set of the module.
Douglas Gregor4332b322011-11-16 17:04:00 +0000210///
211/// \param Module The module we're collecting includes from.
Douglas Gregore5626c42011-12-06 17:15:11 +0000212///
James Dennettc423c532012-06-15 21:48:19 +0000213/// \param Includes Will be augmented with the set of \#includes or \#imports
Douglas Gregore5626c42011-12-06 17:15:11 +0000214/// needed to load all of the named headers.
Rafael Espindolac0809172014-06-12 14:02:15 +0000215static std::error_code
Richard Smith723928c2014-03-11 02:02:47 +0000216collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
217 ModuleMap &ModMap, clang::Module *Module,
218 SmallVectorImpl<char> &Includes) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000219 // Don't collect any headers for unavailable modules.
220 if (!Module->isAvailable())
Rafael Espindolac0809172014-06-12 14:02:15 +0000221 return std::error_code();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000222
Douglas Gregore5626c42011-12-06 17:15:11 +0000223 // Add includes for each of these headers.
Richard Smithf7aeda12016-01-08 22:36:45 +0000224 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
225 for (Module::Header &H : Module->Headers[HK]) {
226 Module->addTopHeader(H.Entry);
227 // Use the path as specified in the module map file. We'll look for this
228 // file relative to the module build directory (the directory containing
229 // the module map file) so this will find the same file that we found
230 // while parsing the module map.
Davide Italiano75df8212016-03-02 06:09:18 +0000231 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
Richard Smithf7aeda12016-01-08 22:36:45 +0000232 }
Douglas Gregor3ec66632012-02-02 18:42:48 +0000233 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000234 // Note that Module->PrivateHeaders will not be a TopHeader.
Douglas Gregore5626c42011-12-06 17:15:11 +0000235
Richard Smith2b63d152015-05-16 02:28:53 +0000236 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
237 Module->addTopHeader(UmbrellaHeader.Entry);
Davide Italiano75df8212016-03-02 06:09:18 +0000238 if (Module->Parent)
Douglas Gregor3ec66632012-02-02 18:42:48 +0000239 // Include the umbrella header for submodules.
Davide Italiano75df8212016-03-02 06:09:18 +0000240 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
241 Module->IsExternC);
Richard Smith2b63d152015-05-16 02:28:53 +0000242 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000243 // Add all of the headers we find in this subdirectory.
Rafael Espindolac0809172014-06-12 14:02:15 +0000244 std::error_code EC;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000245 SmallString<128> DirNative;
Richard Smith2b63d152015-05-16 02:28:53 +0000246 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +0000247
248 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
249 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
250 Dir != End && !EC; Dir.increment(EC)) {
Douglas Gregor524e33e2011-12-08 19:11:24 +0000251 // Check whether this entry has an extension typically associated with
252 // headers.
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +0000253 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
Douglas Gregor524e33e2011-12-08 19:11:24 +0000254 .Cases(".h", ".H", ".hh", ".hpp", true)
255 .Default(false))
256 continue;
Richard Smith3c1a41a2014-12-02 00:08:08 +0000257
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +0000258 const FileEntry *Header = FileMgr.getFile(Dir->getName());
Richard Smith3c1a41a2014-12-02 00:08:08 +0000259 // FIXME: This shouldn't happen unless there is a file system race. Is
260 // that worth diagnosing?
261 if (!Header)
262 continue;
263
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000264 // If this header is marked 'unavailable' in this module, don't include
265 // it.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000266 if (ModMap.isHeaderUnavailableInModule(Header, Module))
267 continue;
268
Richard Smith2b63d152015-05-16 02:28:53 +0000269 // Compute the relative path from the directory to this file.
270 SmallVector<StringRef, 16> Components;
Bruno Cardoso Lopesb171a592016-05-16 16:46:01 +0000271 auto PathIt = llvm::sys::path::rbegin(Dir->getName());
Richard Smith2b63d152015-05-16 02:28:53 +0000272 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
273 Components.push_back(*PathIt);
274 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
275 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
276 ++It)
277 llvm::sys::path::append(RelativeHeader, *It);
278
Bruno Cardoso Lopes295f940c2016-12-12 23:22:30 +0000279 // Include this header as part of the umbrella directory.
280 Module->addTopHeader(Header);
281 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
Douglas Gregor524e33e2011-12-08 19:11:24 +0000282 }
Richard Smith723928c2014-03-11 02:02:47 +0000283
284 if (EC)
285 return EC;
Douglas Gregor4332b322011-11-16 17:04:00 +0000286 }
Richard Smith3c1a41a2014-12-02 00:08:08 +0000287
Douglas Gregor4332b322011-11-16 17:04:00 +0000288 // Recurse into submodules.
Douglas Gregoreb90e832012-01-04 23:32:19 +0000289 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
290 SubEnd = Module->submodule_end();
Douglas Gregore5626c42011-12-06 17:15:11 +0000291 Sub != SubEnd; ++Sub)
Rafael Espindolac0809172014-06-12 14:02:15 +0000292 if (std::error_code Err = collectModuleHeaderIncludes(
Richard Smith723928c2014-03-11 02:02:47 +0000293 LangOpts, FileMgr, ModMap, *Sub, Includes))
294 return Err;
295
Rafael Espindolac0809172014-06-12 14:02:15 +0000296 return std::error_code();
Douglas Gregor4332b322011-11-16 17:04:00 +0000297}
298
Richard Smithbbcc9f02016-08-26 00:14:38 +0000299bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
300 CompilerInstance &CI, StringRef Filename) {
301 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
302
303 if (!GenerateModuleAction::BeginSourceFileAction(CI, Filename))
304 return false;
Richard Smith7e82e012016-02-19 22:25:36 +0000305
Richard Smithfb1e7f72015-08-14 05:02:58 +0000306 // Find the module map file.
307 const FileEntry *ModuleMap =
308 CI.getFileManager().getFile(Filename, /*openFile*/true);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000309 if (!ModuleMap) {
310 CI.getDiagnostics().Report(diag::err_module_map_not_found)
311 << Filename;
312 return false;
313 }
314
315 // Parse the module map file.
316 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Douglas Gregor963c5532013-06-21 16:28:10 +0000317 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000318 return false;
319
320 if (CI.getLangOpts().CurrentModule.empty()) {
321 CI.getDiagnostics().Report(diag::err_missing_module_name);
322
323 // FIXME: Eventually, we could consider asking whether there was just
324 // a single module described in the module map, and use that as a
325 // default. Then it would be fairly trivial to just "compile" a module
326 // map with a single module (the common case).
327 return false;
328 }
Richard Smith7bea1d42014-03-05 20:55:36 +0000329
330 // If we're being run from the command-line, the module build stack will not
331 // have been filled in yet, so complete it now in order to allow us to detect
332 // module cycles.
333 SourceManager &SourceMgr = CI.getSourceManager();
334 if (SourceMgr.getModuleBuildStack().empty())
335 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
336 FullSourceLoc(SourceLocation(), SourceMgr));
337
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000338 // Dig out the module definition.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000339 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
340 /*AllowSearch=*/false);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000341 if (!Module) {
342 CI.getDiagnostics().Report(diag::err_missing_module)
343 << CI.getLangOpts().CurrentModule << Filename;
344
345 return false;
346 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000347
348 // Check whether we can build this module at all.
Richard Smitha3feee22013-10-28 22:18:19 +0000349 clang::Module::Requirement Requirement;
Richard Smith3c1a41a2014-12-02 00:08:08 +0000350 clang::Module::UnresolvedHeaderDirective MissingHeader;
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000351 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
352 MissingHeader)) {
353 if (MissingHeader.FileNameLoc.isValid()) {
Ben Langmuirec8c9752014-04-18 22:07:31 +0000354 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
355 diag::err_module_header_missing)
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000356 << MissingHeader.IsUmbrella << MissingHeader.FileName;
357 } else {
358 CI.getDiagnostics().Report(diag::err_module_unavailable)
359 << Module->getFullModuleName()
360 << Requirement.second << Requirement.first;
361 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000362
363 return false;
364 }
365
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000366 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
367 Module->IsInferred = true;
368 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
369 } else {
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000370 ModuleMapForUniquing = ModuleMap;
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000371 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000372
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000373 FileManager &FileMgr = CI.getFileManager();
374
Douglas Gregor4332b322011-11-16 17:04:00 +0000375 // Collect the set of #includes we need to build the module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000376 SmallString<256> HeaderContents;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000377 std::error_code Err = std::error_code();
Richard Smith2b63d152015-05-16 02:28:53 +0000378 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader())
Davide Italiano75df8212016-03-02 06:09:18 +0000379 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
380 CI.getLangOpts(), Module->IsExternC);
381 Err = collectModuleHeaderIncludes(
Richard Smith723928c2014-03-11 02:02:47 +0000382 CI.getLangOpts(), FileMgr,
383 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
384 HeaderContents);
385
386 if (Err) {
387 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
388 << Module->getFullModuleName() << Err.message();
389 return false;
390 }
Douglas Gregor4332b322011-11-16 17:04:00 +0000391
Richard Smith3c1a41a2014-12-02 00:08:08 +0000392 // Inform the preprocessor that includes from within the input buffer should
393 // be resolved relative to the build directory of the module map file.
394 CI.getPreprocessor().setMainFileDir(Module->Directory);
395
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000396 std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000397 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
398 Module::getModuleInputBufferName());
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000399 // Ownership of InputBuffer will be transferred to the SourceManager.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000400 setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
Douglas Gregora686e1b2012-01-27 19:52:33 +0000401 Module->IsSystem));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000402 return true;
403}
404
Peter Collingbourne03f89072016-07-15 00:55:40 +0000405std::unique_ptr<raw_pwrite_stream>
Richard Smithbbcc9f02016-08-26 00:14:38 +0000406GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
407 StringRef InFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000408 // If no output file was provided, figure out where this module would go
409 // in the module cache.
410 if (CI.getFrontendOpts().OutputFile.empty()) {
411 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000412 CI.getFrontendOpts().OutputFile =
413 HS.getModuleFileName(CI.getLangOpts().CurrentModule,
Manman Ren11f2a472016-08-18 17:42:15 +0000414 ModuleMapForUniquing->getName(),
415 /*UsePrebuiltPath=*/false);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000416 }
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000417
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000418 // We use createOutputFile here because this is exposed via libclang, and we
419 // must disable the RemoveFileOnSignal behavior.
420 // We use a temporary to avoid race conditions.
Richard Smithbbcc9f02016-08-26 00:14:38 +0000421 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
422 /*RemoveFileOnSignal=*/false, InFile,
423 /*Extension=*/"", /*useTemporary=*/true,
424 /*CreateMissingDirectories=*/true);
425}
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000426
Richard Smithbbcc9f02016-08-26 00:14:38 +0000427bool GenerateModuleInterfaceAction::BeginSourceFileAction(CompilerInstance &CI,
428 StringRef Filename) {
429 if (!CI.getLangOpts().ModulesTS) {
430 CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
431 return false;
432 }
433
434 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
435
436 return GenerateModuleAction::BeginSourceFileAction(CI, Filename);
437}
438
439std::unique_ptr<raw_pwrite_stream>
440GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
441 StringRef InFile) {
442 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000443}
444
Etienne Bergeron98de8052016-05-12 19:51:18 +0000445SyntaxOnlyAction::~SyntaxOnlyAction() {
446}
447
David Blaikie6beb6aa2014-08-10 19:56:51 +0000448std::unique_ptr<ASTConsumer>
449SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
450 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000451}
452
David Blaikie6beb6aa2014-08-10 19:56:51 +0000453std::unique_ptr<ASTConsumer>
454DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
455 StringRef InFile) {
456 return llvm::make_unique<ASTConsumer>();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000457}
458
David Blaikie6beb6aa2014-08-10 19:56:51 +0000459std::unique_ptr<ASTConsumer>
460VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
461 return llvm::make_unique<ASTConsumer>();
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000462}
463
464void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000465 CompilerInstance &CI = getCompilerInstance();
466 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
467 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000468 std::unique_ptr<ASTReader> Reader(new ASTReader(
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000469 CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000470 CI.getFrontendOpts().ModuleFileExtensions,
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000471 Sysroot.empty() ? "" : Sysroot.c_str(),
472 /*DisableValidation*/ false,
473 /*AllowPCHWithCompilerErrors*/ false,
474 /*AllowConfigurationMismatch*/ true,
475 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000476
477 Reader->ReadAST(getCurrentFile(),
478 Preamble ? serialization::MK_Preamble
479 : serialization::MK_PCH,
480 SourceLocation(),
481 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000482}
483
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000484namespace {
485 /// \brief AST reader listener that dumps module information for a module
486 /// file.
487 class DumpModuleInfoListener : public ASTReaderListener {
488 llvm::raw_ostream &Out;
489
490 public:
491 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
492
493#define DUMP_BOOLEAN(Value, Text) \
494 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
495
Craig Topperafa7cb32014-03-13 06:07:04 +0000496 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000497 Out.indent(2)
498 << "Generated by "
499 << (FullVersion == getClangFullRepositoryVersion()? "this"
500 : "a different")
501 << " Clang: " << FullVersion << "\n";
502 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
503 }
504
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000505 void ReadModuleName(StringRef ModuleName) override {
506 Out.indent(2) << "Module name: " << ModuleName << "\n";
507 }
508 void ReadModuleMapFile(StringRef ModuleMapPath) override {
509 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
510 }
511
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000512 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
513 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000514 Out.indent(2) << "Language options:\n";
515#define LANGOPT(Name, Bits, Default, Description) \
516 DUMP_BOOLEAN(LangOpts.Name, Description);
517#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
518 Out.indent(4) << Description << ": " \
519 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
520#define VALUE_LANGOPT(Name, Bits, Default, Description) \
521 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
522#define BENIGN_LANGOPT(Name, Bits, Default, Description)
523#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
524#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +0000525
526 if (!LangOpts.ModuleFeatures.empty()) {
527 Out.indent(4) << "Module features:\n";
528 for (StringRef Feature : LangOpts.ModuleFeatures)
529 Out.indent(6) << Feature << "\n";
530 }
531
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000532 return false;
533 }
534
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000535 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
536 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000537 Out.indent(2) << "Target options:\n";
538 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
539 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
540 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000541
542 if (!TargetOpts.FeaturesAsWritten.empty()) {
543 Out.indent(4) << "Target features:\n";
544 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
545 I != N; ++I) {
546 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
547 }
548 }
549
550 return false;
551 }
552
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000553 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
554 bool Complain) override {
Ben Langmuirb92de022014-04-29 16:25:26 +0000555 Out.indent(2) << "Diagnostic options:\n";
556#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
557#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
558 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
559#define VALUE_DIAGOPT(Name, Bits, Default) \
560 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
561#include "clang/Basic/DiagnosticOptions.def"
562
Richard Smith3be1cb22014-08-07 00:24:21 +0000563 Out.indent(4) << "Diagnostic flags:\n";
564 for (const std::string &Warning : DiagOpts->Warnings)
Ben Langmuirb92de022014-04-29 16:25:26 +0000565 Out.indent(6) << "-W" << Warning << "\n";
Richard Smith3be1cb22014-08-07 00:24:21 +0000566 for (const std::string &Remark : DiagOpts->Remarks)
567 Out.indent(6) << "-R" << Remark << "\n";
Ben Langmuirb92de022014-04-29 16:25:26 +0000568
569 return false;
570 }
571
Craig Topperafa7cb32014-03-13 06:07:04 +0000572 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000573 StringRef SpecificModuleCachePath,
Craig Topperafa7cb32014-03-13 06:07:04 +0000574 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000575 Out.indent(2) << "Header search options:\n";
576 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
Argyrios Kyrtzidisbdff27d2017-02-25 18:14:31 +0000577 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000578 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000579 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
580 "Use builtin include directories [-nobuiltininc]");
581 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
582 "Use standard system include directories [-nostdinc]");
583 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
584 "Use standard C++ include directories [-nostdinc++]");
585 DUMP_BOOLEAN(HSOpts.UseLibcxx,
586 "Use libc++ (rather than libstdc++) [-stdlib=]");
587 return false;
588 }
589
Craig Topperafa7cb32014-03-13 06:07:04 +0000590 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
591 bool Complain,
592 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000593 Out.indent(2) << "Preprocessor options:\n";
594 DUMP_BOOLEAN(PPOpts.UsePredefines,
595 "Uses compiler/target-specific predefines [-undef]");
596 DUMP_BOOLEAN(PPOpts.DetailedRecord,
597 "Uses detailed preprocessing record (for indexing)");
598
599 if (!PPOpts.Macros.empty()) {
600 Out.indent(4) << "Predefined macros:\n";
601 }
602
603 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
604 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
605 I != IEnd; ++I) {
606 Out.indent(6);
607 if (I->second)
608 Out << "-U";
609 else
610 Out << "-D";
611 Out << I->first << "\n";
612 }
613 return false;
614 }
Douglas Gregor6623e1f2015-11-03 18:33:07 +0000615
616 /// Indicates that a particular module file extension has been read.
617 void readModuleFileExtension(
618 const ModuleFileExtensionMetadata &Metadata) override {
619 Out.indent(2) << "Module file extension '"
620 << Metadata.BlockName << "' " << Metadata.MajorVersion
621 << "." << Metadata.MinorVersion;
622 if (!Metadata.UserInfo.empty()) {
623 Out << ": ";
624 Out.write_escaped(Metadata.UserInfo);
625 }
626
627 Out << "\n";
628 }
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000629#undef DUMP_BOOLEAN
630 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000631}
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000632
Adrian Prantl576b2db2016-08-17 23:13:53 +0000633bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
634 // The Object file reader also supports raw ast files and there is no point in
635 // being strict about the module file format in -module-file-info mode.
636 CI.getHeaderSearchOpts().ModuleFormat = "obj";
637 return true;
638}
639
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000640void DumpModuleInfoAction::ExecuteAction() {
641 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000642 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000643 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
644 if (!OutputFileName.empty() && OutputFileName != "-") {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000645 std::error_code EC;
646 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
647 llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000648 }
649 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
650
651 Out << "Information for module file '" << getCurrentFile() << "':\n";
Adrian Prantl99e765b2016-08-17 23:14:00 +0000652 auto &FileMgr = getCompilerInstance().getFileManager();
653 auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
654 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
655 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
656 Magic[2] == 'C' && Magic[3] == 'H');
657 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
Adrian Prantl576b2db2016-08-17 23:13:53 +0000658
Manman Ren47a44452016-07-26 17:12:17 +0000659 Preprocessor &PP = getCompilerInstance().getPreprocessor();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000660 DumpModuleInfoListener Listener(Out);
Manman Ren47a44452016-07-26 17:12:17 +0000661 HeaderSearchOptions &HSOpts =
662 PP.getHeaderSearchInfo().getHeaderSearchOpts();
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000663 ASTReader::readASTFileControlBlock(
Adrian Prantl99e765b2016-08-17 23:14:00 +0000664 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
Manman Ren47a44452016-07-26 17:12:17 +0000665 /*FindModuleFileExtensions=*/true, Listener,
666 HSOpts.ModulesValidateDiagnosticOptions);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000667}
668
Daniel Dunbar88357802009-11-14 10:42:57 +0000669//===----------------------------------------------------------------------===//
670// Preprocessor Actions
671//===----------------------------------------------------------------------===//
672
673void DumpRawTokensAction::ExecuteAction() {
674 Preprocessor &PP = getCompilerInstance().getPreprocessor();
675 SourceManager &SM = PP.getSourceManager();
676
677 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000678 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000679 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000680 RawLex.SetKeepWhitespaceMode(true);
681
682 Token RawTok;
683 RawLex.LexFromRawLexer(RawTok);
684 while (RawTok.isNot(tok::eof)) {
685 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000686 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000687 RawLex.LexFromRawLexer(RawTok);
688 }
689}
690
691void DumpTokensAction::ExecuteAction() {
692 Preprocessor &PP = getCompilerInstance().getPreprocessor();
693 // Start preprocessing the specified input file.
694 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000695 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000696 do {
697 PP.Lex(Tok);
698 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000699 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000700 } while (Tok.isNot(tok::eof));
701}
702
703void GeneratePTHAction::ExecuteAction() {
704 CompilerInstance &CI = getCompilerInstance();
Peter Collingbourne03f89072016-07-15 00:55:40 +0000705 std::unique_ptr<raw_pwrite_stream> OS =
706 CI.createDefaultOutputFile(true, getCurrentFile());
NAKAMURA Takumi5594d792015-04-13 08:43:40 +0000707 if (!OS)
708 return;
Daniel Dunbar75546992009-12-03 09:13:30 +0000709
Peter Collingbourne03f89072016-07-15 00:55:40 +0000710 CacheTokens(CI.getPreprocessor(), OS.get());
Daniel Dunbar88357802009-11-14 10:42:57 +0000711}
712
Daniel Dunbar88357802009-11-14 10:42:57 +0000713void PreprocessOnlyAction::ExecuteAction() {
714 Preprocessor &PP = getCompilerInstance().getPreprocessor();
715
Daniel Dunbard839e772010-06-11 20:10:12 +0000716 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000717 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000718
Daniel Dunbar88357802009-11-14 10:42:57 +0000719 Token Tok;
720 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000721 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000722 do {
723 PP.Lex(Tok);
724 } while (Tok.isNot(tok::eof));
725}
726
Daniel Dunbar88357802009-11-14 10:42:57 +0000727void PrintPreprocessedAction::ExecuteAction() {
728 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000729 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000730 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000731 //
732 // Look to see what type of line endings the file uses. If there's a
733 // CRLF, then we won't open the file up in binary mode. If there is
734 // just an LF or CR, then we will open the file up in binary mode.
735 // In this fashion, the output format should match the input format, unless
736 // the input format has inconsistent line endings.
737 //
738 // This should be a relatively fast operation since most files won't have
739 // all of their source code on a single line. However, that is still a
740 // concern, so if we scan for too long, we'll just assume the file should
741 // be opened in binary mode.
742 bool BinaryMode = true;
743 bool InvalidFile = false;
744 const SourceManager& SM = CI.getSourceManager();
745 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
746 &InvalidFile);
747 if (!InvalidFile) {
748 const char *cur = Buffer->getBufferStart();
749 const char *end = Buffer->getBufferEnd();
750 const char *next = (cur != end) ? cur + 1 : end;
751
752 // Limit ourselves to only scanning 256 characters into the source
753 // file. This is mostly a sanity check in case the file has no
754 // newlines whatsoever.
755 if (end - cur > 256) end = cur + 256;
756
757 while (next < end) {
758 if (*cur == 0x0D) { // CR
759 if (*next == 0x0A) // CRLF
760 BinaryMode = false;
761
762 break;
763 } else if (*cur == 0x0A) // LF
764 break;
765
Richard Trieucc3949d2016-02-18 22:34:54 +0000766 ++cur;
767 ++next;
Douglas Gregor52da28b2011-09-23 23:43:36 +0000768 }
769 }
770
Peter Collingbourne03f89072016-07-15 00:55:40 +0000771 std::unique_ptr<raw_ostream> OS =
772 CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000773 if (!OS) return;
774
Peter Collingbourne03f89072016-07-15 00:55:40 +0000775 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
Daniel Dunbar88357802009-11-14 10:42:57 +0000776 CI.getPreprocessorOutputOpts());
777}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000778
779void PrintPreambleAction::ExecuteAction() {
Richard Smith40c0efa2017-04-26 18:57:40 +0000780 switch (getCurrentFileKind().getLanguage()) {
781 case InputKind::C:
782 case InputKind::CXX:
783 case InputKind::ObjC:
784 case InputKind::ObjCXX:
785 case InputKind::OpenCL:
786 case InputKind::CUDA:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000787 break;
788
Richard Smith40c0efa2017-04-26 18:57:40 +0000789 case InputKind::Unknown:
790 case InputKind::Asm:
791 case InputKind::LLVM_IR:
792 case InputKind::RenderScript:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000793 // We can't do anything with these.
794 return;
795 }
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000796
Richard Smith40c0efa2017-04-26 18:57:40 +0000797 // We don't expect to find any #include directives in a preprocessed input.
798 if (getCurrentFileKind().isPreprocessed())
799 return;
800
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000801 CompilerInstance &CI = getCompilerInstance();
Benjamin Kramera8857962014-10-26 22:44:13 +0000802 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
803 if (Buffer) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000804 unsigned Preamble =
Benjamin Kramera8857962014-10-26 22:44:13 +0000805 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
806 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
Douglas Gregoraf82e352010-07-20 20:18:03 +0000807 }
808}