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