1 //===--- IncludeCleaner.cpp - Unused/Missing Headers Analysis ---*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "IncludeCleaner.h" 10 #include "Config.h" 11 #include "Headers.h" 12 #include "ParsedAST.h" 13 #include "Protocol.h" 14 #include "SourceCode.h" 15 #include "support/Logger.h" 16 #include "support/Trace.h" 17 #include "clang/AST/ExprCXX.h" 18 #include "clang/AST/RecursiveASTVisitor.h" 19 #include "clang/Basic/SourceLocation.h" 20 #include "clang/Basic/SourceManager.h" 21 #include "clang/Lex/HeaderSearch.h" 22 #include "clang/Lex/Preprocessor.h" 23 #include "clang/Tooling/Syntax/Tokens.h" 24 #include "llvm/Support/FormatVariadic.h" 25 #include "llvm/Support/Path.h" 26 27 namespace clang { 28 namespace clangd { 29 namespace { 30 31 /// Crawler traverses the AST and feeds in the locations of (sometimes 32 /// implicitly) used symbols into \p Result. 33 class ReferencedLocationCrawler 34 : public RecursiveASTVisitor<ReferencedLocationCrawler> { 35 public: 36 ReferencedLocationCrawler(ReferencedLocations &Result, 37 const SourceManager &SM) 38 : Result(Result), SM(SM) {} 39 40 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 41 add(DRE->getDecl()); 42 add(DRE->getFoundDecl()); 43 return true; 44 } 45 46 bool VisitMemberExpr(MemberExpr *ME) { 47 add(ME->getMemberDecl()); 48 add(ME->getFoundDecl().getDecl()); 49 return true; 50 } 51 52 bool VisitTagType(TagType *TT) { 53 add(TT->getDecl()); 54 return true; 55 } 56 57 bool VisitFunctionDecl(FunctionDecl *FD) { 58 // Function definition will require redeclarations to be included. 59 if (FD->isThisDeclarationADefinition()) 60 add(FD); 61 return true; 62 } 63 64 bool VisitCXXConstructExpr(CXXConstructExpr *CCE) { 65 add(CCE->getConstructor()); 66 return true; 67 } 68 69 bool VisitTemplateSpecializationType(TemplateSpecializationType *TST) { 70 if (isNew(TST)) { 71 add(TST->getTemplateName().getAsTemplateDecl()); // Primary template. 72 add(TST->getAsCXXRecordDecl()); // Specialization 73 } 74 return true; 75 } 76 77 bool VisitTypedefType(TypedefType *TT) { 78 add(TT->getDecl()); 79 return true; 80 } 81 82 // Consider types of any subexpression used, even if the type is not named. 83 // This is helpful in getFoo().bar(), where Foo must be complete. 84 // FIXME(kirillbobyrev): Should we tweak this? It may not be desirable to 85 // consider types "used" when they are not directly spelled in code. 86 bool VisitExpr(Expr *E) { 87 TraverseType(E->getType()); 88 return true; 89 } 90 91 bool TraverseType(QualType T) { 92 if (isNew(T.getTypePtrOrNull())) // don't care about quals 93 Base::TraverseType(T); 94 return true; 95 } 96 97 bool VisitUsingDecl(UsingDecl *D) { 98 for (const auto *Shadow : D->shadows()) 99 add(Shadow->getTargetDecl()); 100 return true; 101 } 102 103 // Enums may be usefully forward-declared as *complete* types by specifying 104 // an underlying type. In this case, the definition should see the declaration 105 // so they can be checked for compatibility. 106 bool VisitEnumDecl(EnumDecl *D) { 107 if (D->isThisDeclarationADefinition() && D->getIntegerTypeSourceInfo()) 108 add(D); 109 return true; 110 } 111 112 // When the overload is not resolved yet, mark all candidates as used. 113 bool VisitOverloadExpr(OverloadExpr *E) { 114 for (const auto *ResolutionDecl : E->decls()) 115 add(ResolutionDecl); 116 return true; 117 } 118 119 private: 120 using Base = RecursiveASTVisitor<ReferencedLocationCrawler>; 121 122 void add(const Decl *D) { 123 if (!D || !isNew(D->getCanonicalDecl())) 124 return; 125 // If we see a declaration in the mainfile, skip all non-definition decls. 126 // We only do this for classes because forward declarations are common and 127 // we don't want to include every header that forward-declares the symbol 128 // because they're often unrelated. 129 if (const auto *RD = llvm::dyn_cast<RecordDecl>(D)) { 130 if (SM.isInMainFile(RD->getMostRecentDecl()->getBeginLoc())) { 131 if (const auto *Definition = RD->getMostRecentDecl()->getDefinition()) 132 Result.insert(Definition->getLocation()); 133 return; 134 } 135 } 136 for (const Decl *Redecl : D->redecls()) 137 Result.insert(Redecl->getLocation()); 138 } 139 140 bool isNew(const void *P) { return P && Visited.insert(P).second; } 141 142 ReferencedLocations &Result; 143 llvm::DenseSet<const void *> Visited; 144 const SourceManager &SM; 145 }; 146 147 // Given a set of referenced FileIDs, determines all the potentially-referenced 148 // files and macros by traversing expansion/spelling locations of macro IDs. 149 // This is used to map the referenced SourceLocations onto real files. 150 struct ReferencedFiles { 151 ReferencedFiles(const SourceManager &SM) : SM(SM) {} 152 llvm::DenseSet<FileID> Files; 153 llvm::DenseSet<FileID> Macros; 154 const SourceManager &SM; 155 156 void add(SourceLocation Loc) { add(SM.getFileID(Loc), Loc); } 157 158 void add(FileID FID, SourceLocation Loc) { 159 if (FID.isInvalid()) 160 return; 161 assert(SM.isInFileID(Loc, FID)); 162 if (Loc.isFileID()) { 163 Files.insert(FID); 164 return; 165 } 166 // Don't process the same macro FID twice. 167 if (!Macros.insert(FID).second) 168 return; 169 const auto &Exp = SM.getSLocEntry(FID).getExpansion(); 170 add(Exp.getSpellingLoc()); 171 add(Exp.getExpansionLocStart()); 172 add(Exp.getExpansionLocEnd()); 173 } 174 }; 175 176 // Returns the range starting at '#' and ending at EOL. Escaped newlines are not 177 // handled. 178 clangd::Range getDiagnosticRange(llvm::StringRef Code, unsigned HashOffset) { 179 clangd::Range Result; 180 Result.end = Result.start = offsetToPosition(Code, HashOffset); 181 182 // Span the warning until the EOL or EOF. 183 Result.end.character += 184 lspLength(Code.drop_front(HashOffset).take_until([](char C) { 185 return C == '\n' || C == '\r'; 186 })); 187 return Result; 188 } 189 190 // Finds locations of macros referenced from within the main file. That includes 191 // references that were not yet expanded, e.g `BAR` in `#define FOO BAR`. 192 void findReferencedMacros(ParsedAST &AST, ReferencedLocations &Result) { 193 trace::Span Tracer("IncludeCleaner::findReferencedMacros"); 194 auto &SM = AST.getSourceManager(); 195 auto &PP = AST.getPreprocessor(); 196 // FIXME(kirillbobyrev): The macros from the main file are collected in 197 // ParsedAST's MainFileMacros. However, we can't use it here because it 198 // doesn't handle macro references that were not expanded, e.g. in macro 199 // definitions or preprocessor-disabled sections. 200 // 201 // Extending MainFileMacros to collect missing references and switching to 202 // this mechanism (as opposed to iterating through all tokens) will improve 203 // the performance of findReferencedMacros and also improve other features 204 // relying on MainFileMacros. 205 for (const syntax::Token &Tok : 206 AST.getTokens().spelledTokens(SM.getMainFileID())) { 207 auto Macro = locateMacroAt(Tok, PP); 208 if (!Macro) 209 continue; 210 auto Loc = Macro->Info->getDefinitionLoc(); 211 if (Loc.isValid()) 212 Result.insert(Loc); 213 } 214 } 215 216 bool mayConsiderUnused(const Inclusion &Inc, ParsedAST &AST) { 217 // FIXME(kirillbobyrev): We currently do not support the umbrella headers. 218 // Standard Library headers are typically umbrella headers, and system 219 // headers are likely to be the Standard Library headers. Until we have a 220 // good support for umbrella headers and Standard Library headers, don't warn 221 // about them. 222 if (Inc.Written.front() == '<') 223 return false; 224 // Headers without include guards have side effects and are not 225 // self-contained, skip them. 226 assert(Inc.HeaderID); 227 auto FE = AST.getSourceManager().getFileManager().getFile( 228 AST.getIncludeStructure().getRealPath( 229 static_cast<IncludeStructure::HeaderID>(*Inc.HeaderID))); 230 assert(FE); 231 if (!AST.getPreprocessor().getHeaderSearchInfo().isFileMultipleIncludeGuarded( 232 *FE)) { 233 dlog("{0} doesn't have header guard and will not be considered unused", 234 (*FE)->getName()); 235 return false; 236 } 237 return true; 238 } 239 240 // In case symbols are coming from non self-contained header, we need to find 241 // its first includer that is self-contained. This is the header users can 242 // include, so it will be responsible for bringing the symbols from given 243 // header into the scope. 244 FileID headerResponsible(FileID ID, const SourceManager &SM, 245 const IncludeStructure &Includes) { 246 // Unroll the chain of non self-contained headers until we find the one that 247 // can be included. 248 for (const FileEntry *FE = SM.getFileEntryForID(ID); ID != SM.getMainFileID(); 249 FE = SM.getFileEntryForID(ID)) { 250 // If FE is nullptr, we consider it to be the responsible header. 251 if (!FE) 252 break; 253 auto HID = Includes.getID(FE); 254 assert(HID && "We're iterating over headers already existing in " 255 "IncludeStructure"); 256 if (Includes.isSelfContained(*HID)) 257 break; 258 // The header is not self-contained: put the responsibility for its symbols 259 // on its includer. 260 ID = SM.getFileID(SM.getIncludeLoc(ID)); 261 } 262 return ID; 263 } 264 265 } // namespace 266 267 ReferencedLocations findReferencedLocations(ParsedAST &AST) { 268 trace::Span Tracer("IncludeCleaner::findReferencedLocations"); 269 ReferencedLocations Result; 270 ReferencedLocationCrawler Crawler(Result, AST.getSourceManager()); 271 Crawler.TraverseAST(AST.getASTContext()); 272 findReferencedMacros(AST, Result); 273 return Result; 274 } 275 276 llvm::DenseSet<FileID> 277 findReferencedFiles(const llvm::DenseSet<SourceLocation> &Locs, 278 const IncludeStructure &Includes, const SourceManager &SM) { 279 std::vector<SourceLocation> Sorted{Locs.begin(), Locs.end()}; 280 llvm::sort(Sorted); // Group by FileID. 281 ReferencedFiles Files(SM); 282 for (auto It = Sorted.begin(); It < Sorted.end();) { 283 FileID FID = SM.getFileID(*It); 284 Files.add(FID, *It); 285 // Cheaply skip over all the other locations from the same FileID. 286 // This avoids lots of redundant Loc->File lookups for the same file. 287 do 288 ++It; 289 while (It != Sorted.end() && SM.isInFileID(*It, FID)); 290 } 291 // If a header is not self-contained, we consider its symbols a logical part 292 // of the including file. Therefore, mark the parents of all used 293 // non-self-contained FileIDs as used. Perform this on FileIDs rather than 294 // HeaderIDs, as each inclusion of a non-self-contained file is distinct. 295 llvm::DenseSet<FileID> Result; 296 for (FileID ID : Files.Files) 297 Result.insert(headerResponsible(ID, SM, Includes)); 298 return Result; 299 } 300 301 std::vector<const Inclusion *> 302 getUnused(ParsedAST &AST, 303 const llvm::DenseSet<IncludeStructure::HeaderID> &ReferencedFiles) { 304 trace::Span Tracer("IncludeCleaner::getUnused"); 305 std::vector<const Inclusion *> Unused; 306 for (const Inclusion &MFI : AST.getIncludeStructure().MainFileIncludes) { 307 if (!MFI.HeaderID) 308 continue; 309 auto IncludeID = static_cast<IncludeStructure::HeaderID>(*MFI.HeaderID); 310 bool Used = ReferencedFiles.contains(IncludeID); 311 if (!Used && !mayConsiderUnused(MFI, AST)) { 312 dlog("{0} was not used, but is not eligible to be diagnosed as unused", 313 MFI.Written); 314 continue; 315 } 316 if (!Used) 317 Unused.push_back(&MFI); 318 dlog("{0} is {1}", MFI.Written, Used ? "USED" : "UNUSED"); 319 } 320 return Unused; 321 } 322 323 #ifndef NDEBUG 324 // Is FID a <built-in>, <scratch space> etc? 325 static bool isSpecialBuffer(FileID FID, const SourceManager &SM) { 326 const SrcMgr::FileInfo &FI = SM.getSLocEntry(FID).getFile(); 327 return FI.getName().startswith("<"); 328 } 329 #endif 330 331 llvm::DenseSet<IncludeStructure::HeaderID> 332 translateToHeaderIDs(const llvm::DenseSet<FileID> &Files, 333 const IncludeStructure &Includes, 334 const SourceManager &SM) { 335 trace::Span Tracer("IncludeCleaner::translateToHeaderIDs"); 336 llvm::DenseSet<IncludeStructure::HeaderID> TranslatedHeaderIDs; 337 TranslatedHeaderIDs.reserve(Files.size()); 338 for (FileID FID : Files) { 339 const FileEntry *FE = SM.getFileEntryForID(FID); 340 if (!FE) { 341 assert(isSpecialBuffer(FID, SM)); 342 continue; 343 } 344 const auto File = Includes.getID(FE); 345 assert(File); 346 TranslatedHeaderIDs.insert(*File); 347 } 348 return TranslatedHeaderIDs; 349 } 350 351 std::vector<const Inclusion *> computeUnusedIncludes(ParsedAST &AST) { 352 const auto &SM = AST.getSourceManager(); 353 354 auto Refs = findReferencedLocations(AST); 355 auto ReferencedFileIDs = findReferencedFiles(Refs, AST.getIncludeStructure(), 356 AST.getSourceManager()); 357 auto ReferencedHeaders = 358 translateToHeaderIDs(ReferencedFileIDs, AST.getIncludeStructure(), SM); 359 return getUnused(AST, ReferencedHeaders); 360 } 361 362 std::vector<Diag> issueUnusedIncludesDiagnostics(ParsedAST &AST, 363 llvm::StringRef Code) { 364 const Config &Cfg = Config::current(); 365 if (Cfg.Diagnostics.UnusedIncludes != Config::UnusedIncludesPolicy::Strict || 366 Cfg.Diagnostics.SuppressAll || 367 Cfg.Diagnostics.Suppress.contains("unused-includes")) 368 return {}; 369 trace::Span Tracer("IncludeCleaner::issueUnusedIncludesDiagnostics"); 370 std::vector<Diag> Result; 371 std::string FileName = 372 AST.getSourceManager() 373 .getFileEntryForID(AST.getSourceManager().getMainFileID()) 374 ->getName() 375 .str(); 376 for (const auto *Inc : computeUnusedIncludes(AST)) { 377 Diag D; 378 D.Message = 379 llvm::formatv("included header {0} is not used", 380 llvm::sys::path::filename( 381 Inc->Written.substr(1, Inc->Written.size() - 2), 382 llvm::sys::path::Style::posix)); 383 D.Name = "unused-includes"; 384 D.Source = Diag::DiagSource::Clangd; 385 D.File = FileName; 386 D.Severity = DiagnosticsEngine::Warning; 387 D.Tags.push_back(Unnecessary); 388 D.Range = getDiagnosticRange(Code, Inc->HashOffset); 389 // FIXME(kirillbobyrev): Removing inclusion might break the code if the 390 // used headers are only reachable transitively through this one. Suggest 391 // including them directly instead. 392 // FIXME(kirillbobyrev): Add fix suggestion for adding IWYU pragmas 393 // (keep/export) remove the warning once we support IWYU pragmas. 394 D.Fixes.emplace_back(); 395 D.Fixes.back().Message = "remove #include directive"; 396 D.Fixes.back().Edits.emplace_back(); 397 D.Fixes.back().Edits.back().range.start.line = Inc->HashLine; 398 D.Fixes.back().Edits.back().range.end.line = Inc->HashLine + 1; 399 D.InsideMainFile = true; 400 Result.push_back(std::move(D)); 401 } 402 return Result; 403 } 404 405 } // namespace clangd 406 } // namespace clang 407