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