blob: 3e0f525e65366b05710a71613f6ab7b99bee335f [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"
Adrian Prantl8bf7af32015-02-25 01:31:45 +000013#include "clang/Basic/TargetInfo.h"
14#include "clang/CodeGen/CodeGenModuleContainer.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000015#include "clang/Frontend/ASTConsumers.h"
16#include "clang/Frontend/ASTUnit.h"
17#include "clang/Frontend/CompilerInstance.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000018#include "clang/Frontend/FrontendDiagnostic.h"
Adrian Prantl8bf7af32015-02-25 01:31:45 +000019#include "clang/Frontend/MultiplexConsumer.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000020#include "clang/Frontend/Utils.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Lex/HeaderSearch.h"
22#include "clang/Lex/Pragma.h"
23#include "clang/Lex/Preprocessor.h"
24#include "clang/Parse/Parser.h"
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +000025#include "clang/Serialization/ASTReader.h"
Sebastian Redl1914c6f2010-08-18 23:56:37 +000026#include "clang/Serialization/ASTWriter.h"
Douglas Gregor524e33e2011-12-08 19:11:24 +000027#include "llvm/Support/FileSystem.h"
Douglas Gregoraf82e352010-07-20 20:18:03 +000028#include "llvm/Support/MemoryBuffer.h"
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000029#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000030#include <memory>
Rafael Espindola8a8e5542014-06-12 17:19:42 +000031#include <system_error>
Douglas Gregor52da28b2011-09-23 23:43:36 +000032
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000033using namespace clang;
34
Daniel Dunbar88357802009-11-14 10:42:57 +000035//===----------------------------------------------------------------------===//
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000036// Custom Actions
37//===----------------------------------------------------------------------===//
38
David Blaikie6beb6aa2014-08-10 19:56:51 +000039std::unique_ptr<ASTConsumer>
40InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
41 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar1c201fb2010-03-19 19:44:04 +000042}
43
44void InitOnlyAction::ExecuteAction() {
45}
46
47//===----------------------------------------------------------------------===//
Daniel Dunbar88357802009-11-14 10:42:57 +000048// AST Consumer Actions
49//===----------------------------------------------------------------------===//
50
David Blaikie6beb6aa2014-08-10 19:56:51 +000051std::unique_ptr<ASTConsumer>
52ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +000053 if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
Alexander Kornienko3db68ee2012-07-26 16:01:23 +000054 return CreateASTPrinter(OS, CI.getFrontendOpts().ASTDumpFilter);
Craig Topper49a27902014-05-22 04:46:25 +000055 return nullptr;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000056}
57
David Blaikie6beb6aa2014-08-10 19:56:51 +000058std::unique_ptr<ASTConsumer>
59ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Richard Smith6ea05822013-06-24 01:45:33 +000060 return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter,
Richard Smith35f986d2014-08-11 22:11:07 +000061 CI.getFrontendOpts().ASTDumpDecls,
Richard Smith6ea05822013-06-24 01:45:33 +000062 CI.getFrontendOpts().ASTDumpLookups);
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000063}
64
David Blaikie6beb6aa2014-08-10 19:56:51 +000065std::unique_ptr<ASTConsumer>
66ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Alexander Kornienko4de03592012-07-31 09:37:40 +000067 return CreateASTDeclNodeLister();
68}
69
David Blaikie6beb6aa2014-08-10 19:56:51 +000070std::unique_ptr<ASTConsumer>
71ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000072 return CreateASTViewer();
73}
74
David Blaikie6beb6aa2014-08-10 19:56:51 +000075std::unique_ptr<ASTConsumer>
76DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
77 StringRef InFile) {
Daniel Dunbar02bd2d72009-11-14 10:42:46 +000078 return CreateDeclContextPrinter();
79}
80
David Blaikie6beb6aa2014-08-10 19:56:51 +000081std::unique_ptr<ASTConsumer>
82GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +000083 std::string Sysroot;
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +000084 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +000085 raw_ostream *OS = nullptr;
Douglas Gregor36db4f92011-08-25 22:35:51 +000086 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, 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 Prantl8bf7af32015-02-25 01:31:45 +000091
92 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
93 Consumers.push_back(llvm::make_unique<PCHGenerator>(CI.getPreprocessor(),
94 OutputFile, nullptr,
95 Sysroot));
96
97 auto CGOpts = CI.getCodeGenOpts();
98 // The debug info emitted by ModuleContainerGenerator is not affected by the
99 // optimization level.
100 CGOpts.OptimizationLevel = 0;
101 CGOpts.setDebugInfo(CodeGenOptions::LimitedDebugInfo);
102 Consumers.push_back(std::unique_ptr<ASTConsumer>(
103 CreateModuleContainerGenerator(CI.getDiagnostics(), "PCH", CGOpts,
104 CI.getTargetOpts(), CI.getLangOpts(), OS,
105 cast<PCHGenerator>(Consumers[0].get()))));
106
107 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000108}
109
110bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000111 StringRef InFile,
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000112 std::string &Sysroot,
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000113 std::string &OutputFile,
Douglas Gregor36db4f92011-08-25 22:35:51 +0000114 raw_ostream *&OS) {
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000115 Sysroot = CI.getHeaderSearchOpts().Sysroot;
116 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
Sebastian Redlea68af42010-08-17 17:55:38 +0000117 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000118 return true;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000119 }
120
Daniel Dunbara2867c72011-01-31 22:00:44 +0000121 // We use createOutputFile here because this is exposed via libclang, and we
122 // must disable the RemoveFileOnSignal behavior.
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000123 // We use a temporary to avoid race conditions.
Daniel Dunbara2867c72011-01-31 22:00:44 +0000124 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
Argyrios Kyrtzidis08a2bfd2011-07-28 00:45:10 +0000125 /*RemoveFileOnSignal=*/false, InFile,
126 /*Extension=*/"", /*useTemporary=*/true);
Daniel Dunbar75546992009-12-03 09:13:30 +0000127 if (!OS)
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000128 return true;
Daniel Dunbar75546992009-12-03 09:13:30 +0000129
Argyrios Kyrtzidis10b23682011-02-15 17:54:22 +0000130 OutputFile = CI.getFrontendOpts().OutputFile;
Douglas Gregor48c8cd32010-08-03 08:14:03 +0000131 return false;
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000132}
133
David Blaikie6beb6aa2014-08-10 19:56:51 +0000134std::unique_ptr<ASTConsumer>
135GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
136 StringRef InFile) {
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000137 std::string Sysroot;
138 std::string OutputFile;
Craig Topper49a27902014-05-22 04:46:25 +0000139 raw_ostream *OS = nullptr;
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000140 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
Craig Topper49a27902014-05-22 04:46:25 +0000141 return nullptr;
142
Adrian Prantl8bf7af32015-02-25 01:31:45 +0000143 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
144 Consumers.push_back(llvm::make_unique<PCHGenerator>(CI.getPreprocessor(),
145 OutputFile, Module,
146 Sysroot));
147
148 auto CGOpts = CI.getCodeGenOpts();
149 // The debug info emitted by ModuleContainerGenerator is not affected by the
150 // optimization level.
151 CGOpts.OptimizationLevel = 0;
152 CGOpts.setDebugInfo(CodeGenOptions::LimitedDebugInfo);
153 Consumers.push_back(
154 std::unique_ptr<ASTConsumer>(CreateModuleContainerGenerator(
155 CI.getDiagnostics(), Module->getFullModuleName(), CGOpts,
156 CI.getTargetOpts(), CI.getLangOpts(), OS,
157 cast<PCHGenerator>(Consumers[0].get()))));
158 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000159}
160
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000161static SmallVectorImpl<char> &
162operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
163 Includes.append(RHS.begin(), RHS.end());
164 return Includes;
165}
166
Rafael Espindolac0809172014-06-12 14:02:15 +0000167static std::error_code addHeaderInclude(StringRef HeaderName,
168 SmallVectorImpl<char> &Includes,
169 const LangOptions &LangOpts,
170 bool IsExternC) {
Richard Smith9bca2982014-03-08 00:03:56 +0000171 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000172 Includes += "extern \"C\" {\n";
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000173 if (LangOpts.ObjC1)
174 Includes += "#import \"";
175 else
176 Includes += "#include \"";
Richard Smith3c1a41a2014-12-02 00:08:08 +0000177
178 Includes += HeaderName;
179
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000180 Includes += "\"\n";
Richard Smith9bca2982014-03-08 00:03:56 +0000181 if (IsExternC && LangOpts.CPlusPlus)
Richard Smith77944862014-03-02 05:58:18 +0000182 Includes += "}\n";
Rafael Espindolac0809172014-06-12 14:02:15 +0000183 return std::error_code();
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000184}
185
Rafael Espindolac0809172014-06-12 14:02:15 +0000186static std::error_code addHeaderInclude(const FileEntry *Header,
187 SmallVectorImpl<char> &Includes,
188 const LangOptions &LangOpts,
189 bool IsExternC) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000190 // Use an absolute path if we don't have a filename as written in the module
191 // map file; this ensures that we will identify the right file independent of
192 // header search paths.
193 if (llvm::sys::path::is_absolute(Header->getName()))
194 return addHeaderInclude(Header->getName(), Includes, LangOpts, IsExternC);
195
196 SmallString<256> AbsName(Header->getName());
197 if (std::error_code Err = llvm::sys::fs::make_absolute(AbsName))
198 return Err;
199 return addHeaderInclude(AbsName, Includes, LangOpts, IsExternC);
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000200}
201
Douglas Gregor4332b322011-11-16 17:04:00 +0000202/// \brief Collect the set of header includes needed to construct the given
Argyrios Kyrtzidisc597c8c2012-10-05 00:22:33 +0000203/// module and update the TopHeaders file set of the module.
Douglas Gregor4332b322011-11-16 17:04:00 +0000204///
205/// \param Module The module we're collecting includes from.
Douglas Gregore5626c42011-12-06 17:15:11 +0000206///
James Dennettc423c532012-06-15 21:48:19 +0000207/// \param Includes Will be augmented with the set of \#includes or \#imports
Douglas Gregore5626c42011-12-06 17:15:11 +0000208/// needed to load all of the named headers.
Rafael Espindolac0809172014-06-12 14:02:15 +0000209static std::error_code
Richard Smith723928c2014-03-11 02:02:47 +0000210collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
211 ModuleMap &ModMap, clang::Module *Module,
212 SmallVectorImpl<char> &Includes) {
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000213 // Don't collect any headers for unavailable modules.
214 if (!Module->isAvailable())
Rafael Espindolac0809172014-06-12 14:02:15 +0000215 return std::error_code();
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000216
Douglas Gregore5626c42011-12-06 17:15:11 +0000217 // Add includes for each of these headers.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000218 for (Module::Header &H : Module->Headers[Module::HK_Normal]) {
219 Module->addTopHeader(H.Entry);
220 // Use the path as specified in the module map file. We'll look for this
221 // file relative to the module build directory (the directory containing
222 // the module map file) so this will find the same file that we found
223 // while parsing the module map.
224 if (std::error_code Err = addHeaderInclude(H.NameAsWritten, Includes,
225 LangOpts, Module->IsExternC))
Richard Smith723928c2014-03-11 02:02:47 +0000226 return Err;
Douglas Gregor3ec66632012-02-02 18:42:48 +0000227 }
Lawrence Crowlb53e5482013-06-20 21:14:14 +0000228 // Note that Module->PrivateHeaders will not be a TopHeader.
Douglas Gregore5626c42011-12-06 17:15:11 +0000229
Douglas Gregor73141fa2011-12-08 17:39:04 +0000230 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
Richard Smith3c1a41a2014-12-02 00:08:08 +0000231 // FIXME: Track the name as written here.
Argyrios Kyrtzidis3c5305c2013-03-13 21:13:43 +0000232 Module->addTopHeader(UmbrellaHeader);
Douglas Gregor3ec66632012-02-02 18:42:48 +0000233 if (Module->Parent) {
234 // Include the umbrella header for submodules.
Rafael Espindolac0809172014-06-12 14:02:15 +0000235 if (std::error_code Err = addHeaderInclude(UmbrellaHeader, Includes,
236 LangOpts, Module->IsExternC))
Richard Smith723928c2014-03-11 02:02:47 +0000237 return Err;
Douglas Gregor3ec66632012-02-02 18:42:48 +0000238 }
Douglas Gregor524e33e2011-12-08 19:11:24 +0000239 } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000240 // Add all of the headers we find in this subdirectory.
Rafael Espindolac0809172014-06-12 14:02:15 +0000241 std::error_code EC;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000242 SmallString<128> DirNative;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000243 llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
Douglas Gregorc1aaf8c2011-12-12 19:13:53 +0000244 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC),
245 DirEnd;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000246 Dir != DirEnd && !EC; Dir.increment(EC)) {
247 // Check whether this entry has an extension typically associated with
248 // headers.
249 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
250 .Cases(".h", ".H", ".hh", ".hpp", true)
251 .Default(false))
252 continue;
Richard Smith3c1a41a2014-12-02 00:08:08 +0000253
254 const FileEntry *Header = FileMgr.getFile(Dir->path());
255 // FIXME: This shouldn't happen unless there is a file system race. Is
256 // that worth diagnosing?
257 if (!Header)
258 continue;
259
Douglas Gregord2a8fe12012-01-05 00:04:05 +0000260 // If this header is marked 'unavailable' in this module, don't include
261 // it.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000262 if (ModMap.isHeaderUnavailableInModule(Header, Module))
263 continue;
264
Richard Smith723928c2014-03-11 02:02:47 +0000265 // Include this header as part of the umbrella directory.
Richard Smith3c1a41a2014-12-02 00:08:08 +0000266 // FIXME: Track the name as written through to here.
267 Module->addTopHeader(Header);
268 if (std::error_code Err =
269 addHeaderInclude(Header, Includes, LangOpts, Module->IsExternC))
Richard Smith723928c2014-03-11 02:02:47 +0000270 return Err;
Douglas Gregor524e33e2011-12-08 19:11:24 +0000271 }
Richard Smith723928c2014-03-11 02:02:47 +0000272
273 if (EC)
274 return EC;
Douglas Gregor4332b322011-11-16 17:04:00 +0000275 }
Richard Smith3c1a41a2014-12-02 00:08:08 +0000276
Douglas Gregor4332b322011-11-16 17:04:00 +0000277 // Recurse into submodules.
Douglas Gregoreb90e832012-01-04 23:32:19 +0000278 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
279 SubEnd = Module->submodule_end();
Douglas Gregore5626c42011-12-06 17:15:11 +0000280 Sub != SubEnd; ++Sub)
Rafael Espindolac0809172014-06-12 14:02:15 +0000281 if (std::error_code Err = collectModuleHeaderIncludes(
Richard Smith723928c2014-03-11 02:02:47 +0000282 LangOpts, FileMgr, ModMap, *Sub, Includes))
283 return Err;
284
Rafael Espindolac0809172014-06-12 14:02:15 +0000285 return std::error_code();
Douglas Gregor4332b322011-11-16 17:04:00 +0000286}
287
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000288bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
289 StringRef Filename) {
290 // Find the module map file.
291 const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
292 if (!ModuleMap) {
293 CI.getDiagnostics().Report(diag::err_module_map_not_found)
294 << Filename;
295 return false;
296 }
297
298 // Parse the module map file.
299 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
Douglas Gregor963c5532013-06-21 16:28:10 +0000300 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000301 return false;
302
303 if (CI.getLangOpts().CurrentModule.empty()) {
304 CI.getDiagnostics().Report(diag::err_missing_module_name);
305
306 // FIXME: Eventually, we could consider asking whether there was just
307 // a single module described in the module map, and use that as a
308 // default. Then it would be fairly trivial to just "compile" a module
309 // map with a single module (the common case).
310 return false;
311 }
Richard Smith7bea1d42014-03-05 20:55:36 +0000312
313 // If we're being run from the command-line, the module build stack will not
314 // have been filled in yet, so complete it now in order to allow us to detect
315 // module cycles.
316 SourceManager &SourceMgr = CI.getSourceManager();
317 if (SourceMgr.getModuleBuildStack().empty())
318 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
319 FullSourceLoc(SourceLocation(), SourceMgr));
320
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000321 // Dig out the module definition.
Douglas Gregor279a6c32012-01-29 17:08:11 +0000322 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
323 /*AllowSearch=*/false);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000324 if (!Module) {
325 CI.getDiagnostics().Report(diag::err_missing_module)
326 << CI.getLangOpts().CurrentModule << Filename;
327
328 return false;
329 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000330
331 // Check whether we can build this module at all.
Richard Smitha3feee22013-10-28 22:18:19 +0000332 clang::Module::Requirement Requirement;
Richard Smith3c1a41a2014-12-02 00:08:08 +0000333 clang::Module::UnresolvedHeaderDirective MissingHeader;
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000334 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
335 MissingHeader)) {
336 if (MissingHeader.FileNameLoc.isValid()) {
Ben Langmuirec8c9752014-04-18 22:07:31 +0000337 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
338 diag::err_module_header_missing)
Daniel Jasper0761a8a2013-12-17 10:31:37 +0000339 << MissingHeader.IsUmbrella << MissingHeader.FileName;
340 } else {
341 CI.getDiagnostics().Report(diag::err_module_unavailable)
342 << Module->getFullModuleName()
343 << Requirement.second << Requirement.first;
344 }
Douglas Gregor1fb5c3a2011-12-31 04:05:44 +0000345
346 return false;
347 }
348
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000349 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
350 Module->IsInferred = true;
351 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
352 } else {
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000353 ModuleMapForUniquing = ModuleMap;
Ben Langmuir9d6448b2014-08-09 00:57:23 +0000354 }
Ben Langmuirbeee15e2014-04-14 18:00:01 +0000355
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000356 FileManager &FileMgr = CI.getFileManager();
357
Douglas Gregor4332b322011-11-16 17:04:00 +0000358 // Collect the set of #includes we need to build the module.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000359 SmallString<256> HeaderContents;
Rafael Espindola8e650d72014-06-12 20:37:59 +0000360 std::error_code Err = std::error_code();
Argyrios Kyrtzidis130190f2012-10-10 02:12:39 +0000361 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
Richard Smith3c1a41a2014-12-02 00:08:08 +0000362 // FIXME: Track the file name as written.
Richard Smith723928c2014-03-11 02:02:47 +0000363 Err = addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts(),
364 Module->IsExternC);
365 if (!Err)
366 Err = collectModuleHeaderIncludes(
367 CI.getLangOpts(), FileMgr,
368 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
369 HeaderContents);
370
371 if (Err) {
372 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
373 << Module->getFullModuleName() << Err.message();
374 return false;
375 }
Douglas Gregor4332b322011-11-16 17:04:00 +0000376
Richard Smith3c1a41a2014-12-02 00:08:08 +0000377 // Inform the preprocessor that includes from within the input buffer should
378 // be resolved relative to the build directory of the module map file.
379 CI.getPreprocessor().setMainFileDir(Module->Directory);
380
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000381 std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
Argyrios Kyrtzidis52595242012-11-15 18:57:27 +0000382 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
383 Module::getModuleInputBufferName());
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000384 // Ownership of InputBuffer will be transferred to the SourceManager.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000385 setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
Douglas Gregora686e1b2012-01-27 19:52:33 +0000386 Module->IsSystem));
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000387 return true;
388}
389
390bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
391 StringRef InFile,
392 std::string &Sysroot,
393 std::string &OutputFile,
394 raw_ostream *&OS) {
395 // 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,
Ben Langmuird89dc562015-02-19 20:23:22 +0000401 ModuleMapForUniquing->getName());
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000402 }
403
404 // We use createOutputFile here because this is exposed via libclang, and we
405 // must disable the RemoveFileOnSignal behavior.
406 // We use a temporary to avoid race conditions.
407 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
408 /*RemoveFileOnSignal=*/false, InFile,
Daniel Dunbarb9c62c02012-03-03 00:36:02 +0000409 /*Extension=*/"", /*useTemporary=*/true,
410 /*CreateMissingDirectories=*/true);
Douglas Gregor2b20cb82011-11-16 00:09:06 +0000411 if (!OS)
412 return true;
413
414 OutputFile = CI.getFrontendOpts().OutputFile;
415 return false;
416}
417
David Blaikie6beb6aa2014-08-10 19:56:51 +0000418std::unique_ptr<ASTConsumer>
419SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
420 return llvm::make_unique<ASTConsumer>();
Daniel Dunbar02bd2d72009-11-14 10:42:46 +0000421}
422
David Blaikie6beb6aa2014-08-10 19:56:51 +0000423std::unique_ptr<ASTConsumer>
424DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
425 StringRef InFile) {
426 return llvm::make_unique<ASTConsumer>();
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000427}
428
David Blaikie6beb6aa2014-08-10 19:56:51 +0000429std::unique_ptr<ASTConsumer>
430VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
431 return llvm::make_unique<ASTConsumer>();
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000432}
433
434void VerifyPCHAction::ExecuteAction() {
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000435 CompilerInstance &CI = getCompilerInstance();
436 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
437 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
Ahmed Charlesb8984322014-03-07 20:03:18 +0000438 std::unique_ptr<ASTReader> Reader(
439 new ASTReader(CI.getPreprocessor(), CI.getASTContext(),
440 Sysroot.empty() ? "" : Sysroot.c_str(),
441 /*DisableValidation*/ false,
442 /*AllowPCHWithCompilerErrors*/ false,
443 /*AllowConfigurationMismatch*/ true,
444 /*ValidateSystemInputs*/ true));
Ben Langmuir3d4417c2014-02-07 17:31:11 +0000445
446 Reader->ReadAST(getCurrentFile(),
447 Preamble ? serialization::MK_Preamble
448 : serialization::MK_PCH,
449 SourceLocation(),
450 ASTReader::ARR_ConfigurationMismatch);
Ben Langmuir2cb4a782014-02-05 22:21:15 +0000451}
452
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000453namespace {
454 /// \brief AST reader listener that dumps module information for a module
455 /// file.
456 class DumpModuleInfoListener : public ASTReaderListener {
457 llvm::raw_ostream &Out;
458
459 public:
460 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
461
462#define DUMP_BOOLEAN(Value, Text) \
463 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
464
Craig Topperafa7cb32014-03-13 06:07:04 +0000465 bool ReadFullVersionInformation(StringRef FullVersion) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000466 Out.indent(2)
467 << "Generated by "
468 << (FullVersion == getClangFullRepositoryVersion()? "this"
469 : "a different")
470 << " Clang: " << FullVersion << "\n";
471 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
472 }
473
Ben Langmuir4f5212a2014-04-14 22:12:44 +0000474 void ReadModuleName(StringRef ModuleName) override {
475 Out.indent(2) << "Module name: " << ModuleName << "\n";
476 }
477 void ReadModuleMapFile(StringRef ModuleMapPath) override {
478 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
479 }
480
Richard Smith1e2cf0d2014-10-31 02:28:58 +0000481 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
482 bool AllowCompatibleDifferences) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000483 Out.indent(2) << "Language options:\n";
484#define LANGOPT(Name, Bits, Default, Description) \
485 DUMP_BOOLEAN(LangOpts.Name, Description);
486#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
487 Out.indent(4) << Description << ": " \
488 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
489#define VALUE_LANGOPT(Name, Bits, Default, Description) \
490 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
491#define BENIGN_LANGOPT(Name, Bits, Default, Description)
492#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
493#include "clang/Basic/LangOptions.def"
494 return false;
495 }
496
Craig Topperafa7cb32014-03-13 06:07:04 +0000497 bool ReadTargetOptions(const TargetOptions &TargetOpts,
498 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000499 Out.indent(2) << "Target options:\n";
500 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
501 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
502 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000503
504 if (!TargetOpts.FeaturesAsWritten.empty()) {
505 Out.indent(4) << "Target features:\n";
506 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
507 I != N; ++I) {
508 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
509 }
510 }
511
512 return false;
513 }
514
Ben Langmuirb92de022014-04-29 16:25:26 +0000515 virtual bool
516 ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
517 bool Complain) override {
518 Out.indent(2) << "Diagnostic options:\n";
519#define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
520#define ENUM_DIAGOPT(Name, Type, Bits, Default) \
521 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
522#define VALUE_DIAGOPT(Name, Bits, Default) \
523 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
524#include "clang/Basic/DiagnosticOptions.def"
525
Richard Smith3be1cb22014-08-07 00:24:21 +0000526 Out.indent(4) << "Diagnostic flags:\n";
527 for (const std::string &Warning : DiagOpts->Warnings)
Ben Langmuirb92de022014-04-29 16:25:26 +0000528 Out.indent(6) << "-W" << Warning << "\n";
Richard Smith3be1cb22014-08-07 00:24:21 +0000529 for (const std::string &Remark : DiagOpts->Remarks)
530 Out.indent(6) << "-R" << Remark << "\n";
Ben Langmuirb92de022014-04-29 16:25:26 +0000531
532 return false;
533 }
534
Craig Topperafa7cb32014-03-13 06:07:04 +0000535 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000536 StringRef SpecificModuleCachePath,
Craig Topperafa7cb32014-03-13 06:07:04 +0000537 bool Complain) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000538 Out.indent(2) << "Header search options:\n";
539 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
Argyrios Kyrtzidisbd0b6512015-02-19 20:12:20 +0000540 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000541 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
542 "Use builtin include directories [-nobuiltininc]");
543 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
544 "Use standard system include directories [-nostdinc]");
545 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
546 "Use standard C++ include directories [-nostdinc++]");
547 DUMP_BOOLEAN(HSOpts.UseLibcxx,
548 "Use libc++ (rather than libstdc++) [-stdlib=]");
549 return false;
550 }
551
Craig Topperafa7cb32014-03-13 06:07:04 +0000552 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
553 bool Complain,
554 std::string &SuggestedPredefines) override {
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000555 Out.indent(2) << "Preprocessor options:\n";
556 DUMP_BOOLEAN(PPOpts.UsePredefines,
557 "Uses compiler/target-specific predefines [-undef]");
558 DUMP_BOOLEAN(PPOpts.DetailedRecord,
559 "Uses detailed preprocessing record (for indexing)");
560
561 if (!PPOpts.Macros.empty()) {
562 Out.indent(4) << "Predefined macros:\n";
563 }
564
565 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
566 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
567 I != IEnd; ++I) {
568 Out.indent(6);
569 if (I->second)
570 Out << "-U";
571 else
572 Out << "-D";
573 Out << I->first << "\n";
574 }
575 return false;
576 }
577#undef DUMP_BOOLEAN
578 };
579}
580
581void DumpModuleInfoAction::ExecuteAction() {
582 // Set up the output file.
Ahmed Charlesb8984322014-03-07 20:03:18 +0000583 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000584 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
585 if (!OutputFileName.empty() && OutputFileName != "-") {
Rafael Espindoladae941a2014-08-25 18:17:04 +0000586 std::error_code EC;
587 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
588 llvm::sys::fs::F_Text));
Douglas Gregorbf7fc9c2013-03-27 16:47:18 +0000589 }
590 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
591
592 Out << "Information for module file '" << getCurrentFile() << "':\n";
593 DumpModuleInfoListener Listener(Out);
594 ASTReader::readASTFileControlBlock(getCurrentFile(),
595 getCompilerInstance().getFileManager(),
596 Listener);
597}
598
Daniel Dunbar88357802009-11-14 10:42:57 +0000599//===----------------------------------------------------------------------===//
600// Preprocessor Actions
601//===----------------------------------------------------------------------===//
602
603void DumpRawTokensAction::ExecuteAction() {
604 Preprocessor &PP = getCompilerInstance().getPreprocessor();
605 SourceManager &SM = PP.getSourceManager();
606
607 // Start lexing the specified input file.
Chris Lattner710bb872009-11-30 04:18:44 +0000608 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
David Blaikiebbafb8a2012-03-11 07:00:24 +0000609 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
Daniel Dunbar88357802009-11-14 10:42:57 +0000610 RawLex.SetKeepWhitespaceMode(true);
611
612 Token RawTok;
613 RawLex.LexFromRawLexer(RawTok);
614 while (RawTok.isNot(tok::eof)) {
615 PP.DumpToken(RawTok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000616 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000617 RawLex.LexFromRawLexer(RawTok);
618 }
619}
620
621void DumpTokensAction::ExecuteAction() {
622 Preprocessor &PP = getCompilerInstance().getPreprocessor();
623 // Start preprocessing the specified input file.
624 Token Tok;
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000625 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000626 do {
627 PP.Lex(Tok);
628 PP.DumpToken(Tok, true);
Daniel Dunbar75024622009-11-25 10:27:48 +0000629 llvm::errs() << "\n";
Daniel Dunbar88357802009-11-14 10:42:57 +0000630 } while (Tok.isNot(tok::eof));
631}
632
633void GeneratePTHAction::ExecuteAction() {
634 CompilerInstance &CI = getCompilerInstance();
635 if (CI.getFrontendOpts().OutputFile.empty() ||
636 CI.getFrontendOpts().OutputFile == "-") {
637 // FIXME: Don't fail this way.
638 // FIXME: Verify that we can actually seek in the given file.
Chris Lattner4b73cfa2010-04-07 22:58:06 +0000639 llvm::report_fatal_error("PTH requires a seekable file for output!");
Daniel Dunbar88357802009-11-14 10:42:57 +0000640 }
641 llvm::raw_fd_ostream *OS =
642 CI.createDefaultOutputFile(true, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000643 if (!OS) return;
644
Daniel Dunbar88357802009-11-14 10:42:57 +0000645 CacheTokens(CI.getPreprocessor(), OS);
646}
647
Daniel Dunbar88357802009-11-14 10:42:57 +0000648void PreprocessOnlyAction::ExecuteAction() {
649 Preprocessor &PP = getCompilerInstance().getPreprocessor();
650
Daniel Dunbard839e772010-06-11 20:10:12 +0000651 // Ignore unknown pragmas.
Lubos Lunak576a0412014-05-01 12:54:03 +0000652 PP.IgnorePragmas();
Daniel Dunbard839e772010-06-11 20:10:12 +0000653
Daniel Dunbar88357802009-11-14 10:42:57 +0000654 Token Tok;
655 // Start parsing the specified input file.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000656 PP.EnterMainSourceFile();
Daniel Dunbar88357802009-11-14 10:42:57 +0000657 do {
658 PP.Lex(Tok);
659 } while (Tok.isNot(tok::eof));
660}
661
Daniel Dunbar88357802009-11-14 10:42:57 +0000662void PrintPreprocessedAction::ExecuteAction() {
663 CompilerInstance &CI = getCompilerInstance();
Douglas Gregor52da28b2011-09-23 23:43:36 +0000664 // Output file may need to be set to 'Binary', to avoid converting Unix style
Steve Naroff3d38a682010-01-05 17:33:23 +0000665 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
Douglas Gregor52da28b2011-09-23 23:43:36 +0000666 //
667 // Look to see what type of line endings the file uses. If there's a
668 // CRLF, then we won't open the file up in binary mode. If there is
669 // just an LF or CR, then we will open the file up in binary mode.
670 // In this fashion, the output format should match the input format, unless
671 // the input format has inconsistent line endings.
672 //
673 // This should be a relatively fast operation since most files won't have
674 // all of their source code on a single line. However, that is still a
675 // concern, so if we scan for too long, we'll just assume the file should
676 // be opened in binary mode.
677 bool BinaryMode = true;
678 bool InvalidFile = false;
679 const SourceManager& SM = CI.getSourceManager();
680 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
681 &InvalidFile);
682 if (!InvalidFile) {
683 const char *cur = Buffer->getBufferStart();
684 const char *end = Buffer->getBufferEnd();
685 const char *next = (cur != end) ? cur + 1 : end;
686
687 // Limit ourselves to only scanning 256 characters into the source
688 // file. This is mostly a sanity check in case the file has no
689 // newlines whatsoever.
690 if (end - cur > 256) end = cur + 256;
691
692 while (next < end) {
693 if (*cur == 0x0D) { // CR
694 if (*next == 0x0A) // CRLF
695 BinaryMode = false;
696
697 break;
698 } else if (*cur == 0x0A) // LF
699 break;
700
701 ++cur, ++next;
702 }
703 }
704
705 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
Daniel Dunbar75546992009-12-03 09:13:30 +0000706 if (!OS) return;
707
Daniel Dunbar88357802009-11-14 10:42:57 +0000708 DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
709 CI.getPreprocessorOutputOpts());
710}
Douglas Gregoraf82e352010-07-20 20:18:03 +0000711
712void PrintPreambleAction::ExecuteAction() {
713 switch (getCurrentFileKind()) {
714 case IK_C:
715 case IK_CXX:
716 case IK_ObjC:
717 case IK_ObjCXX:
718 case IK_OpenCL:
Peter Collingbourne62089b82010-12-01 03:15:20 +0000719 case IK_CUDA:
Douglas Gregoraf82e352010-07-20 20:18:03 +0000720 break;
721
722 case IK_None:
723 case IK_Asm:
724 case IK_PreprocessedC:
725 case IK_PreprocessedCXX:
726 case IK_PreprocessedObjC:
727 case IK_PreprocessedObjCXX:
728 case IK_AST:
729 case IK_LLVM_IR:
730 // We can't do anything with these.
731 return;
732 }
Rafael Espindola6406f7b2014-08-26 19:54:40 +0000733
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +0000734 CompilerInstance &CI = getCompilerInstance();
Benjamin Kramera8857962014-10-26 22:44:13 +0000735 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
736 if (Buffer) {
Rafael Espindolacd0b3802014-08-12 15:46:24 +0000737 unsigned Preamble =
Benjamin Kramera8857962014-10-26 22:44:13 +0000738 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
739 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
Douglas Gregoraf82e352010-07-20 20:18:03 +0000740 }
741}