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/Utils.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/Pragma.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Parse/Parser.h"
22 #include "clang/Serialization/ASTReader.h"
23 #include "clang/Serialization/ASTWriter.h"
24 #include "llvm/ADT/OwningPtr.h"
25 #include "llvm/Support/FileSystem.h"
26 #include "llvm/Support/MemoryBuffer.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Support/system_error.h"
29 
30 using namespace clang;
31 
32 //===----------------------------------------------------------------------===//
33 // Custom Actions
34 //===----------------------------------------------------------------------===//
35 
36 ASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI,
37                                                StringRef InFile) {
38   return new ASTConsumer();
39 }
40 
41 void InitOnlyAction::ExecuteAction() {
42 }
43 
44 //===----------------------------------------------------------------------===//
45 // AST Consumer Actions
46 //===----------------------------------------------------------------------===//
47 
48 ASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI,
49                                                StringRef InFile) {
50   if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
51     return CreateASTPrinter(OS, CI.getFrontendOpts().ASTDumpFilter);
52   return 0;
53 }
54 
55 ASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI,
56                                               StringRef InFile) {
57   return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter);
58 }
59 
60 ASTConsumer *ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI,
61                                                   StringRef InFile) {
62   return CreateASTDeclNodeLister();
63 }
64 
65 ASTConsumer *ASTDumpXMLAction::CreateASTConsumer(CompilerInstance &CI,
66                                                  StringRef InFile) {
67   raw_ostream *OS;
68   if (CI.getFrontendOpts().OutputFile.empty())
69     OS = &llvm::outs();
70   else
71     OS = CI.createDefaultOutputFile(false, InFile);
72   if (!OS) return 0;
73   return CreateASTDumperXML(*OS);
74 }
75 
76 ASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI,
77                                               StringRef InFile) {
78   return CreateASTViewer();
79 }
80 
81 ASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
82                                                        StringRef InFile) {
83   return CreateDeclContextPrinter();
84 }
85 
86 ASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI,
87                                                   StringRef InFile) {
88   std::string Sysroot;
89   std::string OutputFile;
90   raw_ostream *OS = 0;
91   if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
92     return 0;
93 
94   if (!CI.getFrontendOpts().RelocatablePCH)
95     Sysroot.clear();
96   return new PCHGenerator(CI.getPreprocessor(), OutputFile, 0, Sysroot, OS);
97 }
98 
99 bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
100                                                     StringRef InFile,
101                                                     std::string &Sysroot,
102                                                     std::string &OutputFile,
103                                                     raw_ostream *&OS) {
104   Sysroot = CI.getHeaderSearchOpts().Sysroot;
105   if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
106     CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
107     return true;
108   }
109 
110   // We use createOutputFile here because this is exposed via libclang, and we
111   // must disable the RemoveFileOnSignal behavior.
112   // We use a temporary to avoid race conditions.
113   OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
114                            /*RemoveFileOnSignal=*/false, InFile,
115                            /*Extension=*/"", /*useTemporary=*/true);
116   if (!OS)
117     return true;
118 
119   OutputFile = CI.getFrontendOpts().OutputFile;
120   return false;
121 }
122 
123 ASTConsumer *GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
124                                                      StringRef InFile) {
125   std::string Sysroot;
126   std::string OutputFile;
127   raw_ostream *OS = 0;
128   if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
129     return 0;
130 
131   return new PCHGenerator(CI.getPreprocessor(), OutputFile, Module,
132                           Sysroot, OS);
133 }
134 
135 static SmallVectorImpl<char> &
136 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
137   Includes.append(RHS.begin(), RHS.end());
138   return Includes;
139 }
140 
141 static void addHeaderInclude(StringRef HeaderName,
142                              SmallVectorImpl<char> &Includes,
143                              const LangOptions &LangOpts) {
144   if (LangOpts.ObjC1)
145     Includes += "#import \"";
146   else
147     Includes += "#include \"";
148   Includes += HeaderName;
149   Includes += "\"\n";
150 }
151 
152 static void addHeaderInclude(const FileEntry *Header,
153                              SmallVectorImpl<char> &Includes,
154                              const LangOptions &LangOpts) {
155   addHeaderInclude(Header->getName(), Includes, LangOpts);
156 }
157 
158 /// \brief Collect the set of header includes needed to construct the given
159 /// module and update the TopHeaders file set of the module.
160 ///
161 /// \param Module The module we're collecting includes from.
162 ///
163 /// \param Includes Will be augmented with the set of \#includes or \#imports
164 /// needed to load all of the named headers.
165 static void collectModuleHeaderIncludes(const LangOptions &LangOpts,
166                                         FileManager &FileMgr,
167                                         ModuleMap &ModMap,
168                                         clang::Module *Module,
169                                         SmallVectorImpl<char> &Includes) {
170   // Don't collect any headers for unavailable modules.
171   if (!Module->isAvailable())
172     return;
173 
174   // Add includes for each of these headers.
175   for (unsigned I = 0, N = Module->NormalHeaders.size(); I != N; ++I) {
176     const FileEntry *Header = Module->NormalHeaders[I];
177     Module->addTopHeader(Header);
178     addHeaderInclude(Header, Includes, LangOpts);
179   }
180   // Note that Module->PrivateHeaders will not be a TopHeader.
181 
182   if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
183     Module->addTopHeader(UmbrellaHeader);
184     if (Module->Parent) {
185       // Include the umbrella header for submodules.
186       addHeaderInclude(UmbrellaHeader, Includes, LangOpts);
187     }
188   } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
189     // Add all of the headers we find in this subdirectory.
190     llvm::error_code EC;
191     SmallString<128> DirNative;
192     llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
193     for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC),
194                                                      DirEnd;
195          Dir != DirEnd && !EC; Dir.increment(EC)) {
196       // Check whether this entry has an extension typically associated with
197       // headers.
198       if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
199           .Cases(".h", ".H", ".hh", ".hpp", true)
200           .Default(false))
201         continue;
202 
203       // If this header is marked 'unavailable' in this module, don't include
204       // it.
205       if (const FileEntry *Header = FileMgr.getFile(Dir->path())) {
206         if (ModMap.isHeaderInUnavailableModule(Header))
207           continue;
208         Module->addTopHeader(Header);
209       }
210 
211       // Include this header umbrella header for submodules.
212       addHeaderInclude(Dir->path(), Includes, LangOpts);
213     }
214   }
215 
216   // Recurse into submodules.
217   for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
218                                       SubEnd = Module->submodule_end();
219        Sub != SubEnd; ++Sub)
220     collectModuleHeaderIncludes(LangOpts, FileMgr, ModMap, *Sub, Includes);
221 }
222 
223 bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
224                                                  StringRef Filename) {
225   // Find the module map file.
226   const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
227   if (!ModuleMap)  {
228     CI.getDiagnostics().Report(diag::err_module_map_not_found)
229       << Filename;
230     return false;
231   }
232 
233   // Parse the module map file.
234   HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
235   if (HS.loadModuleMapFile(ModuleMap))
236     return false;
237 
238   if (CI.getLangOpts().CurrentModule.empty()) {
239     CI.getDiagnostics().Report(diag::err_missing_module_name);
240 
241     // FIXME: Eventually, we could consider asking whether there was just
242     // a single module described in the module map, and use that as a
243     // default. Then it would be fairly trivial to just "compile" a module
244     // map with a single module (the common case).
245     return false;
246   }
247 
248   // Dig out the module definition.
249   Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
250                            /*AllowSearch=*/false);
251   if (!Module) {
252     CI.getDiagnostics().Report(diag::err_missing_module)
253       << CI.getLangOpts().CurrentModule << Filename;
254 
255     return false;
256   }
257 
258   // Check whether we can build this module at all.
259   StringRef Feature;
260   if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Feature)) {
261     CI.getDiagnostics().Report(diag::err_module_unavailable)
262       << Module->getFullModuleName()
263       << Feature;
264 
265     return false;
266   }
267 
268   FileManager &FileMgr = CI.getFileManager();
269 
270   // Collect the set of #includes we need to build the module.
271   SmallString<256> HeaderContents;
272   if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
273     addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts());
274   collectModuleHeaderIncludes(CI.getLangOpts(), FileMgr,
275     CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(),
276     Module, HeaderContents);
277 
278   llvm::MemoryBuffer *InputBuffer =
279       llvm::MemoryBuffer::getMemBufferCopy(HeaderContents,
280                                            Module::getModuleInputBufferName());
281   // Ownership of InputBuffer will be transfered to the SourceManager.
282   setCurrentInput(FrontendInputFile(InputBuffer, getCurrentFileKind(),
283                                     Module->IsSystem));
284   return true;
285 }
286 
287 bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
288                                                        StringRef InFile,
289                                                        std::string &Sysroot,
290                                                        std::string &OutputFile,
291                                                        raw_ostream *&OS) {
292   // If no output file was provided, figure out where this module would go
293   // in the module cache.
294   if (CI.getFrontendOpts().OutputFile.empty()) {
295     HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
296     SmallString<256> ModuleFileName(HS.getModuleCachePath());
297     llvm::sys::path::append(ModuleFileName,
298                             CI.getLangOpts().CurrentModule + ".pcm");
299     CI.getFrontendOpts().OutputFile = ModuleFileName.str();
300   }
301 
302   // We use createOutputFile here because this is exposed via libclang, and we
303   // must disable the RemoveFileOnSignal behavior.
304   // We use a temporary to avoid race conditions.
305   OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
306                            /*RemoveFileOnSignal=*/false, InFile,
307                            /*Extension=*/"", /*useTemporary=*/true,
308                            /*CreateMissingDirectories=*/true);
309   if (!OS)
310     return true;
311 
312   OutputFile = CI.getFrontendOpts().OutputFile;
313   return false;
314 }
315 
316 ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,
317                                                  StringRef InFile) {
318   return new ASTConsumer();
319 }
320 
321 ASTConsumer *DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI,
322                                                      StringRef InFile) {
323   return new ASTConsumer();
324 }
325 
326 namespace {
327   /// \brief AST reader listener that dumps module information for a module
328   /// file.
329   class DumpModuleInfoListener : public ASTReaderListener {
330     llvm::raw_ostream &Out;
331 
332   public:
333     DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { }
334 
335 #define DUMP_BOOLEAN(Value, Text)                       \
336     Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n"
337 
338     virtual bool ReadFullVersionInformation(StringRef FullVersion) {
339       Out.indent(2)
340         << "Generated by "
341         << (FullVersion == getClangFullRepositoryVersion()? "this"
342                                                           : "a different")
343         << " Clang: " << FullVersion << "\n";
344       return ASTReaderListener::ReadFullVersionInformation(FullVersion);
345     }
346 
347     virtual bool ReadLanguageOptions(const LangOptions &LangOpts,
348                                      bool Complain) {
349       Out.indent(2) << "Language options:\n";
350 #define LANGOPT(Name, Bits, Default, Description) \
351       DUMP_BOOLEAN(LangOpts.Name, Description);
352 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
353       Out.indent(4) << Description << ": "                   \
354                     << static_cast<unsigned>(LangOpts.get##Name()) << "\n";
355 #define VALUE_LANGOPT(Name, Bits, Default, Description) \
356       Out.indent(4) << Description << ": " << LangOpts.Name << "\n";
357 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
358 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
359 #include "clang/Basic/LangOptions.def"
360       return false;
361     }
362 
363     virtual bool ReadTargetOptions(const TargetOptions &TargetOpts,
364                                    bool Complain) {
365       Out.indent(2) << "Target options:\n";
366       Out.indent(4) << "  Triple: " << TargetOpts.Triple << "\n";
367       Out.indent(4) << "  CPU: " << TargetOpts.CPU << "\n";
368       Out.indent(4) << "  ABI: " << TargetOpts.ABI << "\n";
369       Out.indent(4) << "  C++ ABI: " << TargetOpts.CXXABI << "\n";
370       Out.indent(4) << "  Linker version: " << TargetOpts.LinkerVersion << "\n";
371 
372       if (!TargetOpts.FeaturesAsWritten.empty()) {
373         Out.indent(4) << "Target features:\n";
374         for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size();
375              I != N; ++I) {
376           Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n";
377         }
378       }
379 
380       return false;
381     }
382 
383     virtual bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
384                                          bool Complain) {
385       Out.indent(2) << "Header search options:\n";
386       Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n";
387       DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes,
388                    "Use builtin include directories [-nobuiltininc]");
389       DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes,
390                    "Use standard system include directories [-nostdinc]");
391       DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes,
392                    "Use standard C++ include directories [-nostdinc++]");
393       DUMP_BOOLEAN(HSOpts.UseLibcxx,
394                    "Use libc++ (rather than libstdc++) [-stdlib=]");
395       return false;
396     }
397 
398     virtual bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
399                                          bool Complain,
400                                          std::string &SuggestedPredefines) {
401       Out.indent(2) << "Preprocessor options:\n";
402       DUMP_BOOLEAN(PPOpts.UsePredefines,
403                    "Uses compiler/target-specific predefines [-undef]");
404       DUMP_BOOLEAN(PPOpts.DetailedRecord,
405                    "Uses detailed preprocessing record (for indexing)");
406 
407       if (!PPOpts.Macros.empty()) {
408         Out.indent(4) << "Predefined macros:\n";
409       }
410 
411       for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
412              I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end();
413            I != IEnd; ++I) {
414         Out.indent(6);
415         if (I->second)
416           Out << "-U";
417         else
418           Out << "-D";
419         Out << I->first << "\n";
420       }
421       return false;
422     }
423 #undef DUMP_BOOLEAN
424   };
425 }
426 
427 void DumpModuleInfoAction::ExecuteAction() {
428   // Set up the output file.
429   llvm::OwningPtr<llvm::raw_fd_ostream> OutFile;
430   StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile;
431   if (!OutputFileName.empty() && OutputFileName != "-") {
432     std::string ErrorInfo;
433     OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str().c_str(),
434                                            ErrorInfo));
435   }
436   llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs();
437 
438   Out << "Information for module file '" << getCurrentFile() << "':\n";
439   DumpModuleInfoListener Listener(Out);
440   ASTReader::readASTFileControlBlock(getCurrentFile(),
441                                      getCompilerInstance().getFileManager(),
442                                      Listener);
443 }
444 
445 //===----------------------------------------------------------------------===//
446 // Preprocessor Actions
447 //===----------------------------------------------------------------------===//
448 
449 void DumpRawTokensAction::ExecuteAction() {
450   Preprocessor &PP = getCompilerInstance().getPreprocessor();
451   SourceManager &SM = PP.getSourceManager();
452 
453   // Start lexing the specified input file.
454   const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
455   Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
456   RawLex.SetKeepWhitespaceMode(true);
457 
458   Token RawTok;
459   RawLex.LexFromRawLexer(RawTok);
460   while (RawTok.isNot(tok::eof)) {
461     PP.DumpToken(RawTok, true);
462     llvm::errs() << "\n";
463     RawLex.LexFromRawLexer(RawTok);
464   }
465 }
466 
467 void DumpTokensAction::ExecuteAction() {
468   Preprocessor &PP = getCompilerInstance().getPreprocessor();
469   // Start preprocessing the specified input file.
470   Token Tok;
471   PP.EnterMainSourceFile();
472   do {
473     PP.Lex(Tok);
474     PP.DumpToken(Tok, true);
475     llvm::errs() << "\n";
476   } while (Tok.isNot(tok::eof));
477 }
478 
479 void GeneratePTHAction::ExecuteAction() {
480   CompilerInstance &CI = getCompilerInstance();
481   if (CI.getFrontendOpts().OutputFile.empty() ||
482       CI.getFrontendOpts().OutputFile == "-") {
483     // FIXME: Don't fail this way.
484     // FIXME: Verify that we can actually seek in the given file.
485     llvm::report_fatal_error("PTH requires a seekable file for output!");
486   }
487   llvm::raw_fd_ostream *OS =
488     CI.createDefaultOutputFile(true, getCurrentFile());
489   if (!OS) return;
490 
491   CacheTokens(CI.getPreprocessor(), OS);
492 }
493 
494 void PreprocessOnlyAction::ExecuteAction() {
495   Preprocessor &PP = getCompilerInstance().getPreprocessor();
496 
497   // Ignore unknown pragmas.
498   PP.AddPragmaHandler(new EmptyPragmaHandler());
499 
500   Token Tok;
501   // Start parsing the specified input file.
502   PP.EnterMainSourceFile();
503   do {
504     PP.Lex(Tok);
505   } while (Tok.isNot(tok::eof));
506 }
507 
508 void PrintPreprocessedAction::ExecuteAction() {
509   CompilerInstance &CI = getCompilerInstance();
510   // Output file may need to be set to 'Binary', to avoid converting Unix style
511   // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
512   //
513   // Look to see what type of line endings the file uses. If there's a
514   // CRLF, then we won't open the file up in binary mode. If there is
515   // just an LF or CR, then we will open the file up in binary mode.
516   // In this fashion, the output format should match the input format, unless
517   // the input format has inconsistent line endings.
518   //
519   // This should be a relatively fast operation since most files won't have
520   // all of their source code on a single line. However, that is still a
521   // concern, so if we scan for too long, we'll just assume the file should
522   // be opened in binary mode.
523   bool BinaryMode = true;
524   bool InvalidFile = false;
525   const SourceManager& SM = CI.getSourceManager();
526   const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
527                                                      &InvalidFile);
528   if (!InvalidFile) {
529     const char *cur = Buffer->getBufferStart();
530     const char *end = Buffer->getBufferEnd();
531     const char *next = (cur != end) ? cur + 1 : end;
532 
533     // Limit ourselves to only scanning 256 characters into the source
534     // file.  This is mostly a sanity check in case the file has no
535     // newlines whatsoever.
536     if (end - cur > 256) end = cur + 256;
537 
538     while (next < end) {
539       if (*cur == 0x0D) {  // CR
540         if (*next == 0x0A)  // CRLF
541           BinaryMode = false;
542 
543         break;
544       } else if (*cur == 0x0A)  // LF
545         break;
546 
547       ++cur, ++next;
548     }
549   }
550 
551   raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
552   if (!OS) return;
553 
554   DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
555                            CI.getPreprocessorOutputOpts());
556 }
557 
558 void PrintPreambleAction::ExecuteAction() {
559   switch (getCurrentFileKind()) {
560   case IK_C:
561   case IK_CXX:
562   case IK_ObjC:
563   case IK_ObjCXX:
564   case IK_OpenCL:
565   case IK_CUDA:
566     break;
567 
568   case IK_None:
569   case IK_Asm:
570   case IK_PreprocessedC:
571   case IK_PreprocessedCXX:
572   case IK_PreprocessedObjC:
573   case IK_PreprocessedObjCXX:
574   case IK_AST:
575   case IK_LLVM_IR:
576     // We can't do anything with these.
577     return;
578   }
579 
580   CompilerInstance &CI = getCompilerInstance();
581   llvm::MemoryBuffer *Buffer
582       = CI.getFileManager().getBufferForFile(getCurrentFile());
583   if (Buffer) {
584     unsigned Preamble = Lexer::ComputePreamble(Buffer, CI.getLangOpts()).first;
585     llvm::outs().write(Buffer->getBufferStart(), Preamble);
586     delete Buffer;
587   }
588 }
589