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