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 GenerateModuleAction::BeginSourceFileAction(CompilerInstance &CI, 168 StringRef Filename) { 169 // Set up embedding for any specified files. Do this before we load any 170 // source files, including the primary module map for the compilation. 171 for (const auto &F : CI.getFrontendOpts().ModulesEmbedFiles) { 172 if (const auto *FE = CI.getFileManager().getFile(F, /*openFile*/true)) 173 CI.getSourceManager().setFileIsTransient(FE); 174 else 175 CI.getDiagnostics().Report(diag::err_modules_embed_file_not_found) << F; 176 } 177 if (CI.getFrontendOpts().ModulesEmbedAllFiles) 178 CI.getSourceManager().setAllFilesAreTransient(true); 179 180 return true; 181 } 182 183 184 static SmallVectorImpl<char> & 185 operator+=(SmallVectorImpl<char> &Includes, StringRef RHS) { 186 Includes.append(RHS.begin(), RHS.end()); 187 return Includes; 188 } 189 190 static void addHeaderInclude(StringRef HeaderName, 191 SmallVectorImpl<char> &Includes, 192 const LangOptions &LangOpts, 193 bool IsExternC) { 194 if (IsExternC && LangOpts.CPlusPlus) 195 Includes += "extern \"C\" {\n"; 196 if (LangOpts.ObjC1) 197 Includes += "#import \""; 198 else 199 Includes += "#include \""; 200 201 Includes += HeaderName; 202 203 Includes += "\"\n"; 204 if (IsExternC && LangOpts.CPlusPlus) 205 Includes += "}\n"; 206 } 207 208 /// \brief Collect the set of header includes needed to construct the given 209 /// module and update the TopHeaders file set of the module. 210 /// 211 /// \param Module The module we're collecting includes from. 212 /// 213 /// \param Includes Will be augmented with the set of \#includes or \#imports 214 /// needed to load all of the named headers. 215 static std::error_code 216 collectModuleHeaderIncludes(const LangOptions &LangOpts, FileManager &FileMgr, 217 ModuleMap &ModMap, clang::Module *Module, 218 SmallVectorImpl<char> &Includes) { 219 // Don't collect any headers for unavailable modules. 220 if (!Module->isAvailable()) 221 return std::error_code(); 222 223 // Add includes for each of these headers. 224 for (auto HK : {Module::HK_Normal, Module::HK_Private}) { 225 for (Module::Header &H : Module->Headers[HK]) { 226 Module->addTopHeader(H.Entry); 227 // Use the path as specified in the module map file. We'll look for this 228 // file relative to the module build directory (the directory containing 229 // the module map file) so this will find the same file that we found 230 // while parsing the module map. 231 addHeaderInclude(H.NameAsWritten, Includes, LangOpts, Module->IsExternC); 232 } 233 } 234 // Note that Module->PrivateHeaders will not be a TopHeader. 235 236 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) { 237 Module->addTopHeader(UmbrellaHeader.Entry); 238 if (Module->Parent) 239 // Include the umbrella header for submodules. 240 addHeaderInclude(UmbrellaHeader.NameAsWritten, Includes, LangOpts, 241 Module->IsExternC); 242 } else if (Module::DirectoryName UmbrellaDir = Module->getUmbrellaDir()) { 243 // Add all of the headers we find in this subdirectory. 244 std::error_code EC; 245 SmallString<128> DirNative; 246 llvm::sys::path::native(UmbrellaDir.Entry->getName(), DirNative); 247 248 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); 249 for (vfs::recursive_directory_iterator Dir(FS, DirNative, EC), End; 250 Dir != End && !EC; Dir.increment(EC)) { 251 // Check whether this entry has an extension typically associated with 252 // headers. 253 if (!llvm::StringSwitch<bool>(llvm::sys::path::extension(Dir->getName())) 254 .Cases(".h", ".H", ".hh", ".hpp", true) 255 .Default(false)) 256 continue; 257 258 const FileEntry *Header = FileMgr.getFile(Dir->getName()); 259 // FIXME: This shouldn't happen unless there is a file system race. Is 260 // that worth diagnosing? 261 if (!Header) 262 continue; 263 264 // If this header is marked 'unavailable' in this module, don't include 265 // it. 266 if (ModMap.isHeaderUnavailableInModule(Header, Module)) 267 continue; 268 269 // Compute the relative path from the directory to this file. 270 SmallVector<StringRef, 16> Components; 271 auto PathIt = llvm::sys::path::rbegin(Dir->getName()); 272 for (int I = 0; I != Dir.level() + 1; ++I, ++PathIt) 273 Components.push_back(*PathIt); 274 SmallString<128> RelativeHeader(UmbrellaDir.NameAsWritten); 275 for (auto It = Components.rbegin(), End = Components.rend(); It != End; 276 ++It) 277 llvm::sys::path::append(RelativeHeader, *It); 278 279 // Include this header as part of the umbrella directory. 280 Module->addTopHeader(Header); 281 addHeaderInclude(RelativeHeader, Includes, LangOpts, Module->IsExternC); 282 } 283 284 if (EC) 285 return EC; 286 } 287 288 // Recurse into submodules. 289 for (clang::Module::submodule_iterator Sub = Module->submodule_begin(), 290 SubEnd = Module->submodule_end(); 291 Sub != SubEnd; ++Sub) 292 if (std::error_code Err = collectModuleHeaderIncludes( 293 LangOpts, FileMgr, ModMap, *Sub, Includes)) 294 return Err; 295 296 return std::error_code(); 297 } 298 299 bool GenerateModuleFromModuleMapAction::BeginSourceFileAction( 300 CompilerInstance &CI, StringRef Filename) { 301 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleMap); 302 303 if (!GenerateModuleAction::BeginSourceFileAction(CI, Filename)) 304 return false; 305 306 // Find the module map file. 307 const FileEntry *ModuleMap = 308 CI.getFileManager().getFile(Filename, /*openFile*/true); 309 if (!ModuleMap) { 310 CI.getDiagnostics().Report(diag::err_module_map_not_found) 311 << Filename; 312 return false; 313 } 314 315 // Parse the module map file. 316 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 317 if (HS.loadModuleMapFile(ModuleMap, IsSystem)) 318 return false; 319 320 if (CI.getLangOpts().CurrentModule.empty()) { 321 CI.getDiagnostics().Report(diag::err_missing_module_name); 322 323 // FIXME: Eventually, we could consider asking whether there was just 324 // a single module described in the module map, and use that as a 325 // default. Then it would be fairly trivial to just "compile" a module 326 // map with a single module (the common case). 327 return false; 328 } 329 330 // If we're being run from the command-line, the module build stack will not 331 // have been filled in yet, so complete it now in order to allow us to detect 332 // module cycles. 333 SourceManager &SourceMgr = CI.getSourceManager(); 334 if (SourceMgr.getModuleBuildStack().empty()) 335 SourceMgr.pushModuleBuildStack(CI.getLangOpts().CurrentModule, 336 FullSourceLoc(SourceLocation(), SourceMgr)); 337 338 // Dig out the module definition. 339 Module = HS.lookupModule(CI.getLangOpts().CurrentModule, 340 /*AllowSearch=*/false); 341 if (!Module) { 342 CI.getDiagnostics().Report(diag::err_missing_module) 343 << CI.getLangOpts().CurrentModule << Filename; 344 345 return false; 346 } 347 348 // Check whether we can build this module at all. 349 clang::Module::Requirement Requirement; 350 clang::Module::UnresolvedHeaderDirective MissingHeader; 351 if (!Module->isAvailable(CI.getLangOpts(), CI.getTarget(), Requirement, 352 MissingHeader)) { 353 if (MissingHeader.FileNameLoc.isValid()) { 354 CI.getDiagnostics().Report(MissingHeader.FileNameLoc, 355 diag::err_module_header_missing) 356 << MissingHeader.IsUmbrella << MissingHeader.FileName; 357 } else { 358 CI.getDiagnostics().Report(diag::err_module_unavailable) 359 << Module->getFullModuleName() 360 << Requirement.second << Requirement.first; 361 } 362 363 return false; 364 } 365 366 if (ModuleMapForUniquing && ModuleMapForUniquing != ModuleMap) { 367 Module->IsInferred = true; 368 HS.getModuleMap().setInferredModuleAllowedBy(Module, ModuleMapForUniquing); 369 } else { 370 ModuleMapForUniquing = ModuleMap; 371 } 372 373 FileManager &FileMgr = CI.getFileManager(); 374 375 // Collect the set of #includes we need to build the module. 376 SmallString<256> HeaderContents; 377 std::error_code Err = std::error_code(); 378 if (Module::Header UmbrellaHeader = Module->getUmbrellaHeader()) 379 addHeaderInclude(UmbrellaHeader.NameAsWritten, HeaderContents, 380 CI.getLangOpts(), Module->IsExternC); 381 Err = collectModuleHeaderIncludes( 382 CI.getLangOpts(), FileMgr, 383 CI.getPreprocessor().getHeaderSearchInfo().getModuleMap(), Module, 384 HeaderContents); 385 386 if (Err) { 387 CI.getDiagnostics().Report(diag::err_module_cannot_create_includes) 388 << Module->getFullModuleName() << Err.message(); 389 return false; 390 } 391 392 // Inform the preprocessor that includes from within the input buffer should 393 // be resolved relative to the build directory of the module map file. 394 CI.getPreprocessor().setMainFileDir(Module->Directory); 395 396 std::unique_ptr<llvm::MemoryBuffer> InputBuffer = 397 llvm::MemoryBuffer::getMemBufferCopy(HeaderContents, 398 Module::getModuleInputBufferName()); 399 // Ownership of InputBuffer will be transferred to the SourceManager. 400 setCurrentInput(FrontendInputFile(InputBuffer.release(), getCurrentFileKind(), 401 Module->IsSystem)); 402 return true; 403 } 404 405 std::unique_ptr<raw_pwrite_stream> 406 GenerateModuleFromModuleMapAction::CreateOutputFile(CompilerInstance &CI, 407 StringRef InFile) { 408 // If no output file was provided, figure out where this module would go 409 // in the module cache. 410 if (CI.getFrontendOpts().OutputFile.empty()) { 411 HeaderSearch &HS = CI.getPreprocessor().getHeaderSearchInfo(); 412 CI.getFrontendOpts().OutputFile = 413 HS.getModuleFileName(CI.getLangOpts().CurrentModule, 414 ModuleMapForUniquing->getName(), 415 /*UsePrebuiltPath=*/false); 416 } 417 418 // We use createOutputFile here because this is exposed via libclang, and we 419 // must disable the RemoveFileOnSignal behavior. 420 // We use a temporary to avoid race conditions. 421 return CI.createOutputFile(CI.getFrontendOpts().OutputFile, /*Binary=*/true, 422 /*RemoveFileOnSignal=*/false, InFile, 423 /*Extension=*/"", /*useTemporary=*/true, 424 /*CreateMissingDirectories=*/true); 425 } 426 427 bool GenerateModuleInterfaceAction::BeginSourceFileAction(CompilerInstance &CI, 428 StringRef Filename) { 429 if (!CI.getLangOpts().ModulesTS) { 430 CI.getDiagnostics().Report(diag::err_module_interface_requires_modules_ts); 431 return false; 432 } 433 434 CI.getLangOpts().setCompilingModule(LangOptions::CMK_ModuleInterface); 435 436 return GenerateModuleAction::BeginSourceFileAction(CI, Filename); 437 } 438 439 std::unique_ptr<raw_pwrite_stream> 440 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI, 441 StringRef InFile) { 442 return CI.createDefaultOutputFile(/*Binary=*/true, InFile, "pcm"); 443 } 444 445 SyntaxOnlyAction::~SyntaxOnlyAction() { 446 } 447 448 std::unique_ptr<ASTConsumer> 449 SyntaxOnlyAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 450 return llvm::make_unique<ASTConsumer>(); 451 } 452 453 std::unique_ptr<ASTConsumer> 454 DumpModuleInfoAction::CreateASTConsumer(CompilerInstance &CI, 455 StringRef InFile) { 456 return llvm::make_unique<ASTConsumer>(); 457 } 458 459 std::unique_ptr<ASTConsumer> 460 VerifyPCHAction::CreateASTConsumer(CompilerInstance &CI, StringRef InFile) { 461 return llvm::make_unique<ASTConsumer>(); 462 } 463 464 void VerifyPCHAction::ExecuteAction() { 465 CompilerInstance &CI = getCompilerInstance(); 466 bool Preamble = CI.getPreprocessorOpts().PrecompiledPreambleBytes.first != 0; 467 const std::string &Sysroot = CI.getHeaderSearchOpts().Sysroot; 468 std::unique_ptr<ASTReader> Reader(new ASTReader( 469 CI.getPreprocessor(), CI.getASTContext(), CI.getPCHContainerReader(), 470 CI.getFrontendOpts().ModuleFileExtensions, 471 Sysroot.empty() ? "" : Sysroot.c_str(), 472 /*DisableValidation*/ false, 473 /*AllowPCHWithCompilerErrors*/ false, 474 /*AllowConfigurationMismatch*/ true, 475 /*ValidateSystemInputs*/ true)); 476 477 Reader->ReadAST(getCurrentFile(), 478 Preamble ? serialization::MK_Preamble 479 : serialization::MK_PCH, 480 SourceLocation(), 481 ASTReader::ARR_ConfigurationMismatch); 482 } 483 484 namespace { 485 /// \brief AST reader listener that dumps module information for a module 486 /// file. 487 class DumpModuleInfoListener : public ASTReaderListener { 488 llvm::raw_ostream &Out; 489 490 public: 491 DumpModuleInfoListener(llvm::raw_ostream &Out) : Out(Out) { } 492 493 #define DUMP_BOOLEAN(Value, Text) \ 494 Out.indent(4) << Text << ": " << (Value? "Yes" : "No") << "\n" 495 496 bool ReadFullVersionInformation(StringRef FullVersion) override { 497 Out.indent(2) 498 << "Generated by " 499 << (FullVersion == getClangFullRepositoryVersion()? "this" 500 : "a different") 501 << " Clang: " << FullVersion << "\n"; 502 return ASTReaderListener::ReadFullVersionInformation(FullVersion); 503 } 504 505 void ReadModuleName(StringRef ModuleName) override { 506 Out.indent(2) << "Module name: " << ModuleName << "\n"; 507 } 508 void ReadModuleMapFile(StringRef ModuleMapPath) override { 509 Out.indent(2) << "Module map file: " << ModuleMapPath << "\n"; 510 } 511 512 bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain, 513 bool AllowCompatibleDifferences) override { 514 Out.indent(2) << "Language options:\n"; 515 #define LANGOPT(Name, Bits, Default, Description) \ 516 DUMP_BOOLEAN(LangOpts.Name, Description); 517 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 518 Out.indent(4) << Description << ": " \ 519 << static_cast<unsigned>(LangOpts.get##Name()) << "\n"; 520 #define VALUE_LANGOPT(Name, Bits, Default, Description) \ 521 Out.indent(4) << Description << ": " << LangOpts.Name << "\n"; 522 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 523 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 524 #include "clang/Basic/LangOptions.def" 525 526 if (!LangOpts.ModuleFeatures.empty()) { 527 Out.indent(4) << "Module features:\n"; 528 for (StringRef Feature : LangOpts.ModuleFeatures) 529 Out.indent(6) << Feature << "\n"; 530 } 531 532 return false; 533 } 534 535 bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain, 536 bool AllowCompatibleDifferences) override { 537 Out.indent(2) << "Target options:\n"; 538 Out.indent(4) << " Triple: " << TargetOpts.Triple << "\n"; 539 Out.indent(4) << " CPU: " << TargetOpts.CPU << "\n"; 540 Out.indent(4) << " ABI: " << TargetOpts.ABI << "\n"; 541 542 if (!TargetOpts.FeaturesAsWritten.empty()) { 543 Out.indent(4) << "Target features:\n"; 544 for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); 545 I != N; ++I) { 546 Out.indent(6) << TargetOpts.FeaturesAsWritten[I] << "\n"; 547 } 548 } 549 550 return false; 551 } 552 553 bool ReadDiagnosticOptions(IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, 554 bool Complain) override { 555 Out.indent(2) << "Diagnostic options:\n"; 556 #define DIAGOPT(Name, Bits, Default) DUMP_BOOLEAN(DiagOpts->Name, #Name); 557 #define ENUM_DIAGOPT(Name, Type, Bits, Default) \ 558 Out.indent(4) << #Name << ": " << DiagOpts->get##Name() << "\n"; 559 #define VALUE_DIAGOPT(Name, Bits, Default) \ 560 Out.indent(4) << #Name << ": " << DiagOpts->Name << "\n"; 561 #include "clang/Basic/DiagnosticOptions.def" 562 563 Out.indent(4) << "Diagnostic flags:\n"; 564 for (const std::string &Warning : DiagOpts->Warnings) 565 Out.indent(6) << "-W" << Warning << "\n"; 566 for (const std::string &Remark : DiagOpts->Remarks) 567 Out.indent(6) << "-R" << Remark << "\n"; 568 569 return false; 570 } 571 572 bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts, 573 StringRef SpecificModuleCachePath, 574 bool Complain) override { 575 Out.indent(2) << "Header search options:\n"; 576 Out.indent(4) << "System root [-isysroot=]: '" << HSOpts.Sysroot << "'\n"; 577 Out.indent(4) << "Resource dir [ -resource-dir=]: '" << HSOpts.ResourceDir << "'\n"; 578 Out.indent(4) << "Module Cache: '" << SpecificModuleCachePath << "'\n"; 579 DUMP_BOOLEAN(HSOpts.UseBuiltinIncludes, 580 "Use builtin include directories [-nobuiltininc]"); 581 DUMP_BOOLEAN(HSOpts.UseStandardSystemIncludes, 582 "Use standard system include directories [-nostdinc]"); 583 DUMP_BOOLEAN(HSOpts.UseStandardCXXIncludes, 584 "Use standard C++ include directories [-nostdinc++]"); 585 DUMP_BOOLEAN(HSOpts.UseLibcxx, 586 "Use libc++ (rather than libstdc++) [-stdlib=]"); 587 return false; 588 } 589 590 bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts, 591 bool Complain, 592 std::string &SuggestedPredefines) override { 593 Out.indent(2) << "Preprocessor options:\n"; 594 DUMP_BOOLEAN(PPOpts.UsePredefines, 595 "Uses compiler/target-specific predefines [-undef]"); 596 DUMP_BOOLEAN(PPOpts.DetailedRecord, 597 "Uses detailed preprocessing record (for indexing)"); 598 599 if (!PPOpts.Macros.empty()) { 600 Out.indent(4) << "Predefined macros:\n"; 601 } 602 603 for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator 604 I = PPOpts.Macros.begin(), IEnd = PPOpts.Macros.end(); 605 I != IEnd; ++I) { 606 Out.indent(6); 607 if (I->second) 608 Out << "-U"; 609 else 610 Out << "-D"; 611 Out << I->first << "\n"; 612 } 613 return false; 614 } 615 616 /// Indicates that a particular module file extension has been read. 617 void readModuleFileExtension( 618 const ModuleFileExtensionMetadata &Metadata) override { 619 Out.indent(2) << "Module file extension '" 620 << Metadata.BlockName << "' " << Metadata.MajorVersion 621 << "." << Metadata.MinorVersion; 622 if (!Metadata.UserInfo.empty()) { 623 Out << ": "; 624 Out.write_escaped(Metadata.UserInfo); 625 } 626 627 Out << "\n"; 628 } 629 #undef DUMP_BOOLEAN 630 }; 631 } 632 633 bool DumpModuleInfoAction::BeginInvocation(CompilerInstance &CI) { 634 // The Object file reader also supports raw ast files and there is no point in 635 // being strict about the module file format in -module-file-info mode. 636 CI.getHeaderSearchOpts().ModuleFormat = "obj"; 637 return true; 638 } 639 640 void DumpModuleInfoAction::ExecuteAction() { 641 // Set up the output file. 642 std::unique_ptr<llvm::raw_fd_ostream> OutFile; 643 StringRef OutputFileName = getCompilerInstance().getFrontendOpts().OutputFile; 644 if (!OutputFileName.empty() && OutputFileName != "-") { 645 std::error_code EC; 646 OutFile.reset(new llvm::raw_fd_ostream(OutputFileName.str(), EC, 647 llvm::sys::fs::F_Text)); 648 } 649 llvm::raw_ostream &Out = OutFile.get()? *OutFile.get() : llvm::outs(); 650 651 Out << "Information for module file '" << getCurrentFile() << "':\n"; 652 auto &FileMgr = getCompilerInstance().getFileManager(); 653 auto Buffer = FileMgr.getBufferForFile(getCurrentFile()); 654 StringRef Magic = (*Buffer)->getMemBufferRef().getBuffer(); 655 bool IsRaw = (Magic.size() >= 4 && Magic[0] == 'C' && Magic[1] == 'P' && 656 Magic[2] == 'C' && Magic[3] == 'H'); 657 Out << " Module format: " << (IsRaw ? "raw" : "obj") << "\n"; 658 659 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 660 DumpModuleInfoListener Listener(Out); 661 HeaderSearchOptions &HSOpts = 662 PP.getHeaderSearchInfo().getHeaderSearchOpts(); 663 ASTReader::readASTFileControlBlock( 664 getCurrentFile(), FileMgr, getCompilerInstance().getPCHContainerReader(), 665 /*FindModuleFileExtensions=*/true, Listener, 666 HSOpts.ModulesValidateDiagnosticOptions); 667 } 668 669 //===----------------------------------------------------------------------===// 670 // Preprocessor Actions 671 //===----------------------------------------------------------------------===// 672 673 void DumpRawTokensAction::ExecuteAction() { 674 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 675 SourceManager &SM = PP.getSourceManager(); 676 677 // Start lexing the specified input file. 678 const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID()); 679 Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOpts()); 680 RawLex.SetKeepWhitespaceMode(true); 681 682 Token RawTok; 683 RawLex.LexFromRawLexer(RawTok); 684 while (RawTok.isNot(tok::eof)) { 685 PP.DumpToken(RawTok, true); 686 llvm::errs() << "\n"; 687 RawLex.LexFromRawLexer(RawTok); 688 } 689 } 690 691 void DumpTokensAction::ExecuteAction() { 692 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 693 // Start preprocessing the specified input file. 694 Token Tok; 695 PP.EnterMainSourceFile(); 696 do { 697 PP.Lex(Tok); 698 PP.DumpToken(Tok, true); 699 llvm::errs() << "\n"; 700 } while (Tok.isNot(tok::eof)); 701 } 702 703 void GeneratePTHAction::ExecuteAction() { 704 CompilerInstance &CI = getCompilerInstance(); 705 std::unique_ptr<raw_pwrite_stream> OS = 706 CI.createDefaultOutputFile(true, getCurrentFile()); 707 if (!OS) 708 return; 709 710 CacheTokens(CI.getPreprocessor(), OS.get()); 711 } 712 713 void PreprocessOnlyAction::ExecuteAction() { 714 Preprocessor &PP = getCompilerInstance().getPreprocessor(); 715 716 // Ignore unknown pragmas. 717 PP.IgnorePragmas(); 718 719 Token Tok; 720 // Start parsing the specified input file. 721 PP.EnterMainSourceFile(); 722 do { 723 PP.Lex(Tok); 724 } while (Tok.isNot(tok::eof)); 725 } 726 727 void PrintPreprocessedAction::ExecuteAction() { 728 CompilerInstance &CI = getCompilerInstance(); 729 // Output file may need to be set to 'Binary', to avoid converting Unix style 730 // line feeds (<LF>) to Microsoft style line feeds (<CR><LF>). 731 // 732 // Look to see what type of line endings the file uses. If there's a 733 // CRLF, then we won't open the file up in binary mode. If there is 734 // just an LF or CR, then we will open the file up in binary mode. 735 // In this fashion, the output format should match the input format, unless 736 // the input format has inconsistent line endings. 737 // 738 // This should be a relatively fast operation since most files won't have 739 // all of their source code on a single line. However, that is still a 740 // concern, so if we scan for too long, we'll just assume the file should 741 // be opened in binary mode. 742 bool BinaryMode = true; 743 bool InvalidFile = false; 744 const SourceManager& SM = CI.getSourceManager(); 745 const llvm::MemoryBuffer *Buffer = SM.getBuffer(SM.getMainFileID(), 746 &InvalidFile); 747 if (!InvalidFile) { 748 const char *cur = Buffer->getBufferStart(); 749 const char *end = Buffer->getBufferEnd(); 750 const char *next = (cur != end) ? cur + 1 : end; 751 752 // Limit ourselves to only scanning 256 characters into the source 753 // file. This is mostly a sanity check in case the file has no 754 // newlines whatsoever. 755 if (end - cur > 256) end = cur + 256; 756 757 while (next < end) { 758 if (*cur == 0x0D) { // CR 759 if (*next == 0x0A) // CRLF 760 BinaryMode = false; 761 762 break; 763 } else if (*cur == 0x0A) // LF 764 break; 765 766 ++cur; 767 ++next; 768 } 769 } 770 771 std::unique_ptr<raw_ostream> OS = 772 CI.createDefaultOutputFile(BinaryMode, getCurrentFile()); 773 if (!OS) return; 774 775 DoPrintPreprocessedInput(CI.getPreprocessor(), OS.get(), 776 CI.getPreprocessorOutputOpts()); 777 } 778 779 void PrintPreambleAction::ExecuteAction() { 780 switch (getCurrentFileKind()) { 781 case IK_C: 782 case IK_CXX: 783 case IK_ObjC: 784 case IK_ObjCXX: 785 case IK_OpenCL: 786 case IK_CUDA: 787 break; 788 789 case IK_None: 790 case IK_Asm: 791 case IK_PreprocessedC: 792 case IK_PreprocessedCuda: 793 case IK_PreprocessedCXX: 794 case IK_PreprocessedObjC: 795 case IK_PreprocessedObjCXX: 796 case IK_AST: 797 case IK_LLVM_IR: 798 case IK_RenderScript: 799 // We can't do anything with these. 800 return; 801 } 802 803 CompilerInstance &CI = getCompilerInstance(); 804 auto Buffer = CI.getFileManager().getBufferForFile(getCurrentFile()); 805 if (Buffer) { 806 unsigned Preamble = 807 Lexer::ComputePreamble((*Buffer)->getBuffer(), CI.getLangOpts()).first; 808 llvm::outs().write((*Buffer)->getBufferStart(), Preamble); 809 } 810 } 811