FrontendAction.cpp revision 224145
1//===--- FrontendAction.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/FrontendAction.h" 11#include "clang/AST/ASTConsumer.h" 12#include "clang/AST/ASTContext.h" 13#include "clang/AST/DeclGroup.h" 14#include "clang/Lex/HeaderSearch.h" 15#include "clang/Lex/Preprocessor.h" 16#include "clang/Frontend/ASTUnit.h" 17#include "clang/Frontend/CompilerInstance.h" 18#include "clang/Frontend/FrontendDiagnostic.h" 19#include "clang/Frontend/FrontendPluginRegistry.h" 20#include "clang/Frontend/MultiplexConsumer.h" 21#include "clang/Parse/ParseAST.h" 22#include "clang/Serialization/ASTDeserializationListener.h" 23#include "clang/Serialization/ChainedIncludesSource.h" 24#include "llvm/Support/MemoryBuffer.h" 25#include "llvm/Support/Timer.h" 26#include "llvm/Support/ErrorHandling.h" 27#include "llvm/Support/raw_ostream.h" 28using namespace clang; 29 30namespace { 31 32/// \brief Dumps deserialized declarations. 33class DeserializedDeclsDumper : public ASTDeserializationListener { 34 ASTDeserializationListener *Previous; 35 36public: 37 DeserializedDeclsDumper(ASTDeserializationListener *Previous) 38 : Previous(Previous) { } 39 40 virtual void DeclRead(serialization::DeclID ID, const Decl *D) { 41 llvm::outs() << "PCH DECL: " << D->getDeclKindName(); 42 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 43 llvm::outs() << " - " << ND->getNameAsString(); 44 llvm::outs() << "\n"; 45 46 if (Previous) 47 Previous->DeclRead(ID, D); 48 } 49}; 50 51 /// \brief Checks deserialized declarations and emits error if a name 52 /// matches one given in command-line using -error-on-deserialized-decl. 53 class DeserializedDeclsChecker : public ASTDeserializationListener { 54 ASTContext &Ctx; 55 std::set<std::string> NamesToCheck; 56 ASTDeserializationListener *Previous; 57 58 public: 59 DeserializedDeclsChecker(ASTContext &Ctx, 60 const std::set<std::string> &NamesToCheck, 61 ASTDeserializationListener *Previous) 62 : Ctx(Ctx), NamesToCheck(NamesToCheck), Previous(Previous) { } 63 64 virtual void DeclRead(serialization::DeclID ID, const Decl *D) { 65 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D)) 66 if (NamesToCheck.find(ND->getNameAsString()) != NamesToCheck.end()) { 67 unsigned DiagID 68 = Ctx.getDiagnostics().getCustomDiagID(Diagnostic::Error, 69 "%0 was deserialized"); 70 Ctx.getDiagnostics().Report(Ctx.getFullLoc(D->getLocation()), DiagID) 71 << ND->getNameAsString(); 72 } 73 74 if (Previous) 75 Previous->DeclRead(ID, D); 76 } 77}; 78 79} // end anonymous namespace 80 81FrontendAction::FrontendAction() : Instance(0) {} 82 83FrontendAction::~FrontendAction() {} 84 85void FrontendAction::setCurrentFile(llvm::StringRef Value, InputKind Kind, 86 ASTUnit *AST) { 87 CurrentFile = Value; 88 CurrentFileKind = Kind; 89 CurrentASTUnit.reset(AST); 90} 91 92ASTConsumer* FrontendAction::CreateWrappedASTConsumer(CompilerInstance &CI, 93 llvm::StringRef InFile) { 94 ASTConsumer* Consumer = CreateASTConsumer(CI, InFile); 95 if (!Consumer) 96 return 0; 97 98 if (CI.getFrontendOpts().AddPluginActions.size() == 0) 99 return Consumer; 100 101 // Make sure the non-plugin consumer is first, so that plugins can't 102 // modifiy the AST. 103 std::vector<ASTConsumer*> Consumers(1, Consumer); 104 105 for (size_t i = 0, e = CI.getFrontendOpts().AddPluginActions.size(); 106 i != e; ++i) { 107 // This is O(|plugins| * |add_plugins|), but since both numbers are 108 // way below 50 in practice, that's ok. 109 for (FrontendPluginRegistry::iterator 110 it = FrontendPluginRegistry::begin(), 111 ie = FrontendPluginRegistry::end(); 112 it != ie; ++it) { 113 if (it->getName() == CI.getFrontendOpts().AddPluginActions[i]) { 114 llvm::OwningPtr<PluginASTAction> P(it->instantiate()); 115 FrontendAction* c = P.get(); 116 if (P->ParseArgs(CI, CI.getFrontendOpts().AddPluginArgs[i])) 117 Consumers.push_back(c->CreateASTConsumer(CI, InFile)); 118 } 119 } 120 } 121 122 return new MultiplexConsumer(Consumers); 123} 124 125bool FrontendAction::BeginSourceFile(CompilerInstance &CI, 126 llvm::StringRef Filename, 127 InputKind InputKind) { 128 assert(!Instance && "Already processing a source file!"); 129 assert(!Filename.empty() && "Unexpected empty filename!"); 130 setCurrentFile(Filename, InputKind); 131 setCompilerInstance(&CI); 132 133 if (!BeginInvocation(CI)) 134 goto failure; 135 136 // AST files follow a very different path, since they share objects via the 137 // AST unit. 138 if (InputKind == IK_AST) { 139 assert(!usesPreprocessorOnly() && 140 "Attempt to pass AST file to preprocessor only action!"); 141 assert(hasASTFileSupport() && 142 "This action does not have AST file support!"); 143 144 llvm::IntrusiveRefCntPtr<Diagnostic> Diags(&CI.getDiagnostics()); 145 std::string Error; 146 ASTUnit *AST = ASTUnit::LoadFromASTFile(Filename, Diags, 147 CI.getFileSystemOpts()); 148 if (!AST) 149 goto failure; 150 151 setCurrentFile(Filename, InputKind, AST); 152 153 // Set the shared objects, these are reset when we finish processing the 154 // file, otherwise the CompilerInstance will happily destroy them. 155 CI.setFileManager(&AST->getFileManager()); 156 CI.setSourceManager(&AST->getSourceManager()); 157 CI.setPreprocessor(&AST->getPreprocessor()); 158 CI.setASTContext(&AST->getASTContext()); 159 160 // Initialize the action. 161 if (!BeginSourceFileAction(CI, Filename)) 162 goto failure; 163 164 /// Create the AST consumer. 165 CI.setASTConsumer(CreateWrappedASTConsumer(CI, Filename)); 166 if (!CI.hasASTConsumer()) 167 goto failure; 168 169 return true; 170 } 171 172 // Set up the file and source managers, if needed. 173 if (!CI.hasFileManager()) 174 CI.createFileManager(); 175 if (!CI.hasSourceManager()) 176 CI.createSourceManager(CI.getFileManager()); 177 178 // IR files bypass the rest of initialization. 179 if (InputKind == IK_LLVM_IR) { 180 assert(hasIRSupport() && 181 "This action does not have IR file support!"); 182 183 // Inform the diagnostic client we are processing a source file. 184 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0); 185 186 // Initialize the action. 187 if (!BeginSourceFileAction(CI, Filename)) 188 goto failure; 189 190 return true; 191 } 192 193 // Set up the preprocessor. 194 CI.createPreprocessor(); 195 196 // Inform the diagnostic client we are processing a source file. 197 CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 198 &CI.getPreprocessor()); 199 200 // Initialize the action. 201 if (!BeginSourceFileAction(CI, Filename)) 202 goto failure; 203 204 /// Create the AST context and consumer unless this is a preprocessor only 205 /// action. 206 if (!usesPreprocessorOnly()) { 207 CI.createASTContext(); 208 209 llvm::OwningPtr<ASTConsumer> Consumer( 210 CreateWrappedASTConsumer(CI, Filename)); 211 if (!Consumer) 212 goto failure; 213 214 CI.getASTContext().setASTMutationListener(Consumer->GetASTMutationListener()); 215 216 if (!CI.getPreprocessorOpts().ChainedIncludes.empty()) { 217 // Convert headers to PCH and chain them. 218 llvm::OwningPtr<ExternalASTSource> source; 219 source.reset(ChainedIncludesSource::create(CI)); 220 if (!source) 221 goto failure; 222 CI.getASTContext().setExternalSource(source); 223 224 } else if (!CI.getPreprocessorOpts().ImplicitPCHInclude.empty()) { 225 // Use PCH. 226 assert(hasPCHSupport() && "This action does not have PCH support!"); 227 ASTDeserializationListener *DeserialListener 228 = CI.getInvocation().getFrontendOpts().ChainedPCH ? 229 Consumer->GetASTDeserializationListener() : 0; 230 if (CI.getPreprocessorOpts().DumpDeserializedPCHDecls) 231 DeserialListener = new DeserializedDeclsDumper(DeserialListener); 232 if (!CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn.empty()) 233 DeserialListener = new DeserializedDeclsChecker(CI.getASTContext(), 234 CI.getPreprocessorOpts().DeserializedPCHDeclsToErrorOn, 235 DeserialListener); 236 CI.createPCHExternalASTSource( 237 CI.getPreprocessorOpts().ImplicitPCHInclude, 238 CI.getPreprocessorOpts().DisablePCHValidation, 239 CI.getPreprocessorOpts().DisableStatCache, 240 DeserialListener); 241 if (!CI.getASTContext().getExternalSource()) 242 goto failure; 243 } 244 245 CI.setASTConsumer(Consumer.take()); 246 if (!CI.hasASTConsumer()) 247 goto failure; 248 } 249 250 // Initialize builtin info as long as we aren't using an external AST 251 // source. 252 if (!CI.hasASTContext() || !CI.getASTContext().getExternalSource()) { 253 Preprocessor &PP = CI.getPreprocessor(); 254 PP.getBuiltinInfo().InitializeBuiltins(PP.getIdentifierTable(), 255 PP.getLangOptions()); 256 } 257 258 return true; 259 260 // If we failed, reset state since the client will not end up calling the 261 // matching EndSourceFile(). 262 failure: 263 if (isCurrentFileAST()) { 264 CI.setASTContext(0); 265 CI.setPreprocessor(0); 266 CI.setSourceManager(0); 267 CI.setFileManager(0); 268 } 269 270 CI.getDiagnosticClient().EndSourceFile(); 271 setCurrentFile("", IK_None); 272 setCompilerInstance(0); 273 return false; 274} 275 276void FrontendAction::Execute() { 277 CompilerInstance &CI = getCompilerInstance(); 278 279 // Initialize the main file entry. This needs to be delayed until after PCH 280 // has loaded. 281 if (isCurrentFileAST()) { 282 // Set the main file ID to an empty file. 283 // 284 // FIXME: We probably shouldn't need this, but for now this is the 285 // simplest way to reuse the logic in ParseAST. 286 const char *EmptyStr = ""; 287 llvm::MemoryBuffer *SB = 288 llvm::MemoryBuffer::getMemBuffer(EmptyStr, "<dummy input>"); 289 CI.getSourceManager().createMainFileIDForMemBuffer(SB); 290 } else { 291 if (!CI.InitializeSourceManager(getCurrentFile())) 292 return; 293 } 294 295 if (CI.hasFrontendTimer()) { 296 llvm::TimeRegion Timer(CI.getFrontendTimer()); 297 ExecuteAction(); 298 } 299 else ExecuteAction(); 300} 301 302void FrontendAction::EndSourceFile() { 303 CompilerInstance &CI = getCompilerInstance(); 304 305 // Inform the diagnostic client we are done with this source file. 306 CI.getDiagnosticClient().EndSourceFile(); 307 308 // Finalize the action. 309 EndSourceFileAction(); 310 311 // Release the consumer and the AST, in that order since the consumer may 312 // perform actions in its destructor which require the context. 313 // 314 // FIXME: There is more per-file stuff we could just drop here? 315 if (CI.getFrontendOpts().DisableFree) { 316 CI.takeASTConsumer(); 317 if (!isCurrentFileAST()) { 318 CI.takeSema(); 319 CI.resetAndLeakASTContext(); 320 } 321 } else { 322 if (!isCurrentFileAST()) { 323 CI.setSema(0); 324 CI.setASTContext(0); 325 } 326 CI.setASTConsumer(0); 327 } 328 329 // Inform the preprocessor we are done. 330 if (CI.hasPreprocessor()) 331 CI.getPreprocessor().EndSourceFile(); 332 333 if (CI.getFrontendOpts().ShowStats) { 334 llvm::errs() << "\nSTATISTICS FOR '" << getCurrentFile() << "':\n"; 335 CI.getPreprocessor().PrintStats(); 336 CI.getPreprocessor().getIdentifierTable().PrintStats(); 337 CI.getPreprocessor().getHeaderSearchInfo().PrintStats(); 338 CI.getSourceManager().PrintStats(); 339 llvm::errs() << "\n"; 340 } 341 342 // Cleanup the output streams, and erase the output files if we encountered 343 // an error. 344 CI.clearOutputFiles(/*EraseFiles=*/CI.getDiagnostics().hasErrorOccurred()); 345 346 if (isCurrentFileAST()) { 347 CI.takeSema(); 348 CI.resetAndLeakASTContext(); 349 CI.resetAndLeakPreprocessor(); 350 CI.resetAndLeakSourceManager(); 351 CI.resetAndLeakFileManager(); 352 } 353 354 setCompilerInstance(0); 355 setCurrentFile("", IK_None); 356} 357 358//===----------------------------------------------------------------------===// 359// Utility Actions 360//===----------------------------------------------------------------------===// 361 362void ASTFrontendAction::ExecuteAction() { 363 CompilerInstance &CI = getCompilerInstance(); 364 365 // FIXME: Move the truncation aspect of this into Sema, we delayed this till 366 // here so the source manager would be initialized. 367 if (hasCodeCompletionSupport() && 368 !CI.getFrontendOpts().CodeCompletionAt.FileName.empty()) 369 CI.createCodeCompletionConsumer(); 370 371 // Use a code completion consumer? 372 CodeCompleteConsumer *CompletionConsumer = 0; 373 if (CI.hasCodeCompletionConsumer()) 374 CompletionConsumer = &CI.getCodeCompletionConsumer(); 375 376 if (!CI.hasSema()) 377 CI.createSema(usesCompleteTranslationUnit(), CompletionConsumer); 378 379 ParseAST(CI.getSema(), CI.getFrontendOpts().ShowStats); 380} 381 382ASTConsumer * 383PreprocessorFrontendAction::CreateASTConsumer(CompilerInstance &CI, 384 llvm::StringRef InFile) { 385 llvm_unreachable("Invalid CreateASTConsumer on preprocessor action!"); 386} 387 388ASTConsumer *WrapperFrontendAction::CreateASTConsumer(CompilerInstance &CI, 389 llvm::StringRef InFile) { 390 return WrappedAction->CreateASTConsumer(CI, InFile); 391} 392bool WrapperFrontendAction::BeginInvocation(CompilerInstance &CI) { 393 return WrappedAction->BeginInvocation(CI); 394} 395bool WrapperFrontendAction::BeginSourceFileAction(CompilerInstance &CI, 396 llvm::StringRef Filename) { 397 WrappedAction->setCurrentFile(getCurrentFile(), getCurrentFileKind()); 398 WrappedAction->setCompilerInstance(&CI); 399 return WrappedAction->BeginSourceFileAction(CI, Filename); 400} 401void WrapperFrontendAction::ExecuteAction() { 402 WrappedAction->ExecuteAction(); 403} 404void WrapperFrontendAction::EndSourceFileAction() { 405 WrappedAction->EndSourceFileAction(); 406} 407 408bool WrapperFrontendAction::usesPreprocessorOnly() const { 409 return WrappedAction->usesPreprocessorOnly(); 410} 411bool WrapperFrontendAction::usesCompleteTranslationUnit() { 412 return WrappedAction->usesCompleteTranslationUnit(); 413} 414bool WrapperFrontendAction::hasPCHSupport() const { 415 return WrappedAction->hasPCHSupport(); 416} 417bool WrapperFrontendAction::hasASTFileSupport() const { 418 return WrappedAction->hasASTFileSupport(); 419} 420bool WrapperFrontendAction::hasIRSupport() const { 421 return WrappedAction->hasIRSupport(); 422} 423bool WrapperFrontendAction::hasCodeCompletionSupport() const { 424 return WrappedAction->hasCodeCompletionSupport(); 425} 426 427WrapperFrontendAction::WrapperFrontendAction(FrontendAction *WrappedAction) 428 : WrappedAction(WrappedAction) {} 429 430