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().ASTDumpLookups);
63 std::unique_ptr<ASTConsumer>
64 ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
65 return CreateASTDeclNodeLister();
68 std::unique_ptr<ASTConsumer>
69 ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
70 return CreateASTViewer();
73 std::unique_ptr<ASTConsumer>
74 DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
76 return CreateDeclContextPrinter();
79 std::unique_ptr<ASTConsumer>
80 GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
82 std::string OutputFile;
83 std::unique_ptr<raw_pwrite_stream> OS =
84 ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
88 if (!CI.getFrontendOpts().RelocatablePCH)
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, Sysroot,
95 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
96 /*AllowASTWithErrors*/false,
98 +CI.getFrontendOpts().IncludeTimestamps));
99 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
100 CI, InFile, OutputFile, std::move(OS), Buffer));
102 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
105 std::unique_ptr<raw_pwrite_stream>
106 GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
108 std::string &Sysroot,
109 std::string &OutputFile) {
110 Sysroot = CI.getHeaderSearchOpts().Sysroot;
111 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
112 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
116 // We use createOutputFile here because this is exposed via libclang, and we
117 // must disable the RemoveFileOnSignal behavior.
118 // We use a temporary to avoid race conditions.
119 std::unique_ptr<raw_pwrite_stream> OS =
120 CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
121 /*RemoveFileOnSignal=*/false, InFile,
122 /*Extension=*/"", /*useTemporary=*/true);
126 OutputFile = CI.getFrontendOpts().OutputFile;
130 bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI,
131 StringRef Filename) {
132 CI.getLangOpts().CompilingPCH = true;
136 std::unique_ptr<ASTConsumer>
137 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
139 std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
143 std::string OutputFile = CI.getFrontendOpts().OutputFile;
146 auto Buffer = std::make_shared<PCHBuffer>();
147 std::vector<std::unique_ptr<ASTConsumer>> Consumers;
149 Consumers.push_back(llvm::make_unique<PCHGenerator>(
150 CI.getPreprocessor(), OutputFile, Sysroot,
151 Buffer, CI.getFrontendOpts().ModuleFileExtensions,
152 /*AllowASTWithErrors=*/false,
153 /*IncludeTimestamps=*/
154 +CI.getFrontendOpts().BuildingImplicitModule));
155 Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
156 CI, InFile, OutputFile, std::move(OS), Buffer));
157 return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
160 bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
161 StringRef Filename) {
162 // Set up embedding for any specified files. Do this before we load any
163 // source files, including the primary module map for the compilation.
164 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
165 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
166 CI.getSourceManager().setFileIsTransient(FE);
168 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
170 if (CI.getFrontendOpts().ModulesEmbedAllFiles)
171 CI.getSourceManager().setAllFilesAreTransient(true);
177 static SmallVectorImpl<char> &
178 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
179 Includes.append(RHS.begin(), RHS.end());
183 static void addHeaderInclude(StringRef HeaderName,
184 SmallVectorImpl<char> &Includes,
185 const LangOptions &LangOpts,
187 if (IsExternC && LangOpts.CPlusPlus)
188 Includes += "extern \"C\" {\n";
190 Includes += "#import \"";
192 Includes += "#include \"";
194 Includes += HeaderName;
197 if (IsExternC && LangOpts.CPlusPlus)
201 /// \brief Collect the set of header includes needed to construct the given
202 /// module and update the TopHeaders file set of the module.
204 /// \param Module The module we're collecting includes from.
206 /// \param Includes Will be augmented with the set of \#includes or \#imports
207 /// needed to load all of the named headers.
208 static std::error_code
209 collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
210 ModuleMap &ModMap, clang::Module *Module,
211 SmallVectorImpl<char> &Includes) {
212 // Don't collect any headers for unavailable modules.
213 if (!Module->isAvailable())
214 return std::error_code();
216 // Add includes for each of these headers.
217 for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
218 for (Module::Header &H : Module->Headers[HK]) {
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 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
227 // Note that Module->PrivateHeaders will not be a TopHeader.
229 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
230 Module->addTopHeader(UmbrellaHeader.Entry);
232 // Include the umbrella header for submodules.
233 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
235 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
236 // Add all of the headers we find in this subdirectory.
238 SmallString<128> DirNative;
239 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
241 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
242 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
243 Dir != End && !EC; Dir.increment(EC)) {
244 // Check whether this entry has an extension typically associated with
246 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
247 .Cases(".h", ".H", ".hh", ".hpp", true)
251 const FileEntry *Header = FileMgr.getFile(Dir->getName());
252 // FIXME: This shouldn't happen unless there is a file system race. Is
253 // that worth diagnosing?
257 // If this header is marked 'unavailable' in this module, don't include
259 if (ModMap.isHeaderUnavailableInModule(Header, Module))
262 // Compute the relative path from the directory to this file.
263 SmallVector<StringRef, 16> Components;
264 auto PathIt = llvm::sys::path::rbegin(Dir->getName());
265 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
266 Components.push_back(*PathIt);
267 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
268 for (auto It = Components.rbegin(), End = Components.rend(); It != End;
270 llvm::sys::path::append(RelativeHeader, *It);
272 // Include this header as part of the umbrella directory.
273 Module->addTopHeader(Header);
274 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
281 // Recurse into submodules.
282 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
283 SubEnd = Module->submodule_end();
284 Sub != SubEnd; ++Sub)
285 if (std::error_code Err = collectModuleHeaderIncludes(
286 LangOpts, FileMgr, ModMap, *Sub, Includes))
289 return std::error_code();
292 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
293 CompilerInstance &CI, StringRef Filename) {
294 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
296 if (!GenerateModuleAction::BeginSourceFileAction(CI, Filename))
299 // Find the module map file.
300 const FileEntry *ModuleMap =
301 CI.getFileManager().getFile(Filename, /*openFile*/true);
303 CI.getDiagnostics().Report(diag::err_module_map_not_found)
308 // Parse the module map file.
309 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
310 if (HS.loadModuleMapFile(ModuleMap, IsSystem))
313 if (CI.getLangOpts().CurrentModule.empty()) {
314 CI.getDiagnostics().Report(diag::err_missing_module_name);
316 // FIXME: Eventually, we could consider asking whether there was just
317 // a single module described in the module map, and use that as a
318 // default. Then it would be fairly trivial to just "compile" a module
319 // map with a single module (the common case).
323 // If we're being run from the command-line, the module build stack will not
324 // have been filled in yet, so complete it now in order to allow us to detect
326 SourceManager &SourceMgr = CI.getSourceManager();
327 if (SourceMgr.getModuleBuildStack().empty())
328 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
329 FullSourceLoc(SourceLocation(), SourceMgr));
331 // Dig out the module definition.
332 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
333 /*AllowSearch=*/false);
335 CI.getDiagnostics().Report(diag::err_missing_module)
336 << CI.getLangOpts().CurrentModule << Filename;
341 // Check whether we can build this module at all.
342 clang::Module::Requirement Requirement;
343 clang::Module::UnresolvedHeaderDirective MissingHeader;
344 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
346 if (MissingHeader.FileNameLoc.isValid()) {
347 CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
348 diag::err_module_header_missing)
349 << MissingHeader.IsUmbrella << MissingHeader.FileName;
351 CI.getDiagnostics().Report(diag::err_module_unavailable)
352 << Module->getFullModuleName()
353 << Requirement.second << Requirement.first;
359 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
360 Module->IsInferred = true;
361 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
363 ModuleMapForUniquing = ModuleMap;
366 FileManager &FileMgr = CI.getFileManager();
368 // Collect the set of #includes we need to build the module.
369 SmallString<256> HeaderContents;
370 std::error_code Err = std::error_code();
371 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader())
372 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
373 CI.getLangOpts(), Module->IsExternC);
374 Err = collectModuleHeaderIncludes(
375 CI.getLangOpts(), FileMgr,
376 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
380 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
381 << Module->getFullModuleName() << Err.message();
385 // Inform the preprocessor that includes from within the input buffer should
386 // be resolved relative to the build directory of the module map file.
387 CI.getPreprocessor().setMainFileDir(Module->Directory);
389 std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
390 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
391 Module::getModuleInputBufferName());
392 // Ownership of InputBuffer will be transferred to the SourceManager.
393 setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
398 std::unique_ptr<raw_pwrite_stream>
399 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
401 // If no output file was provided, figure out where this module would go
402 // in the module cache.
403 if (CI.getFrontendOpts().OutputFile.empty()) {
404 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
405 CI.getFrontendOpts().OutputFile =
406 HS.getModuleFileName(CI.getLangOpts().CurrentModule,
407 ModuleMapForUniquing->getName(),
408 /*UsePrebuiltPath=*/false);
411 // We use createOutputFile here because this is exposed via libclang, and we
412 // must disable the RemoveFileOnSignal behavior.
413 // We use a temporary to avoid race conditions.
414 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
415 /*RemoveFileOnSignal=*/false, InFile,
416 /*Extension=*/"", /*useTemporary=*/true,
417 /*CreateMissingDirectories=*/true);
420 bool GenerateModuleInterfaceAction::BeginSourceFileAction(CompilerInstance &CI,
421 StringRef Filename) {
422 if (!CI.getLangOpts().ModulesTS) {
423 CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
427 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
429 return GenerateModuleAction::BeginSourceFileAction(CI, Filename);
432 std::unique_ptr<raw_pwrite_stream>
433 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
435 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
438 SyntaxOnlyAction::~SyntaxOnlyAction() {
441 std::unique_ptr<ASTConsumer>
442 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
443 return llvm::make_unique<ASTConsumer>();
446 std::unique_ptr<ASTConsumer>
447 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
449 return llvm::make_unique<ASTConsumer>();
452 std::unique_ptr<ASTConsumer>
453 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
454 return llvm::make_unique<ASTConsumer>();
457 void VerifyPCHAction::ExecuteAction() {
458 CompilerInstance &CI = getCompilerInstance();
459 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
460 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
461 std::unique_ptr<ASTReader> Reader(new ASTReader(
462 CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
463 CI.getFrontendOpts().ModuleFileExtensions,
464 Sysroot.empty() ? "" : Sysroot.c_str(),
465 /*DisableValidation*/ false,
466 /*AllowPCHWithCompilerErrors*/ false,
467 /*AllowConfigurationMismatch*/ true,
468 /*ValidateSystemInputs*/ true));
470 Reader->ReadAST(getCurrentFile(),
471 Preamble ? serialization::MK_Preamble
472 : serialization::MK_PCH,
474 ASTReader::ARR_ConfigurationMismatch);
478 /// \brief AST reader listener that dumps module information for a module
480 class DumpModuleInfoListener : public ASTReaderListener {
481 llvm::raw_ostream &Out;
484 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
486 #define DUMP_BOOLEAN(Value, Text) \
487 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
489 bool ReadFullVersionInformation(StringRef FullVersion) override {
492 << (FullVersion == getClangFullRepositoryVersion()? "this"
494 << " Clang: " << FullVersion << "\n";
495 return ASTReaderListener::ReadFullVersionInformation(FullVersion);
498 void ReadModuleName(StringRef ModuleName) override {
499 Out.indent(2) << "Module name: " << ModuleName << "\n";
501 void ReadModuleMapFile(StringRef ModuleMapPath) override {
502 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
505 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
506 bool AllowCompatibleDifferences) override {
507 Out.indent(2) << "Language options:\n";
508 #define LANGOPT(Name, Bits, Default, Description) \
509 DUMP_BOOLEAN(LangOpts.Name, Description);
510 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
511 Out.indent(4) << Description << ": " \
512 << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
513 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
514 Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
515 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
516 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
517 #include "clang/Basic/LangOptions.def"
519 if (!LangOpts.ModuleFeatures.empty()) {
520 Out.indent(4) << "Module features:\n";
521 for (StringRef Feature : LangOpts.ModuleFeatures)
522 Out.indent(6) << Feature << "\n";
528 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
529 bool AllowCompatibleDifferences) override {
530 Out.indent(2) << "Target options:\n";
531 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n";
532 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n";
533 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n";
535 if (!TargetOpts.FeaturesAsWritten.empty()) {
536 Out.indent(4) << "Target features:\n";
537 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
539 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
546 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
547 bool Complain) override {
548 Out.indent(2) << "Diagnostic options:\n";
549 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
550 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
551 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
552 #define VALUE_DIAGOPT(Name, Bits, Default) \
553 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
554 #include "clang/Basic/DiagnosticOptions.def"
556 Out.indent(4) << "Diagnostic flags:\n";
557 for (const std::string &Warning : DiagOpts->Warnings)
558 Out.indent(6) << "-W" << Warning << "\n";
559 for (const std::string &Remark : DiagOpts->Remarks)
560 Out.indent(6) << "-R" << Remark << "\n";
565 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
566 StringRef SpecificModuleCachePath,
567 bool Complain) override {
568 Out.indent(2) << "Header search options:\n";
569 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
570 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
571 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
572 "Use builtin include directories [-nobuiltininc]");
573 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
574 "Use standard system include directories [-nostdinc]");
575 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
576 "Use standard C++ include directories [-nostdinc++]");
577 DUMP_BOOLEAN(HSOpts.UseLibcxx,
578 "Use libc++ (rather than libstdc++) [-stdlib=]");
582 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
584 std::string &SuggestedPredefines) override {
585 Out.indent(2) << "Preprocessor options:\n";
586 DUMP_BOOLEAN(PPOpts.UsePredefines,
587 "Uses compiler/target-specific predefines [-undef]");
588 DUMP_BOOLEAN(PPOpts.DetailedRecord,
589 "Uses detailed preprocessing record (for indexing)");
591 if (!PPOpts.Macros.empty()) {
592 Out.indent(4) << "Predefined macros:\n";
595 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
596 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
603 Out << I->first << "\n";
608 /// Indicates that a particular module file extension has been read.
609 void readModuleFileExtension(
610 const ModuleFileExtensionMetadata &Metadata) override {
611 Out.indent(2) << "Module file extension '"
612 << Metadata.BlockName << "' " << Metadata.MajorVersion
613 << "." << Metadata.MinorVersion;
614 if (!Metadata.UserInfo.empty()) {
616 Out.write_escaped(Metadata.UserInfo);
625 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
626 // The Object file reader also supports raw ast files and there is no point in
627 // being strict about the module file format in -module-file-info mode.
628 CI.getHeaderSearchOpts().ModuleFormat = "obj";
632 void DumpModuleInfoAction::ExecuteAction() {
633 // Set up the output file.
634 std::unique_ptr<llvm::raw_fd_ostream> OutFile;
635 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
636 if (!OutputFileName.empty() && OutputFileName != "-") {
638 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
639 llvm::sys::fs::F_Text));
641 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
643 Out << "Information for module file '" << getCurrentFile() << "':\n";
644 auto &FileMgr = getCompilerInstance().getFileManager();
645 auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
646 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
647 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
648 Magic[2] == 'C' && Magic[3] == 'H');
649 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n";
651 Preprocessor &PP = getCompilerInstance().getPreprocessor();
652 DumpModuleInfoListener Listener(Out);
653 HeaderSearchOptions &HSOpts =
654 PP.getHeaderSearchInfo().getHeaderSearchOpts();
655 ASTReader::readASTFileControlBlock(
656 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
657 /*FindModuleFileExtensions=*/true, Listener,
658 HSOpts.ModulesValidateDiagnosticOptions);
661 //===----------------------------------------------------------------------===//
662 // Preprocessor Actions
663 //===----------------------------------------------------------------------===//
665 void DumpRawTokensAction::ExecuteAction() {
666 Preprocessor &PP = getCompilerInstance().getPreprocessor();
667 SourceManager &SM = PP.getSourceManager();
669 // Start lexing the specified input file.
670 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
671 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
672 RawLex.SetKeepWhitespaceMode(true);
675 RawLex.LexFromRawLexer(RawTok);
676 while (RawTok.isNot(tok::eof)) {
677 PP.DumpToken(RawTok, true);
678 llvm::errs() << "\n";
679 RawLex.LexFromRawLexer(RawTok);
683 void DumpTokensAction::ExecuteAction() {
684 Preprocessor &PP = getCompilerInstance().getPreprocessor();
685 // Start preprocessing the specified input file.
687 PP.EnterMainSourceFile();
690 PP.DumpToken(Tok, true);
691 llvm::errs() << "\n";
692 } while (Tok.isNot(tok::eof));
695 void GeneratePTHAction::ExecuteAction() {
696 CompilerInstance &CI = getCompilerInstance();
697 std::unique_ptr<raw_pwrite_stream> OS =
698 CI.createDefaultOutputFile(true, getCurrentFile());
702 CacheTokens(CI.getPreprocessor(), OS.get());
705 void PreprocessOnlyAction::ExecuteAction() {
706 Preprocessor &PP = getCompilerInstance().getPreprocessor();
708 // Ignore unknown pragmas.
712 // Start parsing the specified input file.
713 PP.EnterMainSourceFile();
716 } while (Tok.isNot(tok::eof));
719 void PrintPreprocessedAction::ExecuteAction() {
720 CompilerInstance &CI = getCompilerInstance();
721 // Output file may need to be set to 'Binary', to avoid converting Unix style
722 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
724 // Look to see what type of line endings the file uses. If there's a
725 // CRLF, then we won't open the file up in binary mode. If there is
726 // just an LF or CR, then we will open the file up in binary mode.
727 // In this fashion, the output format should match the input format, unless
728 // the input format has inconsistent line endings.
730 // This should be a relatively fast operation since most files won't have
731 // all of their source code on a single line. However, that is still a
732 // concern, so if we scan for too long, we'll just assume the file should
733 // be opened in binary mode.
734 bool BinaryMode = true;
735 bool InvalidFile = false;
736 const SourceManager& SM = CI.getSourceManager();
737 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
740 const char *cur = Buffer->getBufferStart();
741 const char *end = Buffer->getBufferEnd();
742 const char *next = (cur != end) ? cur + 1 : end;
744 // Limit ourselves to only scanning 256 characters into the source
745 // file. This is mostly a sanity check in case the file has no
746 // newlines whatsoever.
747 if (end - cur > 256) end = cur + 256;
750 if (*cur == 0x0D) { // CR
751 if (*next == 0x0A) // CRLF
755 } else if (*cur == 0x0A) // LF
763 std::unique_ptr<raw_ostream> OS =
764 CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
767 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
768 CI.getPreprocessorOutputOpts());
771 void PrintPreambleAction::ExecuteAction() {
772 switch (getCurrentFileKind()) {
783 case IK_PreprocessedC:
784 case IK_PreprocessedCuda:
785 case IK_PreprocessedCXX:
786 case IK_PreprocessedObjC:
787 case IK_PreprocessedObjCXX:
790 case IK_RenderScript:
791 // We can't do anything with these.
795 CompilerInstance &CI = getCompilerInstance();
796 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
799 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
800 llvm::outs().write((*Buffer)->getBufferStart(), Preamble);