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