1 //===--- FrontendActions.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Frontend/FrontendActions.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/Basic/FileManager.h"
13 #include "clang/Frontend/ASTConsumers.h"
14 #include "clang/Frontend/CompilerInstance.h"
15 #include "clang/Frontend/FrontendDiagnostic.h"
16 #include "clang/Frontend/MultiplexConsumer.h"
17 #include "clang/Frontend/Utils.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Lex/PreprocessorOptions.h"
21 #include "clang/Serialization/ASTReader.h"
22 #include "clang/Serialization/ASTWriter.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include "llvm/Support/Path.h"
26 #include "llvm/Support/raw_ostream.h"
28 #include <system_error>
30 using namespace clang;
32 //===----------------------------------------------------------------------===//
34 //===----------------------------------------------------------------------===//
36 std::unique_ptr<ASTConsumer>
37 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
38 return llvm::make_unique<ASTConsumer>();
41 void InitOnlyAction::ExecuteAction() {
44 //===----------------------------------------------------------------------===//
45 // AST Consumer Actions
46 //===----------------------------------------------------------------------===//
48 std::unique_ptr<ASTConsumer>
49 ASTPrintAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
50 if (std::unique_ptr<raw_ostream> OS =
51 CI.createDefaultOutputFile(false, InFile))
52 return CreateASTPrinter(std::move(OS), CI.getFrontendOpts().ASTDumpFilter);
56 std::unique_ptr<ASTConsumer>
57 ASTDumpAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
58 return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter,
59 CI.getFrontendOpts().ASTDumpDecls,
60 CI.getFrontendOpts().ASTDumpAll,
61 CI.getFrontendOpts().ASTDumpLookups);
64 std::unique_ptr<ASTConsumer>
65 ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
66 return CreateASTDeclNodeLister();
69 std::unique_ptr<ASTConsumer>
70 ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
71 return CreateASTViewer();
74 std::unique_ptr<ASTConsumer>
75 DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
77 return CreateDeclContextPrinter();
80 std::unique_ptr<ASTConsumer>
81 GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
83 std::string OutputFile;
84 std::unique_ptr<raw_pwrite_stream> OS =
85 ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
89 if (!CI.getFrontendOpts().RelocatablePCH)
92 auto Buffer = std::make_shared<PCHBuffer>();
93 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
94 Consumers.push_back(llvm::make_unique<PCHGenerator>(
95 CI.getPreprocessor(), OutputFile, Sysroot,
96 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
97 /*AllowASTWithErrors*/CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
99 +CI.getFrontendOpts().IncludeTimestamps));
100 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
101 CI, InFile, OutputFile, std::move(OS), Buffer));
103 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
106 std::unique_ptr<raw_pwrite_stream>
107 GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
109 std::string &Sysroot,
110 std::string &OutputFile) {
111 Sysroot = CI.getHeaderSearchOpts().Sysroot;
112 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
113 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
117 // We use createOutputFile here because this is exposed via libclang, and we
118 // must disable the RemoveFileOnSignal behavior.
119 // We use a temporary to avoid race conditions.
120 std::unique_ptr<raw_pwrite_stream> OS =
121 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
122 /*RemoveFileOnSignal=*/false, InFile,
123 /*Extension=*/"", /*useTemporary=*/true);
127 OutputFile = CI.getFrontendOpts().OutputFile;
131 bool GeneratePCHAction::shouldEraseOutputFiles() {
132 if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
134 return ASTFrontendAction::shouldEraseOutputFiles();
137 bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI,
138 StringRef Filename) {
139 CI.getLangOpts().CompilingPCH = true;
143 std::unique_ptr<ASTConsumer>
144 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
146 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
150 std::string OutputFile = CI.getFrontendOpts().OutputFile;
153 auto Buffer = std::make_shared<PCHBuffer>();
154 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
156 Consumers.push_back(llvm::make_unique<PCHGenerator>(
157 CI.getPreprocessor(), OutputFile, Sysroot,
158 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
159 /*AllowASTWithErrors=*/false,
160 /*IncludeTimestamps=*/
161 +CI.getFrontendOpts().BuildingImplicitModule));
162 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
163 CI, InFile, OutputFile, std::move(OS), Buffer));
164 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
167 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
168 CompilerInstance &CI, StringRef Filename) {
169 return GenerateModuleAction::BeginSourceFileAction(CI, Filename);
172 std::unique_ptr<raw_pwrite_stream>
173 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
175 // If no output file was provided, figure out where this module would go
176 // in the module cache.
177 if (CI.getFrontendOpts().OutputFile.empty()) {
178 StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
179 if (ModuleMapFile.empty())
180 ModuleMapFile = InFile;
182 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
183 CI.getFrontendOpts().OutputFile =
184 HS.getModuleFileName(CI.getLangOpts().CurrentModule, ModuleMapFile,
185 /*UsePrebuiltPath=*/false);
188 // We use createOutputFile here because this is exposed via libclang, and we
189 // must disable the RemoveFileOnSignal behavior.
190 // We use a temporary to avoid race conditions.
191 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
192 /*RemoveFileOnSignal=*/false, InFile,
193 /*Extension=*/"", /*useTemporary=*/true,
194 /*CreateMissingDirectories=*/true);
197 bool GenerateModuleInterfaceAction::BeginSourceFileAction(CompilerInstance &CI,
198 StringRef Filename) {
199 if (!CI.getLangOpts().ModulesTS) {
200 CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
204 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
206 return GenerateModuleAction::BeginSourceFileAction(CI, Filename);
209 std::unique_ptr<raw_pwrite_stream>
210 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
212 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
215 SyntaxOnlyAction::~SyntaxOnlyAction() {
218 std::unique_ptr<ASTConsumer>
219 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
220 return llvm::make_unique<ASTConsumer>();
223 std::unique_ptr<ASTConsumer>
224 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
226 return llvm::make_unique<ASTConsumer>();
229 std::unique_ptr<ASTConsumer>
230 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
231 return llvm::make_unique<ASTConsumer>();
234 void VerifyPCHAction::ExecuteAction() {
235 CompilerInstance &CI = getCompilerInstance();
236 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
237 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
238 std::unique_ptr<ASTReader> Reader(new ASTReader(
239 CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
240 CI.getFrontendOpts().ModuleFileExtensions,
241 Sysroot.empty() ? "" : Sysroot.c_str(),
242 /*DisableValidation*/ false,
243 /*AllowPCHWithCompilerErrors*/ false,
244 /*AllowConfigurationMismatch*/ true,
245 /*ValidateSystemInputs*/ true));
247 Reader->ReadAST(getCurrentFile(),
248 Preamble ? serialization::MK_Preamble
249 : serialization::MK_PCH,
251 ASTReader::ARR_ConfigurationMismatch);
255 /// \brief AST reader listener that dumps module information for a module
257 class DumpModuleInfoListener : public ASTReaderListener {
258 llvm::raw_ostream &Out;
261 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
263 #define DUMP_BOOLEAN(Value, Text) \
264 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
266 bool ReadFullVersionInformation(StringRef FullVersion) override {
269 << (FullVersion == getClangFullRepositoryVersion()? "this"
271 << " Clang: " << FullVersion << "\n";
272 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
275 void ReadModuleName(StringRef ModuleName) override {
276 Out.indent(2) << "Module name: " << ModuleName << "\n";
278 void ReadModuleMapFile(StringRef ModuleMapPath) override {
279 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
282 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
283 bool AllowCompatibleDifferences) override {
284 Out.indent(2) << "Language options:\n";
285 #define LANGOPT(Name, Bits, Default, Description) \
286 DUMP_BOOLEAN(LangOpts.Name, Description);
287 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
288 Out.indent(4) << Description << ": " \
289 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
290 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
291 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
292 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
293 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
294 #include "clang/Basic/LangOptions.def"
296 if (!LangOpts.ModuleFeatures.empty()) {
297 Out.indent(4) << "Module features:\n";
298 for (StringRef Feature : LangOpts.ModuleFeatures)
299 Out.indent(6) << Feature << "\n";
305 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
306 bool AllowCompatibleDifferences) override {
307 Out.indent(2) << "Target options:\n";
308 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
309 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
310 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
312 if (!TargetOpts.FeaturesAsWritten.empty()) {
313 Out.indent(4) << "Target features:\n";
314 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
316 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
323 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
324 bool Complain) override {
325 Out.indent(2) << "Diagnostic options:\n";
326 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
327 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
328 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
329 #define VALUE_DIAGOPT(Name, Bits, Default) \
330 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
331 #include "clang/Basic/DiagnosticOptions.def"
333 Out.indent(4) << "Diagnostic flags:\n";
334 for (const std::string &Warning : DiagOpts->Warnings)
335 Out.indent(6) << "-W" << Warning << "\n";
336 for (const std::string &Remark : DiagOpts->Remarks)
337 Out.indent(6) << "-R" << Remark << "\n";
342 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
343 StringRef SpecificModuleCachePath,
344 bool Complain) override {
345 Out.indent(2) << "Header search options:\n";
346 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
347 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
348 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
349 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
350 "Use builtin include directories [-nobuiltininc]");
351 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
352 "Use standard system include directories [-nostdinc]");
353 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
354 "Use standard C++ include directories [-nostdinc++]");
355 DUMP_BOOLEAN(HSOpts.UseLibcxx,
356 "Use libc++ (rather than libstdc++) [-stdlib=]");
360 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
362 std::string &SuggestedPredefines) override {
363 Out.indent(2) << "Preprocessor options:\n";
364 DUMP_BOOLEAN(PPOpts.UsePredefines,
365 "Uses compiler/target-specific predefines [-undef]");
366 DUMP_BOOLEAN(PPOpts.DetailedRecord,
367 "Uses detailed preprocessing record (for indexing)");
369 if (!PPOpts.Macros.empty()) {
370 Out.indent(4) << "Predefined macros:\n";
373 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
374 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
381 Out << I->first << "\n";
386 /// Indicates that a particular module file extension has been read.
387 void readModuleFileExtension(
388 const ModuleFileExtensionMetadata &Metadata) override {
389 Out.indent(2) << "Module file extension '"
390 << Metadata.BlockName << "' " << Metadata.MajorVersion
391 << "." << Metadata.MinorVersion;
392 if (!Metadata.UserInfo.empty()) {
394 Out.write_escaped(Metadata.UserInfo);
403 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
404 // The Object file reader also supports raw ast files and there is no point in
405 // being strict about the module file format in -module-file-info mode.
406 CI.getHeaderSearchOpts().ModuleFormat = "obj";
410 void DumpModuleInfoAction::ExecuteAction() {
411 // Set up the output file.
412 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
413 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
414 if (!OutputFileName.empty() && OutputFileName != "-") {
416 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
417 llvm::sys::fs::F_Text));
419 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
421 Out << "Information for module file '" << getCurrentFile() << "':\n";
422 auto &FileMgr = getCompilerInstance().getFileManager();
423 auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
424 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
425 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
426 Magic[2] == 'C' && Magic[3] == 'H');
427 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
429 Preprocessor &PP = getCompilerInstance().getPreprocessor();
430 DumpModuleInfoListener Listener(Out);
431 HeaderSearchOptions &HSOpts =
432 PP.getHeaderSearchInfo().getHeaderSearchOpts();
433 ASTReader::readASTFileControlBlock(
434 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
435 /*FindModuleFileExtensions=*/true, Listener,
436 HSOpts.ModulesValidateDiagnosticOptions);
439 //===----------------------------------------------------------------------===//
440 // Preprocessor Actions
441 //===----------------------------------------------------------------------===//
443 void DumpRawTokensAction::ExecuteAction() {
444 Preprocessor &PP = getCompilerInstance().getPreprocessor();
445 SourceManager &SM = PP.getSourceManager();
447 // Start lexing the specified input file.
448 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
449 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
450 RawLex.SetKeepWhitespaceMode(true);
453 RawLex.LexFromRawLexer(RawTok);
454 while (RawTok.isNot(tok::eof)) {
455 PP.DumpToken(RawTok, true);
456 llvm::errs() << "\n";
457 RawLex.LexFromRawLexer(RawTok);
461 void DumpTokensAction::ExecuteAction() {
462 Preprocessor &PP = getCompilerInstance().getPreprocessor();
463 // Start preprocessing the specified input file.
465 PP.EnterMainSourceFile();
468 PP.DumpToken(Tok, true);
469 llvm::errs() << "\n";
470 } while (Tok.isNot(tok::eof));
473 void GeneratePTHAction::ExecuteAction() {
474 CompilerInstance &CI = getCompilerInstance();
475 std::unique_ptr<raw_pwrite_stream> OS =
476 CI.createDefaultOutputFile(true, getCurrentFile());
480 CacheTokens(CI.getPreprocessor(), OS.get());
483 void PreprocessOnlyAction::ExecuteAction() {
484 Preprocessor &PP = getCompilerInstance().getPreprocessor();
486 // Ignore unknown pragmas.
490 // Start parsing the specified input file.
491 PP.EnterMainSourceFile();
494 } while (Tok.isNot(tok::eof));
497 void PrintPreprocessedAction::ExecuteAction() {
498 CompilerInstance &CI = getCompilerInstance();
499 // Output file may need to be set to 'Binary', to avoid converting Unix style
500 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
502 // Look to see what type of line endings the file uses. If there's a
503 // CRLF, then we won't open the file up in binary mode. If there is
504 // just an LF or CR, then we will open the file up in binary mode.
505 // In this fashion, the output format should match the input format, unless
506 // the input format has inconsistent line endings.
508 // This should be a relatively fast operation since most files won't have
509 // all of their source code on a single line. However, that is still a
510 // concern, so if we scan for too long, we'll just assume the file should
511 // be opened in binary mode.
512 bool BinaryMode = true;
513 bool InvalidFile = false;
514 const SourceManager& SM = CI.getSourceManager();
515 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
518 const char *cur = Buffer->getBufferStart();
519 const char *end = Buffer->getBufferEnd();
520 const char *next = (cur != end) ? cur + 1 : end;
522 // Limit ourselves to only scanning 256 characters into the source
523 // file. This is mostly a sanity check in case the file has no
524 // newlines whatsoever.
525 if (end - cur > 256) end = cur + 256;
528 if (*cur == 0x0D) { // CR
529 if (*next == 0x0A) // CRLF
533 } else if (*cur == 0x0A) // LF
541 std::unique_ptr<raw_ostream> OS =
542 CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
545 // If we're preprocessing a module map, start by dumping the contents of the
546 // module itself before switching to the input buffer.
547 auto &Input = getCurrentInput();
548 if (Input.getKind().getFormat() == InputKind::ModuleMap) {
549 if (Input.isFile()) {
551 OS->write_escaped(Input.getFile());
554 // FIXME: Include additional information here so that we don't need the
555 // original source files to exist on disk.
556 getCurrentModule()->print(*OS);
557 (*OS) << "#pragma clang module contents\n";
560 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
561 CI.getPreprocessorOutputOpts());
564 void PrintPreambleAction::ExecuteAction() {
565 switch (getCurrentFileKind().getLanguage()) {
568 case InputKind::ObjC:
569 case InputKind::ObjCXX:
570 case InputKind::OpenCL:
571 case InputKind::CUDA:
574 case InputKind::Unknown:
576 case InputKind::LLVM_IR:
577 case InputKind::RenderScript:
578 // We can't do anything with these.
582 // We don't expect to find any #include directives in a preprocessed input.
583 if (getCurrentFileKind().isPreprocessed())
586 CompilerInstance &CI = getCompilerInstance();
587 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
590 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
591 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);