1 //===- extra/modularize/Modularize.cpp - Check modularized headers --------===// 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 // Introduction 11 // 12 // This file implements a tool that checks whether a set of headers provides 13 // the consistent definitions required to use modules. It can also check an 14 // existing module map for full coverage of the headers in a directory tree. 15 // 16 // For example, in examining headers, it detects whether the same entity 17 // (say, a NULL macro or size_t typedef) is defined in multiple headers 18 // or whether a header produces different definitions under 19 // different circumstances. These conditions cause modules built from the 20 // headers to behave poorly, and should be fixed before introducing a module 21 // map. 22 // 23 // Modularize takes as input either one or more module maps (by default, 24 // "module.modulemap") or one or more text files contatining lists of headers 25 // to check. 26 // 27 // In the case of a module map, the module map must be well-formed in 28 // terms of syntax. Modularize will extract the header file names 29 // from the map. Only normal headers are checked, assuming headers 30 // marked "private", "textual", or "exclude" are not to be checked 31 // as a top-level include, assuming they either are included by 32 // other headers which are checked, or they are not suitable for 33 // modules. 34 // 35 // In the case of a file list, the list is a newline-separated list of headers 36 // to check with respect to each other. 37 // Lines beginning with '#' and empty lines are ignored. 38 // Header file names followed by a colon and other space-separated 39 // file names will include those extra files as dependencies. 40 // The file names can be relative or full paths, but must be on the 41 // same line. 42 // 43 // Modularize also accepts regular clang front-end arguments. 44 // 45 // Usage: modularize [(modularize options)] 46 // [(include-files_list)|(module map)]+ [(front-end-options) ...] 47 // 48 // Options: 49 // -prefix=(optional header path prefix) 50 // Note that unless a "-prefix (header path)" option is specified, 51 // non-absolute file paths in the header list file will be relative 52 // to the header list file directory. Use -prefix to specify a 53 // different directory. 54 // -module-map-path=(module map) 55 // Skip the checks, and instead act as a module.map generation 56 // assistant, generating a module map file based on the header list. 57 // An optional "-root-module=(rootName)" argument can specify a root 58 // module to be created in the generated module.map file. Note that 59 // you will likely need to edit this file to suit the needs of your 60 // headers. 61 // -problem-files-list=(problem files list file name) 62 // For use only with module map assistant. Input list of files that 63 // have problems with respect to modules. These will still be 64 // included in the generated module map, but will be marked as 65 // "excluded" headers. 66 // -root-module=(root module name) 67 // Specifies a root module to be created in the generated module.map 68 // file. 69 // -block-check-header-list-only 70 // Only warn if #include directives are inside extern or namespace 71 // blocks if the included header is in the header list. 72 // -no-coverage-check 73 // Don't do the coverage check. 74 // -coverage-check-only 75 // Only do the coverage check. 76 // -display-file-lists 77 // Display lists of good files (no compile errors), problem files, 78 // and a combined list with problem files preceded by a '#'. 79 // This can be used to quickly determine which files have problems. 80 // The latter combined list might be useful in starting to modularize 81 // a set of headers. You can start with a full list of headers, 82 // use -display-file-lists option, and then use the combined list as 83 // your intermediate list, uncommenting-out headers as you fix them. 84 // 85 // Note that by default, the modularize assumes .h files contain C++ source. 86 // If your .h files in the file list contain another language, you should 87 // append an appropriate -x option to your command line, i.e.: -x c 88 // 89 // Modularization Issue Checks 90 // 91 // In the process of checking headers for modularization issues, modularize 92 // will do normal parsing, reporting normal errors and warnings, 93 // but will also report special error messages like the following: 94 // 95 // error: '(symbol)' defined at multiple locations: 96 // (file):(row):(column) 97 // (file):(row):(column) 98 // 99 // error: header '(file)' has different contents depending on how it was 100 // included 101 // 102 // The latter might be followed by messages like the following: 103 // 104 // note: '(symbol)' in (file) at (row):(column) not always provided 105 // 106 // Checks will also be performed for macro expansions, defined(macro) 107 // expressions, and preprocessor conditional directives that evaluate 108 // inconsistently, and can produce error messages like the following: 109 // 110 // (...)/SubHeader.h:11:5: 111 // #if SYMBOL == 1 112 // ^ 113 // error: Macro instance 'SYMBOL' has different values in this header, 114 // depending on how it was included. 115 // 'SYMBOL' expanded to: '1' with respect to these inclusion paths: 116 // (...)/Header1.h 117 // (...)/SubHeader.h 118 // (...)/SubHeader.h:3:9: 119 // #define SYMBOL 1 120 // ^ 121 // Macro defined here. 122 // 'SYMBOL' expanded to: '2' with respect to these inclusion paths: 123 // (...)/Header2.h 124 // (...)/SubHeader.h 125 // (...)/SubHeader.h:7:9: 126 // #define SYMBOL 2 127 // ^ 128 // Macro defined here. 129 // 130 // Checks will also be performed for '#include' directives that are 131 // nested inside 'extern "C/C++" {}' or 'namespace (name) {}' blocks, 132 // and can produce error message like the following: 133 // 134 // IncludeInExtern.h:2:3 135 // #include "Empty.h" 136 // ^ 137 // error: Include directive within extern "C" {}. 138 // IncludeInExtern.h:1:1 139 // extern "C" { 140 // ^ 141 // The "extern "C" {}" block is here. 142 // 143 // See PreprocessorTracker.cpp for additional details. 144 // 145 // Module Map Coverage Check 146 // 147 // The coverage check uses the Clang ModuleMap class to read and parse the 148 // module map file. Starting at the module map file directory, or just the 149 // include paths, if specified, it will collect the names of all the files it 150 // considers headers (no extension, .h, or .inc--if you need more, modify the 151 // isHeader function). It then compares the headers against those referenced 152 // in the module map, either explicitly named, or implicitly named via an 153 // umbrella directory or umbrella file, as parsed by the ModuleMap object. 154 // If headers are found which are not referenced or covered by an umbrella 155 // directory or file, warning messages will be produced, and this program 156 // will return an error code of 1. Other errors result in an error code of 2. 157 // If no problems are found, an error code of 0 is returned. 158 // 159 // Note that in the case of umbrella headers, this tool invokes the compiler 160 // to preprocess the file, and uses a callback to collect the header files 161 // included by the umbrella header or any of its nested includes. If any 162 // front end options are needed for these compiler invocations, these 163 // can be included on the command line after the module map file argument. 164 // 165 // Warning message have the form: 166 // 167 // warning: module.modulemap does not account for file: Level3A.h 168 // 169 // Note that for the case of the module map referencing a file that does 170 // not exist, the module map parser in Clang will (at the time of this 171 // writing) display an error message. 172 // 173 // Module Map Assistant - Module Map Generation 174 // 175 // Modularize also has an option ("-module-map-path=module.modulemap") that will 176 // skip the checks, and instead act as a module.modulemap generation assistant, 177 // generating a module map file based on the header list. An optional 178 // "-root-module=(rootName)" argument can specify a root module to be 179 // created in the generated module.modulemap file. Note that you will likely 180 // need to edit this file to suit the needs of your headers. 181 // 182 // An example command line for generating a module.modulemap file: 183 // 184 // modularize -module-map-path=module.modulemap -root-module=myroot \ 185 // headerlist.txt 186 // 187 // Note that if the headers in the header list have partial paths, sub-modules 188 // will be created for the subdirectires involved, assuming that the 189 // subdirectories contain headers to be grouped into a module, but still with 190 // individual modules for the headers in the subdirectory. 191 // 192 // See the ModuleAssistant.cpp file comments for additional details about the 193 // implementation of the assistant mode. 194 // 195 // Future directions: 196 // 197 // Basically, we want to add new checks for whatever we can check with respect 198 // to checking headers for module'ability. 199 // 200 // Some ideas: 201 // 202 // 1. Omit duplicate "not always provided" messages 203 // 204 // 2. Add options to disable any of the checks, in case 205 // there is some problem with them, or the messages get too verbose. 206 // 207 // 3. Try to figure out the preprocessor conditional directives that 208 // contribute to problems and tie them to the inconsistent definitions. 209 // 210 // 4. There are some legitimate uses of preprocessor macros that 211 // modularize will flag as errors, such as repeatedly #include'ing 212 // a file and using interleaving defined/undefined macros 213 // to change declarations in the included file. Is there a way 214 // to address this? Maybe have modularize accept a list of macros 215 // to ignore. Otherwise you can just exclude the file, after checking 216 // for legitimate errors. 217 // 218 // 5. What else? 219 // 220 // General clean-up and refactoring: 221 // 222 // 1. The Location class seems to be something that we might 223 // want to design to be applicable to a wider range of tools, and stick it 224 // somewhere into Tooling/ in mainline 225 // 226 //===----------------------------------------------------------------------===// 227 228 #include "Modularize.h" 229 #include "ModularizeUtilities.h" 230 #include "PreprocessorTracker.h" 231 #include "clang/AST/ASTConsumer.h" 232 #include "clang/AST/ASTContext.h" 233 #include "clang/AST/RecursiveASTVisitor.h" 234 #include "clang/Basic/SourceManager.h" 235 #include "clang/Driver/Options.h" 236 #include "clang/Frontend/CompilerInstance.h" 237 #include "clang/Frontend/FrontendActions.h" 238 #include "clang/Lex/Preprocessor.h" 239 #include "clang/Tooling/CompilationDatabase.h" 240 #include "clang/Tooling/Tooling.h" 241 #include "llvm/Option/Arg.h" 242 #include "llvm/Option/ArgList.h" 243 #include "llvm/Option/OptTable.h" 244 #include "llvm/Option/Option.h" 245 #include "llvm/Support/CommandLine.h" 246 #include "llvm/Support/FileSystem.h" 247 #include "llvm/Support/MemoryBuffer.h" 248 #include "llvm/Support/Path.h" 249 #include <algorithm> 250 #include <fstream> 251 #include <iterator> 252 #include <string> 253 #include <vector> 254 255 using namespace clang; 256 using namespace clang::driver; 257 using namespace clang::driver::options; 258 using namespace clang::tooling; 259 using namespace llvm; 260 using namespace llvm::opt; 261 using namespace Modularize; 262 263 // Option to specify a file name for a list of header files to check. 264 static cl::list<std::string> 265 ListFileNames(cl::Positional, cl::value_desc("list"), 266 cl::desc("<list of one or more header list files>"), 267 cl::CommaSeparated); 268 269 // Collect all other arguments, which will be passed to the front end. 270 static cl::list<std::string> 271 CC1Arguments(cl::ConsumeAfter, 272 cl::desc("<arguments to be passed to front end>...")); 273 274 // Option to specify a prefix to be prepended to the header names. 275 static cl::opt<std::string> HeaderPrefix( 276 "prefix", cl::init(""), 277 cl::desc( 278 "Prepend header file paths with this prefix." 279 " If not specified," 280 " the files are considered to be relative to the header list file.")); 281 282 // Option for assistant mode, telling modularize to output a module map 283 // based on the headers list, and where to put it. 284 static cl::opt<std::string> ModuleMapPath( 285 "module-map-path", cl::init(""), 286 cl::desc("Turn on module map output and specify output path or file name." 287 " If no path is specified and if prefix option is specified," 288 " use prefix for file path.")); 289 290 // Option to specify list of problem files for assistant. 291 // This will cause assistant to exclude these files. 292 static cl::opt<std::string> ProblemFilesList( 293 "problem-files-list", cl::init(""), 294 cl::desc( 295 "List of files with compilation or modularization problems for" 296 " assistant mode. This will be excluded.")); 297 298 // Option for assistant mode, telling modularize the name of the root module. 299 static cl::opt<std::string> 300 RootModule("root-module", cl::init(""), 301 cl::desc("Specify the name of the root module.")); 302 303 // Option for limiting the #include-inside-extern-or-namespace-block 304 // check to only those headers explicitly listed in the header list. 305 // This is a work-around for private includes that purposefully get 306 // included inside blocks. 307 static cl::opt<bool> 308 BlockCheckHeaderListOnly("block-check-header-list-only", cl::init(false), 309 cl::desc("Only warn if #include directives are inside extern or namespace" 310 " blocks if the included header is in the header list.")); 311 312 // Option for include paths for coverage check. 313 static cl::list<std::string> 314 IncludePaths("I", cl::desc("Include path for coverage check."), 315 cl::ZeroOrMore, cl::value_desc("path")); 316 317 // Option for disabling the coverage check. 318 static cl::opt<bool> 319 NoCoverageCheck("no-coverage-check", cl::init(false), 320 cl::desc("Don't do the coverage check.")); 321 322 // Option for just doing the coverage check. 323 static cl::opt<bool> 324 CoverageCheckOnly("coverage-check-only", cl::init(false), 325 cl::desc("Only do the coverage check.")); 326 327 // Option for displaying lists of good, bad, and mixed files. 328 static cl::opt<bool> 329 DisplayFileLists("display-file-lists", cl::init(false), 330 cl::desc("Display lists of good files (no compile errors), problem files," 331 " and a combined list with problem files preceded by a '#'.")); 332 333 // Save the program name for error messages. 334 const char *Argv0; 335 // Save the command line for comments. 336 std::string CommandLine; 337 338 // Helper function for finding the input file in an arguments list. 339 static std::string findInputFile(const CommandLineArguments &CLArgs) { 340 std::unique_ptr<OptTable> Opts(createDriverOptTable()); 341 const unsigned IncludedFlagsBitmask = options::CC1Option; 342 unsigned MissingArgIndex, MissingArgCount; 343 SmallVector<const char *, 256> Argv; 344 for (CommandLineArguments::const_iterator I = CLArgs.begin(), 345 E = CLArgs.end(); 346 I != E; ++I) 347 Argv.push_back(I->c_str()); 348 InputArgList Args = Opts->ParseArgs(Argv, MissingArgIndex, MissingArgCount, 349 IncludedFlagsBitmask); 350 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT); 351 return ModularizeUtilities::getCanonicalPath(Inputs.back()); 352 } 353 354 // This arguments adjuster inserts "-include (file)" arguments for header 355 // dependencies. It also inserts a "-w" option and a "-x c++", 356 // if no other "-x" option is present. 357 static ArgumentsAdjuster 358 getModularizeArgumentsAdjuster(DependencyMap &Dependencies) { 359 return [&Dependencies](const CommandLineArguments &Args) { 360 std::string InputFile = findInputFile(Args); 361 DependentsVector &FileDependents = Dependencies[InputFile]; 362 CommandLineArguments NewArgs(Args); 363 if (int Count = FileDependents.size()) { 364 for (int Index = 0; Index < Count; ++Index) { 365 NewArgs.push_back("-include"); 366 std::string File(std::string("\"") + FileDependents[Index] + 367 std::string("\"")); 368 NewArgs.push_back(FileDependents[Index]); 369 } 370 } 371 // Ignore warnings. (Insert after "clang_tool" at beginning.) 372 NewArgs.insert(NewArgs.begin() + 1, "-w"); 373 // Since we are compiling .h files, assume C++ unless given a -x option. 374 if (std::find(NewArgs.begin(), NewArgs.end(), "-x") == NewArgs.end()) { 375 NewArgs.insert(NewArgs.begin() + 2, "-x"); 376 NewArgs.insert(NewArgs.begin() + 3, "c++"); 377 } 378 return NewArgs; 379 }; 380 } 381 382 // FIXME: The Location class seems to be something that we might 383 // want to design to be applicable to a wider range of tools, and stick it 384 // somewhere into Tooling/ in mainline 385 struct Location { 386 const FileEntry *File; 387 unsigned Line, Column; 388 389 Location() : File(), Line(), Column() {} 390 391 Location(SourceManager &SM, SourceLocation Loc) : File(), Line(), Column() { 392 Loc = SM.getExpansionLoc(Loc); 393 if (Loc.isInvalid()) 394 return; 395 396 std::pair<FileID, unsigned> Decomposed = SM.getDecomposedLoc(Loc); 397 File = SM.getFileEntryForID(Decomposed.first); 398 if (!File) 399 return; 400 401 Line = SM.getLineNumber(Decomposed.first, Decomposed.second); 402 Column = SM.getColumnNumber(Decomposed.first, Decomposed.second); 403 } 404 405 operator bool() const { return File != nullptr; } 406 407 friend bool operator==(const Location &X, const Location &Y) { 408 return X.File == Y.File && X.Line == Y.Line && X.Column == Y.Column; 409 } 410 411 friend bool operator!=(const Location &X, const Location &Y) { 412 return !(X == Y); 413 } 414 415 friend bool operator<(const Location &X, const Location &Y) { 416 if (X.File != Y.File) 417 return X.File < Y.File; 418 if (X.Line != Y.Line) 419 return X.Line < Y.Line; 420 return X.Column < Y.Column; 421 } 422 friend bool operator>(const Location &X, const Location &Y) { return Y < X; } 423 friend bool operator<=(const Location &X, const Location &Y) { 424 return !(Y < X); 425 } 426 friend bool operator>=(const Location &X, const Location &Y) { 427 return !(X < Y); 428 } 429 }; 430 431 struct Entry { 432 enum EntryKind { 433 EK_Tag, 434 EK_Value, 435 EK_Macro, 436 437 EK_NumberOfKinds 438 } Kind; 439 440 Location Loc; 441 442 StringRef getKindName() { return getKindName(Kind); } 443 static StringRef getKindName(EntryKind kind); 444 }; 445 446 // Return a string representing the given kind. 447 StringRef Entry::getKindName(Entry::EntryKind kind) { 448 switch (kind) { 449 case EK_Tag: 450 return "tag"; 451 case EK_Value: 452 return "value"; 453 case EK_Macro: 454 return "macro"; 455 case EK_NumberOfKinds: 456 break; 457 } 458 llvm_unreachable("invalid Entry kind"); 459 } 460 461 struct HeaderEntry { 462 std::string Name; 463 Location Loc; 464 465 friend bool operator==(const HeaderEntry &X, const HeaderEntry &Y) { 466 return X.Loc == Y.Loc && X.Name == Y.Name; 467 } 468 friend bool operator!=(const HeaderEntry &X, const HeaderEntry &Y) { 469 return !(X == Y); 470 } 471 friend bool operator<(const HeaderEntry &X, const HeaderEntry &Y) { 472 return X.Loc < Y.Loc || (X.Loc == Y.Loc && X.Name < Y.Name); 473 } 474 friend bool operator>(const HeaderEntry &X, const HeaderEntry &Y) { 475 return Y < X; 476 } 477 friend bool operator<=(const HeaderEntry &X, const HeaderEntry &Y) { 478 return !(Y < X); 479 } 480 friend bool operator>=(const HeaderEntry &X, const HeaderEntry &Y) { 481 return !(X < Y); 482 } 483 }; 484 485 typedef std::vector<HeaderEntry> HeaderContents; 486 487 class EntityMap : public StringMap<SmallVector<Entry, 2> > { 488 public: 489 DenseMap<const FileEntry *, HeaderContents> HeaderContentMismatches; 490 491 void add(const std::string &Name, enum Entry::EntryKind Kind, Location Loc) { 492 // Record this entity in its header. 493 HeaderEntry HE = { Name, Loc }; 494 CurHeaderContents[Loc.File].push_back(HE); 495 496 // Check whether we've seen this entry before. 497 SmallVector<Entry, 2> &Entries = (*this)[Name]; 498 for (unsigned I = 0, N = Entries.size(); I != N; ++I) { 499 if (Entries[I].Kind == Kind && Entries[I].Loc == Loc) 500 return; 501 } 502 503 // We have not seen this entry before; record it. 504 Entry E = { Kind, Loc }; 505 Entries.push_back(E); 506 } 507 508 void mergeCurHeaderContents() { 509 for (DenseMap<const FileEntry *, HeaderContents>::iterator 510 H = CurHeaderContents.begin(), 511 HEnd = CurHeaderContents.end(); 512 H != HEnd; ++H) { 513 // Sort contents. 514 std::sort(H->second.begin(), H->second.end()); 515 516 // Check whether we've seen this header before. 517 DenseMap<const FileEntry *, HeaderContents>::iterator KnownH = 518 AllHeaderContents.find(H->first); 519 if (KnownH == AllHeaderContents.end()) { 520 // We haven't seen this header before; record its contents. 521 AllHeaderContents.insert(*H); 522 continue; 523 } 524 525 // If the header contents are the same, we're done. 526 if (H->second == KnownH->second) 527 continue; 528 529 // Determine what changed. 530 std::set_symmetric_difference( 531 H->second.begin(), H->second.end(), KnownH->second.begin(), 532 KnownH->second.end(), 533 std::back_inserter(HeaderContentMismatches[H->first])); 534 } 535 536 CurHeaderContents.clear(); 537 } 538 539 private: 540 DenseMap<const FileEntry *, HeaderContents> CurHeaderContents; 541 DenseMap<const FileEntry *, HeaderContents> AllHeaderContents; 542 }; 543 544 class CollectEntitiesVisitor 545 : public RecursiveASTVisitor<CollectEntitiesVisitor> { 546 public: 547 CollectEntitiesVisitor(SourceManager &SM, EntityMap &Entities, 548 Preprocessor &PP, PreprocessorTracker &PPTracker, 549 int &HadErrors) 550 : SM(SM), Entities(Entities), PP(PP), PPTracker(PPTracker), 551 HadErrors(HadErrors) {} 552 553 bool TraverseStmt(Stmt *S) { return true; } 554 bool TraverseType(QualType T) { return true; } 555 bool TraverseTypeLoc(TypeLoc TL) { return true; } 556 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; } 557 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { 558 return true; 559 } 560 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) { 561 return true; 562 } 563 bool TraverseTemplateName(TemplateName Template) { return true; } 564 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; } 565 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) { 566 return true; 567 } 568 bool TraverseTemplateArguments(const TemplateArgument *Args, 569 unsigned NumArgs) { 570 return true; 571 } 572 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; } 573 bool TraverseLambdaCapture(LambdaCapture C) { return true; } 574 575 // Check 'extern "*" {}' block for #include directives. 576 bool VisitLinkageSpecDecl(LinkageSpecDecl *D) { 577 // Bail if not a block. 578 if (!D->hasBraces()) 579 return true; 580 SourceRange BlockRange = D->getSourceRange(); 581 const char *LinkageLabel; 582 switch (D->getLanguage()) { 583 case LinkageSpecDecl::lang_c: 584 LinkageLabel = "extern \"C\" {}"; 585 break; 586 case LinkageSpecDecl::lang_cxx: 587 LinkageLabel = "extern \"C++\" {}"; 588 break; 589 } 590 if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, LinkageLabel, 591 errs())) 592 HadErrors = 1; 593 return true; 594 } 595 596 // Check 'namespace (name) {}' block for #include directives. 597 bool VisitNamespaceDecl(const NamespaceDecl *D) { 598 SourceRange BlockRange = D->getSourceRange(); 599 std::string Label("namespace "); 600 Label += D->getName(); 601 Label += " {}"; 602 if (!PPTracker.checkForIncludesInBlock(PP, BlockRange, Label.c_str(), 603 errs())) 604 HadErrors = 1; 605 return true; 606 } 607 608 // Collect definition entities. 609 bool VisitNamedDecl(NamedDecl *ND) { 610 // We only care about file-context variables. 611 if (!ND->getDeclContext()->isFileContext()) 612 return true; 613 614 // Skip declarations that tend to be properly multiply-declared. 615 if (isa<NamespaceDecl>(ND) || isa<UsingDirectiveDecl>(ND) || 616 isa<NamespaceAliasDecl>(ND) || 617 isa<ClassTemplateSpecializationDecl>(ND) || isa<UsingDecl>(ND) || 618 isa<ClassTemplateDecl>(ND) || isa<TemplateTypeParmDecl>(ND) || 619 isa<TypeAliasTemplateDecl>(ND) || isa<UsingShadowDecl>(ND) || 620 isa<FunctionDecl>(ND) || isa<FunctionTemplateDecl>(ND) || 621 (isa<TagDecl>(ND) && 622 !cast<TagDecl>(ND)->isThisDeclarationADefinition())) 623 return true; 624 625 // Skip anonymous declarations. 626 if (!ND->getDeclName()) 627 return true; 628 629 // Get the qualified name. 630 std::string Name; 631 llvm::raw_string_ostream OS(Name); 632 ND->printQualifiedName(OS); 633 OS.flush(); 634 if (Name.empty()) 635 return true; 636 637 Location Loc(SM, ND->getLocation()); 638 if (!Loc) 639 return true; 640 641 Entities.add(Name, isa<TagDecl>(ND) ? Entry::EK_Tag : Entry::EK_Value, Loc); 642 return true; 643 } 644 645 private: 646 SourceManager &SM; 647 EntityMap &Entities; 648 Preprocessor &PP; 649 PreprocessorTracker &PPTracker; 650 int &HadErrors; 651 }; 652 653 class CollectEntitiesConsumer : public ASTConsumer { 654 public: 655 CollectEntitiesConsumer(EntityMap &Entities, 656 PreprocessorTracker &preprocessorTracker, 657 Preprocessor &PP, StringRef InFile, int &HadErrors) 658 : Entities(Entities), PPTracker(preprocessorTracker), PP(PP), 659 HadErrors(HadErrors) { 660 PPTracker.handlePreprocessorEntry(PP, InFile); 661 } 662 663 ~CollectEntitiesConsumer() override { PPTracker.handlePreprocessorExit(); } 664 665 void HandleTranslationUnit(ASTContext &Ctx) override { 666 SourceManager &SM = Ctx.getSourceManager(); 667 668 // Collect declared entities. 669 CollectEntitiesVisitor(SM, Entities, PP, PPTracker, HadErrors) 670 .TraverseDecl(Ctx.getTranslationUnitDecl()); 671 672 // Collect macro definitions. 673 for (Preprocessor::macro_iterator M = PP.macro_begin(), 674 MEnd = PP.macro_end(); 675 M != MEnd; ++M) { 676 Location Loc(SM, M->second.getLatest()->getLocation()); 677 if (!Loc) 678 continue; 679 680 Entities.add(M->first->getName().str(), Entry::EK_Macro, Loc); 681 } 682 683 // Merge header contents. 684 Entities.mergeCurHeaderContents(); 685 } 686 687 private: 688 EntityMap &Entities; 689 PreprocessorTracker &PPTracker; 690 Preprocessor &PP; 691 int &HadErrors; 692 }; 693 694 class CollectEntitiesAction : public SyntaxOnlyAction { 695 public: 696 CollectEntitiesAction(EntityMap &Entities, 697 PreprocessorTracker &preprocessorTracker, 698 int &HadErrors) 699 : Entities(Entities), PPTracker(preprocessorTracker), 700 HadErrors(HadErrors) {} 701 702 protected: 703 std::unique_ptr<clang::ASTConsumer> 704 CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override { 705 return llvm::make_unique<CollectEntitiesConsumer>( 706 Entities, PPTracker, CI.getPreprocessor(), InFile, HadErrors); 707 } 708 709 private: 710 EntityMap &Entities; 711 PreprocessorTracker &PPTracker; 712 int &HadErrors; 713 }; 714 715 class ModularizeFrontendActionFactory : public FrontendActionFactory { 716 public: 717 ModularizeFrontendActionFactory(EntityMap &Entities, 718 PreprocessorTracker &preprocessorTracker, 719 int &HadErrors) 720 : Entities(Entities), PPTracker(preprocessorTracker), 721 HadErrors(HadErrors) {} 722 723 CollectEntitiesAction *create() override { 724 return new CollectEntitiesAction(Entities, PPTracker, HadErrors); 725 } 726 727 private: 728 EntityMap &Entities; 729 PreprocessorTracker &PPTracker; 730 int &HadErrors; 731 }; 732 733 class CompileCheckVisitor 734 : public RecursiveASTVisitor<CompileCheckVisitor> { 735 public: 736 CompileCheckVisitor() {} 737 738 bool TraverseStmt(Stmt *S) { return true; } 739 bool TraverseType(QualType T) { return true; } 740 bool TraverseTypeLoc(TypeLoc TL) { return true; } 741 bool TraverseNestedNameSpecifier(NestedNameSpecifier *NNS) { return true; } 742 bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) { 743 return true; 744 } 745 bool TraverseDeclarationNameInfo(DeclarationNameInfo NameInfo) { 746 return true; 747 } 748 bool TraverseTemplateName(TemplateName Template) { return true; } 749 bool TraverseTemplateArgument(const TemplateArgument &Arg) { return true; } 750 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) { 751 return true; 752 } 753 bool TraverseTemplateArguments(const TemplateArgument *Args, 754 unsigned NumArgs) { 755 return true; 756 } 757 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) { return true; } 758 bool TraverseLambdaCapture(LambdaCapture C) { return true; } 759 760 // Check 'extern "*" {}' block for #include directives. 761 bool VisitLinkageSpecDecl(LinkageSpecDecl *D) { 762 return true; 763 } 764 765 // Check 'namespace (name) {}' block for #include directives. 766 bool VisitNamespaceDecl(const NamespaceDecl *D) { 767 return true; 768 } 769 770 // Collect definition entities. 771 bool VisitNamedDecl(NamedDecl *ND) { 772 return true; 773 } 774 }; 775 776 class CompileCheckConsumer : public ASTConsumer { 777 public: 778 CompileCheckConsumer() {} 779 780 void HandleTranslationUnit(ASTContext &Ctx) override { 781 CompileCheckVisitor().TraverseDecl(Ctx.getTranslationUnitDecl()); 782 } 783 }; 784 785 class CompileCheckAction : public SyntaxOnlyAction { 786 public: 787 CompileCheckAction() {} 788 789 protected: 790 std::unique_ptr<clang::ASTConsumer> 791 CreateASTConsumer(CompilerInstance &CI, StringRef InFile) override { 792 return llvm::make_unique<CompileCheckConsumer>(); 793 } 794 }; 795 796 class CompileCheckFrontendActionFactory : public FrontendActionFactory { 797 public: 798 CompileCheckFrontendActionFactory() {} 799 800 CompileCheckAction *create() override { 801 return new CompileCheckAction(); 802 } 803 }; 804 805 int main(int Argc, const char **Argv) { 806 807 // Save program name for error messages. 808 Argv0 = Argv[0]; 809 810 // Save program arguments for use in module.modulemap comment. 811 CommandLine = sys::path::stem(sys::path::filename(Argv0)); 812 for (int ArgIndex = 1; ArgIndex < Argc; ArgIndex++) { 813 CommandLine.append(" "); 814 CommandLine.append(Argv[ArgIndex]); 815 } 816 817 // This causes options to be parsed. 818 cl::ParseCommandLineOptions(Argc, Argv, "modularize.\n"); 819 820 // No go if we have no header list file. 821 if (ListFileNames.size() == 0) { 822 cl::PrintHelpMessage(); 823 return 1; 824 } 825 826 std::unique_ptr<ModularizeUtilities> ModUtil; 827 int HadErrors = 0; 828 829 ModUtil.reset( 830 ModularizeUtilities::createModularizeUtilities( 831 ListFileNames, HeaderPrefix, ProblemFilesList)); 832 833 // Get header file names and dependencies. 834 if (ModUtil->loadAllHeaderListsAndDependencies()) 835 HadErrors = 1; 836 837 // If we are in assistant mode, output the module map and quit. 838 if (ModuleMapPath.length() != 0) { 839 if (!createModuleMap(ModuleMapPath, ModUtil->HeaderFileNames, 840 ModUtil->ProblemFileNames, 841 ModUtil->Dependencies, HeaderPrefix, RootModule)) 842 return 1; // Failed. 843 return 0; // Success - Skip checks in assistant mode. 844 } 845 846 // If we're doing module maps. 847 if (!NoCoverageCheck && ModUtil->HasModuleMap) { 848 // Do coverage check. 849 if (ModUtil->doCoverageCheck(IncludePaths, CommandLine)) 850 HadErrors = 1; 851 } 852 853 // Bail early if only doing the coverage check. 854 if (CoverageCheckOnly) 855 return HadErrors; 856 857 // Create the compilation database. 858 SmallString<256> PathBuf; 859 sys::fs::current_path(PathBuf); 860 std::unique_ptr<CompilationDatabase> Compilations; 861 Compilations.reset( 862 new FixedCompilationDatabase(Twine(PathBuf), CC1Arguments)); 863 864 // Create preprocessor tracker, to watch for macro and conditional problems. 865 std::unique_ptr<PreprocessorTracker> PPTracker( 866 PreprocessorTracker::create(ModUtil->HeaderFileNames, 867 BlockCheckHeaderListOnly)); 868 869 // Coolect entities here. 870 EntityMap Entities; 871 872 // Because we can't easily determine which files failed 873 // during the tool run, if we're collecting the file lists 874 // for display, we do a first compile pass on individual 875 // files to find which ones don't compile stand-alone. 876 if (DisplayFileLists) { 877 // First, make a pass to just get compile errors. 878 for (auto &CompileCheckFile : ModUtil->HeaderFileNames) { 879 llvm::SmallVector<std::string, 32> CompileCheckFileArray; 880 CompileCheckFileArray.push_back(CompileCheckFile); 881 ClangTool CompileCheckTool(*Compilations, CompileCheckFileArray); 882 CompileCheckTool.appendArgumentsAdjuster( 883 getModularizeArgumentsAdjuster(ModUtil->Dependencies)); 884 int CompileCheckFileErrors = 0; 885 CompileCheckFrontendActionFactory CompileCheckFactory; 886 CompileCheckFileErrors |= CompileCheckTool.run(&CompileCheckFactory); 887 if (CompileCheckFileErrors != 0) { 888 ModUtil->addUniqueProblemFile(CompileCheckFile); // Save problem file. 889 HadErrors |= 1; 890 } 891 else 892 ModUtil->addNoCompileErrorsFile(CompileCheckFile); // Save good file. 893 } 894 } 895 896 // Then we make another pass on the good files to do the rest of the work. 897 ClangTool Tool(*Compilations, 898 (DisplayFileLists ? ModUtil->GoodFileNames : ModUtil->HeaderFileNames)); 899 Tool.appendArgumentsAdjuster( 900 getModularizeArgumentsAdjuster(ModUtil->Dependencies)); 901 ModularizeFrontendActionFactory Factory(Entities, *PPTracker, HadErrors); 902 HadErrors |= Tool.run(&Factory); 903 904 // Create a place to save duplicate entity locations, separate bins per kind. 905 typedef SmallVector<Location, 8> LocationArray; 906 typedef SmallVector<LocationArray, Entry::EK_NumberOfKinds> EntryBinArray; 907 EntryBinArray EntryBins; 908 int KindIndex; 909 for (KindIndex = 0; KindIndex < Entry::EK_NumberOfKinds; ++KindIndex) { 910 LocationArray Array; 911 EntryBins.push_back(Array); 912 } 913 914 // Check for the same entity being defined in multiple places. 915 for (EntityMap::iterator E = Entities.begin(), EEnd = Entities.end(); 916 E != EEnd; ++E) { 917 // If only one occurrence, exit early. 918 if (E->second.size() == 1) 919 continue; 920 // Clear entity locations. 921 for (EntryBinArray::iterator CI = EntryBins.begin(), CE = EntryBins.end(); 922 CI != CE; ++CI) { 923 CI->clear(); 924 } 925 // Walk the entities of a single name, collecting the locations, 926 // separated into separate bins. 927 for (unsigned I = 0, N = E->second.size(); I != N; ++I) { 928 EntryBins[E->second[I].Kind].push_back(E->second[I].Loc); 929 } 930 // Report any duplicate entity definition errors. 931 int KindIndex = 0; 932 for (EntryBinArray::iterator DI = EntryBins.begin(), DE = EntryBins.end(); 933 DI != DE; ++DI, ++KindIndex) { 934 int ECount = DI->size(); 935 // If only 1 occurrence of this entity, skip it, we only report duplicates. 936 if (ECount <= 1) 937 continue; 938 LocationArray::iterator FI = DI->begin(); 939 StringRef kindName = Entry::getKindName((Entry::EntryKind)KindIndex); 940 errs() << "error: " << kindName << " '" << E->first() 941 << "' defined at multiple locations:\n"; 942 for (LocationArray::iterator FE = DI->end(); FI != FE; ++FI) { 943 errs() << " " << FI->File->getName() << ":" << FI->Line << ":" 944 << FI->Column << "\n"; 945 ModUtil->addUniqueProblemFile(FI->File->getName()); 946 } 947 HadErrors = 1; 948 } 949 } 950 951 // Complain about macro instance in header files that differ based on how 952 // they are included. 953 if (PPTracker->reportInconsistentMacros(errs())) 954 HadErrors = 1; 955 956 // Complain about preprocessor conditional directives in header files that 957 // differ based on how they are included. 958 if (PPTracker->reportInconsistentConditionals(errs())) 959 HadErrors = 1; 960 961 // Complain about any headers that have contents that differ based on how 962 // they are included. 963 // FIXME: Could we provide information about which preprocessor conditionals 964 // are involved? 965 for (DenseMap<const FileEntry *, HeaderContents>::iterator 966 H = Entities.HeaderContentMismatches.begin(), 967 HEnd = Entities.HeaderContentMismatches.end(); 968 H != HEnd; ++H) { 969 if (H->second.empty()) { 970 errs() << "internal error: phantom header content mismatch\n"; 971 continue; 972 } 973 974 HadErrors = 1; 975 ModUtil->addUniqueProblemFile(H->first->getName()); 976 errs() << "error: header '" << H->first->getName() 977 << "' has different contents depending on how it was included.\n"; 978 for (unsigned I = 0, N = H->second.size(); I != N; ++I) { 979 errs() << "note: '" << H->second[I].Name << "' in " 980 << H->second[I].Loc.File->getName() << " at " 981 << H->second[I].Loc.Line << ":" << H->second[I].Loc.Column 982 << " not always provided\n"; 983 } 984 } 985 986 if (DisplayFileLists) { 987 ModUtil->displayProblemFiles(); 988 ModUtil->displayGoodFiles(); 989 ModUtil->displayCombinedFiles(); 990 } 991 992 return HadErrors; 993 } 994