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