]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Frontend/FrontendActions.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304659, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Frontend / FrontendActions.cpp
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().ASTDumpAll,
61                          CI.getFrontendOpts().ASTDumpLookups);
62 }
63
64 std::unique_ptr<ASTConsumer>
65 ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
66   return CreateASTDeclNodeLister();
67 }
68
69 std::unique_ptr<ASTConsumer>
70 ASTViewAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
71   return CreateASTViewer();
72 }
73
74 std::unique_ptr<ASTConsumer>
75 DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
76                                           StringRef InFile) {
77   return CreateDeclContextPrinter();
78 }
79
80 std::unique_ptr<ASTConsumer>
81 GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
82   std::string Sysroot;
83   std::string OutputFile;
84   std::unique_ptr<raw_pwrite_stream> OS =
85       ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile);
86   if (!OS)
87     return nullptr;
88
89   if (!CI.getFrontendOpts().RelocatablePCH)
90     Sysroot.clear();
91
92   auto Buffer = std::make_shared<PCHBuffer>();
93   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
94   Consumers.push_back(llvm::make_unique<PCHGenerator>(
95                         CI.getPreprocessor(), OutputFile, Sysroot,
96                         Buffer, CI.getFrontendOpts().ModuleFileExtensions,
97       /*AllowASTWithErrors*/CI.getPreprocessorOpts().AllowPCHWithCompilerErrors,
98                         /*IncludeTimestamps*/
99                           +CI.getFrontendOpts().IncludeTimestamps));
100   Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
101       CI, InFile, OutputFile, std::move(OS), Buffer));
102
103   return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
104 }
105
106 std::unique_ptr<raw_pwrite_stream>
107 GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
108                                                StringRef InFile,
109                                                std::string &Sysroot,
110                                                std::string &OutputFile) {
111   Sysroot = CI.getHeaderSearchOpts().Sysroot;
112   if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
113     CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
114     return nullptr;
115   }
116
117   // We use createOutputFile here because this is exposed via libclang, and we
118   // must disable the RemoveFileOnSignal behavior.
119   // We use a temporary to avoid race conditions.
120   std::unique_ptr<raw_pwrite_stream> OS =
121       CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
122                           /*RemoveFileOnSignal=*/false, InFile,
123                           /*Extension=*/"", /*useTemporary=*/true);
124   if (!OS)
125     return nullptr;
126
127   OutputFile = CI.getFrontendOpts().OutputFile;
128   return OS;
129 }
130
131 bool GeneratePCHAction::shouldEraseOutputFiles() {
132   if (getCompilerInstance().getPreprocessorOpts().AllowPCHWithCompilerErrors)
133     return false;
134   return ASTFrontendAction::shouldEraseOutputFiles();
135 }
136
137 bool GeneratePCHAction::BeginSourceFileAction(CompilerInstance &CI,
138                                               StringRef Filename) {
139   CI.getLangOpts().CompilingPCH = true;
140   return true;
141 }
142
143 std::unique_ptr<ASTConsumer>
144 GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
145                                         StringRef InFile) {
146   std::unique_ptr<raw_pwrite_stream> OS = CreateOutputFile(CI, InFile);
147   if (!OS)
148     return nullptr;
149
150   std::string OutputFile = CI.getFrontendOpts().OutputFile;
151   std::string Sysroot;
152
153   auto Buffer = std::make_shared<PCHBuffer>();
154   std::vector<std::unique_ptr<ASTConsumer>> Consumers;
155
156   Consumers.push_back(llvm::make_unique<PCHGenerator>(
157                         CI.getPreprocessor(), OutputFile, Sysroot,
158                         Buffer, CI.getFrontendOpts().ModuleFileExtensions,
159                         /*AllowASTWithErrors=*/false,
160                         /*IncludeTimestamps=*/
161                           +CI.getFrontendOpts().BuildingImplicitModule));
162   Consumers.push_back(CI.getPCHContainerWriter().CreatePCHContainerGenerator(
163       CI, InFile, OutputFile, std::move(OS), Buffer));
164   return llvm::make_unique<MultiplexConsumer>(std::move(Consumers));
165 }
166
167 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction(
168     CompilerInstance &CI, StringRef Filename) {
169   return GenerateModuleAction::BeginSourceFileAction(CI, Filename);
170 }
171
172 std::unique_ptr<raw_pwrite_stream>
173 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI,
174                                                     StringRef InFile) {
175   // If no output file was provided, figure out where this module would go
176   // in the module cache.
177   if (CI.getFrontendOpts().OutputFile.empty()) {
178     StringRef ModuleMapFile = CI.getFrontendOpts().OriginalModuleMap;
179     if (ModuleMapFile.empty())
180       ModuleMapFile = InFile;
181
182     HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
183     CI.getFrontendOpts().OutputFile =
184         HS.getModuleFileName(CI.getLangOpts().CurrentModule, ModuleMapFile,
185                              /*UsePrebuiltPath=*/false);
186   }
187
188   // We use createOutputFile here because this is exposed via libclang, and we
189   // must disable the RemoveFileOnSignal behavior.
190   // We use a temporary to avoid race conditions.
191   return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
192                              /*RemoveFileOnSignal=*/false, InFile,
193                              /*Extension=*/"", /*useTemporary=*/true,
194                              /*CreateMissingDirectories=*/true);
195 }
196
197 bool GenerateModuleInterfaceAction::BeginSourceFileAction(CompilerInstance &CI,
198                                                           StringRef Filename) {
199   if (!CI.getLangOpts().ModulesTS) {
200     CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts);
201     return false;
202   }
203
204   CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface);
205
206   return GenerateModuleAction::BeginSourceFileAction(CI, Filename);
207 }
208
209 std::unique_ptr<raw_pwrite_stream>
210 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
211                                                 StringRef InFile) {
212   return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm");
213 }
214
215 SyntaxOnlyAction::~SyntaxOnlyAction() {
216 }
217
218 std::unique_ptr<ASTConsumer>
219 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
220   return llvm::make_unique<ASTConsumer>();
221 }
222
223 std::unique_ptr<ASTConsumer>
224 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
225                                         StringRef InFile) {
226   return llvm::make_unique<ASTConsumer>();
227 }
228
229 std::unique_ptr<ASTConsumer>
230 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) {
231   return llvm::make_unique<ASTConsumer>();
232 }
233
234 void VerifyPCHAction::ExecuteAction() {
235   CompilerInstance &CI = getCompilerInstance();
236   bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0;
237   const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot;
238   std::unique_ptr<ASTReader> Reader(new ASTReader(
239       CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(),
240       CI.getFrontendOpts().ModuleFileExtensions,
241       Sysroot.empty() ? "" : Sysroot.c_str(),
242       /*DisableValidation*/ false,
243       /*AllowPCHWithCompilerErrors*/ false,
244       /*AllowConfigurationMismatch*/ true,
245       /*ValidateSystemInputs*/ true));
246
247   Reader->ReadAST(getCurrentFile(),
248                   Preamble ? serialization::MK_Preamble
249                            : serialization::MK_PCH,
250                   SourceLocation(),
251                   ASTReader::ARR_ConfigurationMismatch);
252 }
253
254 namespace {
255   /// \brief AST reader listener that dumps module information for a module
256   /// file.
257   class DumpModuleInfoListener : public ASTReaderListener {
258     llvm::raw_ostream &Out;
259
260   public:
261     DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
262
263 #define DUMP_BOOLEAN(Value, Text)                       \
264     Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
265
266     bool ReadFullVersionInformation(StringRef FullVersion) override {
267       Out.indent(2)
268         << "Generated by "
269         << (FullVersion == getClangFullRepositoryVersion()? "this"
270                                                           : "a different")
271         << " Clang: " << FullVersion << "\n";
272       return ASTReaderListener::ReadFullVersionInformation(FullVersion);
273     }
274
275     void ReadModuleName(StringRef ModuleName) override {
276       Out.indent(2) << "Module name: " << ModuleName << "\n";
277     }
278     void ReadModuleMapFile(StringRef ModuleMapPath) override {
279       Out.indent(2) << "Module map file: " << ModuleMapPath << "\n";
280     }
281
282     bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
283                              bool AllowCompatibleDifferences) override {
284       Out.indent(2) << "Language options:\n";
285 #define LANGOPT(Name, Bits, Default, Description) \
286       DUMP_BOOLEAN(LangOpts.Name, Description);
287 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
288       Out.indent(4) << Description << ": "                   \
289                     << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
290 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
291       Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
292 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
293 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
294 #include "clang/Basic/LangOptions.def"
295
296       if (!LangOpts.ModuleFeatures.empty()) {
297         Out.indent(4) << "Module features:\n";
298         for (StringRef Feature : LangOpts.ModuleFeatures)
299           Out.indent(6) << Feature << "\n";
300       }
301
302       return false;
303     }
304
305     bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
306                            bool AllowCompatibleDifferences) override {
307       Out.indent(2) << "Target options:\n";
308       Out.indent(4) << "  Triple: " << TargetOpts.Triple << "\n";
309       Out.indent(4) << "  CPU: " << TargetOpts.CPU << "\n";
310       Out.indent(4) << "  ABI: " << TargetOpts.ABI << "\n";
311
312       if (!TargetOpts.FeaturesAsWritten.empty()) {
313         Out.indent(4) << "Target features:\n";
314         for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
315              I != N; ++I) {
316           Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
317         }
318       }
319
320       return false;
321     }
322
323     bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
324                                bool Complain) override {
325       Out.indent(2) << "Diagnostic options:\n";
326 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name);
327 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
328       Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n";
329 #define VALUE_DIAGOPT(Name, Bits, Default) \
330       Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n";
331 #include "clang/Basic/DiagnosticOptions.def"
332
333       Out.indent(4) << "Diagnostic flags:\n";
334       for (const std::string &Warning : DiagOpts->Warnings)
335         Out.indent(6) << "-W" << Warning << "\n";
336       for (const std::string &Remark : DiagOpts->Remarks)
337         Out.indent(6) << "-R" << Remark << "\n";
338
339       return false;
340     }
341
342     bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
343                                  StringRef SpecificModuleCachePath,
344                                  bool Complain) override {
345       Out.indent(2) << "Header search options:\n";
346       Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
347       Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n";
348       Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n";
349       DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
350                    "Use builtin include directories [-nobuiltininc]");
351       DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
352                    "Use standard system include directories [-nostdinc]");
353       DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
354                    "Use standard C++ include directories [-nostdinc++]");
355       DUMP_BOOLEAN(HSOpts.UseLibcxx,
356                    "Use libc++ (rather than libstdc++) [-stdlib=]");
357       return false;
358     }
359
360     bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
361                                  bool Complain,
362                                  std::string &SuggestedPredefines) override {
363       Out.indent(2) << "Preprocessor options:\n";
364       DUMP_BOOLEAN(PPOpts.UsePredefines,
365                    "Uses compiler/target-specific predefines [-undef]");
366       DUMP_BOOLEAN(PPOpts.DetailedRecord,
367                    "Uses detailed preprocessing record (for indexing)");
368
369       if (!PPOpts.Macros.empty()) {
370         Out.indent(4) << "Predefined macros:\n";
371       }
372
373       for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
374              I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
375            I != IEnd; ++I) {
376         Out.indent(6);
377         if (I->second)
378           Out << "-U";
379         else
380           Out << "-D";
381         Out << I->first << "\n";
382       }
383       return false;
384     }
385
386     /// Indicates that a particular module file extension has been read.
387     void readModuleFileExtension(
388            const ModuleFileExtensionMetadata &Metadata) override {
389       Out.indent(2) << "Module file extension '"
390                     << Metadata.BlockName << "' " << Metadata.MajorVersion
391                     << "." << Metadata.MinorVersion;
392       if (!Metadata.UserInfo.empty()) {
393         Out << ": ";
394         Out.write_escaped(Metadata.UserInfo);
395       }
396
397       Out << "\n";
398     }
399 #undef DUMP_BOOLEAN
400   };
401 }
402
403 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) {
404   // The Object file reader also supports raw ast files and there is no point in
405   // being strict about the module file format in -module-file-info mode.
406   CI.getHeaderSearchOpts().ModuleFormat = "obj";
407   return true;
408 }
409
410 void DumpModuleInfoAction::ExecuteAction() {
411   // Set up the output file.
412   std::unique_ptr<llvm::raw_fd_ostream> OutFile;
413   StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
414   if (!OutputFileName.empty() && OutputFileName != "-") {
415     std::error_code EC;
416     OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC,
417                                            llvm::sys::fs::F_Text));
418   }
419   llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
420
421   Out << "Information for module file '" << getCurrentFile() << "':\n";
422   auto &FileMgr = getCompilerInstance().getFileManager();
423   auto Buffer = FileMgr.getBufferForFile(getCurrentFile());
424   StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer();
425   bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' &&
426                 Magic[2] == 'C' && Magic[3] == 'H');
427   Out << "  Module format: " << (IsRaw ? "raw" : "obj") << "\n";
428
429   Preprocessor &PP = getCompilerInstance().getPreprocessor();
430   DumpModuleInfoListener Listener(Out);
431   HeaderSearchOptions &HSOpts =
432       PP.getHeaderSearchInfo().getHeaderSearchOpts();
433   ASTReader::readASTFileControlBlock(
434       getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(),
435       /*FindModuleFileExtensions=*/true, Listener,
436       HSOpts.ModulesValidateDiagnosticOptions);
437 }
438
439 //===----------------------------------------------------------------------===//
440 // Preprocessor Actions
441 //===----------------------------------------------------------------------===//
442
443 void DumpRawTokensAction::ExecuteAction() {
444   Preprocessor &PP = getCompilerInstance().getPreprocessor();
445   SourceManager &SM = PP.getSourceManager();
446
447   // Start lexing the specified input file.
448   const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
449   Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
450   RawLex.SetKeepWhitespaceMode(true);
451
452   Token RawTok;
453   RawLex.LexFromRawLexer(RawTok);
454   while (RawTok.isNot(tok::eof)) {
455     PP.DumpToken(RawTok, true);
456     llvm::errs() << "\n";
457     RawLex.LexFromRawLexer(RawTok);
458   }
459 }
460
461 void DumpTokensAction::ExecuteAction() {
462   Preprocessor &PP = getCompilerInstance().getPreprocessor();
463   // Start preprocessing the specified input file.
464   Token Tok;
465   PP.EnterMainSourceFile();
466   do {
467     PP.Lex(Tok);
468     PP.DumpToken(Tok, true);
469     llvm::errs() << "\n";
470   } while (Tok.isNot(tok::eof));
471 }
472
473 void GeneratePTHAction::ExecuteAction() {
474   CompilerInstance &CI = getCompilerInstance();
475   std::unique_ptr<raw_pwrite_stream> OS =
476       CI.createDefaultOutputFile(true, getCurrentFile());
477   if (!OS)
478     return;
479
480   CacheTokens(CI.getPreprocessor(), OS.get());
481 }
482
483 void PreprocessOnlyAction::ExecuteAction() {
484   Preprocessor &PP = getCompilerInstance().getPreprocessor();
485
486   // Ignore unknown pragmas.
487   PP.IgnorePragmas();
488
489   Token Tok;
490   // Start parsing the specified input file.
491   PP.EnterMainSourceFile();
492   do {
493     PP.Lex(Tok);
494   } while (Tok.isNot(tok::eof));
495 }
496
497 void PrintPreprocessedAction::ExecuteAction() {
498   CompilerInstance &CI = getCompilerInstance();
499   // Output file may need to be set to 'Binary', to avoid converting Unix style
500   // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
501   //
502   // Look to see what type of line endings the file uses. If there's a
503   // CRLF, then we won't open the file up in binary mode. If there is
504   // just an LF or CR, then we will open the file up in binary mode.
505   // In this fashion, the output format should match the input format, unless
506   // the input format has inconsistent line endings.
507   //
508   // This should be a relatively fast operation since most files won't have
509   // all of their source code on a single line. However, that is still a 
510   // concern, so if we scan for too long, we'll just assume the file should
511   // be opened in binary mode.
512   bool BinaryMode = true;
513   bool InvalidFile = false;
514   const SourceManager& SM = CI.getSourceManager();
515   const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(), 
516                                                      &InvalidFile);
517   if (!InvalidFile) {
518     const char *cur = Buffer->getBufferStart();
519     const char *end = Buffer->getBufferEnd();
520     const char *next = (cur != end) ? cur + 1 : end;
521
522     // Limit ourselves to only scanning 256 characters into the source
523     // file.  This is mostly a sanity check in case the file has no 
524     // newlines whatsoever.
525     if (end - cur > 256) end = cur + 256;
526           
527     while (next < end) {
528       if (*cur == 0x0D) {  // CR
529         if (*next == 0x0A)  // CRLF
530           BinaryMode = false;
531
532         break;
533       } else if (*cur == 0x0A)  // LF
534         break;
535
536       ++cur;
537       ++next;
538     }
539   }
540
541   std::unique_ptr<raw_ostream> OS =
542       CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
543   if (!OS) return;
544
545   // If we're preprocessing a module map, start by dumping the contents of the
546   // module itself before switching to the input buffer.
547   auto &Input = getCurrentInput();
548   if (Input.getKind().getFormat() == InputKind::ModuleMap) {
549     if (Input.isFile()) {
550       (*OS) << "# 1 \"";
551       OS->write_escaped(Input.getFile());
552       (*OS) << "\"\n";
553     }
554     // FIXME: Include additional information here so that we don't need the
555     // original source files to exist on disk.
556     getCurrentModule()->print(*OS);
557     (*OS) << "#pragma clang module contents\n";
558   }
559
560   DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(),
561                            CI.getPreprocessorOutputOpts());
562 }
563
564 void PrintPreambleAction::ExecuteAction() {
565   switch (getCurrentFileKind().getLanguage()) {
566   case InputKind::C:
567   case InputKind::CXX:
568   case InputKind::ObjC:
569   case InputKind::ObjCXX:
570   case InputKind::OpenCL:
571   case InputKind::CUDA:
572     break;
573       
574   case InputKind::Unknown:
575   case InputKind::Asm:
576   case InputKind::LLVM_IR:
577   case InputKind::RenderScript:
578     // We can't do anything with these.
579     return;
580   }
581
582   // We don't expect to find any #include directives in a preprocessed input.
583   if (getCurrentFileKind().isPreprocessed())
584     return;
585
586   CompilerInstance &CI = getCompilerInstance();
587   auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile());
588   if (Buffer) {
589     unsigned Preamble =
590         Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first;
591     llvm::outs().write((*Buffer)->getBufferStart(), Preamble);
592   }
593 }