1 //===--- 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"
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"
27 #include <memory>
28 #include <system_error>
29 
30 using namespace clang;
31 
32 //===----------------------------------------------------------------------===//
33 // Custom Actions
34 //===----------------------------------------------------------------------===//
35 
36 std::unique_ptr<ASTConsumer>
37 InitOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
38   return llvm::make_unique<ASTConsumer>();
39 }
40 
41 void InitOnlyAction::ExecuteAction() {
42 }
43 
44 //===----------------------------------------------------------------------===//
45 // AST Consumer Actions
46 //===----------------------------------------------------------------------===//
47 
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);
53   return nullptr;
54 }
55 
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);
61 }
62 
63 std::unique_ptr<ASTConsumer>
64 ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
65   return CreateASTDeclNodeLister();
66 }
67 
68 std::unique_ptr<ASTConsumer>
69 ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
70   return CreateASTViewer();
71 }
72 
73 std::unique_ptr<ASTConsumer>
74 DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
75                                           StringRef InFile) {
76   return CreateDeclContextPrinter();
77 }
78 
79 std::unique_ptr<ASTConsumer>
80 GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
81   std::string Sysroot;
82   std::string OutputFile;
83   std::unique_ptr<raw_pwrite_stream> OS =
84       ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
85   if (!OS)
86     return nullptr;
87 
88   if (!CI.getFrontendOpts().RelocatablePCH)
89     Sysroot.clear();
90 
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*/CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
97                         /*IncludeTimestamps*/
98                           +CI.getFrontendOpts().IncludeTimestamps));
99   Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
100       CI, InFile, OutputFile, std::move(OS), Buffer));
101 
102   return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
103 }
104 
105 std::unique_ptr<raw_pwrite_stream>
106 GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
107                                                StringRef InFile,
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);
113     return nullptr;
114   }
115 
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);
123   if (!OS)
124     return nullptr;
125 
126   OutputFile = CI.getFrontendOpts().OutputFile;
127   return OS;
128 }
129 
130 bool GeneratePCHAction::shouldEraseOutputFiles() {
131   if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
132     return false;
133   return ASTFrontendAction::shouldEraseOutputFiles();
134 }
135 
136 bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI,
137                                               StringRef Filename) {
138   CI.getLangOpts().CompilingPCH = true;
139   return true;
140 }
141 
142 std::unique_ptr<ASTConsumer>
143 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
144                                         StringRef InFile) {
145   std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
146   if (!OS)
147     return nullptr;
148 
149   std::string OutputFile = CI.getFrontendOpts().OutputFile;
150   std::string Sysroot;
151 
152   auto Buffer = std::make_shared<PCHBuffer>();
153   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
154 
155   Consumers.push_back(llvm::make_unique<PCHGenerator>(
156                         CI.getPreprocessor(), OutputFile, Sysroot,
157                         Buffer, CI.getFrontendOpts().ModuleFileExtensions,
158                         /*AllowASTWithErrors=*/false,
159                         /*IncludeTimestamps=*/
160                           +CI.getFrontendOpts().BuildingImplicitModule));
161   Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
162       CI, InFile, OutputFile, std::move(OS), Buffer));
163   return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
164 }
165 
166 bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
167                                                  StringRef Filename) {
168   // Set up embedding for any specified files. Do this before we load any
169   // source files, including the primary module map for the compilation.
170   for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) {
171     if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true))
172       CI.getSourceManager().setFileIsTransient(FE);
173     else
174       CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F;
175   }
176   if (CI.getFrontendOpts().ModulesEmbedAllFiles)
177     CI.getSourceManager().setAllFilesAreTransient(true);
178 
179   return true;
180 }
181 
182 
183 static SmallVectorImpl<char> &
184 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
185   Includes.append(RHS.begin(), RHS.end());
186   return Includes;
187 }
188 
189 static void addHeaderInclude(StringRef HeaderName,
190                              SmallVectorImpl<char> &Includes,
191                              const LangOptions &LangOpts,
192                              bool IsExternC) {
193   if (IsExternC && LangOpts.CPlusPlus)
194     Includes += "extern \"C\" {\n";
195   if (LangOpts.ObjC1)
196     Includes += "#import \"";
197   else
198     Includes += "#include \"";
199 
200   Includes += HeaderName;
201 
202   Includes += "\"\n";
203   if (IsExternC && LangOpts.CPlusPlus)
204     Includes += "}\n";
205 }
206 
207 /// \brief Collect the set of header includes needed to construct the given
208 /// module and update the TopHeaders file set of the module.
209 ///
210 /// \param Module The module we're collecting includes from.
211 ///
212 /// \param Includes Will be augmented with the set of \#includes or \#imports
213 /// needed to load all of the named headers.
214 static std::error_code
215 collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr,
216                             ModuleMap &ModMap, clang::Module *Module,
217                             SmallVectorImpl<char> &Includes) {
218   // Don't collect any headers for unavailable modules.
219   if (!Module->isAvailable())
220     return std::error_code();
221 
222   // Add includes for each of these headers.
223   for (auto HK : {Module::HK_Normal, Module::HK_Private}) {
224     for (Module::Header &H : Module->Headers[HK]) {
225       Module->addTopHeader(H.Entry);
226       // Use the path as specified in the module map file. We'll look for this
227       // file relative to the module build directory (the directory containing
228       // the module map file) so this will find the same file that we found
229       // while parsing the module map.
230       addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC);
231     }
232   }
233   // Note that Module->PrivateHeaders will not be a TopHeader.
234 
235   if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) {
236     Module->addTopHeader(UmbrellaHeader.Entry);
237     if (Module->Parent)
238       // Include the umbrella header for submodules.
239       addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts,
240                        Module->IsExternC);
241   } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) {
242     // Add all of the headers we find in this subdirectory.
243     std::error_code EC;
244     SmallString<128> DirNative;
245     llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative);
246 
247     vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
248     for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End;
249          Dir != End && !EC; Dir.increment(EC)) {
250       // Check whether this entry has an extension typically associated with
251       // headers.
252       if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName()))
253           .Cases(".h", ".H", ".hh", ".hpp", true)
254           .Default(false))
255         continue;
256 
257       const FileEntry *Header = FileMgr.getFile(Dir->getName());
258       // FIXME: This shouldn't happen unless there is a file system race. Is
259       // that worth diagnosing?
260       if (!Header)
261         continue;
262 
263       // If this header is marked 'unavailable' in this module, don't include
264       // it.
265       if (ModMap.isHeaderUnavailableInModule(Header, Module))
266         continue;
267 
268       // Compute the relative path from the directory to this file.
269       SmallVector<StringRef, 16> Components;
270       auto PathIt = llvm::sys::path::rbegin(Dir->getName());
271       for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt)
272         Components.push_back(*PathIt);
273       SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten);
274       for (auto It = Components.rbegin(), End = Components.rend(); It != End;
275            ++It)
276         llvm::sys::path::append(RelativeHeader, *It);
277 
278       // Include this header as part of the umbrella directory.
279       Module->addTopHeader(Header);
280       addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC);
281     }
282 
283     if (EC)
284       return EC;
285   }
286 
287   // Recurse into submodules.
288   for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
289                                       SubEnd = Module->submodule_end();
290        Sub != SubEnd; ++Sub)
291     if (std::error_code Err = collectModuleHeaderIncludes(
292             LangOpts, FileMgr, ModMap, *Sub, Includes))
293       return Err;
294 
295   return std::error_code();
296 }
297 
298 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
299     CompilerInstance &CI, StringRef Filename) {
300   CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap);
301 
302   if (!GenerateModuleAction::BeginSourceFileAction(CI, Filename))
303     return false;
304 
305   // Find the module map file.
306   const FileEntry *ModuleMap =
307       CI.getFileManager().getFile(Filename, /*openFile*/true);
308   if (!ModuleMap)  {
309     CI.getDiagnostics().Report(diag::err_module_map_not_found)
310       << Filename;
311     return false;
312   }
313 
314   // Parse the module map file.
315   HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
316   if (HS.loadModuleMapFile(ModuleMap, IsSystem))
317     return false;
318 
319   if (CI.getLangOpts().CurrentModule.empty()) {
320     CI.getDiagnostics().Report(diag::err_missing_module_name);
321 
322     // FIXME: Eventually, we could consider asking whether there was just
323     // a single module described in the module map, and use that as a
324     // default. Then it would be fairly trivial to just "compile" a module
325     // map with a single module (the common case).
326     return false;
327   }
328 
329   // If we're being run from the command-line, the module build stack will not
330   // have been filled in yet, so complete it now in order to allow us to detect
331   // module cycles.
332   SourceManager &SourceMgr = CI.getSourceManager();
333   if (SourceMgr.getModuleBuildStack().empty())
334     SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule,
335                                    FullSourceLoc(SourceLocation(), SourceMgr));
336 
337   // Dig out the module definition.
338   Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
339                            /*AllowSearch=*/false);
340   if (!Module) {
341     CI.getDiagnostics().Report(diag::err_missing_module)
342       << CI.getLangOpts().CurrentModule << Filename;
343 
344     return false;
345   }
346 
347   // Check whether we can build this module at all.
348   clang::Module::Requirement Requirement;
349   clang::Module::UnresolvedHeaderDirective MissingHeader;
350   if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement,
351                            MissingHeader)) {
352     if (MissingHeader.FileNameLoc.isValid()) {
353       CI.getDiagnostics().Report(MissingHeader.FileNameLoc,
354                                  diag::err_module_header_missing)
355         << MissingHeader.IsUmbrella << MissingHeader.FileName;
356     } else {
357       CI.getDiagnostics().Report(diag::err_module_unavailable)
358         << Module->getFullModuleName()
359         << Requirement.second << Requirement.first;
360     }
361 
362     return false;
363   }
364 
365   if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) {
366     Module->IsInferred = true;
367     HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing);
368   } else {
369     ModuleMapForUniquing = ModuleMap;
370   }
371 
372   FileManager &FileMgr = CI.getFileManager();
373 
374   // Collect the set of #includes we need to build the module.
375   SmallString<256> HeaderContents;
376   std::error_code Err = std::error_code();
377   if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader())
378     addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents,
379                      CI.getLangOpts(), Module->IsExternC);
380   Err = collectModuleHeaderIncludes(
381         CI.getLangOpts(), FileMgr,
382         CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module,
383         HeaderContents);
384 
385   if (Err) {
386     CI.getDiagnostics().Report(diag::err_module_cannot_create_includes)
387       << Module->getFullModuleName() << Err.message();
388     return false;
389   }
390 
391   // Inform the preprocessor that includes from within the input buffer should
392   // be resolved relative to the build directory of the module map file.
393   CI.getPreprocessor().setMainFileDir(Module->Directory);
394 
395   std::unique_ptr<llvm::MemoryBuffer> InputBuffer =
396       llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
397                                            Module::getModuleInputBufferName());
398   // Ownership of InputBuffer will be transferred to the SourceManager.
399   setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(),
400                                     Module->IsSystem));
401   return true;
402 }
403 
404 std::unique_ptr<raw_pwrite_stream>
405 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
406                                                     StringRef InFile) {
407   // If no output file was provided, figure out where this module would go
408   // in the module cache.
409   if (CI.getFrontendOpts().OutputFile.empty()) {
410     HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
411     CI.getFrontendOpts().OutputFile =
412         HS.getModuleFileName(CI.getLangOpts().CurrentModule,
413                              ModuleMapForUniquing->getName(),
414                              /*UsePrebuiltPath=*/false);
415   }
416 
417   // We use createOutputFile here because this is exposed via libclang, and we
418   // must disable the RemoveFileOnSignal behavior.
419   // We use a temporary to avoid race conditions.
420   return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
421                              /*RemoveFileOnSignal=*/false, InFile,
422                              /*Extension=*/"", /*useTemporary=*/true,
423                              /*CreateMissingDirectories=*/true);
424 }
425 
426 bool GenerateModuleInterfaceAction::BeginSourceFileAction(CompilerInstance &CI,
427                                                           StringRef Filename) {
428   if (!CI.getLangOpts().ModulesTS) {
429     CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
430     return false;
431   }
432 
433   CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
434 
435   return GenerateModuleAction::BeginSourceFileAction(CI, Filename);
436 }
437 
438 std::unique_ptr<raw_pwrite_stream>
439 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
440                                                 StringRef InFile) {
441   return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
442 }
443 
444 SyntaxOnlyAction::~SyntaxOnlyAction() {
445 }
446 
447 std::unique_ptr<ASTConsumer>
448 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
449   return llvm::make_unique<ASTConsumer>();
450 }
451 
452 std::unique_ptr<ASTConsumer>
453 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
454                                         StringRef InFile) {
455   return llvm::make_unique<ASTConsumer>();
456 }
457 
458 std::unique_ptr<ASTConsumer>
459 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
460   return llvm::make_unique<ASTConsumer>();
461 }
462 
463 void VerifyPCHAction::ExecuteAction() {
464   CompilerInstance &CI = getCompilerInstance();
465   bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
466   const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
467   std::unique_ptr<ASTReader> Reader(new ASTReader(
468       CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
469       CI.getFrontendOpts().ModuleFileExtensions,
470       Sysroot.empty() ? "" : Sysroot.c_str(),
471       /*DisableValidation*/ false,
472       /*AllowPCHWithCompilerErrors*/ false,
473       /*AllowConfigurationMismatch*/ true,
474       /*ValidateSystemInputs*/ true));
475 
476   Reader->ReadAST(getCurrentFile(),
477                   Preamble ? serialization::MK_Preamble
478                            : serialization::MK_PCH,
479                   SourceLocation(),
480                   ASTReader::ARR_ConfigurationMismatch);
481 }
482 
483 namespace {
484   /// \brief AST reader listener that dumps module information for a module
485   /// file.
486   class DumpModuleInfoListener : public ASTReaderListener {
487     llvm::raw_ostream &Out;
488 
489   public:
490     DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
491 
492 #define DUMP_BOOLEAN(Value, Text)                       \
493     Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
494 
495     bool ReadFullVersionInformation(StringRef FullVersion) override {
496       Out.indent(2)
497         << "Generated by "
498         << (FullVersion == getClangFullRepositoryVersion()? "this"
499                                                           : "a different")
500         << " Clang: " << FullVersion << "\n";
501       return ASTReaderListener::ReadFullVersionInformation(FullVersion);
502     }
503 
504     void ReadModuleName(StringRef ModuleName) override {
505       Out.indent(2) << "Module name: " << ModuleName << "\n";
506     }
507     void ReadModuleMapFile(StringRef ModuleMapPath) override {
508       Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
509     }
510 
511     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
512                              bool AllowCompatibleDifferences) override {
513       Out.indent(2) << "Language options:\n";
514 #define LANGOPT(Name, Bits, Default, Description) \
515       DUMP_BOOLEAN(LangOpts.Name, Description);
516 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
517       Out.indent(4) << Description << ": "                   \
518                     << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
519 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
520       Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
521 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
522 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
523 #include "clang/Basic/LangOptions.def"
524 
525       if (!LangOpts.ModuleFeatures.empty()) {
526         Out.indent(4) << "Module features:\n";
527         for (StringRef Feature : LangOpts.ModuleFeatures)
528           Out.indent(6) << Feature << "\n";
529       }
530 
531       return false;
532     }
533 
534     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
535                            bool AllowCompatibleDifferences) override {
536       Out.indent(2) << "Target options:\n";
537       Out.indent(4) << "  Triple: " << TargetOpts.Triple << "\n";
538       Out.indent(4) << "  CPU: " << TargetOpts.CPU << "\n";
539       Out.indent(4) << "  ABI: " << TargetOpts.ABI << "\n";
540 
541       if (!TargetOpts.FeaturesAsWritten.empty()) {
542         Out.indent(4) << "Target features:\n";
543         for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
544              I != N; ++I) {
545           Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
546         }
547       }
548 
549       return false;
550     }
551 
552     bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
553                                bool Complain) override {
554       Out.indent(2) << "Diagnostic options:\n";
555 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
556 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
557       Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
558 #define VALUE_DIAGOPT(Name, Bits, Default) \
559       Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
560 #include "clang/Basic/DiagnosticOptions.def"
561 
562       Out.indent(4) << "Diagnostic flags:\n";
563       for (const std::string &Warning : DiagOpts->Warnings)
564         Out.indent(6) << "-W" << Warning << "\n";
565       for (const std::string &Remark : DiagOpts->Remarks)
566         Out.indent(6) << "-R" << Remark << "\n";
567 
568       return false;
569     }
570 
571     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
572                                  StringRef SpecificModuleCachePath,
573                                  bool Complain) override {
574       Out.indent(2) << "Header search options:\n";
575       Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
576       Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
577       Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
578       DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
579                    "Use builtin include directories [-nobuiltininc]");
580       DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
581                    "Use standard system include directories [-nostdinc]");
582       DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
583                    "Use standard C++ include directories [-nostdinc++]");
584       DUMP_BOOLEAN(HSOpts.UseLibcxx,
585                    "Use libc++ (rather than libstdc++) [-stdlib=]");
586       return false;
587     }
588 
589     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
590                                  bool Complain,
591                                  std::string &SuggestedPredefines) override {
592       Out.indent(2) << "Preprocessor options:\n";
593       DUMP_BOOLEAN(PPOpts.UsePredefines,
594                    "Uses compiler/target-specific predefines [-undef]");
595       DUMP_BOOLEAN(PPOpts.DetailedRecord,
596                    "Uses detailed preprocessing record (for indexing)");
597 
598       if (!PPOpts.Macros.empty()) {
599         Out.indent(4) << "Predefined macros:\n";
600       }
601 
602       for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
603              I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
604            I != IEnd; ++I) {
605         Out.indent(6);
606         if (I->second)
607           Out << "-U";
608         else
609           Out << "-D";
610         Out << I->first << "\n";
611       }
612       return false;
613     }
614 
615     /// Indicates that a particular module file extension has been read.
616     void readModuleFileExtension(
617            const ModuleFileExtensionMetadata &Metadata) override {
618       Out.indent(2) << "Module file extension '"
619                     << Metadata.BlockName << "' " << Metadata.MajorVersion
620                     << "." << Metadata.MinorVersion;
621       if (!Metadata.UserInfo.empty()) {
622         Out << ": ";
623         Out.write_escaped(Metadata.UserInfo);
624       }
625 
626       Out << "\n";
627     }
628 #undef DUMP_BOOLEAN
629   };
630 }
631 
632 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
633   // The Object file reader also supports raw ast files and there is no point in
634   // being strict about the module file format in -module-file-info mode.
635   CI.getHeaderSearchOpts().ModuleFormat = "obj";
636   return true;
637 }
638 
639 void DumpModuleInfoAction::ExecuteAction() {
640   // Set up the output file.
641   std::unique_ptr<llvm::raw_fd_ostream> OutFile;
642   StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
643   if (!OutputFileName.empty() && OutputFileName != "-") {
644     std::error_code EC;
645     OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
646                                            llvm::sys::fs::F_Text));
647   }
648   llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
649 
650   Out << "Information for module file '" << getCurrentFile() << "':\n";
651   auto &FileMgr = getCompilerInstance().getFileManager();
652   auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
653   StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
654   bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
655                 Magic[2] == 'C' && Magic[3] == 'H');
656   Out << "  Module format: " << (IsRaw ? "raw" : "obj") << "\n";
657 
658   Preprocessor &PP = getCompilerInstance().getPreprocessor();
659   DumpModuleInfoListener Listener(Out);
660   HeaderSearchOptions &HSOpts =
661       PP.getHeaderSearchInfo().getHeaderSearchOpts();
662   ASTReader::readASTFileControlBlock(
663       getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
664       /*FindModuleFileExtensions=*/true, Listener,
665       HSOpts.ModulesValidateDiagnosticOptions);
666 }
667 
668 //===----------------------------------------------------------------------===//
669 // Preprocessor Actions
670 //===----------------------------------------------------------------------===//
671 
672 void DumpRawTokensAction::ExecuteAction() {
673   Preprocessor &PP = getCompilerInstance().getPreprocessor();
674   SourceManager &SM = PP.getSourceManager();
675 
676   // Start lexing the specified input file.
677   const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
678   Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
679   RawLex.SetKeepWhitespaceMode(true);
680 
681   Token RawTok;
682   RawLex.LexFromRawLexer(RawTok);
683   while (RawTok.isNot(tok::eof)) {
684     PP.DumpToken(RawTok, true);
685     llvm::errs() << "\n";
686     RawLex.LexFromRawLexer(RawTok);
687   }
688 }
689 
690 void DumpTokensAction::ExecuteAction() {
691   Preprocessor &PP = getCompilerInstance().getPreprocessor();
692   // Start preprocessing the specified input file.
693   Token Tok;
694   PP.EnterMainSourceFile();
695   do {
696     PP.Lex(Tok);
697     PP.DumpToken(Tok, true);
698     llvm::errs() << "\n";
699   } while (Tok.isNot(tok::eof));
700 }
701 
702 void GeneratePTHAction::ExecuteAction() {
703   CompilerInstance &CI = getCompilerInstance();
704   std::unique_ptr<raw_pwrite_stream> OS =
705       CI.createDefaultOutputFile(true, getCurrentFile());
706   if (!OS)
707     return;
708 
709   CacheTokens(CI.getPreprocessor(), OS.get());
710 }
711 
712 void PreprocessOnlyAction::ExecuteAction() {
713   Preprocessor &PP = getCompilerInstance().getPreprocessor();
714 
715   // Ignore unknown pragmas.
716   PP.IgnorePragmas();
717 
718   Token Tok;
719   // Start parsing the specified input file.
720   PP.EnterMainSourceFile();
721   do {
722     PP.Lex(Tok);
723   } while (Tok.isNot(tok::eof));
724 }
725 
726 void PrintPreprocessedAction::ExecuteAction() {
727   CompilerInstance &CI = getCompilerInstance();
728   // Output file may need to be set to 'Binary', to avoid converting Unix style
729   // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
730   //
731   // Look to see what type of line endings the file uses. If there's a
732   // CRLF, then we won't open the file up in binary mode. If there is
733   // just an LF or CR, then we will open the file up in binary mode.
734   // In this fashion, the output format should match the input format, unless
735   // the input format has inconsistent line endings.
736   //
737   // This should be a relatively fast operation since most files won't have
738   // all of their source code on a single line. However, that is still a
739   // concern, so if we scan for too long, we'll just assume the file should
740   // be opened in binary mode.
741   bool BinaryMode = true;
742   bool InvalidFile = false;
743   const SourceManager& SM = CI.getSourceManager();
744   const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
745                                                      &InvalidFile);
746   if (!InvalidFile) {
747     const char *cur = Buffer->getBufferStart();
748     const char *end = Buffer->getBufferEnd();
749     const char *next = (cur != end) ? cur + 1 : end;
750 
751     // Limit ourselves to only scanning 256 characters into the source
752     // file.  This is mostly a sanity check in case the file has no
753     // newlines whatsoever.
754     if (end - cur > 256) end = cur + 256;
755 
756     while (next < end) {
757       if (*cur == 0x0D) {  // CR
758         if (*next == 0x0A)  // CRLF
759           BinaryMode = false;
760 
761         break;
762       } else if (*cur == 0x0A)  // LF
763         break;
764 
765       ++cur;
766       ++next;
767     }
768   }
769 
770   std::unique_ptr<raw_ostream> OS =
771       CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
772   if (!OS) return;
773 
774   DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
775                            CI.getPreprocessorOutputOpts());
776 }
777 
778 void PrintPreambleAction::ExecuteAction() {
779   switch (getCurrentFileKind()) {
780   case IK_C:
781   case IK_CXX:
782   case IK_ObjC:
783   case IK_ObjCXX:
784   case IK_OpenCL:
785   case IK_CUDA:
786     break;
787 
788   case IK_None:
789   case IK_Asm:
790   case IK_PreprocessedC:
791   case IK_PreprocessedCuda:
792   case IK_PreprocessedCXX:
793   case IK_PreprocessedObjC:
794   case IK_PreprocessedObjCXX:
795   case IK_AST:
796   case IK_LLVM_IR:
797   case IK_RenderScript:
798     // We can't do anything with these.
799     return;
800   }
801 
802   CompilerInstance &CI = getCompilerInstance();
803   auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
804   if (Buffer) {
805     unsigned Preamble =
806         Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
807     llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
808   }
809 }
810