1 //===--- FrontendActions.cpp ----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "clang/Frontend/FrontendActions.h"
11 #include "clang/AST/ASTConsumer.h"
12 #include "clang/Lex/HeaderSearch.h"
13 #include "clang/Lex/Pragma.h"
14 #include "clang/Lex/Preprocessor.h"
15 #include "clang/Parse/Parser.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Frontend/ASTConsumers.h"
18 #include "clang/Frontend/ASTUnit.h"
19 #include "clang/Frontend/CompilerInstance.h"
20 #include "clang/Frontend/FrontendDiagnostic.h"
21 #include "clang/Frontend/Utils.h"
22 #include "clang/Serialization/ASTWriter.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/Support/FileSystem.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Support/system_error.h"
29 using namespace clang;
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
35 ASTConsumer *InitOnlyAction::CreateASTConsumer(CompilerInstance &CI,
37 return new ASTConsumer();
40 void InitOnlyAction::ExecuteAction() {
43 //===----------------------------------------------------------------------===//
44 // AST Consumer Actions
45 //===----------------------------------------------------------------------===//
47 ASTConsumer *ASTPrintAction::CreateASTConsumer(CompilerInstance &CI,
49 if (raw_ostream *OS = CI.createDefaultOutputFile(false, InFile))
50 return CreateASTPrinter(OS, CI.getFrontendOpts().ASTDumpFilter);
54 ASTConsumer *ASTDumpAction::CreateASTConsumer(CompilerInstance &CI,
56 return CreateASTDumper(CI.getFrontendOpts().ASTDumpFilter);
59 ASTConsumer *ASTDeclListAction::CreateASTConsumer(CompilerInstance &CI,
61 return CreateASTDeclNodeLister();
64 ASTConsumer *ASTDumpXMLAction::CreateASTConsumer(CompilerInstance &CI,
67 if (CI.getFrontendOpts().OutputFile.empty())
70 OS = CI.createDefaultOutputFile(false, InFile);
72 return CreateASTDumperXML(*OS);
75 ASTConsumer *ASTViewAction::CreateASTConsumer(CompilerInstance &CI,
77 return CreateASTViewer();
80 ASTConsumer *DeclContextPrintAction::CreateASTConsumer(CompilerInstance &CI,
82 return CreateDeclContextPrinter();
85 ASTConsumer *GeneratePCHAction::CreateASTConsumer(CompilerInstance &CI,
88 std::string OutputFile;
90 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
93 if (!CI.getFrontendOpts().RelocatablePCH)
95 return new PCHGenerator(CI.getPreprocessor(), OutputFile, 0, Sysroot, OS);
98 bool GeneratePCHAction::ComputeASTConsumerArguments(CompilerInstance &CI,
100 std::string &Sysroot,
101 std::string &OutputFile,
103 Sysroot = CI.getHeaderSearchOpts().Sysroot;
104 if (CI.getFrontendOpts().RelocatablePCH && Sysroot.empty()) {
105 CI.getDiagnostics().Report(diag::err_relocatable_without_isysroot);
109 // We use createOutputFile here because this is exposed via libclang, and we
110 // must disable the RemoveFileOnSignal behavior.
111 // We use a temporary to avoid race conditions.
112 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
113 /*RemoveFileOnSignal=*/false, InFile,
114 /*Extension=*/"", /*useTemporary=*/true);
118 OutputFile = CI.getFrontendOpts().OutputFile;
122 ASTConsumer *GenerateModuleAction::CreateASTConsumer(CompilerInstance &CI,
125 std::string OutputFile;
127 if (ComputeASTConsumerArguments(CI, InFile, Sysroot, OutputFile, OS))
130 return new PCHGenerator(CI.getPreprocessor(), OutputFile, Module,
134 static SmallVectorImpl<char> &
135 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) {
136 Includes.append(RHS.begin(), RHS.end());
140 static void addHeaderInclude(StringRef HeaderName,
141 SmallVectorImpl<char> &Includes,
142 const LangOptions &LangOpts) {
144 Includes += "#import \"";
146 Includes += "#include \"";
147 Includes += HeaderName;
151 static void addHeaderInclude(const FileEntry *Header,
152 SmallVectorImpl<char> &Includes,
153 const LangOptions &LangOpts) {
154 addHeaderInclude(Header->getName(), Includes, LangOpts);
157 /// \brief Collect the set of header includes needed to construct the given
158 /// module and update the TopHeaders file set of the module.
160 /// \param Module The module we're collecting includes from.
162 /// \param Includes Will be augmented with the set of \#includes or \#imports
163 /// needed to load all of the named headers.
164 static void collectModuleHeaderIncludes(const LangOptions &LangOpts,
165 FileManager &FileMgr,
167 clang::Module *Module,
168 SmallVectorImpl<char> &Includes) {
169 // Don't collect any headers for unavailable modules.
170 if (!Module->isAvailable())
173 // Add includes for each of these headers.
174 for (unsigned I = 0, N = Module->Headers.size(); I != N; ++I) {
175 const FileEntry *Header = Module->Headers[I];
176 Module->TopHeaders.insert(Header);
177 addHeaderInclude(Header, Includes, LangOpts);
180 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader()) {
181 Module->TopHeaders.insert(UmbrellaHeader);
182 if (Module->Parent) {
183 // Include the umbrella header for submodules.
184 addHeaderInclude(UmbrellaHeader, Includes, LangOpts);
186 } else if (const DirectoryEntry *UmbrellaDir = Module->getUmbrellaDir()) {
187 // Add all of the headers we find in this subdirectory.
189 SmallString<128> DirNative;
190 llvm::sys::path::native(UmbrellaDir->getName(), DirNative);
191 for (llvm::sys::fs::recursive_directory_iterator Dir(DirNative.str(), EC),
193 Dir != DirEnd && !EC; Dir.increment(EC)) {
194 // Check whether this entry has an extension typically associated with
196 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->path()))
197 .Cases(".h", ".H", ".hh", ".hpp", true)
201 // If this header is marked 'unavailable' in this module, don't include
203 if (const FileEntry *Header = FileMgr.getFile(Dir->path())) {
204 if (ModMap.isHeaderInUnavailableModule(Header))
206 Module->TopHeaders.insert(Header);
209 // Include this header umbrella header for submodules.
210 addHeaderInclude(Dir->path(), Includes, LangOpts);
214 // Recurse into submodules.
215 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(),
216 SubEnd = Module->submodule_end();
217 Sub != SubEnd; ++Sub)
218 collectModuleHeaderIncludes(LangOpts, FileMgr, ModMap, *Sub, Includes);
221 bool GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI,
222 StringRef Filename) {
223 // Find the module map file.
224 const FileEntry *ModuleMap = CI.getFileManager().getFile(Filename);
226 CI.getDiagnostics().Report(diag::err_module_map_not_found)
231 // Parse the module map file.
232 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
233 if (HS.loadModuleMapFile(ModuleMap))
236 if (CI.getLangOpts().CurrentModule.empty()) {
237 CI.getDiagnostics().Report(diag::err_missing_module_name);
239 // FIXME: Eventually, we could consider asking whether there was just
240 // a single module described in the module map, and use that as a
241 // default. Then it would be fairly trivial to just "compile" a module
242 // map with a single module (the common case).
246 // Dig out the module definition.
247 Module = HS.lookupModule(CI.getLangOpts().CurrentModule,
248 /*AllowSearch=*/false);
250 CI.getDiagnostics().Report(diag::err_missing_module)
251 << CI.getLangOpts().CurrentModule << Filename;
256 // Check whether we can build this module at all.
258 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Feature)) {
259 CI.getDiagnostics().Report(diag::err_module_unavailable)
260 << Module->getFullModuleName()
266 FileManager &FileMgr = CI.getFileManager();
268 // Collect the set of #includes we need to build the module.
269 SmallString<256> HeaderContents;
270 if (const FileEntry *UmbrellaHeader = Module->getUmbrellaHeader())
271 addHeaderInclude(UmbrellaHeader, HeaderContents, CI.getLangOpts());
272 collectModuleHeaderIncludes(CI.getLangOpts(), FileMgr,
273 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(),
274 Module, HeaderContents);
276 StringRef InputName = Module::getModuleInputBufferName();
278 // We consistently construct a buffer as input to build the module.
279 // This means the main file for modules will always be a virtual one.
280 // FIXME: Maybe allow using a memory buffer as input directly instead of
281 // messing with virtual files.
282 const FileEntry *HeaderFile = FileMgr.getVirtualFile(InputName,
283 HeaderContents.size(),
285 llvm::MemoryBuffer *HeaderContentsBuf
286 = llvm::MemoryBuffer::getMemBufferCopy(HeaderContents);
287 CI.getSourceManager().overrideFileContents(HeaderFile, HeaderContentsBuf);
288 setCurrentInput(FrontendInputFile(InputName, getCurrentFileKind(),
293 bool GenerateModuleAction::ComputeASTConsumerArguments(CompilerInstance &CI,
295 std::string &Sysroot,
296 std::string &OutputFile,
298 // If no output file was provided, figure out where this module would go
299 // in the module cache.
300 if (CI.getFrontendOpts().OutputFile.empty()) {
301 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo();
302 SmallString<256> ModuleFileName(HS.getModuleCachePath());
303 llvm::sys::path::append(ModuleFileName,
304 CI.getLangOpts().CurrentModule + ".pcm");
305 CI.getFrontendOpts().OutputFile = ModuleFileName.str();
308 // We use createOutputFile here because this is exposed via libclang, and we
309 // must disable the RemoveFileOnSignal behavior.
310 // We use a temporary to avoid race conditions.
311 OS = CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true,
312 /*RemoveFileOnSignal=*/false, InFile,
313 /*Extension=*/"", /*useTemporary=*/true,
314 /*CreateMissingDirectories=*/true);
318 OutputFile = CI.getFrontendOpts().OutputFile;
322 ASTConsumer *SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI,
324 return new ASTConsumer();
327 //===----------------------------------------------------------------------===//
328 // Preprocessor Actions
329 //===----------------------------------------------------------------------===//
331 void DumpRawTokensAction::ExecuteAction() {
332 Preprocessor &PP = getCompilerInstance().getPreprocessor();
333 SourceManager &SM = PP.getSourceManager();
335 // Start lexing the specified input file.
336 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID());
337 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts());
338 RawLex.SetKeepWhitespaceMode(true);
341 RawLex.LexFromRawLexer(RawTok);
342 while (RawTok.isNot(tok::eof)) {
343 PP.DumpToken(RawTok, true);
344 llvm::errs() << "\n";
345 RawLex.LexFromRawLexer(RawTok);
349 void DumpTokensAction::ExecuteAction() {
350 Preprocessor &PP = getCompilerInstance().getPreprocessor();
351 // Start preprocessing the specified input file.
353 PP.EnterMainSourceFile();
356 PP.DumpToken(Tok, true);
357 llvm::errs() << "\n";
358 } while (Tok.isNot(tok::eof));
361 void GeneratePTHAction::ExecuteAction() {
362 CompilerInstance &CI = getCompilerInstance();
363 if (CI.getFrontendOpts().OutputFile.empty() ||
364 CI.getFrontendOpts().OutputFile == "-") {
365 // FIXME: Don't fail this way.
366 // FIXME: Verify that we can actually seek in the given file.
367 llvm::report_fatal_error("PTH requires a seekable file for output!");
369 llvm::raw_fd_ostream *OS =
370 CI.createDefaultOutputFile(true, getCurrentFile());
373 CacheTokens(CI.getPreprocessor(), OS);
376 void PreprocessOnlyAction::ExecuteAction() {
377 Preprocessor &PP = getCompilerInstance().getPreprocessor();
379 // Ignore unknown pragmas.
380 PP.AddPragmaHandler(new EmptyPragmaHandler());
383 // Start parsing the specified input file.
384 PP.EnterMainSourceFile();
387 } while (Tok.isNot(tok::eof));
390 void PrintPreprocessedAction::ExecuteAction() {
391 CompilerInstance &CI = getCompilerInstance();
392 // Output file may need to be set to 'Binary', to avoid converting Unix style
393 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>).
395 // Look to see what type of line endings the file uses. If there's a
396 // CRLF, then we won't open the file up in binary mode. If there is
397 // just an LF or CR, then we will open the file up in binary mode.
398 // In this fashion, the output format should match the input format, unless
399 // the input format has inconsistent line endings.
401 // This should be a relatively fast operation since most files won't have
402 // all of their source code on a single line. However, that is still a
403 // concern, so if we scan for too long, we'll just assume the file should
404 // be opened in binary mode.
405 bool BinaryMode = true;
406 bool InvalidFile = false;
407 const SourceManager& SM = CI.getSourceManager();
408 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(),
411 const char *cur = Buffer->getBufferStart();
412 const char *end = Buffer->getBufferEnd();
413 const char *next = (cur != end) ? cur + 1 : end;
415 // Limit ourselves to only scanning 256 characters into the source
416 // file. This is mostly a sanity check in case the file has no
417 // newlines whatsoever.
418 if (end - cur > 256) end = cur + 256;
421 if (*cur == 0x0D) { // CR
422 if (*next == 0x0A) // CRLF
426 } else if (*cur == 0x0A) // LF
433 raw_ostream *OS = CI.createDefaultOutputFile(BinaryMode, getCurrentFile());
436 DoPrintPreprocessedInput(CI.getPreprocessor(), OS,
437 CI.getPreprocessorOutputOpts());
440 void PrintPreambleAction::ExecuteAction() {
441 switch (getCurrentFileKind()) {
452 case IK_PreprocessedC:
453 case IK_PreprocessedCXX:
454 case IK_PreprocessedObjC:
455 case IK_PreprocessedObjCXX:
458 // We can't do anything with these.
462 CompilerInstance &CI = getCompilerInstance();
463 llvm::MemoryBuffer *Buffer
464 = CI.getFileManager().getBufferForFile(getCurrentFile());
466 unsigned Preamble = Lexer::ComputePreamble(Buffer, CI.getLangOpts()).first;
467 llvm::outs().write(Buffer->getBufferStart(), Preamble);