blob: 057361811baa63e97cbabe241306b506f307e4e1 [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"
14#include "clang/Frontend/ASTUnit.h"
15#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000016#include "clang/Frontend/FrontendDiagnostic.h"
Adrian Prantlbb165fb2015-06-20 18:53:08 +000017#include "clang/Frontend/MultiplexConsumer.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000018#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Lex/HeaderSearch.h"
20#include "clang/Lex/Pragma.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Parse/Parser.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"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000027#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000028#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000029#include <system_error>
Douglas Gregor52da28b2011-09-23 23:43:36 +000030
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000031using namespace clang;
32
Daniel Dunbar88357802009-11-14 10:42:57 +000033//===----------------------------------------------------------------------===//
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000034// Custom Actions
35//===----------------------------------------------------------------------===//
36
David Blaikie6beb6aa2014-08-10 19:56:51 +000037std::unique_ptr<ASTConsumer>
38InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
39 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000040}
41
42void InitOnlyAction::ExecuteAction() {
43}
44
45//===----------------------------------------------------------------------===//
Daniel Dunbar88357802009-11-14 10:42:57 +000046// AST Consumer Actions
47//===----------------------------------------------------------------------===//
48
David Blaikie6beb6aa2014-08-10 19:56:51 +000049std::unique_ptr<ASTConsumer>
50ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000051 if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
Alexander Kornienko3db68ee2012-07-26 16:01:23 +000052 return CreateASTPrinter(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;
Adrian Prantlbb165fb2015-06-20 18:53:08 +000083 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>(
94 CI.getPreprocessor(), OutputFile, nullptr, Sysroot, Buffer));
95 Consumers.push_back(
Adrian Prantlfb2398d2015-07-17 01:19:54 +000096 CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Adrian Prantlbb165fb2015-06-20 18:53:08 +000097 CI.getDiagnostics(), CI.getHeaderSearchOpts(),
98 CI.getPreprocessorOpts(), CI.getTargetOpts(), CI.getLangOpts(),
99 InFile, OutputFile, OS, Buffer));
100
101 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000102}
103
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000104raw_pwrite_stream *GeneratePCHAction::ComputeASTConsumerArguments(
Rafael Espindola47de1492015-04-10 12:54:53 +0000105 CompilerInstance &CI, StringRef InFile, std::string &Sysroot,
106 std::string &OutputFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000107 Sysroot = CI.getHeaderSearchOpts().Sysroot;
108 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redlea68af42010-08-17 17:55:38 +0000109 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Rafael Espindola47de1492015-04-10 12:54:53 +0000110 return nullptr;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000111 }
112
Daniel Dunbara2867c72011-01-31 22:00:44 +0000113 // We use createOutputFile here because this is exposed via libclang, and we
114 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000115 // We use a temporary to avoid race conditions.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000116 raw_pwrite_stream *OS =
Rafael Espindola47de1492015-04-10 12:54:53 +0000117 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
118 /*RemoveFileOnSignal=*/false, InFile,
119 /*Extension=*/"", /*useTemporary=*/true);
Daniel Dunbar75546992009-12-03 09:13:30 +0000120 if (!OS)
Rafael Espindola47de1492015-04-10 12:54:53 +0000121 return nullptr;
Daniel Dunbar75546992009-12-03 09:13:30 +0000122
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000123 OutputFile = CI.getFrontendOpts().OutputFile;
Rafael Espindola47de1492015-04-10 12:54:53 +0000124 return OS;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000125}
126
David Blaikie6beb6aa2014-08-10 19:56:51 +0000127std::unique_ptr<ASTConsumer>
128GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
129 StringRef InFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000130 std::string Sysroot;
131 std::string OutputFile;
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000132 raw_pwrite_stream *OS =
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000133 ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
134 if (!OS)
Craig Topper49a27902014-05-22 04:46:25 +0000135 return nullptr;
136
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000137 auto Buffer = std::make_shared<PCHBuffer>();
138 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
139 Consumers.push_back(llvm::make_unique<PCHGenerator>(
140 CI.getPreprocessor(), OutputFile, Module, Sysroot, Buffer));
141 Consumers.push_back(
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000142 CI.getPCHContainerWriter().CreatePCHContainerGenerator(
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000143 CI.getDiagnostics(), CI.getHeaderSearchOpts(),
144 CI.getPreprocessorOpts(), CI.getTargetOpts(), CI.getLangOpts(),
145 InFile, OutputFile, OS, Buffer));
146 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000147}
148
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000149static SmallVectorImpl<char> &
150operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
151 Includes.append(RHS.begin(), RHS.end());
152 return Includes;
153}
154
Rafael Espindolac0809172014-06-12 14:02:15 +0000155static std::error_code addHeaderInclude(StringRef HeaderName,
156 SmallVectorImpl<char> &Includes,
157 const LangOptions &LangOpts,
158 bool IsExternC) {
Richard Smith9bca2982014-03-08 00:03:56 +0000159 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000160 Includes += "extern \"C\" {\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000161 if (LangOpts.ObjC1)
162 Includes += "#import \"";
163 else
164 Includes += "#include \"";
Richard Smith3c1a41a2014-12-02 00:08:08 +0000165
166 Includes += HeaderName;
167
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000168 Includes += "\"\n";
Richard Smith9bca2982014-03-08 00:03:56 +0000169 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000170 Includes += "}\n";
Rafael Espindolac0809172014-06-12 14:02:15 +0000171 return std::error_code();
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000172}
173
Douglas Gregor4332b322011-11-16 17:04:00 +0000174/// \brief Collect the set of header includes needed to construct the given
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000175/// module and update the TopHeaders file set of the module.
Douglas Gregor4332b322011-11-16 17:04:00 +0000176///
177/// \param Module The module we're collecting includes from.
Douglas Gregore5626c42011-12-06 17:15:11 +0000178///
James Dennettc423c532012-06-15 21:48:19 +0000179/// \param Includes Will be augmented with the set of \#includes or \#imports
Douglas Gregore5626c42011-12-06 17:15:11 +0000180/// needed to load all of the named headers.
Rafael Espindolac0809172014-06-12 14:02:15 +0000181static std::error_code
Richard Smith723928c2014-03-11 02:02:47 +0000182collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
183 ModuleMap &ModMap, clang::Module *Module,
184 SmallVectorImpl<char> &Includes) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000185 // Don't collect any headers for unavailable modules.
186 if (!Module->isAvailable())
Rafael Espindolac0809172014-06-12 14:02:15 +0000187 return std::error_code();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000188
Douglas Gregore5626c42011-12-06 17:15:11 +0000189 // Add includes for each of these headers.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000190 for (Module::Header &H : Module->Headers[Module::HK_Normal]) {
191 Module->addTopHeader(H.Entry);
192 // Use the path as specified in the module map file. We'll look for this
193 // file relative to the module build directory (the directory containing
194 // the module map file) so this will find the same file that we found
195 // while parsing the module map.
196 if (std::error_code Err = addHeaderInclude(H.NameAsWritten, Includes,
197 LangOpts, Module->IsExternC))
Richard Smith723928c2014-03-11 02:02:47 +0000198 return Err;
Douglas Gregor3ec66632012-02-02 18:42:48 +0000199 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000200 // Note that Module->PrivateHeaders will not be a TopHeader.
Douglas Gregore5626c42011-12-06 17:15:11 +0000201
Richard Smith2b63d152015-05-16 02:28:53 +0000202 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
203 Module->addTopHeader(UmbrellaHeader.Entry);
Douglas Gregor3ec66632012-02-02 18:42:48 +0000204 if (Module->Parent) {
205 // Include the umbrella header for submodules.
Richard Smith2b63d152015-05-16 02:28:53 +0000206 if (std::error_code Err = addHeaderInclude(UmbrellaHeader.NameAsWritten,
207 Includes, LangOpts,
208 Module->IsExternC))
Richard Smith723928c2014-03-11 02:02:47 +0000209 return Err;
Douglas Gregor3ec66632012-02-02 18:42:48 +0000210 }
Richard Smith2b63d152015-05-16 02:28:53 +0000211 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000212 // Add all of the headers we find in this subdirectory.
Rafael Espindolac0809172014-06-12 14:02:15 +0000213 std::error_code EC;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000214 SmallString<128> DirNative;
Richard Smith2b63d152015-05-16 02:28:53 +0000215 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
Yaron Keren92e1b622015-03-18 10:17:07 +0000216 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative, EC),
Douglas Gregorc1aaf8c2011-12-12 19:13:53 +0000217 DirEnd;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000218 Dir != DirEnd && !EC; Dir.increment(EC)) {
219 // Check whether this entry has an extension typically associated with
220 // headers.
221 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
222 .Cases(".h", ".H", ".hh", ".hpp", true)
223 .Default(false))
224 continue;
Richard Smith3c1a41a2014-12-02 00:08:08 +0000225
226 const FileEntry *Header = FileMgr.getFile(Dir->path());
227 // FIXME: This shouldn't happen unless there is a file system race. Is
228 // that worth diagnosing?
229 if (!Header)
230 continue;
231
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000232 // If this header is marked 'unavailable' in this module, don't include
233 // it.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000234 if (ModMap.isHeaderUnavailableInModule(Header, Module))
235 continue;
236
Richard Smith2b63d152015-05-16 02:28:53 +0000237 // Compute the relative path from the directory to this file.
238 SmallVector<StringRef, 16> Components;
239 auto PathIt = llvm::sys::path::rbegin(Dir->path());
240 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
241 Components.push_back(*PathIt);
242 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
243 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
244 ++It)
245 llvm::sys::path::append(RelativeHeader, *It);
246
Richard Smith723928c2014-03-11 02:02:47 +0000247 // Include this header as part of the umbrella directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000248 Module->addTopHeader(Header);
Richard Smith2b63d152015-05-16 02:28:53 +0000249 if (std::error_code Err = addHeaderInclude(RelativeHeader, Includes,
250 LangOpts, Module->IsExternC))
Richard Smith723928c2014-03-11 02:02:47 +0000251 return Err;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000252 }
Richard Smith723928c2014-03-11 02:02:47 +0000253
254 if (EC)
255 return EC;
Douglas Gregor4332b322011-11-16 17:04:00 +0000256 }
Richard Smith3c1a41a2014-12-02 00:08:08 +0000257
Douglas Gregor4332b322011-11-16 17:04:00 +0000258 // Recurse into submodules.
Douglas Gregoreb90e832012-01-04 23:32:19 +0000259 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
260 SubEnd = Module->submodule_end();
Douglas Gregore5626c42011-12-06 17:15:11 +0000261 Sub != SubEnd; ++Sub)
Rafael Espindolac0809172014-06-12 14:02:15 +0000262 if (std::error_code Err = collectModuleHeaderIncludes(
Richard Smith723928c2014-03-11 02:02:47 +0000263 LangOpts, FileMgr, ModMap, *Sub, Includes))
264 return Err;
265
Rafael Espindolac0809172014-06-12 14:02:15 +0000266 return std::error_code();
Douglas Gregor4332b322011-11-16 17:04:00 +0000267}
268
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000269bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
270 StringRef Filename) {
Richard Smithfb1e7f72015-08-14 05:02:58 +0000271 // Find the module map file.
272 const FileEntry *ModuleMap =
273 CI.getFileManager().getFile(Filename, /*openFile*/true);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000274 if (!ModuleMap) {
275 CI.getDiagnostics().Report(diag::err_module_map_not_found)
276 << Filename;
277 return false;
278 }
279
280 // Parse the module map file.
281 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Douglas Gregor963c5532013-06-21 16:28:10 +0000282 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000283 return false;
284
285 if (CI.getLangOpts().CurrentModule.empty()) {
286 CI.getDiagnostics().Report(diag::err_missing_module_name);
287
288 // FIXME: Eventually, we could consider asking whether there was just
289 // a single module described in the module map, and use that as a
290 // default. Then it would be fairly trivial to just "compile" a module
291 // map with a single module (the common case).
292 return false;
293 }
Richard Smith7bea1d42014-03-05 20:55:36 +0000294
Richard Smithfb1e7f72015-08-14 05:02:58 +0000295 // Set up embedding for any specified files.
296 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
297 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
298 CI.getSourceManager().embedFileContentsInModule(FE);
299 else
300 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
301 }
302
Richard Smith7bea1d42014-03-05 20:55:36 +0000303 // If we're being run from the command-line, the module build stack will not
304 // have been filled in yet, so complete it now in order to allow us to detect
305 // module cycles.
306 SourceManager &SourceMgr = CI.getSourceManager();
307 if (SourceMgr.getModuleBuildStack().empty())
308 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
309 FullSourceLoc(SourceLocation(), SourceMgr));
310
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000311 // Dig out the module definition.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000312 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
313 /*AllowSearch=*/false);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000314 if (!Module) {
315 CI.getDiagnostics().Report(diag::err_missing_module)
316 << CI.getLangOpts().CurrentModule << Filename;
317
318 return false;
319 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000320
321 // Check whether we can build this module at all.
Richard Smitha3feee22013-10-28 22:18:19 +0000322 clang::Module::Requirement Requirement;
Richard Smith3c1a41a2014-12-02 00:08:08 +0000323 clang::Module::UnresolvedHeaderDirective MissingHeader;
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000324 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
325 MissingHeader)) {
326 if (MissingHeader.FileNameLoc.isValid()) {
Ben Langmuirec8c9752014-04-18 22:07:31 +0000327 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
328 diag::err_module_header_missing)
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000329 << MissingHeader.IsUmbrella << MissingHeader.FileName;
330 } else {
331 CI.getDiagnostics().Report(diag::err_module_unavailable)
332 << Module->getFullModuleName()
333 << Requirement.second << Requirement.first;
334 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000335
336 return false;
337 }
338
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000339 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
340 Module->IsInferred = true;
341 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
342 } else {
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000343 ModuleMapForUniquing = ModuleMap;
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000344 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000345
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000346 FileManager &FileMgr = CI.getFileManager();
347
Douglas Gregor4332b322011-11-16 17:04:00 +0000348 // Collect the set of #includes we need to build the module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000349 SmallString<256> HeaderContents;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000350 std::error_code Err = std::error_code();
Richard Smith2b63d152015-05-16 02:28:53 +0000351 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader())
352 Err = addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
353 CI.getLangOpts(), Module->IsExternC);
Richard Smith723928c2014-03-11 02:02:47 +0000354 if (!Err)
355 Err = collectModuleHeaderIncludes(
356 CI.getLangOpts(), FileMgr,
357 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
358 HeaderContents);
359
360 if (Err) {
361 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
362 << Module->getFullModuleName() << Err.message();
363 return false;
364 }
Douglas Gregor4332b322011-11-16 17:04:00 +0000365
Richard Smith3c1a41a2014-12-02 00:08:08 +0000366 // Inform the preprocessor that includes from within the input buffer should
367 // be resolved relative to the build directory of the module map file.
368 CI.getPreprocessor().setMainFileDir(Module->Directory);
369
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000370 std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000371 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
372 Module::getModuleInputBufferName());
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000373 // Ownership of InputBuffer will be transferred to the SourceManager.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000374 setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
Douglas Gregora686e1b2012-01-27 19:52:33 +0000375 Module->IsSystem));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000376 return true;
377}
378
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000379raw_pwrite_stream *GenerateModuleAction::ComputeASTConsumerArguments(
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000380 CompilerInstance &CI, StringRef InFile, std::string &Sysroot,
381 std::string &OutputFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000382 // If no output file was provided, figure out where this module would go
383 // in the module cache.
384 if (CI.getFrontendOpts().OutputFile.empty()) {
385 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000386 CI.getFrontendOpts().OutputFile =
387 HS.getModuleFileName(CI.getLangOpts().CurrentModule,
Ben Langmuird89dc562015-02-19 20:23:22 +0000388 ModuleMapForUniquing->getName());
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000389 }
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000390
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000391 // We use createOutputFile here because this is exposed via libclang, and we
392 // must disable the RemoveFileOnSignal behavior.
393 // We use a temporary to avoid race conditions.
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000394 raw_pwrite_stream *OS =
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000395 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
396 /*RemoveFileOnSignal=*/false, InFile,
397 /*Extension=*/"", /*useTemporary=*/true,
398 /*CreateMissingDirectories=*/true);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000399 if (!OS)
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000400 return nullptr;
401
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000402 OutputFile = CI.getFrontendOpts().OutputFile;
Rafael Espindolabfd25d42015-04-10 13:14:31 +0000403 return OS;
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000404}
405
David Blaikie6beb6aa2014-08-10 19:56:51 +0000406std::unique_ptr<ASTConsumer>
407SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
408 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000409}
410
David Blaikie6beb6aa2014-08-10 19:56:51 +0000411std::unique_ptr<ASTConsumer>
412DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
413 StringRef InFile) {
414 return llvm::make_unique<ASTConsumer>();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000415}
416
David Blaikie6beb6aa2014-08-10 19:56:51 +0000417std::unique_ptr<ASTConsumer>
418VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
419 return llvm::make_unique<ASTConsumer>();
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000420}
421
422void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000423 CompilerInstance &CI = getCompilerInstance();
424 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
425 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000426 std::unique_ptr<ASTReader> Reader(new ASTReader(
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000427 CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000428 Sysroot.empty() ? "" : Sysroot.c_str(),
429 /*DisableValidation*/ false,
430 /*AllowPCHWithCompilerErrors*/ false,
431 /*AllowConfigurationMismatch*/ true,
432 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000433
434 Reader->ReadAST(getCurrentFile(),
435 Preamble ? serialization::MK_Preamble
436 : serialization::MK_PCH,
437 SourceLocation(),
438 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000439}
440
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000441namespace {
442 /// \brief AST reader listener that dumps module information for a module
443 /// file.
444 class DumpModuleInfoListener : public ASTReaderListener {
445 llvm::raw_ostream &Out;
446
447 public:
448 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
449
450#define DUMP_BOOLEAN(Value, Text) \
451 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
452
Craig Topperafa7cb32014-03-13 06:07:04 +0000453 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000454 Out.indent(2)
455 << "Generated by "
456 << (FullVersion == getClangFullRepositoryVersion()? "this"
457 : "a different")
458 << " Clang: " << FullVersion << "\n";
459 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
460 }
461
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000462 void ReadModuleName(StringRef ModuleName) override {
463 Out.indent(2) << "Module name: " << ModuleName << "\n";
464 }
465 void ReadModuleMapFile(StringRef ModuleMapPath) override {
466 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
467 }
468
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000469 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
470 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000471 Out.indent(2) << "Language options:\n";
472#define LANGOPT(Name, Bits, Default, Description) \
473 DUMP_BOOLEAN(LangOpts.Name, Description);
474#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
475 Out.indent(4) << Description << ": " \
476 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
477#define VALUE_LANGOPT(Name, Bits, Default, Description) \
478 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
479#define BENIGN_LANGOPT(Name, Bits, Default, Description)
480#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
481#include "clang/Basic/LangOptions.def"
Ben Langmuircd98cb72015-06-23 18:20:18 +0000482
483 if (!LangOpts.ModuleFeatures.empty()) {
484 Out.indent(4) << "Module features:\n";
485 for (StringRef Feature : LangOpts.ModuleFeatures)
486 Out.indent(6) << Feature << "\n";
487 }
488
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000489 return false;
490 }
491
Chandler Carruth0d745bc2015-03-14 04:47:43 +0000492 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
493 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000494 Out.indent(2) << "Target options:\n";
495 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
496 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
497 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000498
499 if (!TargetOpts.FeaturesAsWritten.empty()) {
500 Out.indent(4) << "Target features:\n";
501 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
502 I != N; ++I) {
503 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
504 }
505 }
506
507 return false;
508 }
509
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000510 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
511 bool Complain) override {
Ben Langmuirb92de022014-04-29 16:25:26 +0000512 Out.indent(2) << "Diagnostic options:\n";
513#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
514#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
515 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
516#define VALUE_DIAGOPT(Name, Bits, Default) \
517 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
518#include "clang/Basic/DiagnosticOptions.def"
519
Richard Smith3be1cb22014-08-07 00:24:21 +0000520 Out.indent(4) << "Diagnostic flags:\n";
521 for (const std::string &Warning : DiagOpts->Warnings)
Ben Langmuirb92de022014-04-29 16:25:26 +0000522 Out.indent(6) << "-W" << Warning << "\n";
Richard Smith3be1cb22014-08-07 00:24:21 +0000523 for (const std::string &Remark : DiagOpts->Remarks)
524 Out.indent(6) << "-R" << Remark << "\n";
Ben Langmuirb92de022014-04-29 16:25:26 +0000525
526 return false;
527 }
528
Craig Topperafa7cb32014-03-13 06:07:04 +0000529 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000530 StringRef SpecificModuleCachePath,
Craig Topperafa7cb32014-03-13 06:07:04 +0000531 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000532 Out.indent(2) << "Header search options:\n";
533 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000534 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000535 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
536 "Use builtin include directories [-nobuiltininc]");
537 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
538 "Use standard system include directories [-nostdinc]");
539 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
540 "Use standard C++ include directories [-nostdinc++]");
541 DUMP_BOOLEAN(HSOpts.UseLibcxx,
542 "Use libc++ (rather than libstdc++) [-stdlib=]");
543 return false;
544 }
545
Craig Topperafa7cb32014-03-13 06:07:04 +0000546 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
547 bool Complain,
548 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000549 Out.indent(2) << "Preprocessor options:\n";
550 DUMP_BOOLEAN(PPOpts.UsePredefines,
551 "Uses compiler/target-specific predefines [-undef]");
552 DUMP_BOOLEAN(PPOpts.DetailedRecord,
553 "Uses detailed preprocessing record (for indexing)");
554
555 if (!PPOpts.Macros.empty()) {
556 Out.indent(4) << "Predefined macros:\n";
557 }
558
559 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
560 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
561 I != IEnd; ++I) {
562 Out.indent(6);
563 if (I->second)
564 Out << "-U";
565 else
566 Out << "-D";
567 Out << I->first << "\n";
568 }
569 return false;
570 }
571#undef DUMP_BOOLEAN
572 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000573}
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000574
575void DumpModuleInfoAction::ExecuteAction() {
576 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000577 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000578 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
579 if (!OutputFileName.empty() && OutputFileName != "-") {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000580 std::error_code EC;
581 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
582 llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000583 }
584 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
585
586 Out << "Information for module file '" << getCurrentFile() << "':\n";
587 DumpModuleInfoListener Listener(Out);
Adrian Prantlbb165fb2015-06-20 18:53:08 +0000588 ASTReader::readASTFileControlBlock(
589 getCurrentFile(), getCompilerInstance().getFileManager(),
Adrian Prantlfb2398d2015-07-17 01:19:54 +0000590 getCompilerInstance().getPCHContainerReader(), Listener);
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000591}
592
Daniel Dunbar88357802009-11-14 10:42:57 +0000593//===----------------------------------------------------------------------===//
594// Preprocessor Actions
595//===----------------------------------------------------------------------===//
596
597void DumpRawTokensAction::ExecuteAction() {
598 Preprocessor &PP = getCompilerInstance().getPreprocessor();
599 SourceManager &SM = PP.getSourceManager();
600
601 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000602 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000603 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000604 RawLex.SetKeepWhitespaceMode(true);
605
606 Token RawTok;
607 RawLex.LexFromRawLexer(RawTok);
608 while (RawTok.isNot(tok::eof)) {
609 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000610 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000611 RawLex.LexFromRawLexer(RawTok);
612 }
613}
614
615void DumpTokensAction::ExecuteAction() {
616 Preprocessor &PP = getCompilerInstance().getPreprocessor();
617 // Start preprocessing the specified input file.
618 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000619 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000620 do {
621 PP.Lex(Tok);
622 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000623 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000624 } while (Tok.isNot(tok::eof));
625}
626
627void GeneratePTHAction::ExecuteAction() {
628 CompilerInstance &CI = getCompilerInstance();
Rafael Espindola2f16bc12015-04-14 15:15:49 +0000629 raw_pwrite_stream *OS = CI.createDefaultOutputFile(true, getCurrentFile());
NAKAMURA Takumi5594d792015-04-13 08:43:40 +0000630 if (!OS)
631 return;
Daniel Dunbar75546992009-12-03 09:13:30 +0000632
Daniel Dunbar88357802009-11-14 10:42:57 +0000633 CacheTokens(CI.getPreprocessor(), OS);
634}
635
Daniel Dunbar88357802009-11-14 10:42:57 +0000636void PreprocessOnlyAction::ExecuteAction() {
637 Preprocessor &PP = getCompilerInstance().getPreprocessor();
638
Daniel Dunbard839e772010-06-11 20:10:12 +0000639 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000640 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000641
Daniel Dunbar88357802009-11-14 10:42:57 +0000642 Token Tok;
643 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000644 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000645 do {
646 PP.Lex(Tok);
647 } while (Tok.isNot(tok::eof));
648}
649
Daniel Dunbar88357802009-11-14 10:42:57 +0000650void PrintPreprocessedAction::ExecuteAction() {
651 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000652 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000653 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000654 //
655 // Look to see what type of line endings the file uses. If there's a
656 // CRLF, then we won't open the file up in binary mode. If there is
657 // just an LF or CR, then we will open the file up in binary mode.
658 // In this fashion, the output format should match the input format, unless
659 // the input format has inconsistent line endings.
660 //
661 // This should be a relatively fast operation since most files won't have
662 // all of their source code on a single line. However, that is still a
663 // concern, so if we scan for too long, we'll just assume the file should
664 // be opened in binary mode.
665 bool BinaryMode = true;
666 bool InvalidFile = false;
667 const SourceManager& SM = CI.getSourceManager();
668 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
669 &InvalidFile);
670 if (!InvalidFile) {
671 const char *cur = Buffer->getBufferStart();
672 const char *end = Buffer->getBufferEnd();
673 const char *next = (cur != end) ? cur + 1 : end;
674
675 // Limit ourselves to only scanning 256 characters into the source
676 // file. This is mostly a sanity check in case the file has no
677 // newlines whatsoever.
678 if (end - cur > 256) end = cur + 256;
679
680 while (next < end) {
681 if (*cur == 0x0D) { // CR
682 if (*next == 0x0A) // CRLF
683 BinaryMode = false;
684
685 break;
686 } else if (*cur == 0x0A) // LF
687 break;
688
689 ++cur, ++next;
690 }
691 }
692
693 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000694 if (!OS) return;
695
Daniel Dunbar88357802009-11-14 10:42:57 +0000696 DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
697 CI.getPreprocessorOutputOpts());
698}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000699
700void PrintPreambleAction::ExecuteAction() {
701 switch (getCurrentFileKind()) {
702 case IK_C:
703 case IK_CXX:
704 case IK_ObjC:
705 case IK_ObjCXX:
706 case IK_OpenCL:
Peter Collingbourne62089b82010-12-01 03:15:20 +0000707 case IK_CUDA:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000708 break;
709
710 case IK_None:
711 case IK_Asm:
712 case IK_PreprocessedC:
Artem Belevich83a6dcc2015-03-19 17:32:06 +0000713 case IK_PreprocessedCuda:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000714 case IK_PreprocessedCXX:
715 case IK_PreprocessedObjC:
716 case IK_PreprocessedObjCXX:
717 case IK_AST:
718 case IK_LLVM_IR:
719 // We can't do anything with these.
720 return;
721 }
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000722
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000723 CompilerInstance &CI = getCompilerInstance();
Benjamin Kramera8857962014-10-26 22:44:13 +0000724 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
725 if (Buffer) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000726 unsigned Preamble =
Benjamin Kramera8857962014-10-26 22:44:13 +0000727 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
728 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
Douglas Gregoraf82e352010-07-20 20:18:03 +0000729 }
730}