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