Skip to content

Instantly share code, notes, and snippets.

@vsapsai
Created February 10, 2015 01:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vsapsai/342a87c1135ecc52b116 to your computer and use it in GitHub Desktop.
Save vsapsai/342a87c1135ecc52b116 to your computer and use it in GitHub Desktop.
Check which code parts are exercised by try-catch blocks.
-: 0:Source:/Users/vsapsay/Projects/OpenSource/llvm/llvm/tools/clang/tools/include-what-you-use/iwyu.cc
-: 0:Graph:iwyu.gcno
-: 0:Data:iwyu.gcda
-: 0:Runs:1
-: 0:Programs:1
-: 1://===--- iwyu.cc - main logic and driver for include-what-you-use ---------===//
-: 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:// A Clang-based tool that catches Include-What-You-Use violations:
-: 11://
-: 12:// The analysis enforces the following rule:
-: 13://
-: 14:// - For every symbol (variable, function, constant, type, and macro)
-: 15:// X in C++ file CU.cc, X must be declared in CU.cc or in a header
-: 16:// file directly included by itself, CU.h, or CU-inl.h. Likewise
-: 17:// for CU.h and CU-inl.h.
-: 18://
-: 19:// The rule has a few slight wrinkles:
-: 20:// 1) CU_test.cc can also 'inherit' #includes from CU.h and CU-inl.h.
-: 21:// Likewise for CU_unittest.cc, CU_regtest.cc, etc.
-: 22:// 2) CU.cc can inherit #includes from ../public/CU.h in addition to
-: 23:// ./CU.h (likewise for -inl.h).
-: 24:// 3) For system #includes, and a few google #includes, we hard-code
-: 25:// in knowledge of which #include files are public and which are not.
-: 26:// (For instance, <vector> is public, <bits/stl_vector.h> is not.)
-: 27:// We force CU.cc, CU.h, and CU-inl.h to #include the public version.
-: 28://
-: 29:// iwyu.cc checks if a symbol can be forward-declared instead of fully
-: 30:// declared. If so, it will enforce the rule that the symbol is
-: 31:// forward-declared in the file that references it. We only forward-
-: 32:// declare classes and structs (possibly templatized). We will not
-: 33:// try to forward-declare variables or functions.
-: 34://
-: 35:// Checking iwyu violations for variables, functions, constants, and
-: 36:// macros is easy. Types can be trickier. Obviously, if you declare
-: 37:// a variable of type Foo in cu.cc, it's straightforward to check
-: 38:// whether it's an iwyu violation. But what if you call a function
-: 39:// that returns a type, e.g. 'if (FnReturningSomeSTLType()->empty())'?
-: 40:// Is it an iwyu violation if you don't #include the header for that
-: 41:// STL type? We say no: whatever file provided the function
-: 42:// FnReturningSomeSTLType is also responsible for providing whatever
-: 43:// the STL type is, so we don't have to. Otherwise, we get into an
-: 44:// un-fun propagation problem if we change the signature of
-: 45:// FnReturningSomeSTLType to return a different type of STL type. So
-: 46:// in general, types are only iwyu-checked if they appear explicitly
-: 47:// in the source code.
-: 48://
-: 49:// It can likewise be difficult to say whether a template arg is
-: 50:// forward-declable: set<Foo*> x does not require the full type info
-: 51:// for Foo, but remove_pointer<Foo*>::type does. And f<Foo>() doesn't
-: 52:// require full type info for Foo if f doesn't actually use Foo in it.
-: 53:// For now we do the simple heuristic that if the template arg is a
-: 54:// pointer, it's ok if it's forward-declared, and if not, it's not.
-: 55://
-: 56:// We use the following terminology:
-: 57://
-: 58:// - A *symbol* is the name of a function, variable, constant, type,
-: 59:// macro, etc.
-: 60://
-: 61:// - A *quoted include path* is an include path with the surrounding <>
-: 62:// or "", e.g. <stdio.h> or "ads/util.h".
-: 63://
-: 64:// - Any #include falls into exactly one of three (non-overlapping)
-: 65:// categories:
-: 66://
-: 67:// * it's said to be *necessary* if it's a compiler or IWYU error to
-: 68:// omit the #include;
-: 69://
-: 70:// * it's said to be *optional* if the #include is unnecessary but
-: 71:// having it is not an IWYU error either (e.g. if bar.h is a
-: 72:// necessary #include of foo.h, and foo.cc uses symbols from
-: 73:// bar.h, it's optional for foo.cc to #include bar.h.);
-: 74://
-: 75:// * it's said to be *undesired* if it's an IWYU error to have the
-: 76:// #include.
-: 77://
-: 78:// Therefore, when we say a #include is *desired*, we mean that it's
-: 79:// either necessary or optional.
-: 80://
-: 81:// - We also say that a #include is *recommended* if the IWYU tool
-: 82:// recommends to have it in the C++ source file. Obviously, any
-: 83:// necessary #include must be recommended, and no undesired
-: 84:// #include can be recommended. An optional #include can be
-: 85:// either recommended or not -- the IWYU tool can decide which
-: 86:// case it is. For example, if foo.cc desires bar.h, but can
-: 87:// already get it via foo.h, IWYU won't recommend foo.cc to
-: 88:// #include bar.h, unless it already does so.
-: 89:#include <stddef.h> // for size_t
-: 90:#include <stdio.h> // for snprintf
-: 91:#include <stdlib.h> // for atoi, exit
-: 92:#include <string.h>
-: 93:#include <algorithm> // for swap, find, make_pair
-: 94:#include <deque> // for swap
-: 95:#include <iterator> // for find
-: 96:#include <list> // for swap
-: 97:#include <map> // for map, swap, etc
-: 98:#include <memory> // for unique_ptr
-: 99:#include <set> // for set, set<>::iterator, swap
-: 100:#include <string> // for string, operator+, etc
-: 101:#include <utility> // for pair, make_pair
-: 102:#include <vector> // for vector, swap
-: 103:
-: 104:#include "iwyu_ast_util.h"
-: 105:#include "iwyu_cache.h"
-: 106:#include "iwyu_globals.h"
-: 107:#include "iwyu_location_util.h"
-: 108:#include "iwyu_output.h"
-: 109:#include "iwyu_path_util.h"
-: 110:// This is needed for
-: 111:// preprocessor_info().PublicHeaderIntendsToProvide(). Somehow IWYU
-: 112:// removes it mistakenly.
-: 113:#include "iwyu_preprocessor.h" // IWYU pragma: keep
-: 114:#include "iwyu_stl_util.h"
-: 115:#include "iwyu_string_util.h"
-: 116:#include "iwyu_verrs.h"
-: 117:#include "port.h" // for CHECK_
-: 118:#include "llvm/Support/Casting.h"
-: 119:#include "llvm/Support/raw_ostream.h"
-: 120:#include "clang/AST/ASTConsumer.h"
-: 121:#include "clang/AST/ASTContext.h"
-: 122:#include "clang/AST/Decl.h"
-: 123:#include "clang/AST/DeclBase.h"
-: 124:#include "clang/AST/DeclTemplate.h"
-: 125:#include "clang/AST/NestedNameSpecifier.h"
-: 126:#include "clang/AST/RecursiveASTVisitor.h"
-: 127:#include "clang/AST/Stmt.h"
-: 128:#include "clang/AST/TemplateBase.h"
-: 129:#include "clang/AST/Type.h"
-: 130:#include "clang/AST/TypeLoc.h"
-: 131:#include "clang/Basic/SourceLocation.h"
-: 132:#include "clang/Frontend/CompilerInstance.h"
-: 133:#include "clang/Frontend/FrontendAction.h"
-: 134:#include "clang/Lex/Preprocessor.h"
-: 135:#include "clang/Sema/Sema.h"
-: 136:
-: 137:namespace clang {
-: 138:class FileEntry;
-: 139:class PPCallbacks;
-: 140:class SourceManager;
-: 141:class Token;
-: 142:} // namespace clang
-: 143:
-: 144:namespace include_what_you_use {
-: 145:
-: 146:// I occasionally clean up this list by running:
-: 147:// $ grep "using clang":: iwyu.cc | cut -b14- | tr -d ";" | while read t; do grep -q "[^:]$t" iwyu.cc || echo $t; done
-: 148:using clang::ASTConsumer;
-: 149:using clang::ASTContext;
-: 150:using clang::ASTFrontendAction;
-: 151:using clang::ArrayType;
-: 152:using clang::Attr;
-: 153:using clang::CXXConstructExpr;
-: 154:using clang::CXXConstructorDecl;
-: 155:using clang::CXXCtorInitializer;
-: 156:using clang::CXXDeleteExpr;
-: 157:using clang::CXXDestructorDecl;
-: 158:using clang::CXXMethodDecl;
-: 159:using clang::CXXNewExpr;
-: 160:using clang::CXXOperatorCallExpr;
-: 161:using clang::CXXRecordDecl;
-: 162:using clang::CallExpr;
-: 163:using clang::ClassTemplateDecl;
-: 164:using clang::ClassTemplateSpecializationDecl;
-: 165:using clang::CompilerInstance;
-: 166:using clang::Decl;
-: 167:using clang::DeclContext;
-: 168:using clang::DeclRefExpr;
-: 169:using clang::ElaboratedType;
-: 170:using clang::EnumType;
-: 171:using clang::Expr;
-: 172:using clang::FileEntry;
-: 173:using clang::FriendDecl;
-: 174:using clang::FriendTemplateDecl;
-: 175:using clang::FullSourceLoc;
-: 176:using clang::FunctionDecl;
-: 177:using clang::FunctionProtoType;
-: 178:using clang::FunctionTemplateDecl;
-: 179:using clang::FunctionType;
-: 180:using clang::ImplicitCastExpr;
-: 181:using clang::LValueReferenceType;
-: 182:using clang::LinkageSpecDecl;
-: 183:using clang::MacroInfo;
-: 184:using clang::MemberExpr;
-: 185:using clang::NamedDecl;
-: 186:using clang::NestedNameSpecifier;
-: 187:using clang::NestedNameSpecifierLoc;
-: 188:using clang::OverloadExpr;
-: 189:using clang::ParmVarDecl;
-: 190:using clang::PPCallbacks;
-: 191:using clang::PointerType;
-: 192:using clang::QualType;
-: 193:using clang::QualifiedTypeLoc;
-: 194:using clang::RecordDecl;
-: 195:using clang::RecordType;
-: 196:using clang::RecursiveASTVisitor;
-: 197:using clang::ReferenceType;
-: 198:using clang::SourceLocation;
-: 199:using clang::SourceManager;
-: 200:using clang::Stmt;
-: 201:using clang::SubstTemplateTypeParmType;
-: 202:using clang::TagDecl;
-: 203:using clang::TagType;
-: 204:using clang::TemplateArgument;
-: 205:using clang::TemplateArgumentList;
-: 206:using clang::TemplateArgumentLoc;
-: 207:using clang::TemplateDecl;
-: 208:using clang::TemplateName;
-: 209:using clang::TemplateSpecializationKind;
-: 210:using clang::TemplateSpecializationType;
-: 211:using clang::TemplateTemplateParmDecl;
-: 212:using clang::Token;
-: 213:using clang::TranslationUnitDecl;
-: 214:using clang::Type;
-: 215:using clang::TypeLoc;
-: 216:using clang::TypedefDecl;
-: 217:using clang::TypedefType;
-: 218:using clang::UnaryExprOrTypeTraitExpr;
-: 219:using clang::UsingDecl;
-: 220:using clang::UsingShadowDecl;
-: 221:using clang::ValueDecl;
-: 222:using clang::VarDecl;
-: 223:using llvm::cast;
-: 224:using llvm::dyn_cast;
-: 225:using llvm::dyn_cast_or_null;
-: 226:using llvm::errs;
-: 227:using llvm::isa;
-: 228:using llvm::raw_string_ostream;
-: 229:using std::find;
-: 230:using std::make_pair;
-: 231:using std::map;
-: 232:using std::set;
-: 233:using std::string;
-: 234:using std::swap;
-: 235:using std::vector;
-: 236:
-: 237:namespace {
-: 238:
#####: 239:string IntToString(int i) {
#####: 240: char buf[64]; // big enough for any number
#####: 241: snprintf(buf, sizeof(buf), "%d", i);
#####: 242: return buf;
-: 243:}
-: 244:
112248: 245:bool CanIgnoreLocation(SourceLocation loc) {
-: 246: // If we're in a macro expansion, we always want to treat this as
-: 247: // being in the expansion location, never the as-written location,
1: 248: // since that's what the compiler does. CanIgnoreCurrentASTNode()
-: 249: // is an optimization, so we want to be conservative about what we
-: 250: // ignore.
112248: 251: const FileEntry* file_entry = GetFileEntry(loc);
112248: 252: const FileEntry* file_entry_after_macro_expansion =
112248: 253: GetFileEntry(GetInstantiationLoc(loc));
-: 254:
-: 255: // ignore symbols used outside foo.{h,cc} + check_also
112248: 256: return (!ShouldReportIWYUViolationsFor(file_entry) &&
106487: 257: !ShouldReportIWYUViolationsFor(file_entry_after_macro_expansion));
112248: 258:}
-: 259:
-: 260:} // namespace
-: 261:
-: 262:// ----------------------------------------------------------------------
-: 263:// --- BaseAstVisitor
-: 264:// ----------------------------------------------------------------------
-: 265://
-: 266:// We have a hierarchy of AST visitor classes, to keep the logic
-: 267:// as clear as possible. The top level, BaseAstVisitor, has some
-: 268:// basic, not particularly iwyu-related, functionality:
-: 269://
-: 270:// 1) Maintain current_ast_node_, the current chain in the AST tree.
-: 271:// 2) Provide functions related to the current location.
-: 272:// 3) Print each node we're visiting, depending on --verbose settings.
-: 273:// 4) Add appropriate implicit text. iwyu acts as if all constructor
-: 274:// initializers were explicitly written, all default constructors
-: 275:// were explicitly written, etc, even if they're not. We traverse
-: 276:// the implicit stuff as if it were explicit.
-: 277:// 5) Add two callbacks that subclasses can override (just like any
-: 278:// other AST callback): TraverseImplicitDestructorCall and
-: 279:// HandleFunctionCall. TraverseImplicitDestructorCall is a
-: 280:// callback for a "pseudo-AST" node that covers destruction not
-: 281:// specified in source, such as a destructor destroying one of the
-: 282:// fields in its class. HandleFunctionCall is a convenience
-: 283:// callback that bundles callbacks from many different kinds of
-: 284:// function-calling callbacks (CallExpr, CXXConstructExpr, etc)
-: 285:// into one place.
-: 286://
-: 287:// To maintain current_ast_node_ properly, this class also implements
-: 288:// VisitNestedNameSpecifier, VisitTemplateName, VisitTemplateArg, and
-: 289:// VisitTemplateArgLoc, which are parallel to the Visit*Decl()/etc
-: 290:// visitors. Subclasses should override these Visit routines, and not
-: 291:// the Traverse routine directly.
-: 292:
-: 293:template <class Derived>
-: 294:class BaseAstVisitor : public RecursiveASTVisitor<Derived> {
-: 295: public:
-: 296: typedef RecursiveASTVisitor<Derived> Base;
-: 297:
-: 298: // We need to create implicit ctor/dtor nodes, which requires
-: 299: // non-const methods on CompilerInstance, so the var can't be const.
1021: 300: explicit BaseAstVisitor(CompilerInstance* compiler)
-: 301: : compiler_(compiler),
1021: 302: current_ast_node_(NULL) {}
-: 303:
1019: 304: virtual ~BaseAstVisitor() {}
-: 305:
-: 306: //------------------------------------------------------------
-: 307: // Pure virtual methods that a subclass must implement.
-: 308:
-: 309: // Returns true if we are not interested in the current ast node for
-: 310: // any reason (for instance, it lives in a file we're not
-: 311: // analyzing).
-: 312: virtual bool CanIgnoreCurrentASTNode() const = 0;
-: 313:
-: 314: // Returns true if we should print the information for the
-: 315: // current AST node, given what file it's in. For instance,
-: 316: // except at very high verbosity levels, we don't print AST
-: 317: // nodes from system header files.
-: 318: virtual bool ShouldPrintSymbolFromCurrentFile() const = 0;
-: 319:
-: 320: // A string to add to the information we print for each symbol.
-: 321: // Each subclass can thus annotate if it's handling a node.
-: 322: // The return value, if not empty, should start with a space!
-: 323: virtual string GetSymbolAnnotation() const = 0;
-: 324:
-: 325: //------------------------------------------------------------
-: 326: // (1) Maintain current_ast_node_
-: 327:
-: 328: // How subclasses can access current_ast_node_;
133369: 329: const ASTNode* current_ast_node() const { return current_ast_node_; }
171799: 330: ASTNode* current_ast_node() { return current_ast_node_; }
565: 331: void set_current_ast_node(ASTNode* an) { current_ast_node_ = an; }
-: 332:
36353: 333: bool TraverseDecl(Decl* decl) {
36353: 334: if (current_ast_node_->StackContainsContent(decl))
1: 335: return true; // avoid recursion
36352: 336: ASTNode node(decl, *GlobalSourceManager());
36352: 337: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
36352: 338: return Base::TraverseDecl(decl);
72705: 339: }
-: 340:
86722: 341: bool TraverseStmt(Stmt* stmt) {
86722: 342: if (current_ast_node_->StackContainsContent(stmt))
#####: 343: return true; // avoid recursion
86722: 344: ASTNode node(stmt, *GlobalSourceManager());
86722: 345: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
86722: 346: return Base::TraverseStmt(stmt);
173444: 347: }
-: 348:
5537: 349: bool TraverseType(QualType qualtype) {
5537: 350: if (qualtype.isNull())
#####: 351: return Base::TraverseType(qualtype);
5537: 352: const Type* type = qualtype.getTypePtr();
5537: 353: if (current_ast_node_->StackContainsContent(type))
35: 354: return true; // avoid recursion
5502: 355: ASTNode node(type, *GlobalSourceManager());
5502: 356: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
5502: 357: return Base::TraverseType(qualtype);
11039: 358: }
-: 359:
-: 360: // RecursiveASTVisitor has a hybrid type-visiting system: it will
-: 361: // call TraverseTypeLoc when it can, but will call TraverseType
-: 362: // otherwise. For instance, if we see a FunctionDecl, and it
-: 363: // exposes the return type via a TypeLoc, it will recurse via
-: 364: // TraverseTypeLoc. If it exposes the return type only via a
-: 365: // QualType, though, it will recurse via TraverseType. The upshot
-: 366: // is we need two versions of all the Traverse*Type routines. (We
-: 367: // don't need two versions the Visit*Type routines, since the
-: 368: // default behavior of Visit*TypeLoc is to just call Visit*Type.)
62136: 369: bool TraverseTypeLoc(TypeLoc typeloc) {
-: 370: // QualifiedTypeLoc is a bit of a special case in the typeloc
-: 371: // system, off to the side. We don't care about qualifier
-: 372: // positions, so avoid the need for special-casing by just
-: 373: // traversing the unqualified version instead.
62136: 374: if (typeloc.getAs<QualifiedTypeLoc>()) {
3986: 375: typeloc = typeloc.getUnqualifiedLoc();
3986: 376: }
62136: 377: if (current_ast_node_->StackContainsContent(&typeloc))
#####: 378: return true; // avoid recursion
62136: 379: ASTNode node(&typeloc, *GlobalSourceManager());
62136: 380: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
62136: 381: return Base::TraverseTypeLoc(typeloc);
124272: 382: }
-: 383:
31: 384: bool TraverseNestedNameSpecifier(NestedNameSpecifier* nns) {
31: 385: if (nns == NULL)
#####: 386: return true;
31: 387: ASTNode node(nns, *GlobalSourceManager());
31: 388: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
31: 389: if (!this->getDerived().VisitNestedNameSpecifier(nns))
#####: 390: return false;
31: 391: return Base::TraverseNestedNameSpecifier(nns);
62: 392: }
-: 393:
60043: 394: bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc nns_loc) {
60043: 395: if (!nns_loc) // using NNSLoc::operator bool()
51218: 396: return true;
8825: 397: ASTNode node(&nns_loc, *GlobalSourceManager());
8825: 398: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
-: 399: // TODO(csilvers): have VisitNestedNameSpecifierLoc instead.
17650: 400: if (!this->getDerived().VisitNestedNameSpecifier(
8825: 401: nns_loc.getNestedNameSpecifier()))
#####: 402: return false;
8825: 403: return Base::TraverseNestedNameSpecifierLoc(nns_loc);
68868: 404: }
-: 405:
6678: 406: bool TraverseTemplateName(TemplateName template_name) {
6678: 407: ASTNode node(&template_name, *GlobalSourceManager());
6678: 408: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
6678: 409: if (!this->getDerived().VisitTemplateName(template_name))
#####: 410: return false;
6678: 411: return Base::TraverseTemplateName(template_name);
6678: 412: }
-: 413:
197: 414: bool TraverseTemplateArgument(const TemplateArgument& arg) {
197: 415: ASTNode node(&arg, *GlobalSourceManager());
197: 416: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
197: 417: if (!this->getDerived().VisitTemplateArgument(arg))
#####: 418: return false;
197: 419: return Base::TraverseTemplateArgument(arg);
197: 420: }
-: 421:
12458: 422: bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc& argloc) {
12458: 423: ASTNode node(&argloc, *GlobalSourceManager());
12458: 424: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
12458: 425: if (!this->getDerived().VisitTemplateArgumentLoc(argloc))
#####: 426: return false;
12458: 427: return Base::TraverseTemplateArgumentLoc(argloc);
12458: 428: }
-: 429:
-: 430: //------------------------------------------------------------
-: 431: // (2) Provide functions related to the current location.
-: 432:
-: 433: SourceLocation CurrentLoc() const {
731214: 434: CHECK_(current_ast_node_ && "Call CurrentLoc within Visit* or Traverse*");
243738: 435: const SourceLocation loc = current_ast_node_->GetLocation();
243738: 436: if (!loc.isValid())
1979: 437: return loc;
-: 438: // If the token is formed via macro concatenation, the spelling
-: 439: // location will be in <scratch space>. Use the instantiation
-: 440: // location instead.
241759: 441: const FullSourceLoc spelling_loc = GetSpellingLoc(loc);
250201: 442: if (IsInMacro(loc) && StartsWith(PrintableLoc(spelling_loc), "<scratch "))
99: 443: return GetInstantiationLoc(loc);
-: 444: else
241660: 445: return spelling_loc;
243738: 446: }
-: 447:
-: 448: string CurrentFilePath() const {
-: 449: return GetFilePath(CurrentLoc());
-: 450: }
-: 451:
-: 452: const FileEntry* CurrentFileEntry() const {
237497: 453: return GetFileEntry(CurrentLoc());
-: 454: }
-: 455:
-: 456: string PrintableCurrentLoc() const {
#####: 457: return PrintableLoc(CurrentLoc());
-: 458: }
-: 459:
-: 460: //------------------------------------------------------------
-: 461: // (3) Print each node we're visiting.
-: 462:
-: 463: // The current file location, the class or decl or type name in
-: 464: // brackets, along with annotations such as the indentation depth,
-: 465: // etc.
#####: 466: string AnnotatedName(const string& name) const {
#####: 467: return (PrintableCurrentLoc() + ": (" +
#####: 468: IntToString(current_ast_node_->depth()) + GetSymbolAnnotation() +
#####: 469: (current_ast_node_->in_forward_declare_context() ?
-: 470: ", fwd decl" : "") +
-: 471: ") [ " + name + " ] ");
-: 472: }
-: 473:
-: 474: // At verbose level 7 and above, returns a printable version of
-: 475: // the pointer, suitable for being emitted after AnnotatedName.
-: 476: // At lower verbose levels, returns the empty string.
#####: 477: string PrintablePtr(const void* ptr) const {
#####: 478: if (ShouldPrint(7)) {
#####: 479: char buffer[32];
#####: 480: snprintf(buffer, sizeof(buffer), "%p ", ptr);
#####: 481: return buffer;
-: 482: }
#####: 483: return "";
#####: 484: }
-: 485:
-: 486: // The top-level Decl class. All Decls call this visitor (in
-: 487: // addition to any more-specific visitors that apply for a
-: 488: // particular decl).
33254: 489: bool VisitDecl(clang::Decl* decl) {
33254: 490: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 491: errs() << AnnotatedName(string(decl->getDeclKindName()) + "Decl")
#####: 492: << PrintablePtr(decl) << PrintableDecl(decl) << "\n";
#####: 493: }
33254: 494: return true;
-: 495: }
-: 496:
82821: 497: bool VisitStmt(clang::Stmt* stmt) {
82821: 498: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 499: errs() << AnnotatedName(stmt->getStmtClassName()) << PrintablePtr(stmt);
#####: 500: PrintStmt(stmt);
#####: 501: errs() << "\n";
#####: 502: }
82821: 503: return true;
-: 504: }
-: 505:
65904: 506: bool VisitType(clang::Type* type) {
65904: 507: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 508: errs() << AnnotatedName(string(type->getTypeClassName()) + "Type")
#####: 509: << PrintablePtr(type) << PrintableType(type) << "\n";
#####: 510: }
65904: 511: return true;
-: 512: }
-: 513:
-: 514: // Make sure our logging message shows we're in the TypeLoc hierarchy.
60431: 515: bool VisitTypeLoc(clang::TypeLoc typeloc) {
60431: 516: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 517: errs() << AnnotatedName(string(typeloc.getTypePtr()->getTypeClassName())
-: 518: + "TypeLoc")
#####: 519: << PrintableTypeLoc(typeloc) << "\n";
#####: 520: }
60431: 521: return true;
-: 522: }
-: 523:
8708: 524: bool VisitNestedNameSpecifier(NestedNameSpecifier* nns) {
8708: 525: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 526: errs() << AnnotatedName("NestedNameSpecifier")
#####: 527: << PrintablePtr(nns) << PrintableNestedNameSpecifier(nns) << "\n";
#####: 528: }
8708: 529: return true;
-: 530: }
-: 531:
1074: 532: bool VisitTemplateName(TemplateName template_name) {
1074: 533: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 534: errs() << AnnotatedName("TemplateName")
#####: 535: << PrintableTemplateName(template_name) << "\n";
#####: 536: }
1074: 537: return true;
-: 538: }
-: 539:
197: 540: bool VisitTemplateArgument(const TemplateArgument& arg) {
197: 541: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 542: errs() << AnnotatedName("TemplateArgument")
#####: 543: << PrintablePtr(&arg) << PrintableTemplateArgument(arg) << "\n";
#####: 544: }
197: 545: return true;
-: 546: }
-: 547:
12278: 548: bool VisitTemplateArgumentLoc(const TemplateArgumentLoc& argloc) {
12278: 549: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 550: errs() << AnnotatedName("TemplateArgumentLoc")
#####: 551: << PrintablePtr(&argloc) << PrintableTemplateArgumentLoc(argloc)
-: 552: << "\n";
#####: 553: }
12278: 554: return true;
-: 555: }
-: 556:
-: 557: //------------------------------------------------------------
-: 558: // (4) Add implicit text.
-: 559:
-: 560: // When we see an object that has implicit text that iwyu
-: 561: // wants to look at, we make callbacks as if that text had
-: 562: // been explicitly written. Here's text we consider:
-: 563: //
-: 564: // * CXXDestructorDecl: a destructor call for each non-POD field
-: 565: // in the dtor's class, and each base type of that class.
-: 566: // * CXXConstructorDecl: a constructor call for each type/base
-: 567: // of the class that is not explicitly listed in an initializer.
-: 568: // * CXXRecordDecl: a CXXConstructorDecl for each implicit
-: 569: // constructor (zero-arg and copy). A CXXDestructor decl
-: 570: // if the destructor is implicit. A CXXOperatorCallDecl if
-: 571: // operator= is explicit.
-: 572:
1086: 573: bool TraverseCXXConstructorDecl(clang::CXXConstructorDecl* decl) {
1086: 574: if (!Base::TraverseCXXConstructorDecl(decl)) return false;
1780: 575: if (CanIgnoreCurrentASTNode()) return true;
-: 576: // We only care about classes that are actually defined.
866: 577: if (!decl || !decl->isThisDeclarationADefinition()) return true;
-: 578:
-: 579: // RAV's TraverseCXXConstructorDecl already handles
-: 580: // explicitly-written initializers, so we just want the rest.
854: 581: for (CXXConstructorDecl::init_const_iterator it = decl->init_begin();
778: 582: it != decl->init_end(); ++it) {
234: 583: const CXXCtorInitializer* init = *it;
234: 584: if (!init->isWritten()) {
117: 585: if (!this->getDerived().TraverseStmt(init->getInit()))
#####: 586: return false;
117: 587: }
234: 588: }
310: 589: return true;
1086: 590: }
-: 591:
336: 592: bool TraverseCXXDestructorDecl(clang::CXXDestructorDecl* decl) {
336: 593: if (!Base::TraverseCXXDestructorDecl(decl)) return false;
487: 594: if (CanIgnoreCurrentASTNode()) return true;
-: 595: // We only care about calls that are actually defined.
387: 596: if (!decl || !decl->isThisDeclarationADefinition()) return true;
-: 597:
-: 598: // Collect all the fields (and bases) we destroy, and call the dtor.
168: 599: set<const Type*> member_types;
168: 600: const CXXRecordDecl* record = decl->getParent();
168: 601: for (clang::RecordDecl::field_iterator it = record->field_begin();
576: 602: it != record->field_end(); ++it) {
204: 603: member_types.insert(it->getType().getTypePtr());
204: 604: }
-: 605: for (clang::CXXRecordDecl::base_class_const_iterator
406: 606: it = record->bases_begin(); it != record->bases_end(); ++it) {
35: 607: member_types.insert(it->getType().getTypePtr());
35: 608: }
1298: 609: for (Each<const Type*> it(&member_types); !it.AtEnd(); ++it) {
229: 610: const NamedDecl* member_decl = TypeToDeclAsWritten(*it);
-: 611: // We only want those fields that are c++ classes.
229: 612: if (const CXXRecordDecl* cxx_field_decl = DynCastFrom(member_decl)) {
81: 613: if (const CXXDestructorDecl* field_dtor
81: 614: = cxx_field_decl->getDestructor()) {
138: 615: if (!this->getDerived().TraverseImplicitDestructorCall(
69: 616: const_cast<CXXDestructorDecl*>(field_dtor), *it))
#####: 617: return false;
69: 618: }
81: 619: }
229: 620: }
168: 621: return true;
504: 622: }
-: 623:
-: 624: // clang lazily constructs the implicit methods of a C++ class (the
-: 625: // default constructor and destructor, etc) -- it only bothers to
-: 626: // create a CXXMethodDecl if someone actually calls these classes.
-: 627: // But we need to be non-lazy: iwyu depends on analyzing what future
-: 628: // code *may* call in a class, not what current code *does*. So we
-: 629: // force all the lazy evaluation to happen here. This will
-: 630: // (possibly) add a bunch of MethodDecls to the AST, as children of
-: 631: // decl. We're hoping it will always be safe to modify the AST
-: 632: // while it's being traversed!
332: 633: void InstantiateImplicitMethods(CXXRecordDecl* decl) {
332: 634: if (decl->isDependentType()) // only instantiate if class is instantiated
30: 635: return;
-: 636:
302: 637: clang::Sema& sema = compiler_->getSema();
302: 638: DeclContext::lookup_const_result ctors = sema.LookupConstructors(decl);
3010: 639: for (Each<NamedDecl*> it(&ctors); !it.AtEnd(); ++it) {
-: 640: // Ignore templated constructors.
1052: 641: if (isa<FunctionTemplateDecl>(*it))
139: 642: continue;
913: 643: CXXConstructorDecl* ctor = cast<CXXConstructorDecl>(*it);
1593: 644: if (!ctor->hasBody() && !ctor->isDeleted() && ctor->isImplicit()) {
139: 645: if (sema.getSpecialMember(ctor) == clang::Sema::CXXDefaultConstructor) {
28: 646: sema.DefineImplicitDefaultConstructor(CurrentLoc(), ctor);
28: 647: } else {
-: 648: // TODO(nlewycky): enable this!
-: 649: //sema.DefineImplicitCopyConstructor(CurrentLoc(), ctor);
-: 650: }
139: 651: }
-: 652: // Unreferenced template constructors stay uninstantiated on purpose.
913: 653: }
-: 654:
302: 655: if (CXXDestructorDecl* dtor = sema.LookupDestructor(decl)) {
302: 656: if (!dtor->isDeleted()) {
367: 657: if (!dtor->hasBody() && dtor->isImplicit())
58: 658: sema.DefineImplicitDestructor(CurrentLoc(), dtor);
309: 659: if (!dtor->isDefined() && dtor->getTemplateInstantiationPattern())
7: 660: sema.PendingInstantiations.push_back(make_pair(dtor, CurrentLoc()));
302: 661: }
302: 662: }
-: 663:
-: 664: // TODO(nlewycky): copy assignment operator
-: 665:
-: 666: // clang queues up method instantiations. We need to process them now.
302: 667: sema.PerformPendingInstantiations();
634: 668: }
-: 669:
-: 670: // clang doesn't bother to set a TypeSourceInfo for implicit
-: 671: // methods, since, well, they don't have a location. But
-: 672: // RecursiveASTVisitor crashes without one, so when we lie and say
-: 673: // we're not implicit, we have to lie and give a location as well.
-: 674: // (We give the null location.) This is a small memory leak.
304: 675: void SetTypeSourceInfoForImplicitMethodIfNeeded(FunctionDecl* decl) {
304: 676: if (decl->getTypeSourceInfo() == NULL) {
234: 677: ASTContext& ctx = compiler_->getASTContext();
234: 678: decl->setTypeSourceInfo(ctx.getTrivialTypeSourceInfo(decl->getType()));
234: 679: }
304: 680: }
-: 681:
-: 682: // RAV.h's TraverseDecl() ignores implicit nodes, so we lie a bit.
-: 683: // TODO(csilvers): figure out a more principled way.
304: 684: bool TraverseImplicitDeclHelper(clang::FunctionDecl* decl) {
912: 685: CHECK_(decl->isImplicit() && "TraverseImplicitDecl is for implicit decls");
304: 686: decl->setImplicit(false);
304: 687: SetTypeSourceInfoForImplicitMethodIfNeeded(decl);
304: 688: bool retval = this->getDerived().TraverseDecl(decl);
304: 689: decl->setImplicit(true);
304: 690: return retval;
-: 691: }
-: 692:
-: 693: // Handle implicit methods that otherwise wouldn't be seen by RAV.
975: 694: bool TraverseCXXRecordDecl(clang::CXXRecordDecl* decl) {
975: 695: if (!Base::TraverseCXXRecordDecl(decl)) return false;
1771: 696: if (CanIgnoreCurrentASTNode()) return true;
-: 697: // We only care about classes that are actually defined.
473: 698: if (!decl || !decl->isThisDeclarationADefinition()) return true;
-: 699:
64: 700: InstantiateImplicitMethods(decl);
-: 701:
-: 702: // Check to see if there are any implicit constructors. Can be
-: 703: // several: implicit default constructor, implicit copy constructor.
64: 704: for (CXXRecordDecl::ctor_iterator it = decl->ctor_begin();
236: 705: it != decl->ctor_end(); ++it) {
86: 706: CXXConstructorDecl* ctor = *it;
144: 707: if (ctor->isImplicit() && !ctor->isDeleted()) {
58: 708: if (!TraverseImplicitDeclHelper(ctor))
#####: 709: return false;
58: 710: }
86: 711: }
-: 712:
-: 713: // Check the (single) destructor.
64: 714: bool hasImplicitDeclaredDestructor = (!decl->needsImplicitDestructor() &&
38: 715: !decl->hasUserDeclaredDestructor());
64: 716: if (hasImplicitDeclaredDestructor) {
31: 717: if (!TraverseImplicitDeclHelper(decl->getDestructor()))
#####: 718: return false;
31: 719: }
-: 720:
-: 721: // Check copy and move assignment operators.
64: 722: for (CXXRecordDecl::method_iterator it = decl->method_begin();
478: 723: it != decl->method_end(); ++it) {
207: 724: bool isAssignmentOperator = it->isCopyAssignmentOperator() ||
411: 725: it->isMoveAssignmentOperator();
210: 726: if (isAssignmentOperator && it->isImplicit()) {
1: 727: if (!TraverseImplicitDeclHelper(*it))
#####: 728: return false;
1: 729: }
207: 730: }
-: 731:
64: 732: return true;
975: 733: }
-: 734:
-: 735: //------------------------------------------------------------
-: 736: // (5) Add TraverseImplicitDestructorCall and HandleFunctionCall.
-: 737:
-: 738: // TraverseImplicitDestructorCall: This is a callback this class
-: 739: // introduces that is a first-class callback just like any AST-node
-: 740: // callback. It is used to cover two places where the compiler
-: 741: // destroys objects, but there's no written indication of that in
-: 742: // the text: (1) when a local variable or a temporary goes out of
-: 743: // scope (NOTE: in this case, we attribute the destruction to the
-: 744: // same line as the corresponding construction, not to where the
-: 745: // scope ends). (2) When a destructor destroys one of the fields of
-: 746: // a class. For instance: 'class Foo { MyClass b; }': In addition
-: 747: // to executing its body, Foo::~Foo calls MyClass::~Myclass on b.
-: 748: // Note we only call this if an actual destructor is being executed:
-: 749: // we don't call it when an int goes out of scope!
-: 750: //
-: 751: // HandleFunctionCall: A convenience callback that 'bundles'
-: 752: // the following Expr's, each of which causes one or more
-: 753: // function calls when evaluated (though most of them are
-: 754: // not a child of CallExpr):
-: 755: // * CallExpr (obviously)
-: 756: // * CXXMemberCallExpr
-: 757: // * CXXOperatorCallExpr -- a call to operatorXX()
-: 758: // * CXXConstructExpr -- calls a constructor to create an object,
-: 759: // and maybe a destructor when the object goes out of scope.
-: 760: // * CXXTemporaryObjectExpr -- subclass of CXXConstructExpr
-: 761: // * CXXNewExpr -- calls operator new and a constructor
-: 762: // * CXXDeleteExpr -- calls operator delete and a destructor
-: 763: // * DeclRefExpr -- if the declref is a function pointer, we
-: 764: // treat it as a function call, since it can act like one
-: 765: // in the future
-: 766: // * ImplicitDestructorCall -- calls a destructor
-: 767: // Each of these calls HandleFunctionCall for the function calls
-: 768: // it does. A subclass interested only in function calls, and
-: 769: // not exactly what expression caused them, can override
-: 770: // HandleFunctionCall. Note: subclasses should expect that
-: 771: // the first argument to HandleFunctionCall may be NULL (e.g. when
-: 772: // constructing a built-in type), in which case the handler should
-: 773: // immediately return.
-: 774:
-: 775: // If the function being called is a member of a class, parent_type
-: 776: // is the type of the method's owner (parent), as it is written in
-: 777: // the source. (We need the type-as-written so we can distinguish
-: 778: // explicitly-written template args from default template args.) We
-: 779: // also pass in the CallExpr (or CXXConstructExpr, etc). This may
-: 780: // be NULL if the function call is implicit.
1877: 781: bool HandleFunctionCall(clang::FunctionDecl* callee,
1877: 782: const clang::Type* parent_type,
1877: 783: const clang::Expr* calling_expr) {
2073: 784: if (!callee) return true;
1681: 785: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 786: errs() << AnnotatedName("FunctionCall")
#####: 787: << PrintablePtr(callee) << PrintableDecl(callee) << "\n";
#####: 788: }
1681: 789: return true;
1877: 790: }
-: 791:
305: 792: bool TraverseImplicitDestructorCall(clang::CXXDestructorDecl* decl,
305: 793: const Type* type_being_destroyed) {
305: 794: if (CanIgnoreCurrentASTNode()) return true;
305: 795: if (!decl) return true;
305: 796: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 797: errs() << AnnotatedName("Destruction")
#####: 798: << PrintableType(type_being_destroyed) << "\n";
#####: 799: }
305: 800: return this->getDerived().HandleFunctionCall(decl, type_being_destroyed,
-: 801: static_cast<Expr*>(NULL));
305: 802: }
-: 803:
-: 804:
6716: 805: bool TraverseCallExpr(clang::CallExpr* expr) {
6716: 806: if (!Base::TraverseCallExpr(expr)) return false;
13033: 807: if (CanIgnoreCurrentASTNode()) return true;
798: 808: return this->getDerived().HandleFunctionCall(expr->getDirectCallee(),
399: 809: TypeOfParentIfMethod(expr),
-: 810: expr);
6716: 811: }
-: 812:
583: 813: bool TraverseCXXMemberCallExpr(clang::CXXMemberCallExpr* expr) {
583: 814: if (!Base::TraverseCXXMemberCallExpr(expr)) return false;
843: 815: if (CanIgnoreCurrentASTNode()) return true;
646: 816: return this->getDerived().HandleFunctionCall(expr->getDirectCallee(),
323: 817: TypeOfParentIfMethod(expr),
-: 818: expr);
583: 819: }
-: 820:
2896: 821: bool TraverseCXXOperatorCallExpr(clang::CXXOperatorCallExpr* expr) {
2896: 822: if (!Base::TraverseCXXOperatorCallExpr(expr)) return false;
5720: 823: if (CanIgnoreCurrentASTNode()) return true;
-: 824:
72: 825: const Type* parent_type = TypeOfParentIfMethod(expr);
-: 826: // If we're a free function -- bool operator==(MyClass a, MyClass b) --
-: 827: // we still want to have a parent_type, as if we were defined as
-: 828: // MyClass::operator==. So we go through the arguments and take the
-: 829: // first one that's a class, and associate the function with that.
72: 830: if (!parent_type) {
72: 831: if (const Expr* first_argument = GetFirstClassArgument(expr))
51: 832: parent_type = GetTypeOf(first_argument);
72: 833: }
72: 834: return this->getDerived().HandleFunctionCall(expr->getDirectCallee(),
-: 835: parent_type, expr);
2896: 836: }
-: 837:
580: 838: bool TraverseCXXConstructExpr(clang::CXXConstructExpr* expr) {
580: 839: if (!Base::TraverseCXXConstructExpr(expr)) return false;
772: 840: if (CanIgnoreCurrentASTNode()) return true;
-: 841:
776: 842: if (!this->getDerived().HandleFunctionCall(expr->getConstructor(),
388: 843: GetTypeOf(expr),
-: 844: expr))
#####: 845: return false;
-: 846:
-: 847: // When creating a local variable or a temporary, but not a pointer, the
-: 848: // constructor is also responsible for destruction (which happens
-: 849: // implicitly when the variable goes out of scope). Only when initializing
-: 850: // a field of a class does the constructor not have to worry
-: 851: // about destruction. It turns out it's easier to check for that.
388: 852: bool willCallImplicitDestructorOnLeavingScope =
388: 853: !IsCXXConstructExprInInitializer(current_ast_node()) &&
253: 854: !IsCXXConstructExprInNewExpr(current_ast_node());
388: 855: if (willCallImplicitDestructorOnLeavingScope) {
-: 856: // Create the destructor if it hasn't been lazily created yet.
236: 857: InstantiateImplicitMethods(expr->getConstructor()->getParent());
236: 858: if (const CXXDestructorDecl* dtor_decl = GetSiblingDestructorFor(expr)) {
472: 859: if (!this->getDerived().TraverseImplicitDestructorCall(
236: 860: const_cast<CXXDestructorDecl*>(dtor_decl), GetTypeOf(expr)))
#####: 861: return false;
236: 862: }
236: 863: }
388: 864: return true;
580: 865: }
-: 866:
71: 867: bool TraverseCXXTemporaryObjectExpr(clang::CXXTemporaryObjectExpr* expr) {
71: 868: if (!Base::TraverseCXXTemporaryObjectExpr(expr)) return false;
110: 869: if (CanIgnoreCurrentASTNode()) return true;
-: 870:
-: 871: // In this case, we *know* we're responsible for destruction as well.
32: 872: InstantiateImplicitMethods(expr->getConstructor()->getParent());
32: 873: CXXConstructorDecl* ctor_decl = expr->getConstructor();
32: 874: CXXDestructorDecl* dtor_decl =
32: 875: const_cast<CXXDestructorDecl*>(GetSiblingDestructorFor(expr));
32: 876: const Type* type = GetTypeOf(expr);
32: 877: return (this->getDerived().HandleFunctionCall(ctor_decl, type, expr) &&
32: 878: this->getDerived().HandleFunctionCall(dtor_decl, type, expr));
71: 879: }
-: 880:
129: 881: bool TraverseCXXNewExpr(clang::CXXNewExpr* expr) {
129: 882: if (!Base::TraverseCXXNewExpr(expr)) return false;
222: 883: if (CanIgnoreCurrentASTNode()) return true;
-: 884:
36: 885: const Type* parent_type = expr->getAllocatedType().getTypePtrOrNull();
-: 886: // 'new' calls operator new in addition to the ctor of the new-ed type.
36: 887: if (FunctionDecl* operator_new = expr->getOperatorNew()) {
-: 888: // If operator new is a method, it must (by the semantics of
-: 889: // per-class operator new) be a method on the class we're newing.
25: 890: const Type* op_parent = NULL;
25: 891: if (isa<CXXMethodDecl>(operator_new))
1: 892: op_parent = parent_type;
25: 893: if (!this->getDerived().HandleFunctionCall(operator_new, op_parent, expr))
#####: 894: return false;
25: 895: }
36: 896: return true;
129: 897: }
-: 898:
54: 899: bool TraverseCXXDeleteExpr(clang::CXXDeleteExpr* expr) {
54: 900: if (!Base::TraverseCXXDeleteExpr(expr)) return false;
-: 901:
72: 902: if (CanIgnoreCurrentASTNode()) return true;
-: 903:
36: 904: const Type* parent_type = expr->getDestroyedType().getTypePtrOrNull();
-: 905: // We call operator delete in addition to the dtor of the deleted type.
36: 906: if (FunctionDecl* operator_delete = expr->getOperatorDelete()) {
-: 907: // If operator delete is a method, it must (by the semantics of per-
-: 908: // class operator delete) be a method on the class we're deleting.
27: 909: const Type* op_parent = NULL;
27: 910: if (isa<CXXMethodDecl>(operator_delete))
1: 911: op_parent = parent_type;
27: 912: if (!this->getDerived().HandleFunctionCall(operator_delete, op_parent,
-: 913: expr))
#####: 914: return false;
27: 915: }
36: 916: const CXXDestructorDecl* dtor = GetDestructorForDeleteExpr(expr);
36: 917: return this->getDerived().HandleFunctionCall(
-: 918: const_cast<CXXDestructorDecl*>(dtor), parent_type, expr);
54: 919: }
-: 920:
-: 921: // This is to catch assigning template functions to function pointers.
-: 922: // For instance, 'MyFunctionPtr p = &TplFn<MyClass*>;': we need to
-: 923: // expand TplFn to see if it needs full type info for MyClass.
18601: 924: bool TraverseDeclRefExpr(clang::DeclRefExpr* expr) {
18601: 925: if (!Base::TraverseDeclRefExpr(expr)) return false;
35784: 926: if (CanIgnoreCurrentASTNode()) return true;
-: 927:
-: 928: // If it's a normal function call, that was already handled by a
-: 929: // CallExpr somewhere. We want only assignments.
1418: 930: if (current_ast_node()->template ParentIsA<CallExpr>() ||
1223: 931: (current_ast_node()->template ParentIsA<ImplicitCastExpr>() &&
676: 932: current_ast_node()->template AncestorIsA<CallExpr>(2))) {
545: 933: return true;
-: 934: }
-: 935:
873: 936: if (FunctionDecl* fn_decl = DynCastFrom(expr->getDecl())) {
-: 937: // If fn_decl has a class-name before it -- 'MyClass::method' --
-: 938: // it's a method pointer.
17: 939: const Type* parent_type = NULL;
26: 940: if (expr->getQualifier() && expr->getQualifier()->getAsType())
9: 941: parent_type = expr->getQualifier()->getAsType();
17: 942: if (!this->getDerived().HandleFunctionCall(fn_decl, parent_type, expr))
#####: 943: return false;
17: 944: }
873: 945: return true;
18601: 946: }
-: 947:
-: 948: protected:
1253: 949: CompilerInstance* compiler() { return compiler_; }
-: 950:
-: 951: private:
-: 952: template <typename T> friend class BaseAstVisitor;
-: 953: CompilerInstance* const compiler_;
-: 954:
-: 955: // The currently active decl/stmt/type/etc -- that is, the node
-: 956: // being currently visited in a Visit*() or Traverse*() method. The
-: 957: // advantage of ASTNode over the object passed in to Visit*() and
-: 958: // Traverse*() is ASTNode knows its parent.
-: 959: ASTNode* current_ast_node_;
-: 960:};
-: 961:
-: 962:
-: 963:// ----------------------------------------------------------------------
-: 964:// --- AstTreeFlattenerVisitor
-: 965:// ----------------------------------------------------------------------
-: 966://
-: 967:// This simple visitor just creates a set of all AST nodes (stored as
-: 968:// void*'s) seen while traversing via BaseAstVisitor.
-: 969:
2038: 970:class AstFlattenerVisitor : public BaseAstVisitor<AstFlattenerVisitor> {
-: 971: public:
-: 972: typedef BaseAstVisitor<AstFlattenerVisitor> Base;
-: 973:
-: 974: // We divide our set of nodes into category by type. For most AST
-: 975: // nodes, we can store just a pointer to the node. However, for
-: 976: // some AST nodes we don't get a pointer into the AST, we get a
-: 977: // temporary (stack-allocated) object, and have to store the full
-: 978: // object ourselves and use its operator== to test for equality.
-: 979: // These types each get their own set (or, usually, vector, since
-: 980: // the objects tend not to support operator< or hash<>()).
8266: 981: class NodeSet {
-: 982: public:
-: 983: // We could add more versions, but these are the only useful ones so far.
5510: 984: bool Contains(const Type* type) const {
5510: 985: return ContainsKey(others, type);
-: 986: }
2708: 987: bool Contains(const Decl* decl) const {
2708: 988: return ContainsKey(others, decl);
-: 989: }
13138: 990: bool Contains(const ASTNode& node) const {
13138: 991: if (const TypeLoc* tl = node.GetAs<TypeLoc>()) {
3766: 992: return ContainsValue(typelocs, *tl);
9372: 993: } else if (const NestedNameSpecifierLoc* nl
9372: 994: = node.GetAs<NestedNameSpecifierLoc>()) {
#####: 995: return ContainsValue(nnslocs, *nl);
9372: 996: } else if (const TemplateName* tn = node.GetAs<TemplateName>()) {
-: 997: // The best we can do is to compare the associated decl
#####: 998: if (tn->getAsTemplateDecl() == NULL)
#####: 999: return false; // be conservative if we can't compare decls
#####: 1000: for (Each<TemplateName> it(&tpl_names); it.AtEnd(); ++it) {
#####: 1001: if (it->getAsTemplateDecl() == tn->getAsTemplateDecl())
#####: 1002: return true;
#####: 1003: }
#####: 1004: return false;
9372: 1005: } else if (const TemplateArgument* ta = node.GetAs<TemplateArgument>()) {
-: 1006: // TODO(csilvers): figure out how to compare template arguments
-: 1007: (void)ta;
#####: 1008: return false;
9372: 1009: } else if (const TemplateArgumentLoc* tal =
9372: 1010: node.GetAs<TemplateArgumentLoc>()) {
-: 1011: // TODO(csilvers): figure out how to compare template argument-locs
-: 1012: (void)tal;
#####: 1013: return false;
-: 1014: } else {
9372: 1015: return ContainsKey(others, node.GetAs<void>());
-: 1016: }
13138: 1017: }
-: 1018:
667: 1019: void AddAll(const NodeSet& that) {
667: 1020: Extend(&typelocs, that.typelocs);
667: 1021: Extend(&nnslocs, that.nnslocs);
667: 1022: Extend(&tpl_names, that.tpl_names);
667: 1023: Extend(&tpl_args, that.tpl_args);
667: 1024: Extend(&tpl_arglocs, that.tpl_arglocs);
667: 1025: InsertAllInto(that.others, &others);
667: 1026: }
-: 1027:
-: 1028: // Needed since we're treated like an stl-like object.
-: 1029: bool empty() const {
2870: 1030: return (typelocs.empty() && nnslocs.empty() &&
2519: 1031: tpl_names.empty() && tpl_args.empty() &&
2518: 1032: tpl_arglocs.empty() && others.empty());
1610: 1033: }
-: 1034: void clear() {
566: 1035: typelocs.clear();
566: 1036: nnslocs.clear();
566: 1037: tpl_names.clear();
566: 1038: tpl_args.clear();
566: 1039: tpl_arglocs.clear();
566: 1040: others.clear();
566: 1041: }
-: 1042:
-: 1043: private:
-: 1044: friend class AstFlattenerVisitor;
-: 1045:
-: 1046: // It's ok not to check for duplicates; we're just traversing the tree.
1705: 1047: void Add(TypeLoc tl) { typelocs.push_back(tl); }
-: 1048: void Add(NestedNameSpecifierLoc nl) { nnslocs.push_back(nl); }
119: 1049: void Add(TemplateName tn) { tpl_names.push_back(tn); }
#####: 1050: void Add(TemplateArgument ta) { tpl_args.push_back(ta); }
180: 1051: void Add(TemplateArgumentLoc tal) { tpl_arglocs.push_back(tal); }
4696: 1052: void Add(const void* o) { others.insert(o); }
-: 1053:
-: 1054: vector<TypeLoc> typelocs;
-: 1055: vector<NestedNameSpecifierLoc> nnslocs;
-: 1056: vector<TemplateName> tpl_names;
-: 1057: vector<TemplateArgument> tpl_args;
-: 1058: vector<TemplateArgumentLoc> tpl_arglocs;
-: 1059: set<const void*> others;
-: 1060: };
-: 1061:
-: 1062: //------------------------------------------------------------
-: 1063: // Public interface:
-: 1064:
2038: 1065: explicit AstFlattenerVisitor(CompilerInstance* compiler) : Base(compiler) { }
-: 1066:
805: 1067: const NodeSet& GetNodesBelow(Decl* decl) {
2415: 1068: CHECK_(seen_nodes_.empty() && "Nodes should be clear before GetNodesBelow");
805: 1069: NodeSet* node_set = &nodeset_decl_cache_[decl];
805: 1070: if (node_set->empty()) {
405: 1071: if (decl->isImplicit()) {
#####: 1072: TraverseImplicitDeclHelper(dyn_cast_or_null<FunctionDecl>(decl));
#####: 1073: } else {
405: 1074: TraverseDecl(decl);
-: 1075: }
405: 1076: swap(*node_set, seen_nodes_); // move the seen_nodes_ into the cache
405: 1077: }
805: 1078: return *node_set; // returns the cache entry
-: 1079: }
-: 1080:
-: 1081: //------------------------------------------------------------
-: 1082: // Pure virtual methods that the base class requires.
-: 1083:
-: 1084: virtual bool CanIgnoreCurrentASTNode() const {
539: 1085: return false;
-: 1086: }
-: 1087: virtual bool ShouldPrintSymbolFromCurrentFile() const {
40: 1088: return false;
-: 1089: }
-: 1090: virtual string GetSymbolAnnotation() const {
#####: 1091: return "[Uninstantiated template AST-node] ";
-: 1092: }
-: 1093:
-: 1094: //------------------------------------------------------------
-: 1095: // Top-level handlers that construct the tree.
-: 1096:
898: 1097: bool VisitDecl(Decl*) { AddCurrentAstNodeAsPointer(); return true; }
1700: 1098: bool VisitStmt(Stmt*) { AddCurrentAstNodeAsPointer(); return true; }
1734: 1099: bool VisitType(Type*) { AddCurrentAstNodeAsPointer(); return true; }
1705: 1100: bool VisitTypeLoc(TypeLoc typeloc) {
3410: 1101: VERRS(7) << GetSymbolAnnotation() << PrintableTypeLoc(typeloc) << "\n";
1705: 1102: seen_nodes_.Add(typeloc);
1705: 1103: return true;
-: 1104: }
148: 1105: bool VisitNestedNameSpecifier(NestedNameSpecifier*) {
148: 1106: AddCurrentAstNodeAsPointer();
148: 1107: return true;
-: 1108: }
119: 1109: bool VisitTemplateName(TemplateName tpl_name) {
238: 1110: VERRS(7) << GetSymbolAnnotation()
#####: 1111: << PrintableTemplateName(tpl_name) << "\n";
119: 1112: seen_nodes_.Add(tpl_name);
119: 1113: return true;
-: 1114: }
#####: 1115: bool VisitTemplateArgument(const TemplateArgument& tpl_arg) {
#####: 1116: VERRS(7) << GetSymbolAnnotation()
#####: 1117: << PrintableTemplateArgument(tpl_arg) << "\n";
#####: 1118: seen_nodes_.Add(tpl_arg);
#####: 1119: return true;
-: 1120: }
180: 1121: bool VisitTemplateArgumentLoc(const TemplateArgumentLoc& tpl_argloc) {
360: 1122: VERRS(7) << GetSymbolAnnotation()
#####: 1123: << PrintableTemplateArgumentLoc(tpl_argloc) << "\n";
180: 1124: seen_nodes_.Add(tpl_argloc);
180: 1125: return true;
-: 1126: }
5: 1127: bool TraverseImplicitDestructorCall(clang::CXXDestructorDecl* decl,
5: 1128: const Type* type) {
10: 1129: VERRS(7) << GetSymbolAnnotation() << "[implicit dtor] "
-: 1130: << static_cast<void*>(decl)
#####: 1131: << (decl ? PrintableDecl(decl) : "NULL") << "\n";
5: 1132: AddAstNodeAsPointer(decl);
5: 1133: return Base::TraverseImplicitDestructorCall(decl, type);
-: 1134: }
211: 1135: bool HandleFunctionCall(clang::FunctionDecl* callee,
211: 1136: const clang::Type* parent_type,
211: 1137: const clang::Expr* calling_expr) {
422: 1138: VERRS(7) << GetSymbolAnnotation() << "[function call] "
-: 1139: << static_cast<void*>(callee)
#####: 1140: << (callee ? PrintableDecl(callee) : "NULL") << "\n";
211: 1141: AddAstNodeAsPointer(callee);
211: 1142: return Base::HandleFunctionCall(callee, parent_type, calling_expr);
-: 1143: }
-: 1144:
-: 1145: //------------------------------------------------------------
-: 1146: // Class logic.
-: 1147:
4696: 1148: void AddAstNodeAsPointer(const void* node) {
4696: 1149: seen_nodes_.Add(node);
4696: 1150: }
-: 1151:
-: 1152: void AddCurrentAstNodeAsPointer() {
4480: 1153: if (ShouldPrint(7)) {
#####: 1154: errs() << GetSymbolAnnotation() << current_ast_node()->GetAs<void>()
-: 1155: << " ";
#####: 1156: PrintASTNode(current_ast_node());
#####: 1157: errs() << "\n";
#####: 1158: }
4480: 1159: AddAstNodeAsPointer(current_ast_node()->GetAs<void>());
4480: 1160: }
-: 1161:
-: 1162: private:
-: 1163: NodeSet seen_nodes_;
-: 1164:
-: 1165: // Because we make a new AstFlattenerVisitor each time we flatten, we
-: 1166: // need to make this map static.
-: 1167: // TODO(csilvers): just have one flattener, so this needn't be static.
-: 1168: static map<const Decl*, NodeSet> nodeset_decl_cache_;
-: 1169:};
-: 1170:
-: 1171:map<const Decl*, AstFlattenerVisitor::NodeSet>
1: 1172:AstFlattenerVisitor::nodeset_decl_cache_;
-: 1173:
-: 1174:
-: 1175:// ----------------------------------------------------------------------
-: 1176:// --- VisitorState
-: 1177:// ----------------------------------------------------------------------
-: 1178://
-: 1179:// This is a simple struct holding data that IwyuBaseASTVisitor will
-: 1180:// need to access and manipulate. It's held separately from
-: 1181:// IwyuBaseASTVisitor because we want this information to be shared
-: 1182:// between the IwyuASTConsumer and the InstantiatedTemplateVisitor,
-: 1183:// each of which gets its own copy of IwyuBaseASTVisitor data. So to
-: 1184:// share data, we need to hold it somewhere else.
-: 1185:
-: 1186:struct VisitorState {
2: 1187: VisitorState(CompilerInstance* c, const IwyuPreprocessorInfo& ipi)
2: 1188: : compiler(c), preprocessor_info(ipi) {}
-: 1189:
-: 1190: CompilerInstance* const compiler;
-: 1191:
-: 1192: // Information gathered at preprocessor time, including #include info.
-: 1193: const IwyuPreprocessorInfo& preprocessor_info;
-: 1194:
-: 1195: // When we see an overloaded function that depends on a template
-: 1196: // parameter, we can't resolve the overload until the template
-: 1197: // is instantiated (e.g., MyFunc<int> in the following example):
-: 1198: // template<typename T> MyFunc() { OverloadedFunction(T()); }
-: 1199: // However, sometimes we can do iwyu even before resolving the
-: 1200: // overload, if *all* potential overloads live in the same file. We
-: 1201: // mark the location of such 'early-processed' functions here, so
-: 1202: // when we see the function again at template-instantiation time, we
-: 1203: // know not to do iwyu-checking on it again. (Since the actual
-: 1204: // function-call exprs are different between the uninstantiated and
-: 1205: // instantiated calls, we can't store the exprs themselves, but have
-: 1206: // to store their location.)
-: 1207: set<SourceLocation> processed_overload_locs;
-: 1208:
-: 1209: // When we see a using declaration, we want to keep track of what
-: 1210: // file it's in, because other files may depend on that using
-: 1211: // declaration to get the names of their types right. We want to
-: 1212: // make sure we don't replace an #include with a forward-declare
-: 1213: // when we might need the #include's using declaration.
-: 1214: // The key is the type being 'used', the FileEntry is the file
-: 1215: // that has the using decl. If there are multiple using decls
-: 1216: // for a file, we prefer the one that has NamedDecl in it.
-: 1217: multimap<const NamedDecl*, const UsingDecl*> using_declarations;
-: 1218:};
-: 1219:
-: 1220:
-: 1221:// ----------------------------------------------------------------------
-: 1222:// --- IwyuBaseAstVisitor
-: 1223:// ----------------------------------------------------------------------
-: 1224://
-: 1225:// We use two AST visitor classes to implement IWYU: IwyuAstConsumer
-: 1226:// is the main visitor that traverses the AST corresponding to what's
-: 1227:// actually written in the source code, and
-: 1228:// InstantiatedTemplateVisitor is for traversing template
-: 1229:// instantiations. This class template holds iwyu work that is be
-: 1230:// shared by both.
-: 1231:
-: 1232:template <class Derived>
-: 1233:class IwyuBaseAstVisitor : public BaseAstVisitor<Derived> {
-: 1234: public:
-: 1235: typedef BaseAstVisitor<Derived> Base;
-: 1236:
2: 1237: explicit IwyuBaseAstVisitor(VisitorState* visitor_state)
-: 1238: : Base(visitor_state->compiler),
2: 1239: visitor_state_(visitor_state) {}
-: 1240:
#####: 1241: virtual ~IwyuBaseAstVisitor() {}
-: 1242:
-: 1243: // To avoid having this-> pointers everywhere, we re-export Base's
-: 1244: // functions that we use in this class. This is a language nit(?)
-: 1245: // when a templated class subclasses from another templated class.
-: 1246: using Base::CanIgnoreCurrentASTNode;
-: 1247: using Base::CurrentLoc;
-: 1248: using Base::CurrentFileEntry;
-: 1249: using Base::PrintableCurrentLoc;
-: 1250: using Base::current_ast_node;
-: 1251:
-: 1252: //------------------------------------------------------------
-: 1253: // Pure virtual methods that a subclass must implement.
-: 1254:
-: 1255: // Returns true if we are not interested in iwyu information for the
-: 1256: // given type, where the type is *not* the current AST node.
-: 1257: // TODO(csilvers): check we're calling this consistent with its API.
-: 1258: virtual bool CanIgnoreType(const Type* type) const = 0;
-: 1259:
-: 1260: // Returns true if we are not interested in doing an iwyu check on
-: 1261: // the given decl, where the decl is *not* the current AST node.
-: 1262: // TODO(csilvers): check we're calling this consistent with its API.
-: 1263: virtual bool CanIgnoreDecl(const Decl* decl) const = 0;
-: 1264:
-: 1265: //------------------------------------------------------------
-: 1266: // IWYU logic.
-: 1267:
-: 1268: // Helper for MapPrivateDeclToPublicDecl. Returns true if the decl
-: 1269: // is a template specialization whose (written qualified) name matches
-: 1270: // the given name, has the given number of template arguments, and
-: 1271: // whose specified tpl argument is a type.
-: 1272: bool DeclIsTemplateWithNameAndNumArgsAndTypeArg(
12096: 1273: const Decl* decl, const string& name,
12096: 1274: size_t num_args, size_t type_arg_idx) const {
12096: 1275: const ClassTemplateSpecializationDecl* tpl_decl = DynCastFrom(decl);
12096: 1276: if (!tpl_decl)
7932: 1277: return false;
4164: 1278: const string actual_name = GetWrittenQualifiedNameAsString(tpl_decl);
4164: 1279: if (name != actual_name)
3941: 1280: return false;
223: 1281: const TemplateArgumentList& tpl_args = tpl_decl->getTemplateArgs();
223: 1282: if (tpl_args.size() != num_args)
#####: 1283: return false;
223: 1284: if (tpl_args.get(type_arg_idx).getKind() != TemplateArgument::Type)
#####: 1285: return false;
223: 1286: return true;
16260: 1287: }
-: 1288:
-: 1289: // This requires the above function to have been called on decl, first.
223: 1290: const Type* GetTplTypeArg(const Decl* decl, size_t type_arg_idx) const {
223: 1291: const ClassTemplateSpecializationDecl* tpl_decl = DynCastFrom(decl);
669: 1292: CHECK_(tpl_decl && "Must call DeclIsTemplateWithNameAndNumArgsAndTypeArg");
223: 1293: const TemplateArgumentList& tpl_args = tpl_decl->getTemplateArgs();
669: 1294: CHECK_(tpl_args.size() > type_arg_idx && "Invalid type_arg_idx");
669: 1295: CHECK_(tpl_args.get(type_arg_idx).getKind() == TemplateArgument::Type);
223: 1296: return tpl_args.get(type_arg_idx).getAsType().getTypePtr();
-: 1297: }
-: 1298:
-: 1299: // Some types, such as __gnu_cxx::__normal_iterator or std::__wrap_iter, are
-: 1300: // private types that should not be exposed to the user. Instead, they're
-: 1301: // exposed to the user via typedefs, like vector::iterator.
-: 1302: // Sometimes, the typedef gets lost (such as for find(myvec.begin(),
-: 1303: // myvec.end(), foo)), so we need to manually map back. We map
-: 1304: // __normal_iterator<foo, vector> to vector<> and __wrap_iter<foo> to foo,
-: 1305: // assuming that the vector<> class includes the typedef. Likewise, we map
-: 1306: // any free function taking a private iterator (such as operator==) the
-: 1307: // same way, assuming that that (templatized) function is instantiated
-: 1308: // as part of the vector class.
-: 1309: // We do something similar for _List_iterator and _List_const_iterator
-: 1310: // from GNU libstdc++, and for __list_iterator and __list_const_iterator
-: 1311: // from libc++. These private names are defined in stl_list.h and list
-: 1312: // respectively, so we don't need to re-map them, but we do want to re-map
-: 1313: // reverse_iterator<_List_iterator> to something in list header.
-: 1314: // If the input decl does not correspond to one of these private
-: 1315: // decls, we return NULL. This method is actually a helper for
-: 1316: // MapPrivateDeclToPublicDecl() and MapPrivateTypeToPublicType().
3992: 1317: const Type* MapPrivateDeclToPublicType(const NamedDecl* decl) const {
3992: 1318: const NamedDecl* class_decl = decl;
-: 1319: // If we're a member method, then the __normal_iterator or __wrap_iter will
-: 1320: // be the parent: __normal_iterator::operator=. If we're a free
-: 1321: // overloaded operator, then the __normal_iterator will be the
-: 1322: // first argument: operator==(__normal_iterator<...>& lhs, ...);
3992: 1323: if (const CXXMethodDecl* method_decl = DynCastFrom(class_decl)) {
1362: 1324: class_decl = method_decl->getParent();
3992: 1325: } else if (const FunctionDecl* fn = DynCastFrom(decl)) {
300: 1326: if (fn->isOverloadedOperator() && fn->getNumParams() >= 1) {
84: 1327: const Type* firstarg_type = fn->getParamDecl(0)->getType().getTypePtr();
84: 1328: firstarg_type = RemovePointersAndReferencesAsWritten(firstarg_type);
84: 1329: class_decl = TypeToDeclAsWritten(firstarg_type);
84: 1330: }
216: 1331: }
-: 1332:
-: 1333: // In addition to __normal_iterator<x> and __wrap_iter<x>, we want
-: 1334: // to handle reverse_iterator<__normal_iterator<x>>, and in the same way.
3992: 1335: if (DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1336: class_decl, "std::reverse_iterator", 1, 0)) {
30: 1337: const Type* reversed_iterator_type = GetTplTypeArg(class_decl, 0);
-: 1338: // Gets class_decl to be reversed iterator.
30: 1339: class_decl = TypeToDeclAsWritten(reversed_iterator_type);
-: 1340:
-: 1341: // If it's reverse_iterator<_List_iterator>, map to
-: 1342: // _List_iterator, which is defined in stl_list like we want. Also map
-: 1343: // reverse_iterator<__list_iterator> to __list_iterator which is defined
-: 1344: // in list.
30: 1345: if (DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1346: class_decl, "std::_List_iterator", 1, 0) ||
30: 1347: DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1348: class_decl, "std::_List_const_iterator", 1, 0) ||
30: 1349: DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1350: class_decl, "std::__list_iterator", 2, 0) ||
240: 1351: DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1352: class_decl, "std::__list_const_iterator", 2, 0)) {
#####: 1353: return reversed_iterator_type;
-: 1354: }
30: 1355: }
-: 1356:
3992: 1357: if (DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1358: class_decl, "__gnu_cxx::__normal_iterator", 2, 1)) {
#####: 1359: return GetTplTypeArg(class_decl, 1);
-: 1360: }
3992: 1361: if (DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1362: class_decl, "std::__wrap_iter", 1, 0)) {
193: 1363: return GetTplTypeArg(class_decl, 0);
-: 1364: }
-: 1365:
3799: 1366: return NULL;
3992: 1367: }
-: 1368:
3234: 1369: const NamedDecl* MapPrivateDeclToPublicDecl(const NamedDecl* decl) const {
3234: 1370: const Type* public_type = MapPrivateDeclToPublicType(decl);
3234: 1371: if (public_type)
145: 1372: return TypeToDeclAsWritten(public_type);
3089: 1373: return decl;
3234: 1374: }
-: 1375:
758: 1376: const Type* MapPrivateTypeToPublicType(const Type* type) const {
758: 1377: const NamedDecl* private_decl = TypeToDeclAsWritten(type);
758: 1378: const Type* public_type = MapPrivateDeclToPublicType(private_decl);
758: 1379: if (public_type)
48: 1380: return public_type;
710: 1381: return type;
758: 1382: }
-: 1383:
-: 1384: // Re-assign uses from macro authors to macro callers when possible.
-: 1385: // With macros, it can be very difficult to tell what types are the
-: 1386: // responsibility of the macro-caller, and which the macro-author. e.g.
-: 1387: // #define SIZE_IN_FOOS(ptr) ( sizeof(*ptr) / sizeof(Foo) )
-: 1388: // Here the type of *ptr is the responsibility of the caller, while the
-: 1389: // type of Foo is the responsibility of the author, even though the
-: 1390: // Exprs for *ptr and Foo are both located inside the macro (the Expr
-: 1391: // for ptr is located at the macro-calling site, but not for *ptr).
-: 1392: // To help us guess the owner, we use this rule: if the macro-file
-: 1393: // intends-to-provide the type, then we keep ownership of the type
-: 1394: // at the macro. Otherwise, we assume it's with the caller. This
-: 1395: // works well as long as the file defining the macro is well-behaved.
-: 1396: // This function should be called with a use-loc that is within
-: 1397: // an expanded macro (so the use-loc will point to either inside a
-: 1398: // macro definition, or to an argument to a macro call). If it
-: 1399: // points within a macro definition, and that macro-definition file
-: 1400: // does not mean to re-export the symbol being used, then we reassign
-: 1401: // use of the decl to the macro-caller.
2: 1402: SourceLocation GetUseLocationForMacroExpansion(SourceLocation use_loc,
2: 1403: const Decl* used_decl) {
6: 1404: CHECK_(IsInMacro(use_loc) && "Unexpected non-macro-expansion call");
4: 1405: if (!preprocessor_info().PublicHeaderIntendsToProvide(
2: 1406: GetFileEntry(use_loc), GetFileEntry(used_decl)))
1: 1407: return GetInstantiationLoc(use_loc);
1: 1408: return use_loc;
2: 1409: }
-: 1410:
-: 1411: // There are a few situations where iwyu is more restrictive than
-: 1412: // C++: where C++ allows a forward-declare but iwyu wants the full
-: 1413: // type. One is in a typedef: if you write 'typedef Foo MyTypedef',
-: 1414: // iwyu says that you are responsible for #including "foo.h", but
-: 1415: // the language allows a forward-declare. Another is for
-: 1416: // 'autocast': if your function has a parameter with a conversion
-: 1417: // (one-arg, not-explicit) constructor, iwyu requires that the
-: 1418: // function-author provides the full type of that parameter, but
-: 1419: // the language doesn't. (It's ok with all callers providing the
-: 1420: // full type instead.)
-: 1421: //
-: 1422: // In each of these situations, we allow the user to say that iwyu
-: 1423: // should not require #includes for these underlying types, but
-: 1424: // allow forward-declares instead. The author can do this by
-: 1425: // explicitly forward-declaring in the same file: for instance, they
-: 1426: // would do
-: 1427: // class Foo; typedef Foo MyTypedef; // can be on different lines :-)
-: 1428: // class AutocastType; void MyFunc(AutocastType); // but in same file
-: 1429: // If a definition- or declaration-site does this forward-declaring
-: 1430: // *and* does not directly #include the necessary file for Foo or
-: 1431: // AutocastType, we take that as a signal from the code-author that
-: 1432: // iwyu should relax its policies. These functions calculate the
-: 1433: // types (which may have many component-types if it's a templated
-: 1434: // type) for which the code-author has made this decision.
2714: 1435: bool CodeAuthorWantsJustAForwardDeclare(const Type* type,
2714: 1436: SourceLocation use_loc) {
2714: 1437: const NamedDecl* decl = TypeToDeclAsWritten(type);
2714: 1438: if (decl == NULL) // only class-types are candidates for returning true
1489: 1439: return false;
-: 1440:
-: 1441: // If we're a template specialization, we also accept
-: 1442: // forward-declarations of the underlying template (vector<T>, not
-: 1443: // vector<int>).
1225: 1444: set<const NamedDecl*> redecls = GetClassRedecls(decl);
1225: 1445: if (const ClassTemplateSpecializationDecl* spec_decl = DynCastFrom(decl)) {
262: 1446: InsertAllInto(GetClassRedecls(spec_decl->getSpecializedTemplate()),
-: 1447: &redecls);
262: 1448: }
-: 1449:
-: 1450: // Check if the author forward-declared the class in the same file.
1225: 1451: bool found_earlier_forward_declare_in_same_file = false;
6058: 1452: for (Each<const NamedDecl*> it(&redecls); !it.AtEnd(); ++it) {
816: 1453: if (IsBeforeInSameFile(*it, use_loc)) {
158: 1454: found_earlier_forward_declare_in_same_file = true;
158: 1455: break;
-: 1456: }
658: 1457: }
1225: 1458: if (!found_earlier_forward_declare_in_same_file)
1067: 1459: return false;
-: 1460:
-: 1461: // Check if the the author is not #including the file with the
-: 1462: // definition. PublicHeaderIntendsToProvide has exactly the
-: 1463: // semantics we want. Note if there's no definition anywhere, we
-: 1464: // say the author does not want the full type (which is a good
-: 1465: // thing, since there isn't one!)
158: 1466: if (const NamedDecl* dfn = GetDefinitionForClass(decl)) {
157: 1467: if (IsBeforeInSameFile(dfn, use_loc))
125: 1468: return false;
64: 1469: if (preprocessor_info().PublicHeaderIntendsToProvide(
32: 1470: GetFileEntry(use_loc), GetFileEntry(dfn))) {
26: 1471: return false;
-: 1472: }
6: 1473: }
-: 1474:
-: 1475: // OK, looks like the author has stated they don't want the fulll type.
7: 1476: return true;
3939: 1477: }
-: 1478:
-: 1479: const Type* GetUnderlyingType(const Type* type) {
-: 1480: if (const TypedefType* typedef_type = DynCastFrom(type)) {
-: 1481: return GetUnderlyingType(typedef_type->getDecl()->getUnderlyingType().getTypePtr());
-: 1482: }
-: 1483: return type;
-: 1484: }
-: 1485:
-: 1486: set<const Type*> GetCallerResponsibleTypesForTypedef(
119: 1487: const TypedefDecl* decl) {
119: 1488: set<const Type*> retval;
119: 1489: const Type* underlying_type = decl->getUnderlyingType().getTypePtr();
-: 1490: // If the underlying type is itself a typedef, we recurse.
119: 1491: if (const TypedefType* underlying_typedef = DynCastFrom(underlying_type)) {
4: 1492: if (const TypedefDecl* underlying_typedef_decl
4: 1493: = DynCastFrom(TypeToDeclAsWritten(underlying_typedef))) {
-: 1494: // TODO(csilvers): if one of the intermediate typedefs
-: 1495: // #includes the necessary definition of the 'final'
-: 1496: // underlying type, do we want to return the empty set here?
4: 1497: return GetCallerResponsibleTypesForTypedef(underlying_typedef_decl);
-: 1498: }
#####: 1499: }
-: 1500:
115: 1501: const Type* deref_type
115: 1502: = RemovePointersAndReferencesAsWritten(underlying_type);
115: 1503: if (CodeAuthorWantsJustAForwardDeclare(deref_type, GetLocation(decl))) {
1: 1504: retval.insert(deref_type);
-: 1505: // TODO(csilvers): include template type-args if appropriate.
-: 1506: // This requires doing an iwyu visit of the instantiated
-: 1507: // underlying type and seeing which type-args we require full
-: 1508: // use for. Also have to handle the case where the type-args
-: 1509: // are themselves templates. It will require pretty substantial
-: 1510: // iwyu surgery.
1: 1511: }
115: 1512: return retval;
119: 1513: }
-: 1514:
-: 1515: // ast_node is the node for the autocast CastExpr. We use it to get
-: 1516: // the parent CallExpr to figure out what function is being called.
-: 1517: set<const Type*> GetCallerResponsibleTypesForAutocast(
8: 1518: const ASTNode* ast_node) {
118: 1519: while (ast_node && !ast_node->IsA<CallExpr>())
47: 1520: ast_node = ast_node->parent();
24: 1521: CHECK_(ast_node && "Should only check Autocast if under a CallExpr");
8: 1522: const CallExpr* call_expr = ast_node->GetAs<CallExpr>();
8: 1523: const FunctionDecl* fn_decl = call_expr->getDirectCallee();
8: 1524: if (!fn_decl) // TODO(csilvers): what to do for fn ptrs and the like?
#####: 1525: return set<const Type*>();
-: 1526:
-: 1527: // Collect the non-explicit, one-arg constructor ('autocast') types.
8: 1528: set<const Type*> autocast_types;
21: 1529: for (FunctionDecl::param_const_iterator param = fn_decl->param_begin();
18: 1530: param != fn_decl->param_end(); ++param) {
5: 1531: const Type* param_type = GetTypeOf(*param);
5: 1532: if (HasImplicitConversionConstructor(param_type)) {
2: 1533: const Type* deref_param_type =
2: 1534: RemovePointersAndReferencesAsWritten(param_type);
2: 1535: autocast_types.insert(deref_param_type);
2: 1536: }
5: 1537: }
-: 1538:
-: 1539: // Now look at all the function decls that are visible from the
-: 1540: // call-location. We keep only the autocast params that *all*
-: 1541: // the function decl authors want the caller to be responsible
-: 1542: // for. We do this by elimination: start with all types, and
-: 1543: // remove them as we see authors providing the full type.
8: 1544: set<const Type*> retval = autocast_types;
8: 1545: for (FunctionDecl::redecl_iterator fn_redecl = fn_decl->redecls_begin();
26: 1546: fn_redecl != fn_decl->redecls_end(); ++fn_redecl) {
-: 1547: // Ignore function-decls that we can't see from the use-location.
18: 1548: if (!preprocessor_info().FileTransitivelyIncludes(
9: 1549: GetFileEntry(call_expr), GetFileEntry(*fn_redecl))) {
#####: 1550: continue;
-: 1551: }
9: 1552: for (set<const Type*>::iterator it = retval.begin();
11: 1553: it != retval.end(); ) {
2: 1554: if (!CodeAuthorWantsJustAForwardDeclare(*it, GetLocation(*fn_redecl))) {
-: 1555: // set<> has nice property that erasing doesn't invalidate iterators.
-: 1556:
2: 1557: retval.erase(it++);
2: 1558: } else {
#####: 1559: ++it;
-: 1560: }
2: 1561: }
9: 1562: }
-: 1563:
-: 1564: // TODO(csilvers): include template type-args of each entry of retval.
-: 1565:
8: 1566: return retval;
16: 1567: }
-: 1568:
-: 1569: set<const Type*> GetCallerResponsibleTypesForFnReturn(
1426: 1570: const FunctionDecl* decl) {
1426: 1571: set<const Type*> retval;
1426: 1572: const Type* return_type
1426: 1573: = RemoveElaboration(decl->getReturnType().getTypePtr());
1426: 1574: if (CodeAuthorWantsJustAForwardDeclare(return_type, GetLocation(decl))) {
#####: 1575: retval.insert(return_type);
-: 1576: // TODO(csilvers): include template type-args if appropriate.
#####: 1577: }
1426: 1578: return retval;
2852: 1579: }
-: 1580:
-: 1581: //------------------------------------------------------------
-: 1582: // Checkers, that tell iwyu_output about uses of symbols.
-: 1583: // We let, but don't require, subclasses to override these.
-: 1584:
-: 1585: // The comment, if not NULL, is extra text that is included along
-: 1586: // with the warning message that iwyu emits.
2934: 1587: virtual void ReportDeclUseWithComment(SourceLocation used_loc,
2934: 1588: const NamedDecl* decl,
2934: 1589: const char* comment) {
-: 1590: // Map private decls like __normal_iterator to their public counterpart.
2934: 1591: decl = MapPrivateDeclToPublicDecl(decl);
2934: 1592: if (CanIgnoreDecl(decl))
135: 1593: return;
-: 1594:
-: 1595: // Figure out the best location to attribute uses inside macros.
2799: 1596: if (IsInMacro(used_loc))
2: 1597: used_loc = GetUseLocationForMacroExpansion(used_loc, decl);
2799: 1598: const FileEntry* used_in = GetFileEntry(used_loc);
-: 1599:
5598: 1600: preprocessor_info().FileInfoFor(used_in)->ReportFullSymbolUse(
2799: 1601: used_loc, decl, IsNodeInsideCXXMethodBody(current_ast_node()),
-: 1602: comment);
-: 1603:
-: 1604: // Sometimes using a decl drags in a few other uses as well:
-: 1605:
-: 1606: // If we're a use that depends on a using declaration, make sure
-: 1607: // we #include the file with the using declaration.
-: 1608: // TODO(csilvers): check that our getQualifier() does not match
-: 1609: // the namespace of the decl. If we have 'using std::vector;' +
-: 1610: // 'std::vector<int> foo;' we don't actually care about the
-: 1611: // using-decl.
-: 1612: // TODO(csilvers): maybe just insert our own using declaration
-: 1613: // instead? We can call it "Use what you use". :-)
-: 1614: // TODO(csilvers): check for using statements and namespace aliases too.
2799: 1615: if (const UsingDecl* using_decl
2799: 1616: = GetUsingDeclarationOf(decl, GetDeclContext(current_ast_node()))) {
4: 1617: preprocessor_info().FileInfoFor(used_in)->ReportFullSymbolUse(
2: 1618: used_loc, using_decl, IsNodeInsideCXXMethodBody(current_ast_node()),
-: 1619: "(for using decl)");
2: 1620: }
-: 1621:
-: 1622: // For typedefs, the user of the type is sometimes the one
-: 1623: // responsible for the underlying type. We check if that is the
-: 1624: // case here, since we might be using a typedef type from
-: 1625: // anywhere. ('autocast' is similar, but is handled in
-: 1626: // VisitCastExpr; 'fn-return-type' is also similar and is
-: 1627: // handled in HandleFunctionCall.)
2799: 1628: if (const TypedefDecl* typedef_decl = DynCastFrom(decl)) {
-: 1629: // One exception: if this TypedefType is being used in another
-: 1630: // typedef (that is, 'typedef MyTypedef OtherTypdef'), then the
-: 1631: // user -- the other typedef -- is never responsible for the
-: 1632: // underlying type. Instead, users of that typedef are.
117: 1633: if (!current_ast_node()->template ParentIsA<TypedefDecl>()) {
115: 1634: const set<const Type*>& underlying_types
115: 1635: = GetCallerResponsibleTypesForTypedef(typedef_decl);
115: 1636: if (!underlying_types.empty()) {
2: 1637: VERRS(6) << "User, not author, of typedef "
#####: 1638: << typedef_decl->getQualifiedNameAsString()
-: 1639: << " owns the underlying type:\n";
-: 1640: // If any of the used types are themselves typedefs, this will
-: 1641: // result in a recursive expansion. Note we are careful to
-: 1642: // recurse inside this class, and not go back to subclasses.
5: 1643: for (Each<const Type*> it(&underlying_types); !it.AtEnd(); ++it)
1: 1644: IwyuBaseAstVisitor<Derived>::ReportTypeUseWithComment(used_loc, *it,
-: 1645: NULL);
1: 1646: }
115: 1647: }
117: 1648: }
2934: 1649: }
-: 1650:
-: 1651: // The comment, if not NULL, is extra text that is included along
-: 1652: // with the warning message that iwyu emits.
300: 1653: virtual void ReportDeclForwardDeclareUseWithComment(SourceLocation used_loc,
300: 1654: const NamedDecl* decl,
300: 1655: const char* comment) {
300: 1656: decl = MapPrivateDeclToPublicDecl(decl);
300: 1657: if (CanIgnoreDecl(decl))
#####: 1658: return;
-: 1659:
-: 1660: // Figure out the best location to attribute uses inside macros.
300: 1661: if (IsInMacro(used_loc))
#####: 1662: used_loc = GetUseLocationForMacroExpansion(used_loc, decl);
300: 1663: const FileEntry* used_in = GetFileEntry(used_loc);
-: 1664:
600: 1665: preprocessor_info().FileInfoFor(used_in)->ReportForwardDeclareUse(
300: 1666: used_loc, decl, IsNodeInsideCXXMethodBody(current_ast_node()),
-: 1667: comment);
-: 1668:
-: 1669: // If we're a use that depends on a using declaration, make sure
-: 1670: // we #include the file with the using declaration.
300: 1671: if (const UsingDecl* using_decl
300: 1672: = GetUsingDeclarationOf(decl, GetDeclContext(current_ast_node()))) {
8: 1673: preprocessor_info().FileInfoFor(used_in)->ReportFullSymbolUse(
4: 1674: used_loc, using_decl, IsNodeInsideCXXMethodBody(current_ast_node()),
-: 1675: "(for using decl)");
4: 1676: }
300: 1677: }
-: 1678:
-: 1679: // Like ReportDeclUse, but for the common case of no comment.
2303: 1680: void ReportDeclUse(SourceLocation used_loc, const NamedDecl* decl) {
2303: 1681: return ReportDeclUseWithComment(used_loc, decl, NULL);
-: 1682: }
-: 1683:
287: 1684: void ReportDeclForwardDeclareUse(SourceLocation used_loc,
287: 1685: const NamedDecl* decl) {
287: 1686: return ReportDeclForwardDeclareUseWithComment(used_loc, decl, NULL);
-: 1687: }
-: 1688:
291: 1689: void ReportDeclsUse(SourceLocation used_loc,
291: 1690: const set<const NamedDecl*>& decls) {
943: 1691: for (Each<const NamedDecl*> it(&decls); !it.AtEnd(); ++it)
35: 1692: ReportDeclUse(used_loc, *it);
291: 1693: }
-: 1694:
-: 1695: // Called when the given type is fully used at used_loc, regardless
-: 1696: // of the type being explicitly written in the source code or not.
-: 1697: // The comment, if not NULL, is extra text that is included along
-: 1698: // with the warning message that iwyu emits.
758: 1699: virtual void ReportTypeUseWithComment(SourceLocation used_loc,
758: 1700: const Type* type,
758: 1701: const char* comment) {
-: 1702: // TODO(csilvers): figure out if/when calling CanIgnoreType() is correct.
758: 1703: if (!type)
#####: 1704: return;
-: 1705:
-: 1706: // Map private types like __normal_iterator to their public counterpart.
758: 1707: type = MapPrivateTypeToPublicType(type);
-: 1708: // For the below, we want to be careful to call *our*
-: 1709: // ReportDeclUse(), not any of the ones in subclasses.
758: 1710: if (IsPointerOrReferenceAsWritten(type)) {
50: 1711: type = RemovePointersAndReferencesAsWritten(type);
50: 1712: if (const NamedDecl* decl = TypeToDeclAsWritten(type)) {
26: 1713: VERRS(6) << "(For pointer type " << PrintableType(type) << "):\n";
13: 1714: IwyuBaseAstVisitor<Derived>::ReportDeclForwardDeclareUseWithComment(
-: 1715: used_loc, decl, comment);
13: 1716: }
50: 1717: } else {
708: 1718: if (const NamedDecl* decl = TypeToDeclAsWritten(type)) {
631: 1719: decl = GetDefinitionAsWritten(decl);
631: 1720: std::string type_name = PrintableType(type);
631: 1721: if ((type_name == "class std::basic_string<char>")
631: 1722: || (type_name == "value_type")) {
#####: 1723: VERRS(6) << "Place for breakpoint\n";
#####: 1724: }
1262: 1725: VERRS(6) << "(For type " << PrintableType(type) << "):\n";
631: 1726: IwyuBaseAstVisitor<Derived>::ReportDeclUseWithComment(
-: 1727: used_loc, decl, comment);
631: 1728: }
-: 1729: }
758: 1730: }
-: 1731:
-: 1732: // Like ReportTypeUse, but for the common case of no comment.
751: 1733: void ReportTypeUse(SourceLocation used_loc, const Type* type) {
751: 1734: return ReportTypeUseWithComment(used_loc, type, NULL);
-: 1735: }
-: 1736:
291: 1737: void ReportTypesUse(SourceLocation used_loc, const set<const Type*>& types) {
1207: 1738: for (Each<const Type*> it(&types); !it.AtEnd(); ++it)
167: 1739: ReportTypeUse(used_loc, *it);
291: 1740: }
-: 1741:
-: 1742: //------------------------------------------------------------
-: 1743: // Visitors of types derived from clang::Decl.
-: 1744:
-: 1745: // Friend declarations only need their types forward-declared.
252: 1746: bool VisitFriendDecl(clang::FriendDecl* decl) {
416: 1747: if (CanIgnoreCurrentASTNode()) return true;
88: 1748: current_ast_node()->set_in_forward_declare_context(true);
88: 1749: return true;
252: 1750: }
-: 1751:
#####: 1752: bool VisitFriendTemplateDecl(clang::FriendTemplateDecl* decl) {
#####: 1753: if (CanIgnoreCurrentASTNode()) return true;
#####: 1754: current_ast_node()->set_in_forward_declare_context(true);
#####: 1755: return true;
#####: 1756: }
-: 1757:
-: 1758: // If you say 'typedef Foo Bar', C++ says you just need to
-: 1759: // forward-declare Foo. But iwyu would rather you fully define Foo,
-: 1760: // so all users of Bar don't have to. We make two exceptions:
-: 1761: // 1) The author of the typedef doesn't *want* to provide Foo, and
-: 1762: // is happy making all the callers do so. The author indicates
-: 1763: // this by explicitly forward-declaring Foo and not #including
-: 1764: // foo.h.
-: 1765: // 2) The typedef is a member of a templated class, and the
-: 1766: // underlying type is a template parameter:
-: 1767: // template<class T> struct C { typedef T value_type; };
-: 1768: // This is not a re-export because you need the type to
-: 1769: // access the typedef (via 'C<Someclass>::value_type'), so
-: 1770: // there's no need for the typedef-file to provide the type
-: 1771: // too. TODO(csilvers): this is patently wrong; figure out
-: 1772: // something better. We need something that doesn't require
-: 1773: // the full type info for creating a scoped_ptr<MyClass>.
-: 1774: // As an extension of (2), if the typedef is a template type that
-: 1775: // contains T as a template parameter, the typedef still re-exports
-: 1776: // the template type (it's not (2)), but the template parameter
-: 1777: // itself can be forward-declared, just as in (2). That is:
-: 1778: // template<class T> struct C { typedef pair<T,T> value_type; };
-: 1779: // iwyu will demand the full type of pair, but not of its template
-: 1780: // arguments. This is handled not here, but below, in
-: 1781: // VisitSubstTemplateTypeParmType.
2523: 1782: bool VisitTypedefDecl(clang::TypedefDecl* decl) {
4059: 1783: if (CanIgnoreCurrentASTNode()) return true;
987: 1784: const Type* underlying_type = decl->getUnderlyingType().getTypePtr();
987: 1785: const Type* deref_type
987: 1786: = RemovePointersAndReferencesAsWritten(underlying_type);
-: 1787:
987: 1788: if (CodeAuthorWantsJustAForwardDeclare(deref_type, GetLocation(decl)) ||
983: 1789: isa<SubstTemplateTypeParmType>(underlying_type)) {
181: 1790: current_ast_node()->set_in_forward_declare_context(true);
181: 1791: } else {
806: 1792: current_ast_node()->set_in_forward_declare_context(false);
-: 1793: }
-: 1794:
987: 1795: return Base::VisitTypedefDecl(decl);
2523: 1796: }
-: 1797:
-: 1798: // If we're a declared (not defined) function, all our types --
-: 1799: // return type and argument types -- are forward-declarable. The
-: 1800: // one exception required by the language is the throw types, which
-: 1801: // we clean up in VisitType().
-: 1802: // There are two more exceptions that iwyu imposes:
-: 1803: // (1) iwyu asks the function author to provide the full type
-: 1804: // information for the return type. That way the user doesn't
-: 1805: // have to.
-: 1806: // (2) If any of our function parameters have a type with a
-: 1807: // non-explicit, one-arg constructor, or is a const reference to
-: 1808: // such a type, mark that type as not forward declarable. The
-: 1809: // worry is that people might need the full type for the
-: 1810: // implicit conversion (the 'autocast'), for instance, passing
-: 1811: // in a char* to Fn(const StringPiece& foo) { ... }
-: 1812: // Both of these iwyu requirements can be overridden by the function
-: 1813: // author; for details, see CodeAuthorWantsJustAForwardDeclare.
6883: 1814: bool VisitFunctionDecl(clang::FunctionDecl* decl) {
12707: 1815: if (CanIgnoreCurrentASTNode()) return true;
-: 1816:
1059: 1817: if (!decl->isThisDeclarationADefinition()) {
-: 1818: // Make all our types forward-declarable...
252: 1819: current_ast_node()->set_in_forward_declare_context(true);
252: 1820: }
-: 1821:
-: 1822: // (The exceptions below don't apply to friend declarations; we
-: 1823: // never need full types for them.)
1059: 1824: if (IsFriendDecl(decl))
32: 1825: return true;
-: 1826:
-: 1827: // ...except the return value.
1027: 1828: const Type* return_type
1027: 1829: = RemoveElaboration(decl->getReturnType().getTypePtr());
1027: 1830: const bool is_responsible_for_return_type
1027: 1831: = (!CanIgnoreType(return_type) &&
183: 1832: !IsPointerOrReferenceAsWritten(return_type) &&
175: 1833: !CodeAuthorWantsJustAForwardDeclare(return_type, GetLocation(decl)));
-: 1834: // Don't bother to report here, when the language agrees with us
-: 1835: // we need the full type; that will be reported elsewhere, so
-: 1836: // reporting here would be double-counting.
1027: 1837: const bool type_use_reported_in_visit_function_type
1027: 1838: = (!current_ast_node()->in_forward_declare_context() ||
1254: 1839: !IsClassType(return_type));
1200: 1840: if (is_responsible_for_return_type &&
-: 1841: !type_use_reported_in_visit_function_type) {
2: 1842: ReportTypeUseWithComment(GetLocation(decl), return_type,
-: 1843: "(for fn return type)");
2: 1844: }
-: 1845:
-: 1846: // ...and non-explicit, one-arg ('autocast') constructor types.
2673: 1847: for (FunctionDecl::param_iterator param = decl->param_begin();
2265: 1848: param != decl->param_end(); ++param) {
619: 1849: const Type* param_type = GetTypeOf(*param);
619: 1850: if (!HasImplicitConversionConstructor(param_type))
565: 1851: continue;
54: 1852: const Type* deref_param_type =
54: 1853: RemovePointersAndReferencesAsWritten(param_type);
98: 1854: if (CanIgnoreType(param_type) && CanIgnoreType(deref_param_type))
37: 1855: continue;
-: 1856:
-: 1857: // TODO(csilvers): remove this 'if' check when we've resolved the
-: 1858: // clang bug where getTypeSourceInfo() can return NULL.
17: 1859: if ((*param)->getTypeSourceInfo()) {
9: 1860: const TypeLoc param_tl = (*param)->getTypeSourceInfo()->getTypeLoc();
-: 1861: // While iwyu requires the full type of autocast parameters,
-: 1862: // c++ does not. Function-writers can force iwyu to follow
-: 1863: // the language by explicitly forward-declaring the type.
-: 1864: // Check for that now, and don't require the full type.
18: 1865: if (CodeAuthorWantsJustAForwardDeclare(deref_param_type,
9: 1866: GetLocation(&param_tl)))
#####: 1867: continue;
-: 1868: // This is a 'full type required' check, to 'turn off' fwd decl.
-: 1869: // But don't bother to report in situations where we need the
-: 1870: // full type for other reasons; that's just double-reporting.
9: 1871: if (current_ast_node()->in_forward_declare_context() ||
6: 1872: IsPointerOrReferenceAsWritten(param_type)) {
4: 1873: ReportTypeUseWithComment(GetLocation(&param_tl), deref_param_type,
-: 1874: "(for autocast)");
4: 1875: }
9: 1876: } else {
16: 1877: VERRS(6) << "WARNING: NULL TypeSourceInfo for " << PrintableDecl(*param)
#####: 1878: << " (type " << PrintableType(param_type) << ")\n";
-: 1879: }
17: 1880: }
1027: 1881: return true;
6883: 1882: }
-: 1883:
-: 1884: // Special handling for C++ methods to detect covariant return types.
-: 1885: // These are defined as a derived class overriding a method with a different
-: 1886: // return type from the base.
4784: 1887: bool VisitCXXMethodDecl(CXXMethodDecl* method_decl) {
8676: 1888: if (CanIgnoreCurrentASTNode()) return true;
-: 1889:
892: 1890: if (HasCovariantReturnType(method_decl)) {
#####: 1891: const Type* return_type = RemovePointersAndReferencesAsWritten(
#####: 1892: method_decl->getReturnType().getTypePtr());
-: 1893:
#####: 1894: VERRS(3) << "Found covariant return type in "
#####: 1895: << method_decl->getQualifiedNameAsString()
-: 1896: << ", needs complete type of "
#####: 1897: << PrintableType(return_type)
-: 1898: << ".\n";
-: 1899:
#####: 1900: ReportTypeUse(CurrentLoc(), return_type);
#####: 1901: }
-: 1902:
892: 1903: return Base::VisitCXXMethodDecl(method_decl);
4784: 1904: }
-: 1905:
-: 1906: //------------------------------------------------------------
-: 1907: // Visitors of types derived from clang::Stmt.
-: 1908:
-: 1909: // Catch statements always require the full type to be visible,
-: 1910: // no matter if we're catching by value, reference or pointer.
91: 1911: bool VisitCXXCatchStmt(clang::CXXCatchStmt* stmt) {
177: 1912: if (CanIgnoreCurrentASTNode()) return true;
-: 1913:
5: 1914: if (const Type* caught_type = stmt->getCaughtType().getTypePtrOrNull()) {
-: 1915: // Strip off pointers/references to get to the 'base' type.
4: 1916: caught_type = RemovePointersAndReferencesAsWritten(caught_type);
4: 1917: ReportTypeUse(CurrentLoc(), caught_type);
4: 1918: } else {
-: 1919: // catch(...): no type to act on here.
-: 1920: }
-: 1921:
5: 1922: return Base::VisitCXXCatchStmt(stmt);
91: 1923: }
-: 1924:
-: 1925: // When casting non-pointers, iwyu will do the right thing
-: 1926: // automatically, but sometimes when casting from one pointer to
-: 1927: // another, you still need the full type information of both types:
-: 1928: // for instance, when static-casting from a sub-class to a
-: 1929: // super-class. Testing shows this is true for static, dynamic
-: 1930: // casts, and implicit casts, but not for reinterpret casts, const
-: 1931: // casts, or C-style casts. (Functional casts like int(3.5) are
-: 1932: // treated the same as C-style casts.) clang helpfully provides a
-: 1933: // 'cast kind', which we use to determine when full types are
-: 1934: // needed. When we notice that the cast is a cast up or down a
-: 1935: // class hierarchy, we require full type info for both types even
-: 1936: // for C-style casts (though the language doesn't), to give the
-: 1937: // compiler a fighting chance of generating correct code.
6940: 1938: bool VisitCastExpr(clang::CastExpr* expr) {
12329: 1939: if (CanIgnoreCurrentASTNode()) return true;
1551: 1940: const Type* const from_type = GetTypeOf(expr->getSubExprAsWritten());
1551: 1941: const Type* const to_type = GetTypeOf(expr);
1551: 1942: const Type* const deref_from_type = RemovePointersAndReferences(from_type);
1551: 1943: const Type* const deref_to_type = RemovePointersAndReferences(to_type);
-: 1944:
-: 1945: // For all those casts that don't result in function calls
-: 1946: // (everything except a user-defined cast or a constructor cast),
-: 1947: // we only care about the need for full types when casting either
-: 1948: // a pointer to a pointer, or any type to a reference.
-: 1949: // Unfortunately, when casting to a reference, clang seems to
-: 1950: // strip the reference off of to_type, so we need a separate
-: 1951: // function call to tell.
1551: 1952: if (expr->getCastKind() != clang::CK_UserDefinedConversion &&
1521: 1953: expr->getCastKind() != clang::CK_ConstructorConversion) {
1501: 1954: if (!((from_type->hasPointerRepresentation() && // pointer or reference
479: 1955: to_type->hasPointerRepresentation()) ||
1043: 1956: IsCastToReferenceType(expr)))
940: 1957: return true; // we only care about ptr-to-ptr casts for this check
561: 1958: }
-: 1959:
1222: 1960: bool need_full_deref_from_type = false;
1222: 1961: bool need_full_deref_to_type = false;
-: 1962: // The list of kinds: http://clang.llvm.org/doxygen/namespaceclang.html
1222: 1963: switch (expr->getCastKind()) {
-: 1964: // This cast still isn't handled directly.
-: 1965: case clang::CK_Dependent:
#####: 1966: break;
-: 1967:
-: 1968: // These casts don't require any iwyu action.
-: 1969: case clang::CK_LValueToRValue:
-: 1970: case clang::CK_AtomicToNonAtomic:
-: 1971: case clang::CK_NonAtomicToAtomic:
-: 1972: case clang::CK_ReinterpretMemberPointer:
-: 1973: case clang::CK_BuiltinFnToFnPtr:
-: 1974: case clang::CK_ZeroToOCLEvent: // OpenCL event_t is a built-in type.
-: 1975: case clang::CK_AddressSpaceConversion: // Address spaces are associated
-: 1976: // with pointers, so no need for
-: 1977: // the full type.
298: 1978: break;
-: 1979:
-: 1980: // We shouldn't be seeing any of these kinds.
-: 1981: case clang::CK_ArrayToPointerDecay:
-: 1982: case clang::CK_FloatingCast:
-: 1983: case clang::CK_FloatingComplexCast:
-: 1984: case clang::CK_FloatingComplexToBoolean:
-: 1985: case clang::CK_FloatingComplexToIntegralComplex:
-: 1986: case clang::CK_FloatingComplexToReal:
-: 1987: case clang::CK_FloatingRealToComplex:
-: 1988: case clang::CK_FloatingToBoolean:
-: 1989: case clang::CK_FloatingToIntegral:
-: 1990: case clang::CK_FunctionToPointerDecay:
-: 1991: case clang::CK_IntegralCast:
-: 1992: case clang::CK_IntegralComplexCast:
-: 1993: case clang::CK_IntegralComplexToBoolean:
-: 1994: case clang::CK_IntegralComplexToFloatingComplex:
-: 1995: case clang::CK_IntegralComplexToReal:
-: 1996: case clang::CK_IntegralRealToComplex:
-: 1997: case clang::CK_IntegralToBoolean:
-: 1998: case clang::CK_IntegralToFloating:
-: 1999: case clang::CK_IntegralToPointer:
-: 2000: case clang::CK_MemberPointerToBoolean:
-: 2001: case clang::CK_NullToMemberPointer:
-: 2002: case clang::CK_NullToPointer:
-: 2003: case clang::CK_PointerToBoolean:
-: 2004: case clang::CK_PointerToIntegral:
-: 2005: case clang::CK_ToUnion:
-: 2006: case clang::CK_ToVoid:
-: 2007: // Due to a bug in clang, we sometimes get IntegralToPointer
-: 2008: // kinds for a cast that should be a NoOp kind:
-: 2009: // http://llvm.org/bugs/show_bug.cgi?id=8543
-: 2010: // It's possible clang mis-categorizes in other cases too. So
-: 2011: // I just log here, rather than asserting and possibly
-: 2012: // crashing iwyu.
#####: 2013: VERRS(3) << "WARNING: Unexpected cast that involves a non-pointer: "
#####: 2014: << expr->getCastKindName() << "\n";
#####: 2015: break;
-: 2016: case clang::CK_AnyPointerToBlockPointerCast:
-: 2017: case clang::CK_ARCConsumeObject:
-: 2018: case clang::CK_ARCExtendBlockObject:
-: 2019: case clang::CK_ARCProduceObject:
-: 2020: case clang::CK_ARCReclaimReturnedObject:
-: 2021: case clang::CK_BlockPointerToObjCPointerCast:
-: 2022: case clang::CK_CopyAndAutoreleaseBlockObject:
-: 2023: case clang::CK_CPointerToObjCPointerCast:
-: 2024: case clang::CK_ObjCObjectLValueCast:
-: 2025: case clang::CK_VectorSplat:
#####: 2026: CHECK_UNREACHABLE_(
-: 2027: "TODO(csilvers): for objc and clang lang extensions");
-: 2028: break;
-: 2029:
-: 2030: // Kinds for reinterpret_cast and const_cast, which need no full types.
-: 2031: case clang::CK_BitCast: // used for reinterpret_cast
-: 2032: case clang::CK_LValueBitCast: // used for reinterpret_cast
-: 2033: case clang::CK_NoOp: // used for const_cast, etc
154: 2034: break;
-: 2035:
-: 2036: // Need the full to-type so we can call its constructor.
-: 2037: case clang::CK_ConstructorConversion:
-: 2038: // 'Autocast' -- calling a one-arg, non-explicit constructor
-: 2039: // -- is a special case when it's done for a function call.
-: 2040: // iwyu requires the function-writer to provide the #include
-: 2041: // for the casted-to type, just so we don't have to require it
-: 2042: // here. *However*, the function-author can override this
-: 2043: // iwyu requirement, in which case we're responsible for the
-: 2044: // casted-to type. See IwyuBaseASTVisitor::VisitFunctionDecl.
20: 2045: if (!current_ast_node()->template HasAncestorOfType<CallExpr>() ||
56: 2046: ContainsKey(
8: 2047: GetCallerResponsibleTypesForAutocast(current_ast_node()),
-: 2048: deref_to_type)) {
12: 2049: need_full_deref_to_type = true;
12: 2050: }
20: 2051: break;
-: 2052: // Need the full from-type so we can call its 'operator <totype>()'.
-: 2053: case clang::CK_UserDefinedConversion:
30: 2054: need_full_deref_from_type = true;
30: 2055: break;
-: 2056:
-: 2057: // Kinds that cast up or down an inheritance hierarchy.
-: 2058: case clang::CK_BaseToDerived:
-: 2059: case clang::CK_BaseToDerivedMemberPointer:
-: 2060: // Just 'to' type is enough: full type for derived gets base type too.
4: 2061: need_full_deref_to_type = true;
4: 2062: break;
-: 2063: case clang::CK_DerivedToBase:
-: 2064: case clang::CK_UncheckedDerivedToBase:
-: 2065: case clang::CK_DerivedToBaseMemberPointer:
103: 2066: need_full_deref_from_type = true;
103: 2067: break;
-: 2068: case clang::CK_Dynamic:
-: 2069: // Usually dynamic casting is a base-to-derived cast, but it is
-: 2070: // possible to dynamic-cast between siblings, in which case we
-: 2071: // need both types.
2: 2072: need_full_deref_from_type = true;
2: 2073: need_full_deref_to_type = true;
2: 2074: break;
-: 2075: }
-: 2076:
-: 2077: // TODO(csilvers): test if we correctly say we use FooPtr for
-: 2078: // typedef Foo* FooPtr; ... static_cast<FooPtr>(...) ...
746: 2079: if (need_full_deref_from_type && !CanIgnoreType(deref_from_type)) {
47: 2080: ReportTypeUse(CurrentLoc(), deref_from_type);
47: 2081: }
629: 2082: if (need_full_deref_to_type && !CanIgnoreType(deref_to_type)) {
14: 2083: ReportTypeUse(CurrentLoc(), deref_to_type);
14: 2084: }
611: 2085: return true;
6940: 2086: }
-: 2087:
-: 2088: // Mark that we need the full type info for our base type -- the
-: 2089: // thing we're a member of -- and it's not just forward-declarable.
-: 2090: // For instance, for code 'Mytype* myvar; myvar->a;', we'll get a
-: 2091: // MemberExpr callback whose base has the type of myvar.
3289: 2092: bool VisitMemberExpr(clang::MemberExpr* expr) {
5964: 2093: if (CanIgnoreCurrentASTNode()) return true;
-: 2094:
614: 2095: const Expr* base_expr = expr->getBase()->IgnoreParenImpCasts();
614: 2096: const Type* base_type = GetTypeOf(base_expr);
1842: 2097: CHECK_(base_type && "Member's base does not have a type?");
-: 2098: //base_type = GetUnderlyingType(base_type);
614: 2099: const Type* deref_base_type // For myvar->a, base-type will have a *
1842: 2100: = expr->isArrow() ? RemovePointerFromType(base_type) : base_type;
1082: 2101: if (CanIgnoreType(base_type) && CanIgnoreType(deref_base_type))
410: 2102: return true;
-: 2103: // Technically, we should say the type is being used at the
-: 2104: // location of base_expr. That may be a different file than us in
-: 2105: // cases like MACRO.b(). However, while one can imagine
-: 2106: // situations where the base-type is the responsibility of the
-: 2107: // macro-author ('SOME_GLOBAL_OBJECT.a()'), the more common case
-: 2108: // is it's our responsibility ('CHECK_NOTNULL(x).a()'). Until we
-: 2109: // can better distinguish whether a macro body is an expression
-: 2110: // that's responsible for its type or not, we just assume it is.
-: 2111: // TODO(csilvers): fix when we can determine what the macro-text
-: 2112: // is responsible for and what we're responsible for.
-: 2113: // TODO(csilvers): we should be reporting a fwd-decl use for
-: 2114: // GetTypeOf(expr), not on deref_base_type.
204: 2115: ReportTypeUse(CurrentLoc(), deref_base_type);
204: 2116: return true;
3289: 2117: }
-: 2118:
-: 2119: // For a[4], report that we need the full type of *a (to get its
-: 2120: // size; otherwise the compiler can't tell the address of a[4]).
150: 2121: bool VisitArraySubscriptExpr(clang::ArraySubscriptExpr* expr) {
296: 2122: if (CanIgnoreCurrentASTNode()) return true;
-: 2123:
4: 2124: const Type* element_type = GetTypeOf(expr);
4: 2125: if (CanIgnoreType(element_type))
2: 2126: return true;
2: 2127: ReportTypeUse(CurrentLoc(), element_type);
2: 2128: return true;
150: 2129: }
-: 2130:
-: 2131: // Mark that we need the full type info for the thing we're taking
-: 2132: // sizeof of. Sometimes this is double-counting: for
-: 2133: // sizeof(some_type), RecursiveASTVisitor will visit some_type and
-: 2134: // say it needs the full type information there, and for
-: 2135: // sizeof(some_var), we'll report we need full type information when
-: 2136: // some_var is defined. But if the arg is a reference, nobody else
-: 2137: // will say we need full type info but us.
29: 2138: bool VisitUnaryExprOrTypeTraitExpr(clang::UnaryExprOrTypeTraitExpr* expr) {
29: 2139: if (CanIgnoreCurrentASTNode()) return true;
-: 2140:
-: 2141: // Calling sizeof on a reference-to-X is the same as calling it on X.
-: 2142: // If sizeof() takes a type, this is easy to check. If sizeof()
-: 2143: // takes an expr, it's hard to tell -- GetTypeOf(expr) 'sees through'
-: 2144: // references. Luckily, we want to see through references, so we
-: 2145: // just use the GetTypeOf().
29: 2146: if (expr->isArgumentType()) {
26: 2147: const TypeLoc& arg_tl = expr->getArgumentTypeInfo()->getTypeLoc();
26: 2148: if (const ReferenceType* reftype = DynCastFrom(arg_tl.getTypePtr())) {
#####: 2149: const Type* dereftype = reftype->getPointeeTypeAsWritten().getTypePtr();
#####: 2150: if (!CanIgnoreType(reftype) || !CanIgnoreType(dereftype))
#####: 2151: ReportTypeUse(GetLocation(&arg_tl), dereftype);
#####: 2152: } else {
-: 2153: // No need to report on non-ref types, RecursiveASTVisitor will get 'em.
-: 2154: }
26: 2155: } else {
3: 2156: const Expr* arg_expr = expr->getArgumentExpr();
3: 2157: const Type* dereftype = arg_expr->getType().getTypePtr();
3: 2158: if (!CanIgnoreType(dereftype))
-: 2159: // This reports even if the expr ends up not being a reference, but
-: 2160: // that's ok (if potentially redundant).
3: 2161: ReportTypeUse(GetLocation(arg_expr), dereftype);
-: 2162: }
29: 2163: return true;
29: 2164: }
-: 2165:
-: 2166: // We want to mark use of the base type For 'free function' operator
-: 2167: // overloads ('ostream& operator<<(ostream& o, int x)') just like we
-: 2168: // do for member functions ('ostream& ostream::operator<<(int x)')
-: 2169: // -- for iwyu purposes, 'x << 4' is just semantic sugar around
-: 2170: // x.operator<<(4).
2876: 2171: bool VisitCXXOperatorCallExpr(clang::CXXOperatorCallExpr* expr) {
5700: 2172: if (CanIgnoreCurrentASTNode()) return true;
-: 2173:
52: 2174: if (const Expr* owner_expr = GetFirstClassArgument(expr)) {
50: 2175: const Type* owner_type = GetTypeOf(owner_expr);
-: 2176: // Note we report the type use is the location of owner_expr
-: 2177: // (the 'a' in 'a << b' or the 'MACRO' in 'MACRO << b'), rather
-: 2178: // than our location (which is the '<<'). That way, we properly
-: 2179: // situate the owner when it's a macro.
50: 2180: if (!CanIgnoreType(owner_type))
33: 2181: ReportTypeUse(GetLocation(owner_expr), owner_type);
50: 2182: }
52: 2183: return true;
2876: 2184: }
-: 2185:
-: 2186: // We have to check the type being deleted is fully defined (the
-: 2187: // language doesn't require it, but bad things happen if it's not:
-: 2188: // the destructor isn't run).
48: 2189: bool VisitCXXDeleteExpr(clang::CXXDeleteExpr* expr) {
66: 2190: if (CanIgnoreCurrentASTNode()) return true;
-: 2191:
30: 2192: const Expr* delete_arg = expr->getArgument()->IgnoreParenImpCasts();
-: 2193: // We always delete a pointer, so do one dereference to get the
-: 2194: // actual type being deleted.
30: 2195: const Type* delete_ptr_type = GetTypeOf(delete_arg);
30: 2196: const Type* delete_type = RemovePointerFromType(delete_ptr_type);
41: 2197: if (CanIgnoreType(delete_ptr_type) && CanIgnoreType(delete_type))
2: 2198: return true;
-: 2199:
55: 2200: if (delete_type && !IsPointerOrReferenceAsWritten(delete_type))
25: 2201: ReportTypeUse(CurrentLoc(), delete_type);
-: 2202:
28: 2203: return true;
48: 2204: }
-: 2205:
-: 2206: // Handle the case of passing references to variadic functions
-: 2207: // (those with '...'). We need the full type information for the
-: 2208: // reference in that case, since compilers seem to just deref the
-: 2209: // var before passing it in. Note we subclass all the
-: 2210: // function-calling methods rather than HandleFunctionCall, because
-: 2211: // a) we need type-specific caller information anyway, and b)
-: 2212: // HandleFunctionCall isn't called for calls via function-pointers,
-: 2213: // which we want.
534: 2214: void ReportIfReferenceVararg(const Expr* const* args, unsigned num_args,
534: 2215: const FunctionProtoType* callee_type) {
1068: 2216: if (callee_type && callee_type->isVariadic()) {
3: 2217: const unsigned first_vararg_index = callee_type->getNumParams();
20: 2218: for (unsigned i = first_vararg_index; i < num_args; i++) {
-: 2219: // We only care about reporting for references, but it's ok if
-: 2220: // we catch a few non-ref types too (it's just redundant).
-: 2221: // All expressions that are references will have their
-: 2222: // valuekind be an LValue, so we use that as the test.
7: 2223: if (args[i]->getValueKind() == clang::VK_LValue) {
-: 2224: // The types of expressions 'see through' the reference to
-: 2225: // the underlying type, which is exactly what we want here.
#####: 2226: ReportTypeUse(CurrentLoc(), GetTypeOf(args[i]));
#####: 2227: }
7: 2228: }
3: 2229: }
534: 2230: }
255: 2231: void ReportIfReferenceVararg(const Expr* const* args, unsigned num_args,
255: 2232: const FunctionDecl* callee) {
255: 2233: if (callee) {
255: 2234: const FunctionProtoType* callee_type =
255: 2235: DynCastFrom(callee->getType().getTypePtr());
765: 2236: CHECK_(callee_type &&
-: 2237: "The type of a FunctionDecl must be a FunctionProtoType.");
255: 2238: ReportIfReferenceVararg(args, num_args, callee_type);
255: 2239: }
255: 2240: }
-: 2241:
-: 2242: // We only need visitors for CallExpr, ConstructExpr, and NewExpr
-: 2243: // (which also captures their subclasses). We can ignore DeleteExpr
-: 2244: // since destructors never have arguments. NewExpr we treat below,
-: 2245: // since it requires other checks as well.
10009: 2246: bool VisitCallExpr(clang::CallExpr* expr) {
19410: 2247: if (CanIgnoreCurrentASTNode()) return true;
-: 2248: // Nothing to do if the called function is an old K&R-style function.
608: 2249: const FunctionType* fn_type = GetCalleeFunctionType(expr);
608: 2250: if (const FunctionProtoType* fn_proto = DynCastFrom(fn_type))
279: 2251: ReportIfReferenceVararg(expr->getArgs(), expr->getNumArgs(), fn_proto);
608: 2252: return true;
10009: 2253: }
-: 2254:
455: 2255: bool VisitCXXConstructExpr(clang::CXXConstructExpr* expr) {
672: 2256: if (CanIgnoreCurrentASTNode()) return true;
476: 2257: ReportIfReferenceVararg(expr->getArgs(), expr->getNumArgs(),
238: 2258: expr->getConstructor());
238: 2259: return true;
455: 2260: }
-: 2261:
-: 2262: // An OverloadExpr is an overloaded function (or method) in an
-: 2263: // uninstantiated template, that can't be resolved until the
-: 2264: // template is instantiated. The simplest case is something like:
-: 2265: // void Foo(int) { ... }
-: 2266: // void Foo(float) { ... }
-: 2267: // template<typename T> Fn(T t) { Foo(t); }
-: 2268: // But by far the most common case is when the function-to-be-called
-: 2269: // is also a templated function:
-: 2270: // template<typename T> Fn1(T t) { ... }
-: 2271: // template<typename T> Fn2(T t) { Fn1(t); }
-: 2272: // In either case, we look at all the potential overloads. If they
-: 2273: // all exist in the same file -- which is pretty much always the
-: 2274: // case, especially with a template calling a template -- we can do
-: 2275: // an iwyu warning now, even without knowing the exact overload.
-: 2276: // In that case, we store the fact we warned, so we won't warn again
-: 2277: // when the template is instantiated.
-: 2278: // TODO(csilvers): to be really correct, we should report *every*
-: 2279: // overload that callers couldn't match via ADL.
4747: 2280: bool VisitOverloadExpr(clang::OverloadExpr* expr) {
-: 2281: // No CanIgnoreCurrentASTNode() check here! It's later in the function.
-: 2282:
-: 2283: // Make sure all overloads are in the same file.
4747: 2284: if (expr->decls_begin() == expr->decls_end()) // not sure this is possible
5: 2285: return true;
4742: 2286: const NamedDecl* first_decl = *expr->decls_begin();
4742: 2287: const FileEntry* first_decl_file_entry = GetFileEntry(first_decl);
4742: 2288: for (OverloadExpr::decls_iterator it = expr->decls_begin();
24712: 2289: it != expr->decls_end(); ++it) {
12280: 2290: if (GetFileEntry(*it) != first_decl_file_entry)
2295: 2291: return true;
9985: 2292: }
-: 2293:
-: 2294: // For now, we're only worried about function calls.
-: 2295: // TODO(csilvers): are there other kinds of overloads we need to check?
2447: 2296: const FunctionDecl* arbitrary_fn_decl = NULL;
2447: 2297: for (OverloadExpr::decls_iterator it = expr->decls_begin();
2447: 2298: it != expr->decls_end(); ++it) {
2447: 2299: const NamedDecl* decl = *it;
-: 2300: // Sometimes a UsingShadowDecl comes between us and the 'real' decl.
2447: 2301: if (const UsingShadowDecl* using_shadow_decl = DynCastFrom(decl))
33: 2302: decl = using_shadow_decl->getTargetDecl();
2447: 2303: if (const FunctionDecl* fn_decl = DynCastFrom(decl)) {
692: 2304: arbitrary_fn_decl = fn_decl;
692: 2305: break;
1755: 2306: } else if (const FunctionTemplateDecl* tpl_decl = DynCastFrom(decl)) {
1755: 2307: arbitrary_fn_decl = tpl_decl->getTemplatedDecl();
1755: 2308: break;
-: 2309: }
#####: 2310: }
-: 2311:
-: 2312: // If we're an overloaded operator, we can never do the iwyu check
-: 2313: // before instantiation-time, because we don't know if we might
-: 2314: // end up being the built-in form of the operator. (Even if the
-: 2315: // only operator==() we see is in foo.h, we don't need to #include
-: 2316: // foo.h if the only call to operator== we see is on two integers.)
4894: 2317: if (arbitrary_fn_decl && !arbitrary_fn_decl->isOverloadedOperator()) {
1625: 2318: AddProcessedOverloadLoc(CurrentLoc());
3250: 2319: VERRS(7) << "Adding to processed_overload_locs: "
#####: 2320: << PrintableCurrentLoc() << "\n";
-: 2321: // Because processed_overload_locs might be set in one visitor
-: 2322: // but used in another, each with a different definition of
-: 2323: // CanIgnoreCurrentASTNode(), we have to be conservative and set
-: 2324: // the has-considered flag always. But of course we only
-: 2325: // actually report the function use if CanIgnoreCurrentASTNode()
-: 2326: // is *currently* false.
1625: 2327: if (!CanIgnoreCurrentASTNode())
2: 2328: ReportDeclUse(CurrentLoc(), arbitrary_fn_decl);
1625: 2329: }
2447: 2330: return true;
4747: 2331: }
-: 2332:
-: 2333: // TODO(csilvers): handle some special cases when we're a
-: 2334: // CXXDependentScopeMemberExpr (e.g. vector<T>::resize().). If the
-: 2335: // base class is a TemplateSpecializationType, get its TemplateDecl
-: 2336: // and if all explicit specializations and patterns are defined in
-: 2337: // the same file, treat it as an expr with only one decl. May have
-: 2338: // trouble with methods defined in a different file than they're
-: 2339: // declared.
-: 2340:
-: 2341: // If getOperatorNew() returns NULL, it means the operator-new is
-: 2342: // overloaded, and technically we can't know which operator-new is
-: 2343: // being called until the template is instantiated. But if it looks
-: 2344: // like a placement-new, we handle it at template-writing time
-: 2345: // anyway.
122: 2346: bool VisitCXXNewExpr(clang::CXXNewExpr* expr) {
-: 2347: // Like in VisitOverloadExpr(), we update processed_overload_locs
-: 2348: // regardless of the value of CanIgnoreCurrentASTNode().
-: 2349:
-: 2350: // We say it's placement-new if the (lone) placment-arg is a
-: 2351: // pointer. Unfortunately, often clang will just say it's a
-: 2352: // dependent type. In that case, we can still say it's a pointer
-: 2353: // in the (common) case the placement arg looks like '&something'.
-: 2354: // (This is possibly wrong for classes that override operator&, but
-: 2355: // those classes deserve what they get.)
122: 2356: if (!expr->getOperatorNew() &&
94: 2357: expr->getNumPlacementArgs() == 1 &&
78: 2358: (GetTypeOf(expr->getPlacementArg(0))->isPointerType() ||
30: 2359: GetTypeOf(expr->getPlacementArg(0))->isArrayType() ||
29: 2360: IsAddressOf(expr->getPlacementArg(0)))) {
-: 2361: // Treat this like an OverloadExpr.
56: 2362: AddProcessedOverloadLoc(CurrentLoc());
112: 2363: VERRS(7) << "Adding to processed_overload_locs (placement-new): "
#####: 2364: << PrintableCurrentLoc() << "\n";
56: 2365: if (!CanIgnoreCurrentASTNode()) {
-: 2366: // We have to 'make up' a full file path for 'new'. We'll
-: 2367: // parse it to '<new>' before using, so any path that does
-: 2368: // that, and is clearly a c++ path, is fine; its exact
-: 2369: // contents don't matter that much.
3: 2370: const FileEntry* use_file = CurrentFileEntry();
6: 2371: preprocessor_info().FileInfoFor(use_file)->ReportFullSymbolUse(
3: 2372: CurrentLoc(), "<new>", "operator new");
3: 2373: }
56: 2374: }
-: 2375:
-: 2376: // We also need to do a varargs check, like for other function calls.
215: 2377: if (CanIgnoreCurrentASTNode()) return true;
-: 2378: // ... only if this NewExpr involves a constructor call.
29: 2379: const Expr* Init = expr->getInitializer();
29: 2380: if (const CXXConstructExpr* CCE =
29: 2381: dyn_cast_or_null<CXXConstructExpr>(Init)){
34: 2382: ReportIfReferenceVararg(CCE->getArgs(),
17: 2383: CCE->getNumArgs(),
17: 2384: CCE->getConstructor());
17: 2385: }
29: 2386: return true;
122: 2387: }
-: 2388:
-: 2389: // When we call (or potentially call) a function, do an IWYU check
-: 2390: // via ReportDeclUse() to make sure the definition of the function
-: 2391: // is properly #included.
1666: 2392: bool HandleFunctionCall(FunctionDecl* callee, const Type* parent_type,
1666: 2393: const clang::Expr* calling_expr) {
1666: 2394: if (!Base::HandleFunctionCall(callee, parent_type, calling_expr))
#####: 2395: return false;
4958: 2396: if (!callee || CanIgnoreCurrentASTNode() || CanIgnoreDecl(callee))
58: 2397: return true;
-: 2398: // We may have already been checked in a previous
-: 2399: // VisitOverloadExpr() call. Don't check again in that case.
1608: 2400: if (IsProcessedOverloadLoc(CurrentLoc()))
182: 2401: return true;
-: 2402:
1426: 2403: ReportDeclUse(CurrentLoc(), callee);
-: 2404:
-: 2405: // Usually the function-author is responsible for providing the
-: 2406: // full type information for the return type of the function, but
-: 2407: // in cases where it's not, we have to take responsibility.
-: 2408: // TODO(csilvers): check the fn argument types as well.
1426: 2409: const Type* return_type = callee->getReturnType().getTypePtr();
1426: 2410: if (ContainsKey(GetCallerResponsibleTypesForFnReturn(callee),
-: 2411: return_type)) {
#####: 2412: ReportTypeUse(CurrentLoc(), return_type);
#####: 2413: }
-: 2414:
1426: 2415: return true;
1666: 2416: }
-: 2417:
-: 2418: //------------------------------------------------------------
-: 2419: // Visitors of types derived from clang::Type.
-: 2420:
65904: 2421: bool VisitType(clang::Type* type) {
-: 2422: // In VisitFunctionDecl(), we say all children of function
-: 2423: // declarations are forward-declarable. This is true, *except*
-: 2424: // for the exception (throw) types. We clean that up here.
-: 2425: // TODO(csilvers): figure out how to do these two steps in one place.
65904: 2426: const FunctionProtoType* fn_type = NULL;
65904: 2427: if (!fn_type) {
65904: 2428: fn_type = current_ast_node()->template GetParentAs<FunctionProtoType>();
65904: 2429: }
65904: 2430: if (!fn_type) {
58504: 2431: if (const FunctionDecl* fn_decl
58504: 2432: = current_ast_node()->template GetParentAs<FunctionDecl>())
7290: 2433: fn_type = dyn_cast<FunctionProtoType>(GetTypeOf(fn_decl));
58504: 2434: }
65904: 2435: if (fn_type) {
14690: 2436: for (FunctionProtoType::exception_iterator it =
29411: 2437: fn_type->exception_begin();
14752: 2438: it != fn_type->exception_end(); ++it)
45: 2439: if (it->getTypePtr() == type) { // *we're* an exception decl
14: 2440: current_ast_node()->set_in_forward_declare_context(false);
14: 2441: break;
31: 2442: }
14690: 2443: }
-: 2444:
65904: 2445: return Base::VisitType(type);
-: 2446: }
-: 2447:
-: 2448: bool VisitTemplateSpecializationType(
1070: 2449: clang::TemplateSpecializationType* type) {
1110: 2450: if (CanIgnoreCurrentASTNode()) return true;
1884: 2451: if (CanIgnoreType(type)) return true;
-: 2452:
176: 2453: const NamedDecl* decl = TypeToDeclAsWritten(type);
-: 2454:
-: 2455: // If we are forward-declarable, so are our template arguments.
176: 2456: if (CanForwardDeclareType(current_ast_node())) {
39: 2457: ReportDeclForwardDeclareUse(CurrentLoc(), decl);
39: 2458: current_ast_node()->set_in_forward_declare_context(true);
39: 2459: } else {
137: 2460: ReportDeclUse(CurrentLoc(), decl);
-: 2461: }
-: 2462:
176: 2463: return true;
1070: 2464: }
-: 2465:
-: 2466: //------------------------------------------------------------
-: 2467: // Visitors defined by BaseAstVisitor.
-: 2468:
8708: 2469: bool VisitNestedNameSpecifier(NestedNameSpecifier* nns) {
8708: 2470: if (!Base::VisitNestedNameSpecifier(nns)) return false;
-: 2471: // If we're in an nns (e.g. the Foo in Foo::bar), we're never
-: 2472: // forward-declarable, even if we're part of a pointer type, or in
-: 2473: // a template argument, or whatever.
8708: 2474: current_ast_node()->set_in_forward_declare_context(false);
8708: 2475: return true;
8708: 2476: }
-: 2477:
-: 2478: // Template arguments are forward-declarable by default. However,
-: 2479: // default template template args shouldn't be: we're responsible for
-: 2480: // the full type info for default args. So no forward-declaring
-: 2481: // MyClass in 'template<template<typename A> class T = MyClass> C ...'
-: 2482: // We detect because MyClass's parent is TemplateTemplateParmDecl.
-: 2483: // TODO(csilvers): And not when they're a type that's in
-: 2484: // known_fully_used_tpl_type_args_. See if that solves the problem with
-: 2485: // I1_TemplateClass<std::vector<I1_Class> > i1_nested_templateclass(...)
12475: 2486: void DetermineForwardDeclareStatusForTemplateArg(ASTNode* ast_node) {
37425: 2487: CHECK_(ast_node->IsA<TemplateArgument>() &&
-: 2488: "Should only pass in a template arg to DFDSFTA");
-: 2489:
12475: 2490: if (!IsDefaultTemplateTemplateArg(ast_node)) {
12475: 2491: ast_node->set_in_forward_declare_context(true);
12475: 2492: return;
-: 2493: }
12475: 2494: }
-: 2495:
197: 2496: bool VisitTemplateArgument(const TemplateArgument& arg) {
197: 2497: if (!Base::VisitTemplateArgument(arg)) return false;
-: 2498: // Template arguments are forward-declarable...usually.
197: 2499: DetermineForwardDeclareStatusForTemplateArg(current_ast_node());
197: 2500: return true;
197: 2501: }
-: 2502:
12278: 2503: bool VisitTemplateArgumentLoc(const TemplateArgumentLoc& argloc) {
12278: 2504: if (!Base::VisitTemplateArgumentLoc(argloc)) return false;
-: 2505: // Template arguments are forward-declarable...usually.
12278: 2506: DetermineForwardDeclareStatusForTemplateArg(current_ast_node());
12278: 2507: return true;
12278: 2508: }
-: 2509:
-: 2510: //------------------------------------------------------------
-: 2511: // Helper routines for visiting and traversing. These helpers
-: 2512: // encode the logic of whether a particular type of object
-: 2513: // can be forward-declared or not.
-: 2514:
-: 2515: // TODO(csilvers): get rid of in_forward_declare_context() and make
-: 2516: // this the canonical place to figure out if we can forward-declare.
1709: 2517: bool CanForwardDeclareType(const ASTNode* ast_node) const {
5127: 2518: CHECK_(ast_node->IsA<Type>());
-: 2519: // Cannot forward-declare an enum even if it's in a forward-declare context.
-: 2520: // TODO(vsapsai): make enums forward-declarable in C++11.
1709: 2521: if (ast_node->IsA<EnumType>())
86: 2522: return false;
-: 2523: // If we're in a forward-declare context, well then, there you have it.
1623: 2524: if (ast_node->in_forward_declare_context())
254: 2525: return true;
-: 2526: // If we're in a typedef, we don't want to forward-declare even if
-: 2527: // we're a pointer. ('typedef Foo* Bar; Bar x; x->a' needs full
-: 2528: // type of Foo.)
1369: 2529: if (ast_node->ParentIsA<TypedefDecl>())
101: 2530: return false;
-: 2531:
-: 2532: // If we ourselves are a forward-decl -- that is, we're the type
-: 2533: // component of a forward-declaration (which would be our parent
-: 2534: // AST node) -- then we're forward-declarable by definition.
1268: 2535: if (const TagDecl* parent
1268: 2536: = current_ast_node()->template GetParentAs<TagDecl>()) {
25: 2537: if (IsForwardDecl(parent))
#####: 2538: return true;
25: 2539: }
-: 2540:
-: 2541: // Another place we disregard what the language allows: if we're
-: 2542: // a dependent type, in theory we can be forward-declared. But
-: 2543: // we require the full definition anyway, so all the template
-: 2544: // callers don't have to provide it instead. Thus we don't
-: 2545: // run the following commented-out code (left here for reference):
-: 2546: //if (ast_node->GetAs<TemplateSpecializationType>()->isDependentType())
-: 2547: // return false;
-: 2548:
-: 2549: // Read past elaborations like 'class' keyword or namespaces.
2636: 2550: while (ast_node->ParentIsA<ElaboratedType>()) {
100: 2551: ast_node = ast_node->parent();
100: 2552: }
-: 2553:
-: 2554: // Now there are two options: either we have a type or we have a declaration
-: 2555: // involving a type.
1268: 2556: const Type* parent_type = ast_node->GetParentAs<Type>();
1268: 2557: if (parent_type == NULL) {
-: 2558: // Since it's not a type, it must be a decl.
-: 2559: // Our target here is record members, all of which derive from ValueDecl.
1014: 2560: if (const ValueDecl *decl = ast_node->GetParentAs<ValueDecl>()) {
-: 2561: // We can shortcircuit static data member declarations immediately,
-: 2562: // they can always be forward-declared.
328: 2563: if (const VarDecl *var_decl = DynCastFrom(decl)) {
227: 2564: if (!var_decl->isThisDeclarationADefinition() &&
#####: 2565: var_decl->isStaticDataMember()) {
#####: 2566: return true;
-: 2567: }
227: 2568: }
-: 2569:
328: 2570: parent_type = GetTypeOf(decl);
328: 2571: }
1014: 2572: }
-: 2573:
-: 2574: // TODO(csilvers): should probably just be IsPointerOrReference
1850: 2575: return parent_type && IsPointerOrReferenceAsWritten(parent_type);
1709: 2576: }
-: 2577:
-: 2578: protected:
-: 2579: const IwyuPreprocessorInfo& preprocessor_info() const {
4551: 2580: return visitor_state_->preprocessor_info;
-: 2581: }
-: 2582:
426: 2583: void AddUsingDeclaration(const NamedDecl* target_decl, // what's being used
426: 2584: const UsingDecl* using_decl) {
426: 2585: visitor_state_->using_declarations.insert(make_pair(target_decl,
-: 2586: using_decl));
426: 2587: }
-: 2588:
-: 2589: private:
-: 2590: template <typename T> friend class IwyuBaseAstVisitor;
-: 2591:
1608: 2592: bool IsProcessedOverloadLoc(SourceLocation loc) const {
1608: 2593: return ContainsKey(visitor_state_->processed_overload_locs, loc);
-: 2594: }
-: 2595:
1681: 2596: void AddProcessedOverloadLoc(SourceLocation loc) {
1681: 2597: visitor_state_->processed_overload_locs.insert(loc);
1681: 2598: }
-: 2599:
3099: 2600: const UsingDecl* GetUsingDeclarationOf(const NamedDecl* decl,
3099: 2601: const DeclContext* using_context) {
-: 2602: // We look through all the using-decls of the given decl. We
-: 2603: // limit them to ones that are visible from the decl-context we're
-: 2604: // currently in (that is, what namespaces we're in). Of those, we
-: 2605: // pick the one that's in the same file as decl, if possible,
-: 2606: // otherwise we pick one arbitrarily.
3099: 2607: const UsingDecl* retval = NULL;
3099: 2608: vector<const UsingDecl*> using_decls
3099: 2609: = FindInMultiMap(visitor_state_->using_declarations, decl);
9337: 2610: for (Each<const UsingDecl*> it(&using_decls); !it.AtEnd(); ++it) {
20: 2611: if (!(*it)->getDeclContext()->Encloses(using_context))
14: 2612: continue;
12: 2613: if (GetFileEntry(decl) == GetFileEntry(*it) || // in same file, prefer
-: 2614: retval == NULL) { // not in same file, but better than nothing
6: 2615: retval = *it;
6: 2616: }
6: 2617: }
3099: 2618: return retval;
3099: 2619: }
-: 2620:
-: 2621: // Do not any variables here! If you do, they will not be shared
-: 2622: // between the normal iwyu ast visitor and the
-: 2623: // template-instantiation visitor, which is almost always a mistake.
-: 2624: // Instead, add them to the VisitorState struct, above.
-: 2625: VisitorState* const visitor_state_;
-: 2626:};
-: 2627:
-: 2628:
-: 2629:// ----------------------------------------------------------------------
-: 2630:// --- InstantiatedTemplateVisitor
-: 2631:// ----------------------------------------------------------------------
-: 2632://
-: 2633:// This class is used to find all template-specified types used in an
-: 2634:// instantiated template class, function, or method -- or rather, all
-: 2635:// such types that are used in a way that can't be forward-declared.
-: 2636:// That is, for
-: 2637:// template<class T, class U> int Myfunc() { T* t; U u; Thirdclass z; }
-: 2638:// if we saw an instantiation such as myfunc<Foo, Bar>, we would pass
-: 2639:// that instantiation to this traversal class, and it would report
-: 2640:// that Bar is used in a non-forward-declarable way. (It would not
-: 2641:// report Foo, which is used only in a forward-declarable way, and
-: 2642:// would not report Thirdclass, which is not a type specified in a
-: 2643:// template.)
-: 2644://
-: 2645:// This class has two main entry points: one for instantiated
-: 2646:// template functions and methods (including static methods,
-: 2647:// constructor calls, and operator overloads), and one for
-: 2648:// instantiated template classes.
-: 2649://
-: 2650:// In each case, it is given the appropriate node from the AST that
-: 2651:// captures the instantiation (a TemplateSpecializationType or
-: 2652:// CallExpr), and returns a set of Type* nodes of types that are used
-: 2653:// in a non-forward-declarable way. Note it's safe to call this even
-: 2654:// on non-templatized functions and classes; we'll just always return
-: 2655:// the empty set in that case.
-: 2656://
-: 2657:// The traversal of the AST is done via RecursiveASTVisitor, which uses
-: 2658:// CRTP (http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)
-: 2659:// TODO(csilvers): move this to its own file?
-: 2660:
#####: 2661:class InstantiatedTemplateVisitor
-: 2662: : public IwyuBaseAstVisitor<InstantiatedTemplateVisitor> {
-: 2663: public:
-: 2664: typedef IwyuBaseAstVisitor<InstantiatedTemplateVisitor> Base;
-: 2665:
2: 2666: InstantiatedTemplateVisitor(VisitorState* visitor_state)
1: 2667: : Base(visitor_state) {
1: 2668: Clear();
2: 2669: }
-: 2670:
-: 2671: //------------------------------------------------------------
-: 2672: // Public entry points
-: 2673:
-: 2674: // ScanInstantiatedFunction() looks through the template definition of
-: 2675: // the given function as well as the definitions of all functions
-: 2676: // called from it (directly or indirectly) and records all template
-: 2677: // type arguments fully used by them and all methods used by them.
-: 2678: // The "fully used type arguments" are a subset of
-: 2679: // tpl_type_args_of_interest, which are the types we care about, and
-: 2680: // usually explicitly written at the call site.
-: 2681: //
-: 2682: // ScanInstantiatedType() is similar, except that it looks through
-: 2683: // the definition of a class template instead of a statement.
-: 2684:
-: 2685: // resugar_map is a map from an unsugared (canonicalized) template
-: 2686: // type to the template type as written (or as close as we can find
-: 2687: // to it). If a type is not in resugar-map, it might be due to a
-: 2688: // recursive template call and encode a template type we don't care
-: 2689: // about ourselves. If it's in the resugar_map but with a NULL
-: 2690: // value, it's a default template parameter, that the
-: 2691: // template-caller may or may not be responsible for.
-: 2692: void ScanInstantiatedFunction(
427: 2693: const FunctionDecl* fn_decl, const Type* parent_type,
427: 2694: const ASTNode* caller_ast_node,
427: 2695: const map<const Type*, const Type*>& resugar_map) {
427: 2696: Clear();
427: 2697: caller_ast_node_ = caller_ast_node;
427: 2698: resugar_map_ = resugar_map;
-: 2699:
-: 2700: // Make sure that the caller didn't already put the decl on the ast-stack.
1281: 2701: CHECK_(caller_ast_node->GetAs<Decl>() != fn_decl && "AST node already set");
-: 2702: // caller_ast_node requires a non-const ASTNode, but our node is
-: 2703: // const. This cast is safe because we don't do anything with this
-: 2704: // node (instead, we immediately push a new node on top of it).
427: 2705: set_current_ast_node(const_cast<ASTNode*>(caller_ast_node));
-: 2706:
427: 2707: TraverseExpandedTemplateFunctionHelper(fn_decl, parent_type);
427: 2708: }
-: 2709:
-: 2710: // This isn't a Stmt, but sometimes we need to fully instantiate
-: 2711: // a template class to get at a field of it, for instance:
-: 2712: // MyClass<T>::size_type s;
-: 2713: void ScanInstantiatedType(
138: 2714: const Type* type, const ASTNode* caller_ast_node,
138: 2715: const map<const Type*, const Type*>& resugar_map) {
138: 2716: Clear();
138: 2717: caller_ast_node_ = caller_ast_node;
138: 2718: resugar_map_ = resugar_map;
-: 2719:
-: 2720: // Make sure that the caller didn't already put the type on the ast-stack.
414: 2721: CHECK_(caller_ast_node->GetAs<Type>() != type && "AST node already set");
-: 2722: // caller_ast_node requires a non-const ASTNode, but our node is
-: 2723: // const. This cast is safe because we don't do anything with this
-: 2724: // node (instead, we immediately push a new node on top of it).
138: 2725: set_current_ast_node(const_cast<ASTNode*>(caller_ast_node));
-: 2726:
-: 2727: // As in TraverseExpandedTemplateFunctionHelper, we ignore all AST nodes
-: 2728: // that will be reported when we traverse the uninstantiated type.
138: 2729: if (const NamedDecl* type_decl_as_written = TypeToDeclAsWritten(type)) {
138: 2730: AstFlattenerVisitor nodeset_getter(compiler());
138: 2731: nodes_to_ignore_ = nodeset_getter.GetNodesBelow(
-: 2732: const_cast<NamedDecl*>(type_decl_as_written));
138: 2733: }
-: 2734:
138: 2735: TraverseType(QualType(type, 0));
138: 2736: }
-: 2737:
-: 2738: //------------------------------------------------------------
-: 2739: // Implements virtual methods from Base.
-: 2740:
-: 2741: // When checking a template instantiation, we don't care where the
-: 2742: // template definition is, so we never have any reason to ignore a
-: 2743: // node.
-: 2744: virtual bool CanIgnoreCurrentASTNode() const {
-: 2745: // TODO(csilvers): call CanIgnoreType() if we're a type.
13138: 2746: return nodes_to_ignore_.Contains(*current_ast_node());
-: 2747: }
-: 2748:
-: 2749: // For template instantiations, we want to print the symbol even if
-: 2750: // it's not from the main compilation unit.
-: 2751: virtual bool ShouldPrintSymbolFromCurrentFile() const {
29138: 2752: return GlobalFlags().verbose >= 5;
-: 2753: }
-: 2754:
#####: 2755: virtual string GetSymbolAnnotation() const { return " in tpl"; }
-: 2756:
-: 2757: // We only care about types that would have been dependent in the
-: 2758: // uninstantiated template: that is, SubstTemplateTypeParmType types
-: 2759: // or types derived from them. We use nodes_to_ignore_ to select
-: 2760: // down to those. Even amongst subst-type, we only want ones in the
-: 2761: // resugar-map: the rest we have chosen to ignore for some reason.
5510: 2762: virtual bool CanIgnoreType(const Type* type) const {
5510: 2763: if (nodes_to_ignore_.Contains(type))
#####: 2764: return true;
-: 2765:
-: 2766: // If we're a default template argument, we should ignore the type
-: 2767: // if the template author intend-to-provide it, but otherwise we
-: 2768: // should not ignore it -- the caller is responsible for the type.
-: 2769: // This captures cases like hash_set<Foo>, where the caller is
-: 2770: // responsible for defining hash<Foo>.
-: 2771: // SomeInstantiatedTemplateIntendsToProvide handles the case we
-: 2772: // have a templated class that #includes "foo.h" and has a
-: 2773: // scoped_ptr<Foo>: we say the templated class provides Foo, even
-: 2774: // though it's scoped_ptr.h that's actually trying to call
-: 2775: // Foo::Foo and ::~Foo.
-: 2776: // TODO(csilvers): this isn't ideal: ideally we'd want
-: 2777: // 'TheInstantiatedTemplateForWhichTypeWasADefaultTemplateArgumentIntendsToProvide',
-: 2778: // but clang doesn't store that information.
5510: 2779: if (IsDefaultTemplateParameter(type))
237: 2780: return SomeInstantiatedTemplateIntendsToProvide(type);
-: 2781:
-: 2782: // If we're not in the resugar-map at all, we're not a type
-: 2783: // corresponding to the template being instantiated, so we
-: 2784: // can be ignored.
5273: 2785: type = RemoveSubstTemplateTypeParm(type);
5273: 2786: return !ContainsKey(resugar_map_, type);
5510: 2787: }
-: 2788:
-: 2789: // We ignore function calls in nodes_to_ignore_, which were already
-: 2790: // handled by the template-as-written, and function names that we
-: 2791: // are not responsible for because the template code is (for
-: 2792: // instance, we're not responsible for a vector's call to
-: 2793: // allocator::allocator(), because <vector> provides it for us).
2708: 2794: virtual bool CanIgnoreDecl(const Decl* decl) const {
2708: 2795: return nodes_to_ignore_.Contains(decl);
-: 2796: }
-: 2797:
-: 2798: // We always attribute type uses to the template instantiator. For
-: 2799: // decls, we do unless it looks like the template "intends to
-: 2800: // provide" the decl, by #including the file that defines the decl
-: 2801: // (if templates call other templates, we have to find the right
-: 2802: // template).
631: 2803: virtual void ReportDeclUseWithComment(SourceLocation used_loc,
631: 2804: const NamedDecl* decl,
631: 2805: const char* comment) {
631: 2806: const SourceLocation actual_used_loc = GetLocOfTemplateThatProvides(decl);
631: 2807: if (actual_used_loc.isValid()) {
-: 2808: // If a template is responsible for this decl, then we don't add
-: 2809: // it to the cache; the cache is only for decls that the
-: 2810: // original caller is responsible for.
537: 2811: Base::ReportDeclUseWithComment(actual_used_loc, decl, comment);
537: 2812: } else {
-: 2813: // Let all the currently active types and decls know about this
-: 2814: // report, so they can update their cache entries.
424: 2815: for (Each<CacheStoringScope*> it(&cache_storers_); !it.AtEnd(); ++it)
71: 2816: (*it)->NoteReportedDecl(decl);
94: 2817: Base::ReportDeclUseWithComment(caller_loc(), decl, comment);
-: 2818: }
631: 2819: }
-: 2820:
546: 2821: virtual void ReportTypeUseWithComment(SourceLocation used_loc,
546: 2822: const Type* type,
546: 2823: const char* comment) {
-: 2824: // clang desugars template types, so Foo<MyTypedef>() gets turned
-: 2825: // into Foo<UnderlyingType>(). Try to convert back.
546: 2826: type = ResugarType(type);
3162: 2827: for (Each<CacheStoringScope*> it(&cache_storers_); !it.AtEnd(); ++it)
762: 2828: (*it)->NoteReportedType(type);
546: 2829: Base::ReportTypeUseWithComment(caller_loc(), type, comment);
546: 2830: }
-: 2831:
-: 2832: //------------------------------------------------------------
-: 2833: // Overridden traverse-style methods from Base.
-: 2834:
-: 2835: // The 'convenience' HandleFunctionCall is perfect for us!
822: 2836: bool HandleFunctionCall(FunctionDecl* callee, const Type* parent_type,
822: 2837: const clang::Expr* calling_expr) {
822: 2838: if (const Type* resugared_type = ResugarType(parent_type))
678: 2839: parent_type = resugared_type;
822: 2840: if (!Base::HandleFunctionCall(callee, parent_type, calling_expr))
#####: 2841: return false;
2454: 2842: if (!callee || CanIgnoreCurrentASTNode() || CanIgnoreDecl(callee))
44: 2843: return true;
778: 2844: return TraverseExpandedTemplateFunctionHelper(callee, parent_type);
822: 2845: }
-: 2846:
24: 2847: bool TraverseUnaryExprOrTypeTraitExpr(clang::UnaryExprOrTypeTraitExpr* expr) {
24: 2848: if (!Base::TraverseUnaryExprOrTypeTraitExpr(expr)) return false;
24: 2849: if (CanIgnoreCurrentASTNode()) return true;
24: 2850: const Type* arg_type = expr->getTypeOfArgument().getTypePtr();
-: 2851: // Calling sizeof on a reference-to-X is the same as calling it on X.
24: 2852: if (const ReferenceType* reftype = DynCastFrom(arg_type)) {
#####: 2853: arg_type = reftype->getPointeeTypeAsWritten().getTypePtr();
#####: 2854: }
24: 2855: if (const TemplateSpecializationType* type = DynCastFrom(arg_type)) {
-: 2856: // Even though sizeof(MyClass<T>) only requires knowing how much
-: 2857: // storage MyClass<T> takes, the language seems to require that
-: 2858: // MyClass<T> be fully instantiated, even typedefs. (Try
-: 2859: // compiling 'template<class T> struct C { typedef typename T::a t; };
-: 2860: // class S; int main() { return sizeof(C<S>); }'.)
3: 2861: return TraverseDataAndTypeMembersOfClassHelper(type);
-: 2862: }
21: 2863: return true;
24: 2864: }
-: 2865:
-: 2866: bool TraverseTemplateSpecializationTypeHelper(
894: 2867: const clang::TemplateSpecializationType* type) {
934: 2868: if (CanIgnoreCurrentASTNode()) return true;
854: 2869: if (CanForwardDeclareType(current_ast_node()))
149: 2870: current_ast_node()->set_in_forward_declare_context(true);
854: 2871: return TraverseDataAndTypeMembersOfClassHelper(type);
894: 2872: }
-: 2873: bool TraverseTemplateSpecializationType(
173: 2874: clang::TemplateSpecializationType* type) {
173: 2875: if (!Base::TraverseTemplateSpecializationType(type)) return false;
173: 2876: return TraverseTemplateSpecializationTypeHelper(type);
173: 2877: }
-: 2878: bool TraverseTemplateSpecializationTypeLoc(
721: 2879: clang::TemplateSpecializationTypeLoc typeloc) {
721: 2880: if (!Base::TraverseTemplateSpecializationTypeLoc(typeloc)) return false;
721: 2881: return TraverseTemplateSpecializationTypeHelper(typeloc.getTypePtr());
721: 2882: }
-: 2883:
-: 2884: bool TraverseSubstTemplateTypeParmTypeHelper(
1172: 2885: const clang::SubstTemplateTypeParmType* type) {
1173: 2886: if (CanIgnoreCurrentASTNode()) return true;
1828: 2887: if (CanIgnoreType(type)) return true;
514: 2888: const Type* actual_type = ResugarType(type);
1542: 2889: CHECK_(actual_type && "If !CanIgnoreType(), we should be resugar-able");
514: 2890: return TraverseType(QualType(actual_type, 0));
1172: 2891: }
-: 2892: // When we see a template argument used inside an instantiated
-: 2893: // template, we want to explore the type recursively. For instance
-: 2894: // if we see Inner<Outer<Foo> >(), we want to recurse onto Foo.
-: 2895: bool TraverseSubstTemplateTypeParmType(
10: 2896: clang::SubstTemplateTypeParmType* type) {
10: 2897: if (!Base::TraverseSubstTemplateTypeParmType(type))
#####: 2898: return false;
10: 2899: return TraverseSubstTemplateTypeParmTypeHelper(type);
10: 2900: }
-: 2901: bool TraverseSubstTemplateTypeParmTypeLoc(
1162: 2902: clang::SubstTemplateTypeParmTypeLoc typeloc) {
1162: 2903: if (!Base::TraverseSubstTemplateTypeParmTypeLoc(typeloc))
#####: 2904: return false;
1162: 2905: return TraverseSubstTemplateTypeParmTypeHelper(typeloc.getTypePtr());
1162: 2906: }
-: 2907:
-: 2908: // These do the actual work of finding the types to return. Our
-: 2909: // task is made easier since (at least in theory), every time we
-: 2910: // instantiate a template type, the instantiation has type
-: 2911: // SubstTemplateTypeParmTypeLoc in the AST tree.
1172: 2912: bool VisitSubstTemplateTypeParmType(clang::SubstTemplateTypeParmType* type) {
1173: 2913: if (CanIgnoreCurrentASTNode()) return true;
1828: 2914: if (CanIgnoreType(type)) return true;
-: 2915:
-: 2916: // Figure out how this type was actually written. clang always
-: 2917: // canonicalizes SubstTemplateTypeParmType, losing typedef info, etc.
514: 2918: const Type* actual_type = ResugarType(type);
1542: 2919: CHECK_(actual_type && "If !CanIgnoreType(), we should be resugar-able");
-: 2920:
-: 2921: // TODO(csilvers): whenever we report a type use here, we want to
-: 2922: // do an iwyu check on this type (to see if sub-types are used).
-: 2923:
-: 2924: // If we're a nested-name-specifier class (the Foo in Foo::bar),
-: 2925: // we need our full type info no matter what the context (even if
-: 2926: // we're a pointer, or a template arg, or whatever).
-: 2927: // TODO(csilvers): consider encoding this logic via
-: 2928: // in_forward_declare_context. I think this will require changing
-: 2929: // in_forward_declare_context to yes/no/maybe.
514: 2930: if (current_ast_node()->ParentIsA<NestedNameSpecifier>()) {
5: 2931: ReportTypeUse(CurrentLoc(), actual_type);
5: 2932: return Base::VisitSubstTemplateTypeParmType(type);
-: 2933: }
-: 2934:
-: 2935: // If we're inside a typedef, we don't need our full type info --
-: 2936: // in this case we follow what the C++ language allows and let
-: 2937: // the underlying type of a typedef be forward-declared. This has
-: 2938: // the effect that code like:
-: 2939: // class MyClass;
-: 2940: // template<class T> struct Foo { typedef T value_type; ... }
-: 2941: // Foo<MyClass> f;
-: 2942: // does not make us require the full type of MyClass. The idea
-: 2943: // is that using Foo<MyClass>::value_type already requires the
-: 2944: // type for MyClass, so it doesn't make sense for the typedef
-: 2945: // to require it as well. TODO(csilvers): this doesn't really
-: 2946: // make any sense. Who figures out we need the full type if
-: 2947: // you do 'Foo<MyClass>::value_type m;'?
4935: 2948: for (const ASTNode* ast_node = current_ast_node();
3917: 2949: ast_node != caller_ast_node_; ast_node = ast_node->parent()) {
4026: 2950: if (ast_node->IsA<TypedefDecl>())
109: 2951: return Base::VisitSubstTemplateTypeParmType(type);
3917: 2952: }
-: 2953:
-: 2954: // sizeof(a reference type) is the same as sizeof(underlying type).
-: 2955: // We have to handle that specially here, or else we'll say the
-: 2956: // reference is forward-declarable, below.
400: 2957: if (current_ast_node()->ParentIsA<UnaryExprOrTypeTraitExpr>() &&
10: 2958: isa<ReferenceType>(actual_type)) {
#####: 2959: const ReferenceType* actual_reftype = cast<ReferenceType>(actual_type);
#####: 2960: ReportTypeUse(CurrentLoc(),
#####: 2961: actual_reftype->getPointeeTypeAsWritten().getTypePtr());
#####: 2962: return Base::VisitSubstTemplateTypeParmType(type);
-: 2963: }
-: 2964:
-: 2965: // If we're used in a forward-declare context (MyFunc<T>() { T* t; }),
-: 2966: // or are ourselves a pointer type (MyFunc<Myclass*>()),
-: 2967: // we don't need to do anything: we're fine being forward-declared.
400: 2968: if (current_ast_node()->in_forward_declare_context())
143: 2969: return Base::VisitSubstTemplateTypeParmType(type);
-: 2970:
257: 2971: if (current_ast_node()->ParentIsA<PointerType>() ||
176: 2972: current_ast_node()->ParentIsA<LValueReferenceType>() ||
162: 2973: IsPointerOrReferenceAsWritten(actual_type))
117: 2974: return Base::VisitSubstTemplateTypeParmType(type);
-: 2975:
-: 2976: // We attribute all uses in an instantiated template to the
-: 2977: // template's caller.
140: 2978: ReportTypeUse(caller_loc(), actual_type);
140: 2979: return Base::VisitSubstTemplateTypeParmType(type);
1172: 2980: }
-: 2981:
-: 2982: // If constructing an object, check the type we're constructing.
-: 2983: // Normally we'd see that type later, when traversing the return
-: 2984: // type of the constructor-decl, but if we wait for that, we'll lose
-: 2985: // any SubstTemplateTypeParmType's we have (we lose all
-: 2986: // SubstTemplateTypeParmType's going from Expr to Decl).
-: 2987: // TODO(csilvers): This should maybe move to HandleFunctionCall.
238: 2988: bool VisitCXXConstructExpr(clang::CXXConstructExpr* expr) {
252: 2989: if (CanIgnoreCurrentASTNode()) return true;
224: 2990: const Type* class_type = GetTypeOf(expr);
396: 2991: if (CanIgnoreType(class_type)) return true;
-: 2992:
-: 2993: // If the ctor type is a SubstTemplateTypeParmType, get the type-as-typed.
52: 2994: const Type* actual_type = ResugarType(class_type);
156: 2995: CHECK_(actual_type && "If !CanIgnoreType(), we should be resugar-able");
52: 2996: ReportTypeUse(caller_loc(), actual_type);
52: 2997: return Base::VisitCXXConstructExpr(expr);
238: 2998: }
-: 2999:
-: 3000: private:
-: 3001: // Clears the state of the visitor.
-: 3002: void Clear() {
566: 3003: caller_ast_node_ = NULL;
566: 3004: resugar_map_.clear();
566: 3005: traversed_decls_.clear();
566: 3006: nodes_to_ignore_.clear();
566: 3007: cache_storers_.clear();
566: 3008: }
-: 3009:
-: 3010: // If we see the instantiated template using a type or decl (such as
-: 3011: // std::allocator), we want to know if the author of the template is
-: 3012: // providing the type or decl, so the code using the instantiated
-: 3013: // template doesn't have to. For instance:
-: 3014: // vector<int, /*allocator<int>*/> v; // in foo.cc
-: 3015: // Does <vector> provide the definition of allocator<int>? If not,
-: 3016: // foo.cc will have to #include <allocator>.
-: 3017: // We say the template-as-written does provide the decl if it, or
-: 3018: // any other header seen since we started instantiating the
-: 3019: // template, sees it. The latter requirement is to deal with a
-: 3020: // situation like this: we have a templated class that #includes
-: 3021: // "foo.h" and has a scoped_ptr<Foo>; we say the templated class
-: 3022: // provides Foo, even though it's scoped_ptr.h that's actually
-: 3023: // trying to call Foo::Foo and Foo::~Foo.
868: 3024: SourceLocation GetLocOfTemplateThatProvides(const NamedDecl* decl) const {
868: 3025: if (!decl)
#####: 3026: return SourceLocation(); // an invalid source-loc
2295: 3027: for (const ASTNode* ast_node = current_ast_node();
559: 3028: ast_node != caller_ast_node_; ast_node = ast_node->parent()) {
2646: 3029: if (preprocessor_info().PublicHeaderIntendsToProvide(
1323: 3030: GetFileEntry(ast_node->GetLocation()),
1323: 3031: GetFileEntry(decl)))
764: 3032: return ast_node->GetLocation();
559: 3033: }
104: 3034: return SourceLocation(); // an invalid source-loc
868: 3035: }
-: 3036:
-: 3037: bool SomeInstantiatedTemplateIntendsToProvide(const NamedDecl* decl) const {
-: 3038: return GetLocOfTemplateThatProvides(decl).isValid();
-: 3039: }
237: 3040: bool SomeInstantiatedTemplateIntendsToProvide(const Type* type) const {
237: 3041: type = RemoveSubstTemplateTypeParm(type);
237: 3042: type = RemovePointersAndReferences(type); // get down to the decl
237: 3043: if (const NamedDecl* decl = TypeToDeclAsWritten(type))
237: 3044: return GetLocOfTemplateThatProvides(decl).isValid();
#####: 3045: return true; // we always provide non-decl types like int, etc.
237: 3046: }
-: 3047:
-: 3048: // For a SubstTemplateTypeParmType, says whether it corresponds to a
-: 3049: // default template parameter (one not explicitly specified when the
-: 3050: // class was instantiated) or not. We store this in resugar_map by
-: 3051: // having the value be NULL.
5510: 3052: bool IsDefaultTemplateParameter(const Type* type) const {
5510: 3053: type = RemoveSubstTemplateTypeParm(type);
5510: 3054: return ContainsKeyValue(resugar_map_, type, static_cast<Type*>(NULL));
-: 3055: }
-: 3056:
-: 3057: // clang desugars template types, so Foo<MyTypedef>() gets turned
-: 3058: // into Foo<UnderlyingType>(). We can 'resugar' using resugar_map_.
-: 3059: // If we're not in the resugar-map, then we weren't canonicalized,
-: 3060: // so we can just use the input type unchanged.
2448: 3061: const Type* ResugarType(const Type* type) const {
2448: 3062: type = RemoveSubstTemplateTypeParm(type);
-: 3063: // If we're the resugar-map but with a value of NULL, it means
-: 3064: // we're a default template arg, which means we don't have anything
-: 3065: // to resugar to. So just return the input type.
2448: 3066: if (ContainsKeyValue(resugar_map_, type, static_cast<const Type*>(NULL)))
38: 3067: return type;
2410: 3068: return GetOrDefault(resugar_map_, type, type);
2448: 3069: }
-: 3070:
1205: 3071: bool TraverseExpandedTemplateFunctionHelper(const FunctionDecl* fn_decl,
1205: 3072: const Type* parent_type) {
2410: 3073: if (!fn_decl || ContainsKey(traversed_decls_, fn_decl))
154: 3074: return true; // avoid recursion and repetition
1051: 3075: traversed_decls_.insert(fn_decl);
-: 3076:
-: 3077: // If we have cached the reporting done for this decl before,
-: 3078: // report again (but with the new caller_loc this time).
-: 3079: // Otherwise, for all reporting done in the rest of this scope,
-: 3080: // store in the cache for this function.
2102: 3081: if (ReplayUsesFromCache(*FunctionCallsFullUseCache(),
1051: 3082: fn_decl, caller_loc()))
170: 3083: return true;
-: 3084: // Make sure all the types we report in the recursive TraverseDecl
-: 3085: // calls, below, end up in the cache for fn_decl.
881: 3086: CacheStoringScope css(&cache_storers_, FunctionCallsFullUseCache(),
-: 3087: fn_decl, resugar_map_);
-: 3088:
-: 3089: // We want to ignore all nodes that are the same in this
-: 3090: // instantiated function as they are in the uninstantiated version
-: 3091: // of the function. The latter will be reported when we traverse
-: 3092: // the uninstantiated function, so we don't need to re-traverse
-: 3093: // them here.
881: 3094: AstFlattenerVisitor nodeset_getter(compiler());
-: 3095: // This gets to the decl for the (uninstantiated) template-as-written:
881: 3096: const FunctionDecl* decl_as_written
881: 3097: = fn_decl->getTemplateInstantiationPattern();
881: 3098: if (!decl_as_written) {
295: 3099: if (fn_decl->isImplicit()) { // TIP not set up for implicit methods
-: 3100: // TODO(csilvers): handle implicit template methods
214: 3101: } else { // not a templated decl
81: 3102: decl_as_written = fn_decl;
-: 3103: }
295: 3104: }
881: 3105: if (decl_as_written) {
667: 3106: FunctionDecl* const daw = const_cast<FunctionDecl*>(decl_as_written);
667: 3107: nodes_to_ignore_.AddAll(nodeset_getter.GetNodesBelow(daw));
667: 3108: }
-: 3109:
-: 3110: // We need to iterate over the function. We do so even if it's
-: 3111: // an implicit function.
881: 3112: if (fn_decl->isImplicit()) {
214: 3113: if (!TraverseImplicitDeclHelper(const_cast<FunctionDecl*>(fn_decl)))
#####: 3114: return false;
214: 3115: } else {
667: 3116: if (!TraverseDecl(const_cast<FunctionDecl*>(fn_decl)))
#####: 3117: return false;
-: 3118: }
-: 3119:
-: 3120: // If we're a constructor, we also need to construct the entire class,
-: 3121: // even typedefs that aren't used at construct time. Try compiling
-: 3122: // template<class T> struct C { typedef typename T::a t; };
-: 3123: // class S; int main() { C<S> c; }
881: 3124: if (isa<CXXConstructorDecl>(fn_decl)) {
780: 3125: CHECK_(parent_type && "How can a constructor have no parent?");
260: 3126: parent_type = RemoveElaboration(parent_type);
260: 3127: if (!TraverseDataAndTypeMembersOfClassHelper(
260: 3128: dyn_cast<TemplateSpecializationType>(parent_type)))
#####: 3129: return false;
260: 3130: }
881: 3131: return true;
2086: 3132: }
-: 3133:
-: 3134: // Does the actual recursing over data members and type members of
-: 3135: // the instantiated class. Unlike
-: 3136: // TraverseClassTemplateSpecializationDecl() in the base class, it
-: 3137: // does *not* traverse the methods.
-: 3138: bool TraverseDataAndTypeMembersOfClassHelper(
1117: 3139: const TemplateSpecializationType* type) {
1117: 3140: if (!type)
103: 3141: return true;
-: 3142:
-: 3143: // No point in doing traversal if we're forward-declared
1014: 3144: if (current_ast_node()->in_forward_declare_context())
154: 3145: return true;
-: 3146:
1720: 3147: while (type->isTypeAlias()) {
#####: 3148: type = DynCastFrom(type->getAliasedType().getTypePtr());
#####: 3149: if (!type)
#####: 3150: return true;
#####: 3151: }
-: 3152:
-: 3153: // If we're a dependent type, we only try to be analyzed if we're
-: 3154: // in the precomputed list -- in general, the only thing clang
-: 3155: // tells us about dependent types is their name (which is all we
-: 3156: // need for the precomputed list!). This means iwyu will properly
-: 3157: // analyze the use of SomeClass in code like 'map<T, SomeClass>',
-: 3158: // but not in 'MyMap<T, SomeClass>', since we have precomputed
-: 3159: // information about the STL map<>, but not the user type MyMap.
-: 3160: // TODO(csilvers): do better here.
860: 3161: if (type->isDependentType()) {
-: 3162: // TODO(csilvers): This is currently always a noop; need to fix
-: 3163: // GetTplTypeResugarMapForClassNoComponentTypes to do something
-: 3164: // useful for dependent types.
31: 3165: ReplayClassMemberUsesFromPrecomputedList(type); // best-effort
31: 3166: return true;
-: 3167: }
-: 3168:
829: 3169: const ClassTemplateSpecializationDecl* class_decl
829: 3170: = DynCastFrom(TypeToDeclAsWritten(type));
2487: 3171: CHECK_(class_decl && "TemplateSpecializationType is not a TplSpecDecl?");
829: 3172: if (ContainsKey(traversed_decls_, class_decl))
209: 3173: return true; // avoid recursion & repetition
620: 3174: traversed_decls_.insert(class_decl);
-: 3175:
-: 3176: // If we have cached the reporting done for this decl before,
-: 3177: // report again (but with the new caller_loc this time).
-: 3178: // Otherwise, for all reporting done in the rest of this scope,
-: 3179: // store in the cache for this function.
1240: 3180: if (ReplayUsesFromCache(*ClassMembersFullUseCache(),
620: 3181: class_decl, caller_loc()))
121: 3182: return true;
499: 3183: if (ReplayClassMemberUsesFromPrecomputedList(type))
50: 3184: return true;
-: 3185:
-: 3186: // Make sure all the types we report in the recursive TraverseDecl
-: 3187: // calls, below, end up in the cache for class_decl.
449: 3188: CacheStoringScope css(&cache_storers_, ClassMembersFullUseCache(),
-: 3189: class_decl, resugar_map_);
-: 3190:
449: 3191: for (DeclContext::decl_iterator it = class_decl->decls_begin();
8297: 3192: it != class_decl->decls_end(); ++it) {
6318: 3193: if (isa<CXXMethodDecl>(*it) || isa<FunctionTemplateDecl>(*it))
1840: 3194: continue;
2084: 3195: if (!TraverseDecl(*it))
#####: 3196: return false;
2084: 3197: }
-: 3198:
-: 3199: // Most methods on template classes are instantiated when they're
-: 3200: // called, and we don't need to deal with them here. But virtual
-: 3201: // methods are instantiated when the class's key method is
-: 3202: // instantiated, and since template classes rarely have a key
-: 3203: // method, it means they're instantiated whenever the class is
-: 3204: // instantiated. So we need to instantiate virtual methods here.
449: 3205: for (DeclContext::decl_iterator it = class_decl->decls_begin();
8297: 3206: it != class_decl->decls_end(); ++it) {
3924: 3207: if (const CXXMethodDecl* method_decl = DynCastFrom(*it)) {
1530: 3208: if (method_decl->isVirtual()) {
#####: 3209: if (!TraverseExpandedTemplateFunctionHelper(method_decl, type))
#####: 3210: return false;
#####: 3211: }
1530: 3212: }
3924: 3213: }
-: 3214:
449: 3215: return true;
1566: 3216: }
-: 3217:
-: 3218: //------------------------------------------------------------
-: 3219: // Cache methods. Caches hold the list of full uses found when we
-: 3220: // last instantiated a given decl, saving a lot of tree-walking if
-: 3221: // we have to do it again.
-: 3222:
-: 3223: // Returns true if we replayed uses, false if key isn't in the cache.
1671: 3224: bool ReplayUsesFromCache(const FullUseCache& cache, const NamedDecl* key,
1671: 3225: SourceLocation use_loc) {
1671: 3226: if (!cache.Contains(key, resugar_map_))
1380: 3227: return false;
582: 3228: VERRS(6) << "(Replaying full-use information from the cache for "
#####: 3229: << key->getQualifiedNameAsString() << ")\n";
291: 3230: ReportTypesUse(use_loc, cache.GetFullUseTypes(key, resugar_map_));
291: 3231: ReportDeclsUse(use_loc, cache.GetFullUseDecls(key, resugar_map_));
291: 3232: return true;
1671: 3233: }
-: 3234:
-: 3235: // We precompute (hard-code) results of calling
-: 3236: // TraverseDataAndTypeMembersOfClassHelper for some types (mostly
-: 3237: // STL types). This way we don't even need to traverse them once.
-: 3238: // Returns true iff we did appropriate reporting for this type.
-: 3239: bool ReplayClassMemberUsesFromPrecomputedList(
530: 3240: const TemplateSpecializationType* tpl_type) {
1060: 3241: if (current_ast_node() && current_ast_node()->in_forward_declare_context())
#####: 3242: return true; // never depend on any types if a fwd-decl
-: 3243:
530: 3244: const NamedDecl* tpl_decl = TypeToDeclAsWritten(tpl_type);
-: 3245:
-: 3246: // This says how the template-args are used by this hard-coded type
-: 3247: // (a set<>, or map<>, or ...), to avoid having to recurse into them.
530: 3248: const map<const Type*, const Type*>& resugar_map_for_precomputed_type =
530: 3249: FullUseCache::GetPrecomputedResugarMap(tpl_type);
-: 3250: // But we need to reconcile that with the types-of-interest, as
-: 3251: // stored in resugar_map_. To do this, we take only those entries
-: 3252: // from resugar_map_for_precomputed_type that are also present in
-: 3253: // resugar_map_. We consider type components, so if
-: 3254: // resugar_map_for_precomputed_type has less_than<Foo> or hash<Foo>,
-: 3255: // we'll add those in even if resugar_map_ only includes 'Foo'.
530: 3256: map<const Type*, const Type*> resugar_map;
530: 3257: for (Each<const Type*, const Type*> it(&resugar_map_for_precomputed_type);
1282: 3258: !it.AtEnd(); ++it) {
-: 3259: // TODO(csilvers): for default template args, it->first is sometimes
-: 3260: // a RecordType even when it's a template specialization. Figure out
-: 3261: // how to get the proper type components in that situation.
111: 3262: const set<const Type*> type_components = GetComponentsOfType(it->first);
111: 3263: if (ContainsAnyKey(resugar_map_, type_components)) {
104: 3264: resugar_map.insert(*it);
104: 3265: }
111: 3266: }
530: 3267: if (resugar_map.empty())
480: 3268: return false;
-: 3269:
100: 3270: VERRS(6) << "(Using pre-computed list of full-use information for "
#####: 3271: << tpl_decl->getQualifiedNameAsString() << ")\n";
-: 3272: // For entries with a non-NULL value, we report the value, which
-: 3273: // is the unsugared type, as being fully used. Entries with a
-: 3274: // NULL value are default template args, and we only report them
-: 3275: // if the template class doesn't intend-to-provide them.
358: 3276: for (Each<const Type*, const Type*> it(&resugar_map); !it.AtEnd(); ++it) {
104: 3277: const Type* resugared_type = NULL;
104: 3278: if (it->second) {
55: 3279: resugared_type = it->second;
55: 3280: } else {
49: 3281: const NamedDecl* resugared_decl = TypeToDeclAsWritten(it->first);
98: 3282: if (!preprocessor_info().PublicHeaderIntendsToProvide(
49: 3283: GetFileEntry(tpl_decl), GetFileEntry(resugared_decl)))
#####: 3284: resugared_type = it->first;
-: 3285: }
159: 3286: if (resugared_type && !resugared_type->isPointerType()) {
55: 3287: ReportTypeUse(caller_loc(), resugared_type);
-: 3288: // For a templated type, check the template args as well.
55: 3289: if (const TemplateSpecializationType* spec_type
55: 3290: = DynCastFrom(resugared_type)) {
#####: 3291: TraverseDataAndTypeMembersOfClassHelper(spec_type);
#####: 3292: }
55: 3293: }
104: 3294: }
50: 3295: return true;
1060: 3296: }
-: 3297:
-: 3298: //------------------------------------------------------------
-: 3299: // Member accessors.
-: 3300:
-: 3301: SourceLocation caller_loc() const {
2558: 3302: return caller_ast_node_->GetLocation();
-: 3303: }
-: 3304:
-: 3305: //------------------------------------------------------------
-: 3306: // Member variables.
-: 3307:
-: 3308: // The AST-chain when this template was instantiated.
-: 3309: const ASTNode* caller_ast_node_;
-: 3310:
-: 3311: // resugar_map is a map from an unsugared (canonicalized) template
-: 3312: // type to the template type as written (or as close as we can find
-: 3313: // to it). If a type is not in resugar-map, it might be due to a
-: 3314: // recursive template call and encode a template type we don't care
-: 3315: // about ourselves. If it's in the resugar_map but with a NULL
-: 3316: // value, it's a default template parameter, that the
-: 3317: // template-caller may or may not be responsible for.
-: 3318: map<const Type*, const Type*> resugar_map_;
-: 3319:
-: 3320: // Used to avoid recursion in the *Helper() methods.
-: 3321: set<const Decl*> traversed_decls_;
-: 3322:
-: 3323: AstFlattenerVisitor::NodeSet nodes_to_ignore_;
-: 3324:
-: 3325: // The current set of nodes we're updating cache entries for.
-: 3326: set<CacheStoringScope*> cache_storers_;
-: 3327:}; // class InstantiatedTemplateVisitor
-: 3328:
-: 3329:
-: 3330:// ----------------------------------------------------------------------
-: 3331:// --- IwyuAstConsumer
-: 3332:// ----------------------------------------------------------------------
-: 3333://
-: 3334:// This class listens to Clang's events as the AST is generated.
-: 3335://
-: 3336:// The traversal of the AST is done via RecursiveASTVisitor, which uses
-: 3337:// CRTP (http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)
-: 3338:
#####: 3339:class IwyuAstConsumer
-: 3340: : public ASTConsumer, public IwyuBaseAstVisitor<IwyuAstConsumer> {
-: 3341: public:
-: 3342: typedef IwyuBaseAstVisitor<IwyuAstConsumer> Base;
-: 3343:
2: 3344: IwyuAstConsumer(VisitorState* visitor_state)
-: 3345: : Base(visitor_state),
2: 3346: instantiated_template_visitor_(visitor_state) {}
-: 3347:
-: 3348: //------------------------------------------------------------
-: 3349: // Implements pure virtual methods from Base.
-: 3350:
-: 3351: // Returns true if we are not interested in symbols used in used_in
-: 3352: // for whatever reason. For instance, we can ignore nodes that are
-: 3353: // neither in the file we're compiling nor in its associated .h file.
-: 3354: virtual bool CanIgnoreCurrentASTNode() const {
-: 3355: // If we're outside of foo.{h,cc} and the set of check_also files,
-: 3356: // just ignore.
112248: 3357: if (CanIgnoreLocation(current_ast_node()->GetLocation()))
106401: 3358: return true;
-: 3359:
-: 3360: // If we're a field of a typedef type, ignore us: our rule is that
-: 3361: // the author of the typedef is responsible for everything
-: 3362: // involving the typedef.
5847: 3363: if (IsMemberOfATypedef(current_ast_node()))
10: 3364: return true;
-: 3365:
-: 3366: // TODO(csilvers): if we're a type, call CanIgnoreType().
-: 3367:
5837: 3368: return false;
178067: 3369: }
-: 3370:
-: 3371: // We print symbols from files in the main compilation unit (foo.cc,
-: 3372: // foo.h, foo-inl.h) if the debug level is 5 or 6, for non-system
-: 3373: // files if the debug level is 7, and all files if the debug level
-: 3374: // is 8 or more.
-: 3375: virtual bool ShouldPrintSymbolFromCurrentFile() const {
237475: 3376: return ShouldPrintSymbolFromFile(CurrentFileEntry());
237475: 3377: }
-: 3378:
#####: 3379: virtual string GetSymbolAnnotation() const { return ""; }
-: 3380:
-: 3381: // We are interested in all types for iwyu checking.
1088: 3382: virtual bool CanIgnoreType(const Type* type) const {
544: 3383: return type == NULL;
544: 3384: }
-: 3385:
6806: 3386: virtual bool CanIgnoreDecl(const Decl* decl) const {
3818: 3387: return decl == NULL;
2988: 3388: }
-: 3389:
-: 3390: //------------------------------------------------------------
-: 3391: // Parser event handlers. Clang will call them to notify this
-: 3392: // ASTConsumer as it parses the source code. See class ASTConsumer in
-: 3393: // clang/AST/ASTConsumer.h
-: 3394: // for all the handlers we can override.
-: 3395:
-: 3396: // Called once at the beginning of the compilation.
1: 3397: virtual void Initialize(ASTContext& context) {} // NOLINT
-: 3398:
-: 3399: // Called once at the end of the compilation.
1: 3400: virtual void HandleTranslationUnit(ASTContext& context) { // NOLINT
-: 3401: // TODO(csilvers): automatically detect preprocessing is done, somehow.
1: 3402: const_cast<IwyuPreprocessorInfo*>(&preprocessor_info())->
-: 3403: HandlePreprocessingDone();
-: 3404:
-: 3405: // We run a separate pass to force parsing of late-parsed function
-: 3406: // templates.
1: 3407: ParseFunctionTemplates(context.getTranslationUnitDecl());
-: 3408:
1: 3409: TraverseDecl(context.getTranslationUnitDecl());
-: 3410:
-: 3411: // We have to calculate the .h files before the .cc file, since
-: 3412: // the .cc file inherits #includes from the .h files, and we
-: 3413: // need to figure out what those #includes are going to be.
1: 3414: size_t num_edits = 0;
1: 3415: const FileEntry* const main_file = preprocessor_info().main_file();
1: 3416: const set<const FileEntry*>* const files_to_report_iwyu_violations_for
1: 3417: = preprocessor_info().files_to_report_iwyu_violations_for();
1: 3418: for (Each<const FileEntry*> file(files_to_report_iwyu_violations_for);
8: 3419: !file.AtEnd(); ++file) {
3: 3420: if (*file == main_file)
1: 3421: continue;
6: 3422: CHECK_(preprocessor_info().FileInfoFor(*file));
2: 3423: num_edits += preprocessor_info().FileInfoFor(*file)
-: 3424: ->CalculateAndReportIwyuViolations();
2: 3425: }
3: 3426: CHECK_(preprocessor_info().FileInfoFor(main_file));
1: 3427: num_edits += preprocessor_info().FileInfoFor(main_file)
-: 3428: ->CalculateAndReportIwyuViolations();
-: 3429:
-: 3430: // We need to force the compile to fail so we can re-run.
1: 3431: exit(EXIT_SUCCESS_OFFSET + num_edits);
#####: 3432: }
-: 3433:
1: 3434: void ParseFunctionTemplates(TranslationUnitDecl* decl) {
1: 3435: set<FunctionDecl*> late_parsed_decls = GetLateParsedFunctionDecls(decl);
1: 3436: clang::Sema& sema = compiler()->getSema();
-: 3437:
-: 3438: // If we have any late-parsed functions, make sure the
-: 3439: // -fdelayed-template-parsing flag is on. Otherwise we don't know where
-: 3440: // they came from.
4: 3441: CHECK_((compiler()->getLangOpts().DelayedTemplateParsing ||
-: 3442: late_parsed_decls.empty()) &&
-: 3443: "Should not have late-parsed decls without "
-: 3444: "-fdelayed-template-parsing.");
-: 3445:
4: 3446: for (const FunctionDecl* fd : late_parsed_decls) {
#####: 3447: CHECK_(fd->isLateTemplateParsed());
-: 3448:
#####: 3449: if (CanIgnoreLocation(GetLocation(fd)))
#####: 3450: continue;
-: 3451:
-: 3452: // Force parsing and AST building of the yet-uninstantiated function
-: 3453: // template body.
#####: 3454: clang::LateParsedTemplate* lpt = sema.LateParsedTemplateMap[fd];
#####: 3455: sema.LateTemplateParser(sema.OpaqueParser, *lpt);
#####: 3456: }
1: 3457: }
-: 3458:
-: 3459: //------------------------------------------------------------
-: 3460: // AST visitors. We start by adding a visitor callback for
-: 3461: // most of the subclasses of Decl/Stmt/Type listed in:
-: 3462: // clang/AST/DeclNodes.def
-: 3463: // clang/AST/StmtNodes.td
-: 3464: // clang/AST/TypeNodes.def
-: 3465: // We exclude only:
-: 3466: // 1) abstract declarations and types with no logic (e.g. NamedDecl)
-: 3467: // 2) ObjC declarations, statements, and types (e.g. ObjcIvarDecl)
-: 3468: // RecursiveASTVisitor defines specialized visitors for each specific
-: 3469: // math operation (MulAssign, OffsetOf, etc). We don't override
-: 3470: // those callbacks, but use their default behavior, which is to call
-: 3471: // back to VisitUnaryOperator, VisitBinaryOperator, etc.
-: 3472: //
-: 3473: // Over time, as we understand when a callback is called and
-: 3474: // which can be ignored by iwyu, we will pare down the list.
-: 3475: // Each of these returns a bool: false if we want to abort the
-: 3476: // traversal (we never do). For Visit*(), we can abort early if
-: 3477: // we're not in the main compilation-unit, since we only ever give
-: 3478: // iwyu warnings on symbols in those files.
-: 3479:
-: 3480: // --- Visitors of types derived from clang::Decl.
-: 3481:
1: 3482: bool VisitNamespaceAliasDecl(clang::NamespaceAliasDecl* decl) {
1: 3483: if (CanIgnoreCurrentASTNode()) return true;
1: 3484: ReportDeclUse(CurrentLoc(), decl->getNamespace());
1: 3485: return Base::VisitNamespaceAliasDecl(decl);
1: 3486: }
-: 3487:
268: 3488: bool VisitUsingDecl(clang::UsingDecl* decl) {
-: 3489: // If somebody in a different file tries to use one of these decls
-: 3490: // with the shortened name, then they had better #include us in
-: 3491: // order to get our using declaration. We store the necessary
-: 3492: // information here. Note: we have to store this even if this is
-: 3493: // an ast node we would otherwise ignore, since other AST nodes
-: 3494: // (which we might not ignore) can depend on it.
268: 3495: for (UsingDecl::shadow_iterator it = decl->shadow_begin();
1120: 3496: it != decl->shadow_end(); ++it) {
426: 3497: AddUsingDeclaration((*it)->getTargetDecl(), decl);
426: 3498: }
-: 3499:
532: 3500: if (CanIgnoreCurrentASTNode()) return true;
-: 3501:
-: 3502: // The shadow decls hold the declarations for the var/fn/etc we're
-: 3503: // using. (There may be more than one if, say, we're using an
-: 3504: // overloaded function.) We check to make sure nothing we're
-: 3505: // using is an iwyu violation.
4: 3506: for (UsingDecl::shadow_iterator it = decl->shadow_begin();
12: 3507: it != decl->shadow_end(); ++it) {
4: 3508: ReportDeclForwardDeclareUse(CurrentLoc(), (*it)->getTargetDecl());
4: 3509: }
-: 3510:
4: 3511: return Base::VisitUsingDecl(decl);
268: 3512: }
-: 3513:
1378: 3514: bool VisitTagDecl(clang::TagDecl* decl) {
2681: 3515: if (CanIgnoreCurrentASTNode()) return true;
-: 3516:
75: 3517: if (IsForwardDecl(decl)) {
-: 3518: // If we're a templated class, make sure we add the whole template.
19: 3519: const NamedDecl* decl_to_fwd_declare = decl;
19: 3520: if (const CXXRecordDecl* cxx_decl = DynCastFrom(decl))
19: 3521: if (cxx_decl->getDescribedClassTemplate())
24: 3522: decl_to_fwd_declare = cxx_decl->getDescribedClassTemplate();
-: 3523:
-: 3524: // We've found a forward-declaration. We'll report we've found
-: 3525: // it, but we also want to report if we know already that we
-: 3526: // should keep this forward-declaration around (and not consider
-: 3527: // it for deletion if it's never used). There are a few
-: 3528: // situations we can do this, described below.
19: 3529: bool definitely_keep_fwd_decl = false;
-: 3530:
-: 3531: // (1) If the forward-decl has a linkage spec ('extern "C"')
-: 3532: // then it can't be removed, since that information probably
-: 3533: // isn't encoded anywhere else.
-: 3534: // (Surprisingly classes can have linkage specs! -- they are
-: 3535: // applied to all static methods of the class. See
-: 3536: // http://msdn.microsoft.com/en-us/library/ms882260.aspx.)
19: 3537: if (current_ast_node()->ParentIsA<LinkageSpecDecl>()) {
1: 3538: definitely_keep_fwd_decl = true;
-: 3539:
-: 3540: // (2) GCC-style __attributes__ work the same way: we can't assume
-: 3541: // that attributes are consistent between declarations, so we can't
-: 3542: // remove a decl with attributes unless they're inherited, i.e. propagated
-: 3543: // from another redeclaration as opposed to explicitly written.
19: 3544: } else if (decl->hasAttrs()) {
#####: 3545: for (Each<const Attr*> it(&decl->getAttrs()); !it.AtEnd(); ++it) {
#####: 3546: if (!(*it)->isInherited()) {
#####: 3547: definitely_keep_fwd_decl = true;
#####: 3548: break;
-: 3549: }
#####: 3550: }
-: 3551:
-: 3552: // (3) If we're a nested class ("class A { class SubA; };"),
-: 3553: // then we can't necessary be removed either, since we're part
-: 3554: // of the public API of the enclosing class -- it's illegal to
-: 3555: // have a nested class and not at least declare it in the
-: 3556: // enclosing class. If the nested class is actually defined in
-: 3557: // the enclosing class, then we're fine; if not, we need to keep
-: 3558: // the first forward-declaration.
18: 3559: } else if (IsNestedClassAsWritten(current_ast_node())) {
5: 3560: if (!decl->getDefinition() || decl->getDefinition()->isOutOfLine()) {
-: 3561: // TODO(kimgr): Member class redeclarations are illegal, per C++
-: 3562: // standard DR85, so this check for first redecl can be removed.
-: 3563: // Nested classes should always be definitely kept. More details here:
-: 3564: // http://comments.gmane.org/gmane.comp.compilers.clang.scm/74782
-: 3565: // GCC and MSVC both still allow redeclarations of nested classes,
-: 3566: // though, so it seems hygienic to remove all but one.
3: 3567: if (const NamedDecl* first_decl = GetFirstRedecl(decl)) {
-: 3568: // Check if we're the decl with the smallest line number.
3: 3569: if (decl == first_decl)
3: 3570: definitely_keep_fwd_decl = true;
3: 3571: }
3: 3572: }
3: 3573: }
-: 3574:
19: 3575: preprocessor_info().FileInfoFor(CurrentFileEntry())->AddForwardDeclare(
-: 3576: decl_to_fwd_declare, definitely_keep_fwd_decl);
19: 3577: }
75: 3578: return Base::VisitTagDecl(decl);
1378: 3579: }
-: 3580:
-: 3581: // If you specialize a template, you need a declaration of the
-: 3582: // template you're specializing. That is, for code like this:
-: 3583: // template <class T> struct Foo;
-: 3584: // template<> struct Foo<int> { ... };
-: 3585: // we don't want iwyu to recommend removing the 'forward declare' of Foo.
-: 3586: bool VisitClassTemplateSpecializationDecl(
483: 3587: clang::ClassTemplateSpecializationDecl* decl) {
961: 3588: if (CanIgnoreCurrentASTNode()) return true;
5: 3589: ClassTemplateDecl* specialized_decl = decl->getSpecializedTemplate();
5: 3590: ReportDeclForwardDeclareUse(CurrentLoc(), specialized_decl);
5: 3591: return Base::VisitClassTemplateSpecializationDecl(decl);
483: 3592: }
-: 3593:
-: 3594: // If you say 'typedef Foo Bar', then clients can use Bar however
-: 3595: // they want without having to worry about #including anything
-: 3596: // except you. That puts you on the hook for all the #includes that
-: 3597: // Bar might need, for *anything* one might want to do to a Bar.
-: 3598: // TODO(csilvers): we can probably relax this rule in .cc files.
-: 3599: // TODO(csilvers): this should really move into IwyuBaseASTVisitor
-: 3600: // (that way we'll correctly identify need for hash<> in hash_set).
-: 3601: // This is a Traverse*() because Visit*() can't call HandleFunctionCall().
1569: 3602: bool TraverseTypedefDecl(clang::TypedefDecl* decl) {
-: 3603: // Before we go up the tree, make sure the parents know we don't
-: 3604: // forward-declare the underlying type of a typedef decl.
1569: 3605: current_ast_node()->set_in_forward_declare_context(false);
1569: 3606: if (!Base::TraverseTypedefDecl(decl))
#####: 3607: return false;
3105: 3608: if (CanIgnoreCurrentASTNode()) return true;
-: 3609:
33: 3610: const Type* underlying_type = decl->getUnderlyingType().getTypePtr();
33: 3611: const Decl* underlying_decl = TypeToDeclAsWritten(underlying_type);
-: 3612:
-: 3613: // We simulate a user calling all the methods in a class.
33: 3614: if (const CXXRecordDecl* record_decl = DynCastFrom(underlying_decl)) {
17: 3615: for (DeclContext::decl_iterator it = record_decl->decls_begin();
665: 3616: it != record_decl->decls_end(); ++it) {
324: 3617: FunctionDecl* fn_decl = NULL;
324: 3618: if (CXXMethodDecl* method_decl = DynCastFrom(*it)) {
199: 3619: fn_decl = method_decl;
324: 3620: } else if (FunctionTemplateDecl* tpl_decl = DynCastFrom(*it)) {
22: 3621: fn_decl = tpl_decl->getTemplatedDecl(); // templated method decl
22: 3622: } else {
103: 3623: continue; // not a method or static method
-: 3624: }
221: 3625: if (!this->getDerived().HandleFunctionCall(
-: 3626: fn_decl, underlying_type, static_cast<Expr*>(NULL)))
#####: 3627: return false;
221: 3628: }
17: 3629: }
-: 3630: // We don't have to simulate a user instantiating the type, because
-: 3631: // RecursiveASTVisitor.h will recurse on the typedef'ed type for us.
33: 3632: return true;
1569: 3633: }
-: 3634:
-: 3635: // --- Visitors of types derived from clang::Stmt.
-: 3636:
-: 3637: // Called whenever a variable, function, enum, etc is used.
17600: 3638: bool VisitDeclRefExpr(clang::DeclRefExpr* expr) {
34758: 3639: if (CanIgnoreCurrentASTNode()) return true;
442: 3640: ReportDeclUse(CurrentLoc(), expr->getDecl());
442: 3641: return Base::VisitDeclRefExpr(expr);
17600: 3642: }
-: 3643:
-: 3644: // This Expr is for sizeof(), alignof() and similar. The compiler
-: 3645: // fully instantiates a template class before taking the size of it.
-: 3646: // So so do we.
217: 3647: bool VisitUnaryExprOrTypeTraitExpr(clang::UnaryExprOrTypeTraitExpr* expr) {
429: 3648: if (CanIgnoreCurrentASTNode()) return true;
-: 3649:
5: 3650: const Type* arg_type = expr->getTypeOfArgument().getTypePtr();
-: 3651: // Calling sizeof on a reference-to-X is the same as calling it on X.
5: 3652: if (const ReferenceType* reftype = DynCastFrom(arg_type)) {
#####: 3653: arg_type = reftype->getPointeeTypeAsWritten().getTypePtr();
#####: 3654: }
5: 3655: if (!IsTemplatizedType(arg_type))
4: 3656: return Base::VisitUnaryExprOrTypeTraitExpr(expr);
-: 3657:
1: 3658: const map<const Type*, const Type*> resugar_map
1: 3659: = GetTplTypeResugarMapForClass(arg_type);
2: 3660: instantiated_template_visitor_.ScanInstantiatedType(
1: 3661: arg_type, current_ast_node(), resugar_map);
-: 3662:
1: 3663: return Base::VisitUnaryExprOrTypeTraitExpr(expr);
218: 3664: }
-: 3665:
-: 3666: // --- Visitors of types derived from clang::Type.
-: 3667:
9956: 3668: bool VisitTypedefType(clang::TypedefType* type) {
19845: 3669: if (CanIgnoreCurrentASTNode()) return true;
-: 3670: // TypedefType::getDecl() returns the place where the typedef is defined.
67: 3671: if (CanForwardDeclareType(current_ast_node())) {
14: 3672: ReportDeclForwardDeclareUse(CurrentLoc(), type->getDecl());
14: 3673: } else {
53: 3674: ReportDeclUse(CurrentLoc(), type->getDecl());
-: 3675: }
67: 3676: return Base::VisitTypedefType(type);
9956: 3677: }
-: 3678:
-: 3679: // This is a superclass of RecordType and CXXRecordType.
2802: 3680: bool VisitTagType(clang::TagType* type) {
5168: 3681: if (CanIgnoreCurrentASTNode()) return true;
-: 3682:
-: 3683: // If we're forward-declarable, then no complicated checking is
-: 3684: // needed: just forward-declare.
436: 3685: if (CanForwardDeclareType(current_ast_node())) {
232: 3686: current_ast_node()->set_in_forward_declare_context(true);
232: 3687: if (compiler()->getLangOpts().CPlusPlus) {
-: 3688: // In C++, if we're already elaborated ('class Foo x') but not
-: 3689: // namespace-qualified ('class ns::Foo x') there's no need even to
-: 3690: // forward-declare.
-: 3691: // Note that enums are never forward-declarable, so elaborated enums are
-: 3692: // short-circuited in CanForwardDeclareType.
232: 3693: const ASTNode* parent = current_ast_node()->parent();
241: 3694: if (!IsElaborationNode(parent) || IsNamespaceQualifiedNode(parent))
225: 3695: ReportDeclForwardDeclareUse(CurrentLoc(), type->getDecl());
232: 3696: } else {
-: 3697: // In C, all struct references are elaborated, so we really never need
-: 3698: // to forward-declare. But there's one case where an elaborated struct
-: 3699: // decl in a parameter list causes Clang to warn about constrained
-: 3700: // visibility, so we recommend forward declaration to avoid the warning.
-: 3701: // E.g.
-: 3702: // void init(struct mystruct* s);
-: 3703: // warning: declaration of 'struct mystruct' will not be visible
-: 3704: // outside of this function [-Wvisibility]
#####: 3705: if (current_ast_node()->HasAncestorOfType<ParmVarDecl>())
#####: 3706: ReportDeclForwardDeclareUse(CurrentLoc(), type->getDecl());
-: 3707: }
232: 3708: return Base::VisitTagType(type);
-: 3709: }
-: 3710:
-: 3711: // OK, seems to be a use that requires the full type.
204: 3712: ReportDeclUse(CurrentLoc(), type->getDecl());
204: 3713: return Base::VisitTagType(type);
2802: 3714: }
-: 3715:
-: 3716: // Like for CXXConstructExpr, etc., we sometimes need to instantiate
-: 3717: // a class when looking at TemplateSpecializationType -- for instance,
-: 3718: // when we need to access a class typedef: MyClass<A>::value_type.
-: 3719: bool VisitTemplateSpecializationType(
5661: 3720: clang::TemplateSpecializationType* type) {
11146: 3721: if (CanIgnoreCurrentASTNode()) return true;
-: 3722:
-: 3723: // If we're not in a forward-declare context, use of a template
-: 3724: // specialization requires having the full type information.
176: 3725: if (!CanForwardDeclareType(current_ast_node())) {
137: 3726: const map<const Type*, const Type*> resugar_map
137: 3727: = GetTplTypeResugarMapForClass(type);
-: 3728: // ScanInstantiatedType requires that type not already be on the
-: 3729: // ast-stack that it sees, but in our case it will be. So we
-: 3730: // pass in the parent-node.
137: 3731: const ASTNode* ast_parent = current_ast_node()->parent();
137: 3732: instantiated_template_visitor_.ScanInstantiatedType(
-: 3733: type, ast_parent, resugar_map);
137: 3734: }
-: 3735:
176: 3736: return Base::VisitTemplateSpecializationType(type);
5661: 3737: }
-: 3738:
-: 3739: // --- Visitors defined by BaseASTVisitor (not RecursiveASTVisitor).
-: 3740:
5664: 3741: bool VisitTemplateName(TemplateName template_name) {
11149: 3742: if (CanIgnoreCurrentASTNode()) return true;
179: 3743: if (!Base::VisitTemplateName(template_name)) return false;
-: 3744: // The only time we can see a TemplateName not in the
-: 3745: // context of a TemplateSpecializationType is when it's
-: 3746: // the default argument of a template template arg:
-: 3747: // template<template<class T> class A = TplNameWithoutTST> class Foo ...
-: 3748: // So that's the only case we need to handle here.
-: 3749: // TODO(csilvers): check if this is really forward-declarable or
-: 3750: // not. You *could* do something like: 'template<template<class
-: 3751: // T> class A = Foo> class C { A<int>* x; };' and never
-: 3752: // dereference x, but that's pretty unlikely. So for now, we just
-: 3753: // assume these default template template args always need full
-: 3754: // type info.
179: 3755: if (IsDefaultTemplateTemplateArg(current_ast_node())) {
3: 3756: current_ast_node()->set_in_forward_declare_context(false);
3: 3757: ReportDeclUse(CurrentLoc(), template_name.getAsTemplateDecl());
3: 3758: }
179: 3759: return true;
5664: 3760: }
-: 3761:
-: 3762: // For expressions that require us to instantiate a template
-: 3763: // (CallExpr of a template function, or CXXConstructExpr of a
-: 3764: // template class, etc), we need to instantiate the template and
-: 3765: // check IWYU status of the template parameters *in the template
-: 3766: // code* (so for 'MyFunc<T>() { T t; ... }', the contents of
-: 3767: // MyFunc<MyClass> add an iwyu requirement on MyClass).
844: 3768: bool HandleFunctionCall(FunctionDecl* callee, const Type* parent_type,
844: 3769: const clang::Expr* calling_expr) {
844: 3770: if (!Base::HandleFunctionCall(callee, parent_type, calling_expr))
#####: 3771: return false;
2504: 3772: if (!callee || CanIgnoreCurrentASTNode() || CanIgnoreDecl(callee))
14: 3773: return true;
-: 3774:
1591: 3775: if (!IsTemplatizedFunctionDecl(callee) && !IsTemplatizedType(parent_type))
403: 3776: return true;
-: 3777:
427: 3778: map<const Type*, const Type*> resugar_map
427: 3779: = GetTplTypeResugarMapForFunction(callee, calling_expr);
-: 3780:
427: 3781: if (parent_type) { // means we're a method of a class
398: 3782: InsertAllInto(GetTplTypeResugarMapForClass(parent_type), &resugar_map);
398: 3783: }
-: 3784:
854: 3785: instantiated_template_visitor_.ScanInstantiatedFunction(
-: 3786: callee, parent_type,
427: 3787: current_ast_node(), resugar_map);
427: 3788: return true;
1271: 3789: }
-: 3790:
-: 3791: private:
-: 3792: // Class we call to handle instantiated template functions and classes.
-: 3793: InstantiatedTemplateVisitor instantiated_template_visitor_;
-: 3794:}; // class IwyuAstConsumer
-: 3795:
-: 3796:// We use an ASTFrontendAction to hook up IWYU with Clang.
2: 3797:class IwyuAction : public ASTFrontendAction {
-: 3798: protected:
-: 3799: virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(
1: 3800: CompilerInstance& compiler, // NOLINT
1: 3801: llvm::StringRef /* dummy */) {
-: 3802: // Do this first thing after getting our hands on a CompilerInstance.
2: 3803: InitGlobals(&compiler.getSourceManager(),
1: 3804: &compiler.getPreprocessor().getHeaderSearchInfo());
-: 3805:
1: 3806: IwyuPreprocessorInfo* const preprocessor_consumer =
-: 3807: new IwyuPreprocessorInfo();
1: 3808: compiler.getPreprocessor().addPPCallbacks(
-: 3809: std::unique_ptr<PPCallbacks>(preprocessor_consumer));
3: 3810: compiler.getPreprocessor().addCommentHandler(preprocessor_consumer);
-: 3811:
1: 3812: VisitorState* const visitor_state
-: 3813: = new VisitorState(&compiler, *preprocessor_consumer);
1: 3814: return std::unique_ptr<IwyuAstConsumer>(new IwyuAstConsumer(visitor_state));
-: 3815: }
-: 3816:};
-: 3817:
-: 3818:
-: 3819:} // namespace include_what_you_use
-: 3820:
-: 3821:#include "iwyu_driver.h"
-: 3822:#include "clang/Frontend/FrontendAction.h"
-: 3823:#include "llvm/Support/ManagedStatic.h"
-: 3824:#include "llvm/Support/TargetSelect.h"
-: 3825:
-: 3826:using include_what_you_use::OptionsParser;
-: 3827:using include_what_you_use::IwyuAction;
-: 3828:using include_what_you_use::CreateCompilerInstance;
-: 3829:
1: 3830:int main(int argc, char **argv) {
-: 3831: // Must initialize X86 target to be able to parse Microsoft inline
-: 3832: // assembly. We do this unconditionally, because it allows an IWYU
-: 3833: // built for non-X86 targets to parse MS inline asm without choking.
1: 3834: LLVMInitializeX86TargetInfo();
1: 3835: LLVMInitializeX86TargetMC();
1: 3836: LLVMInitializeX86AsmParser();
-: 3837:
-: 3838: // The command line should look like
-: 3839: // path/to/iwyu -Xiwyu --verbose=4 [-Xiwyu --other_iwyu_flag]... CLANG_FLAGS... foo.cc
1: 3840: OptionsParser options_parser(argc, argv);
-: 3841:
2: 3842: std::unique_ptr<clang::CompilerInstance> compiler(CreateCompilerInstance(
1: 3843: options_parser.clang_argc(), options_parser.clang_argv()));
1: 3844: if (compiler) {
-: 3845: // Create and execute the frontend to generate an LLVM bitcode module.
1: 3846: std::unique_ptr<clang::ASTFrontendAction> action(new IwyuAction);
1: 3847: compiler->ExecuteAction(*action);
1: 3848: }
-: 3849:
#####: 3850: llvm::llvm_shutdown();
-: 3851:
-: 3852: // We always return a failure exit code, to indicate we didn't
-: 3853: // successfully compile (produce a .o for) the source files we were
-: 3854: // given.
#####: 3855: return 1;
#####: 3856:}
-: 0:Source:/Users/vsapsay/Projects/OpenSource/llvm/llvm/tools/clang/tools/include-what-you-use/iwyu.cc
-: 0:Graph:iwyu.gcno
-: 0:Data:iwyu.gcda
-: 0:Runs:1
-: 0:Programs:1
-: 1://===--- iwyu.cc - main logic and driver for include-what-you-use ---------===//
-: 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:// A Clang-based tool that catches Include-What-You-Use violations:
-: 11://
-: 12:// The analysis enforces the following rule:
-: 13://
-: 14:// - For every symbol (variable, function, constant, type, and macro)
-: 15:// X in C++ file CU.cc, X must be declared in CU.cc or in a header
-: 16:// file directly included by itself, CU.h, or CU-inl.h. Likewise
-: 17:// for CU.h and CU-inl.h.
-: 18://
-: 19:// The rule has a few slight wrinkles:
-: 20:// 1) CU_test.cc can also 'inherit' #includes from CU.h and CU-inl.h.
-: 21:// Likewise for CU_unittest.cc, CU_regtest.cc, etc.
-: 22:// 2) CU.cc can inherit #includes from ../public/CU.h in addition to
-: 23:// ./CU.h (likewise for -inl.h).
-: 24:// 3) For system #includes, and a few google #includes, we hard-code
-: 25:// in knowledge of which #include files are public and which are not.
-: 26:// (For instance, <vector> is public, <bits/stl_vector.h> is not.)
-: 27:// We force CU.cc, CU.h, and CU-inl.h to #include the public version.
-: 28://
-: 29:// iwyu.cc checks if a symbol can be forward-declared instead of fully
-: 30:// declared. If so, it will enforce the rule that the symbol is
-: 31:// forward-declared in the file that references it. We only forward-
-: 32:// declare classes and structs (possibly templatized). We will not
-: 33:// try to forward-declare variables or functions.
-: 34://
-: 35:// Checking iwyu violations for variables, functions, constants, and
-: 36:// macros is easy. Types can be trickier. Obviously, if you declare
-: 37:// a variable of type Foo in cu.cc, it's straightforward to check
-: 38:// whether it's an iwyu violation. But what if you call a function
-: 39:// that returns a type, e.g. 'if (FnReturningSomeSTLType()->empty())'?
-: 40:// Is it an iwyu violation if you don't #include the header for that
-: 41:// STL type? We say no: whatever file provided the function
-: 42:// FnReturningSomeSTLType is also responsible for providing whatever
-: 43:// the STL type is, so we don't have to. Otherwise, we get into an
-: 44:// un-fun propagation problem if we change the signature of
-: 45:// FnReturningSomeSTLType to return a different type of STL type. So
-: 46:// in general, types are only iwyu-checked if they appear explicitly
-: 47:// in the source code.
-: 48://
-: 49:// It can likewise be difficult to say whether a template arg is
-: 50:// forward-declable: set<Foo*> x does not require the full type info
-: 51:// for Foo, but remove_pointer<Foo*>::type does. And f<Foo>() doesn't
-: 52:// require full type info for Foo if f doesn't actually use Foo in it.
-: 53:// For now we do the simple heuristic that if the template arg is a
-: 54:// pointer, it's ok if it's forward-declared, and if not, it's not.
-: 55://
-: 56:// We use the following terminology:
-: 57://
-: 58:// - A *symbol* is the name of a function, variable, constant, type,
-: 59:// macro, etc.
-: 60://
-: 61:// - A *quoted include path* is an include path with the surrounding <>
-: 62:// or "", e.g. <stdio.h> or "ads/util.h".
-: 63://
-: 64:// - Any #include falls into exactly one of three (non-overlapping)
-: 65:// categories:
-: 66://
-: 67:// * it's said to be *necessary* if it's a compiler or IWYU error to
-: 68:// omit the #include;
-: 69://
-: 70:// * it's said to be *optional* if the #include is unnecessary but
-: 71:// having it is not an IWYU error either (e.g. if bar.h is a
-: 72:// necessary #include of foo.h, and foo.cc uses symbols from
-: 73:// bar.h, it's optional for foo.cc to #include bar.h.);
-: 74://
-: 75:// * it's said to be *undesired* if it's an IWYU error to have the
-: 76:// #include.
-: 77://
-: 78:// Therefore, when we say a #include is *desired*, we mean that it's
-: 79:// either necessary or optional.
-: 80://
-: 81:// - We also say that a #include is *recommended* if the IWYU tool
-: 82:// recommends to have it in the C++ source file. Obviously, any
-: 83:// necessary #include must be recommended, and no undesired
-: 84:// #include can be recommended. An optional #include can be
-: 85:// either recommended or not -- the IWYU tool can decide which
-: 86:// case it is. For example, if foo.cc desires bar.h, but can
-: 87:// already get it via foo.h, IWYU won't recommend foo.cc to
-: 88:// #include bar.h, unless it already does so.
-: 89:#include <stddef.h> // for size_t
-: 90:#include <stdio.h> // for snprintf
-: 91:#include <stdlib.h> // for atoi, exit
-: 92:#include <string.h>
-: 93:#include <algorithm> // for swap, find, make_pair
-: 94:#include <deque> // for swap
-: 95:#include <iterator> // for find
-: 96:#include <list> // for swap
-: 97:#include <map> // for map, swap, etc
-: 98:#include <memory> // for unique_ptr
-: 99:#include <set> // for set, set<>::iterator, swap
-: 100:#include <string> // for string, operator+, etc
-: 101:#include <utility> // for pair, make_pair
-: 102:#include <vector> // for vector, swap
-: 103:
-: 104:#include "iwyu_ast_util.h"
-: 105:#include "iwyu_cache.h"
-: 106:#include "iwyu_globals.h"
-: 107:#include "iwyu_location_util.h"
-: 108:#include "iwyu_output.h"
-: 109:#include "iwyu_path_util.h"
-: 110:// This is needed for
-: 111:// preprocessor_info().PublicHeaderIntendsToProvide(). Somehow IWYU
-: 112:// removes it mistakenly.
-: 113:#include "iwyu_preprocessor.h" // IWYU pragma: keep
-: 114:#include "iwyu_stl_util.h"
-: 115:#include "iwyu_string_util.h"
-: 116:#include "iwyu_verrs.h"
-: 117:#include "port.h" // for CHECK_
-: 118:#include "llvm/Support/Casting.h"
-: 119:#include "llvm/Support/raw_ostream.h"
-: 120:#include "clang/AST/ASTConsumer.h"
-: 121:#include "clang/AST/ASTContext.h"
-: 122:#include "clang/AST/Decl.h"
-: 123:#include "clang/AST/DeclBase.h"
-: 124:#include "clang/AST/DeclTemplate.h"
-: 125:#include "clang/AST/NestedNameSpecifier.h"
-: 126:#include "clang/AST/RecursiveASTVisitor.h"
-: 127:#include "clang/AST/Stmt.h"
-: 128:#include "clang/AST/TemplateBase.h"
-: 129:#include "clang/AST/Type.h"
-: 130:#include "clang/AST/TypeLoc.h"
-: 131:#include "clang/Basic/SourceLocation.h"
-: 132:#include "clang/Frontend/CompilerInstance.h"
-: 133:#include "clang/Frontend/FrontendAction.h"
-: 134:#include "clang/Lex/Preprocessor.h"
-: 135:#include "clang/Sema/Sema.h"
-: 136:
-: 137:namespace clang {
-: 138:class FileEntry;
-: 139:class PPCallbacks;
-: 140:class SourceManager;
-: 141:class Token;
-: 142:} // namespace clang
-: 143:
-: 144:namespace include_what_you_use {
-: 145:
-: 146:// I occasionally clean up this list by running:
-: 147:// $ grep "using clang":: iwyu.cc | cut -b14- | tr -d ";" | while read t; do grep -q "[^:]$t" iwyu.cc || echo $t; done
-: 148:using clang::ASTConsumer;
-: 149:using clang::ASTContext;
-: 150:using clang::ASTFrontendAction;
-: 151:using clang::ArrayType;
-: 152:using clang::Attr;
-: 153:using clang::CXXConstructExpr;
-: 154:using clang::CXXConstructorDecl;
-: 155:using clang::CXXCtorInitializer;
-: 156:using clang::CXXDeleteExpr;
-: 157:using clang::CXXDestructorDecl;
-: 158:using clang::CXXMethodDecl;
-: 159:using clang::CXXNewExpr;
-: 160:using clang::CXXOperatorCallExpr;
-: 161:using clang::CXXRecordDecl;
-: 162:using clang::CallExpr;
-: 163:using clang::ClassTemplateDecl;
-: 164:using clang::ClassTemplateSpecializationDecl;
-: 165:using clang::CompilerInstance;
-: 166:using clang::Decl;
-: 167:using clang::DeclContext;
-: 168:using clang::DeclRefExpr;
-: 169:using clang::ElaboratedType;
-: 170:using clang::EnumType;
-: 171:using clang::Expr;
-: 172:using clang::FileEntry;
-: 173:using clang::FriendDecl;
-: 174:using clang::FriendTemplateDecl;
-: 175:using clang::FullSourceLoc;
-: 176:using clang::FunctionDecl;
-: 177:using clang::FunctionProtoType;
-: 178:using clang::FunctionTemplateDecl;
-: 179:using clang::FunctionType;
-: 180:using clang::ImplicitCastExpr;
-: 181:using clang::LValueReferenceType;
-: 182:using clang::LinkageSpecDecl;
-: 183:using clang::MacroInfo;
-: 184:using clang::MemberExpr;
-: 185:using clang::NamedDecl;
-: 186:using clang::NestedNameSpecifier;
-: 187:using clang::NestedNameSpecifierLoc;
-: 188:using clang::OverloadExpr;
-: 189:using clang::ParmVarDecl;
-: 190:using clang::PPCallbacks;
-: 191:using clang::PointerType;
-: 192:using clang::QualType;
-: 193:using clang::QualifiedTypeLoc;
-: 194:using clang::RecordDecl;
-: 195:using clang::RecordType;
-: 196:using clang::RecursiveASTVisitor;
-: 197:using clang::ReferenceType;
-: 198:using clang::SourceLocation;
-: 199:using clang::SourceManager;
-: 200:using clang::Stmt;
-: 201:using clang::SubstTemplateTypeParmType;
-: 202:using clang::TagDecl;
-: 203:using clang::TagType;
-: 204:using clang::TemplateArgument;
-: 205:using clang::TemplateArgumentList;
-: 206:using clang::TemplateArgumentLoc;
-: 207:using clang::TemplateDecl;
-: 208:using clang::TemplateName;
-: 209:using clang::TemplateSpecializationKind;
-: 210:using clang::TemplateSpecializationType;
-: 211:using clang::TemplateTemplateParmDecl;
-: 212:using clang::Token;
-: 213:using clang::TranslationUnitDecl;
-: 214:using clang::Type;
-: 215:using clang::TypeLoc;
-: 216:using clang::TypedefDecl;
-: 217:using clang::TypedefType;
-: 218:using clang::UnaryExprOrTypeTraitExpr;
-: 219:using clang::UsingDecl;
-: 220:using clang::UsingShadowDecl;
-: 221:using clang::ValueDecl;
-: 222:using clang::VarDecl;
-: 223:using llvm::cast;
-: 224:using llvm::dyn_cast;
-: 225:using llvm::dyn_cast_or_null;
-: 226:using llvm::errs;
-: 227:using llvm::isa;
-: 228:using llvm::raw_string_ostream;
-: 229:using std::find;
-: 230:using std::make_pair;
-: 231:using std::map;
-: 232:using std::set;
-: 233:using std::string;
-: 234:using std::swap;
-: 235:using std::vector;
-: 236:
-: 237:namespace {
-: 238:
#####: 239:string IntToString(int i) {
#####: 240: char buf[64]; // big enough for any number
#####: 241: snprintf(buf, sizeof(buf), "%d", i);
#####: 242: return buf;
-: 243:}
-: 244:
112192: 245:bool CanIgnoreLocation(SourceLocation loc) {
-: 246: // If we're in a macro expansion, we always want to treat this as
-: 247: // being in the expansion location, never the as-written location,
1: 248: // since that's what the compiler does. CanIgnoreCurrentASTNode()
-: 249: // is an optimization, so we want to be conservative about what we
-: 250: // ignore.
112192: 251: const FileEntry* file_entry = GetFileEntry(loc);
112192: 252: const FileEntry* file_entry_after_macro_expansion =
112192: 253: GetFileEntry(GetInstantiationLoc(loc));
-: 254:
-: 255: // ignore symbols used outside foo.{h,cc} + check_also
112192: 256: return (!ShouldReportIWYUViolationsFor(file_entry) &&
106480: 257: !ShouldReportIWYUViolationsFor(file_entry_after_macro_expansion));
112192: 258:}
-: 259:
-: 260:} // namespace
-: 261:
-: 262:// ----------------------------------------------------------------------
-: 263:// --- BaseAstVisitor
-: 264:// ----------------------------------------------------------------------
-: 265://
-: 266:// We have a hierarchy of AST visitor classes, to keep the logic
-: 267:// as clear as possible. The top level, BaseAstVisitor, has some
-: 268:// basic, not particularly iwyu-related, functionality:
-: 269://
-: 270:// 1) Maintain current_ast_node_, the current chain in the AST tree.
-: 271:// 2) Provide functions related to the current location.
-: 272:// 3) Print each node we're visiting, depending on --verbose settings.
-: 273:// 4) Add appropriate implicit text. iwyu acts as if all constructor
-: 274:// initializers were explicitly written, all default constructors
-: 275:// were explicitly written, etc, even if they're not. We traverse
-: 276:// the implicit stuff as if it were explicit.
-: 277:// 5) Add two callbacks that subclasses can override (just like any
-: 278:// other AST callback): TraverseImplicitDestructorCall and
-: 279:// HandleFunctionCall. TraverseImplicitDestructorCall is a
-: 280:// callback for a "pseudo-AST" node that covers destruction not
-: 281:// specified in source, such as a destructor destroying one of the
-: 282:// fields in its class. HandleFunctionCall is a convenience
-: 283:// callback that bundles callbacks from many different kinds of
-: 284:// function-calling callbacks (CallExpr, CXXConstructExpr, etc)
-: 285:// into one place.
-: 286://
-: 287:// To maintain current_ast_node_ properly, this class also implements
-: 288:// VisitNestedNameSpecifier, VisitTemplateName, VisitTemplateArg, and
-: 289:// VisitTemplateArgLoc, which are parallel to the Visit*Decl()/etc
-: 290:// visitors. Subclasses should override these Visit routines, and not
-: 291:// the Traverse routine directly.
-: 292:
-: 293:template <class Derived>
-: 294:class BaseAstVisitor : public RecursiveASTVisitor<Derived> {
-: 295: public:
-: 296: typedef RecursiveASTVisitor<Derived> Base;
-: 297:
-: 298: // We need to create implicit ctor/dtor nodes, which requires
-: 299: // non-const methods on CompilerInstance, so the var can't be const.
1021: 300: explicit BaseAstVisitor(CompilerInstance* compiler)
-: 301: : compiler_(compiler),
1021: 302: current_ast_node_(NULL) {}
-: 303:
1019: 304: virtual ~BaseAstVisitor() {}
-: 305:
-: 306: //------------------------------------------------------------
-: 307: // Pure virtual methods that a subclass must implement.
-: 308:
-: 309: // Returns true if we are not interested in the current ast node for
-: 310: // any reason (for instance, it lives in a file we're not
-: 311: // analyzing).
-: 312: virtual bool CanIgnoreCurrentASTNode() const = 0;
-: 313:
-: 314: // Returns true if we should print the information for the
-: 315: // current AST node, given what file it's in. For instance,
-: 316: // except at very high verbosity levels, we don't print AST
-: 317: // nodes from system header files.
-: 318: virtual bool ShouldPrintSymbolFromCurrentFile() const = 0;
-: 319:
-: 320: // A string to add to the information we print for each symbol.
-: 321: // Each subclass can thus annotate if it's handling a node.
-: 322: // The return value, if not empty, should start with a space!
-: 323: virtual string GetSymbolAnnotation() const = 0;
-: 324:
-: 325: //------------------------------------------------------------
-: 326: // (1) Maintain current_ast_node_
-: 327:
-: 328: // How subclasses can access current_ast_node_;
133252: 329: const ASTNode* current_ast_node() const { return current_ast_node_; }
171697: 330: ASTNode* current_ast_node() { return current_ast_node_; }
564: 331: void set_current_ast_node(ASTNode* an) { current_ast_node_ = an; }
-: 332:
36348: 333: bool TraverseDecl(Decl* decl) {
36348: 334: if (current_ast_node_->StackContainsContent(decl))
1: 335: return true; // avoid recursion
36347: 336: ASTNode node(decl, *GlobalSourceManager());
36347: 337: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
36347: 338: return Base::TraverseDecl(decl);
72695: 339: }
-: 340:
86677: 341: bool TraverseStmt(Stmt* stmt) {
86677: 342: if (current_ast_node_->StackContainsContent(stmt))
#####: 343: return true; // avoid recursion
86677: 344: ASTNode node(stmt, *GlobalSourceManager());
86677: 345: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
86677: 346: return Base::TraverseStmt(stmt);
173354: 347: }
-: 348:
5537: 349: bool TraverseType(QualType qualtype) {
5537: 350: if (qualtype.isNull())
#####: 351: return Base::TraverseType(qualtype);
5537: 352: const Type* type = qualtype.getTypePtr();
5537: 353: if (current_ast_node_->StackContainsContent(type))
35: 354: return true; // avoid recursion
5502: 355: ASTNode node(type, *GlobalSourceManager());
5502: 356: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
5502: 357: return Base::TraverseType(qualtype);
11039: 358: }
-: 359:
-: 360: // RecursiveASTVisitor has a hybrid type-visiting system: it will
-: 361: // call TraverseTypeLoc when it can, but will call TraverseType
-: 362: // otherwise. For instance, if we see a FunctionDecl, and it
-: 363: // exposes the return type via a TypeLoc, it will recurse via
-: 364: // TraverseTypeLoc. If it exposes the return type only via a
-: 365: // QualType, though, it will recurse via TraverseType. The upshot
-: 366: // is we need two versions of all the Traverse*Type routines. (We
-: 367: // don't need two versions the Visit*Type routines, since the
-: 368: // default behavior of Visit*TypeLoc is to just call Visit*Type.)
62126: 369: bool TraverseTypeLoc(TypeLoc typeloc) {
-: 370: // QualifiedTypeLoc is a bit of a special case in the typeloc
-: 371: // system, off to the side. We don't care about qualifier
-: 372: // positions, so avoid the need for special-casing by just
-: 373: // traversing the unqualified version instead.
62126: 374: if (typeloc.getAs<QualifiedTypeLoc>()) {
3986: 375: typeloc = typeloc.getUnqualifiedLoc();
3986: 376: }
62126: 377: if (current_ast_node_->StackContainsContent(&typeloc))
#####: 378: return true; // avoid recursion
62126: 379: ASTNode node(&typeloc, *GlobalSourceManager());
62126: 380: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
62126: 381: return Base::TraverseTypeLoc(typeloc);
124252: 382: }
-: 383:
31: 384: bool TraverseNestedNameSpecifier(NestedNameSpecifier* nns) {
31: 385: if (nns == NULL)
#####: 386: return true;
31: 387: ASTNode node(nns, *GlobalSourceManager());
31: 388: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
31: 389: if (!this->getDerived().VisitNestedNameSpecifier(nns))
#####: 390: return false;
31: 391: return Base::TraverseNestedNameSpecifier(nns);
62: 392: }
-: 393:
60030: 394: bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc nns_loc) {
60030: 395: if (!nns_loc) // using NNSLoc::operator bool()
51206: 396: return true;
8824: 397: ASTNode node(&nns_loc, *GlobalSourceManager());
8824: 398: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
-: 399: // TODO(csilvers): have VisitNestedNameSpecifierLoc instead.
17648: 400: if (!this->getDerived().VisitNestedNameSpecifier(
8824: 401: nns_loc.getNestedNameSpecifier()))
#####: 402: return false;
8824: 403: return Base::TraverseNestedNameSpecifierLoc(nns_loc);
68854: 404: }
-: 405:
6678: 406: bool TraverseTemplateName(TemplateName template_name) {
6678: 407: ASTNode node(&template_name, *GlobalSourceManager());
6678: 408: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
6678: 409: if (!this->getDerived().VisitTemplateName(template_name))
#####: 410: return false;
6678: 411: return Base::TraverseTemplateName(template_name);
6678: 412: }
-: 413:
197: 414: bool TraverseTemplateArgument(const TemplateArgument& arg) {
197: 415: ASTNode node(&arg, *GlobalSourceManager());
197: 416: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
197: 417: if (!this->getDerived().VisitTemplateArgument(arg))
#####: 418: return false;
197: 419: return Base::TraverseTemplateArgument(arg);
197: 420: }
-: 421:
12458: 422: bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc& argloc) {
12458: 423: ASTNode node(&argloc, *GlobalSourceManager());
12458: 424: CurrentASTNodeUpdater canu(&current_ast_node_, &node);
12458: 425: if (!this->getDerived().VisitTemplateArgumentLoc(argloc))
#####: 426: return false;
12458: 427: return Base::TraverseTemplateArgumentLoc(argloc);
12458: 428: }
-: 429:
-: 430: //------------------------------------------------------------
-: 431: // (2) Provide functions related to the current location.
-: 432:
-: 433: SourceLocation CurrentLoc() const {
730902: 434: CHECK_(current_ast_node_ && "Call CurrentLoc within Visit* or Traverse*");
243634: 435: const SourceLocation loc = current_ast_node_->GetLocation();
243634: 436: if (!loc.isValid())
1979: 437: return loc;
-: 438: // If the token is formed via macro concatenation, the spelling
-: 439: // location will be in <scratch space>. Use the instantiation
-: 440: // location instead.
241655: 441: const FullSourceLoc spelling_loc = GetSpellingLoc(loc);
250090: 442: if (IsInMacro(loc) && StartsWith(PrintableLoc(spelling_loc), "<scratch "))
99: 443: return GetInstantiationLoc(loc);
-: 444: else
241556: 445: return spelling_loc;
243634: 446: }
-: 447:
-: 448: string CurrentFilePath() const {
-: 449: return GetFilePath(CurrentLoc());
-: 450: }
-: 451:
-: 452: const FileEntry* CurrentFileEntry() const {
237423: 453: return GetFileEntry(CurrentLoc());
-: 454: }
-: 455:
-: 456: string PrintableCurrentLoc() const {
#####: 457: return PrintableLoc(CurrentLoc());
-: 458: }
-: 459:
-: 460: //------------------------------------------------------------
-: 461: // (3) Print each node we're visiting.
-: 462:
-: 463: // The current file location, the class or decl or type name in
-: 464: // brackets, along with annotations such as the indentation depth,
-: 465: // etc.
#####: 466: string AnnotatedName(const string& name) const {
#####: 467: return (PrintableCurrentLoc() + ": (" +
#####: 468: IntToString(current_ast_node_->depth()) + GetSymbolAnnotation() +
#####: 469: (current_ast_node_->in_forward_declare_context() ?
-: 470: ", fwd decl" : "") +
-: 471: ") [ " + name + " ] ");
-: 472: }
-: 473:
-: 474: // At verbose level 7 and above, returns a printable version of
-: 475: // the pointer, suitable for being emitted after AnnotatedName.
-: 476: // At lower verbose levels, returns the empty string.
#####: 477: string PrintablePtr(const void* ptr) const {
#####: 478: if (ShouldPrint(7)) {
#####: 479: char buffer[32];
#####: 480: snprintf(buffer, sizeof(buffer), "%p ", ptr);
#####: 481: return buffer;
-: 482: }
#####: 483: return "";
#####: 484: }
-: 485:
-: 486: // The top-level Decl class. All Decls call this visitor (in
-: 487: // addition to any more-specific visitors that apply for a
-: 488: // particular decl).
33250: 489: bool VisitDecl(clang::Decl* decl) {
33250: 490: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 491: errs() << AnnotatedName(string(decl->getDeclKindName()) + "Decl")
#####: 492: << PrintablePtr(decl) << PrintableDecl(decl) << "\n";
#####: 493: }
33250: 494: return true;
-: 495: }
-: 496:
82779: 497: bool VisitStmt(clang::Stmt* stmt) {
82779: 498: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 499: errs() << AnnotatedName(stmt->getStmtClassName()) << PrintablePtr(stmt);
#####: 500: PrintStmt(stmt);
#####: 501: errs() << "\n";
#####: 502: }
82779: 503: return true;
-: 504: }
-: 505:
65894: 506: bool VisitType(clang::Type* type) {
65894: 507: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 508: errs() << AnnotatedName(string(type->getTypeClassName()) + "Type")
#####: 509: << PrintablePtr(type) << PrintableType(type) << "\n";
#####: 510: }
65894: 511: return true;
-: 512: }
-: 513:
-: 514: // Make sure our logging message shows we're in the TypeLoc hierarchy.
60421: 515: bool VisitTypeLoc(clang::TypeLoc typeloc) {
60421: 516: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 517: errs() << AnnotatedName(string(typeloc.getTypePtr()->getTypeClassName())
-: 518: + "TypeLoc")
#####: 519: << PrintableTypeLoc(typeloc) << "\n";
#####: 520: }
60421: 521: return true;
-: 522: }
-: 523:
8707: 524: bool VisitNestedNameSpecifier(NestedNameSpecifier* nns) {
8707: 525: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 526: errs() << AnnotatedName("NestedNameSpecifier")
#####: 527: << PrintablePtr(nns) << PrintableNestedNameSpecifier(nns) << "\n";
#####: 528: }
8707: 529: return true;
-: 530: }
-: 531:
1074: 532: bool VisitTemplateName(TemplateName template_name) {
1074: 533: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 534: errs() << AnnotatedName("TemplateName")
#####: 535: << PrintableTemplateName(template_name) << "\n";
#####: 536: }
1074: 537: return true;
-: 538: }
-: 539:
197: 540: bool VisitTemplateArgument(const TemplateArgument& arg) {
197: 541: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 542: errs() << AnnotatedName("TemplateArgument")
#####: 543: << PrintablePtr(&arg) << PrintableTemplateArgument(arg) << "\n";
#####: 544: }
197: 545: return true;
-: 546: }
-: 547:
12278: 548: bool VisitTemplateArgumentLoc(const TemplateArgumentLoc& argloc) {
12278: 549: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 550: errs() << AnnotatedName("TemplateArgumentLoc")
#####: 551: << PrintablePtr(&argloc) << PrintableTemplateArgumentLoc(argloc)
-: 552: << "\n";
#####: 553: }
12278: 554: return true;
-: 555: }
-: 556:
-: 557: //------------------------------------------------------------
-: 558: // (4) Add implicit text.
-: 559:
-: 560: // When we see an object that has implicit text that iwyu
-: 561: // wants to look at, we make callbacks as if that text had
-: 562: // been explicitly written. Here's text we consider:
-: 563: //
-: 564: // * CXXDestructorDecl: a destructor call for each non-POD field
-: 565: // in the dtor's class, and each base type of that class.
-: 566: // * CXXConstructorDecl: a constructor call for each type/base
-: 567: // of the class that is not explicitly listed in an initializer.
-: 568: // * CXXRecordDecl: a CXXConstructorDecl for each implicit
-: 569: // constructor (zero-arg and copy). A CXXDestructor decl
-: 570: // if the destructor is implicit. A CXXOperatorCallDecl if
-: 571: // operator= is explicit.
-: 572:
1086: 573: bool TraverseCXXConstructorDecl(clang::CXXConstructorDecl* decl) {
1086: 574: if (!Base::TraverseCXXConstructorDecl(decl)) return false;
1780: 575: if (CanIgnoreCurrentASTNode()) return true;
-: 576: // We only care about classes that are actually defined.
866: 577: if (!decl || !decl->isThisDeclarationADefinition()) return true;
-: 578:
-: 579: // RAV's TraverseCXXConstructorDecl already handles
-: 580: // explicitly-written initializers, so we just want the rest.
854: 581: for (CXXConstructorDecl::init_const_iterator it = decl->init_begin();
778: 582: it != decl->init_end(); ++it) {
234: 583: const CXXCtorInitializer* init = *it;
234: 584: if (!init->isWritten()) {
117: 585: if (!this->getDerived().TraverseStmt(init->getInit()))
#####: 586: return false;
117: 587: }
234: 588: }
310: 589: return true;
1086: 590: }
-: 591:
336: 592: bool TraverseCXXDestructorDecl(clang::CXXDestructorDecl* decl) {
336: 593: if (!Base::TraverseCXXDestructorDecl(decl)) return false;
487: 594: if (CanIgnoreCurrentASTNode()) return true;
-: 595: // We only care about calls that are actually defined.
387: 596: if (!decl || !decl->isThisDeclarationADefinition()) return true;
-: 597:
-: 598: // Collect all the fields (and bases) we destroy, and call the dtor.
168: 599: set<const Type*> member_types;
168: 600: const CXXRecordDecl* record = decl->getParent();
168: 601: for (clang::RecordDecl::field_iterator it = record->field_begin();
576: 602: it != record->field_end(); ++it) {
204: 603: member_types.insert(it->getType().getTypePtr());
204: 604: }
-: 605: for (clang::CXXRecordDecl::base_class_const_iterator
406: 606: it = record->bases_begin(); it != record->bases_end(); ++it) {
35: 607: member_types.insert(it->getType().getTypePtr());
35: 608: }
1298: 609: for (Each<const Type*> it(&member_types); !it.AtEnd(); ++it) {
229: 610: const NamedDecl* member_decl = TypeToDeclAsWritten(*it);
-: 611: // We only want those fields that are c++ classes.
229: 612: if (const CXXRecordDecl* cxx_field_decl = DynCastFrom(member_decl)) {
81: 613: if (const CXXDestructorDecl* field_dtor
81: 614: = cxx_field_decl->getDestructor()) {
138: 615: if (!this->getDerived().TraverseImplicitDestructorCall(
69: 616: const_cast<CXXDestructorDecl*>(field_dtor), *it))
#####: 617: return false;
69: 618: }
81: 619: }
229: 620: }
168: 621: return true;
504: 622: }
-: 623:
-: 624: // clang lazily constructs the implicit methods of a C++ class (the
-: 625: // default constructor and destructor, etc) -- it only bothers to
-: 626: // create a CXXMethodDecl if someone actually calls these classes.
-: 627: // But we need to be non-lazy: iwyu depends on analyzing what future
-: 628: // code *may* call in a class, not what current code *does*. So we
-: 629: // force all the lazy evaluation to happen here. This will
-: 630: // (possibly) add a bunch of MethodDecls to the AST, as children of
-: 631: // decl. We're hoping it will always be safe to modify the AST
-: 632: // while it's being traversed!
331: 633: void InstantiateImplicitMethods(CXXRecordDecl* decl) {
331: 634: if (decl->isDependentType()) // only instantiate if class is instantiated
30: 635: return;
-: 636:
301: 637: clang::Sema& sema = compiler_->getSema();
301: 638: DeclContext::lookup_const_result ctors = sema.LookupConstructors(decl);
2999: 639: for (Each<NamedDecl*> it(&ctors); !it.AtEnd(); ++it) {
-: 640: // Ignore templated constructors.
1048: 641: if (isa<FunctionTemplateDecl>(*it))
138: 642: continue;
910: 643: CXXConstructorDecl* ctor = cast<CXXConstructorDecl>(*it);
1590: 644: if (!ctor->hasBody() && !ctor->isDeleted() && ctor->isImplicit()) {
139: 645: if (sema.getSpecialMember(ctor) == clang::Sema::CXXDefaultConstructor) {
28: 646: sema.DefineImplicitDefaultConstructor(CurrentLoc(), ctor);
28: 647: } else {
-: 648: // TODO(nlewycky): enable this!
-: 649: //sema.DefineImplicitCopyConstructor(CurrentLoc(), ctor);
-: 650: }
139: 651: }
-: 652: // Unreferenced template constructors stay uninstantiated on purpose.
910: 653: }
-: 654:
301: 655: if (CXXDestructorDecl* dtor = sema.LookupDestructor(decl)) {
301: 656: if (!dtor->isDeleted()) {
366: 657: if (!dtor->hasBody() && dtor->isImplicit())
58: 658: sema.DefineImplicitDestructor(CurrentLoc(), dtor);
308: 659: if (!dtor->isDefined() && dtor->getTemplateInstantiationPattern())
7: 660: sema.PendingInstantiations.push_back(make_pair(dtor, CurrentLoc()));
301: 661: }
301: 662: }
-: 663:
-: 664: // TODO(nlewycky): copy assignment operator
-: 665:
-: 666: // clang queues up method instantiations. We need to process them now.
301: 667: sema.PerformPendingInstantiations();
632: 668: }
-: 669:
-: 670: // clang doesn't bother to set a TypeSourceInfo for implicit
-: 671: // methods, since, well, they don't have a location. But
-: 672: // RecursiveASTVisitor crashes without one, so when we lie and say
-: 673: // we're not implicit, we have to lie and give a location as well.
-: 674: // (We give the null location.) This is a small memory leak.
304: 675: void SetTypeSourceInfoForImplicitMethodIfNeeded(FunctionDecl* decl) {
304: 676: if (decl->getTypeSourceInfo() == NULL) {
234: 677: ASTContext& ctx = compiler_->getASTContext();
234: 678: decl->setTypeSourceInfo(ctx.getTrivialTypeSourceInfo(decl->getType()));
234: 679: }
304: 680: }
-: 681:
-: 682: // RAV.h's TraverseDecl() ignores implicit nodes, so we lie a bit.
-: 683: // TODO(csilvers): figure out a more principled way.
304: 684: bool TraverseImplicitDeclHelper(clang::FunctionDecl* decl) {
912: 685: CHECK_(decl->isImplicit() && "TraverseImplicitDecl is for implicit decls");
304: 686: decl->setImplicit(false);
304: 687: SetTypeSourceInfoForImplicitMethodIfNeeded(decl);
304: 688: bool retval = this->getDerived().TraverseDecl(decl);
304: 689: decl->setImplicit(true);
304: 690: return retval;
-: 691: }
-: 692:
-: 693: // Handle implicit methods that otherwise wouldn't be seen by RAV.
975: 694: bool TraverseCXXRecordDecl(clang::CXXRecordDecl* decl) {
975: 695: if (!Base::TraverseCXXRecordDecl(decl)) return false;
1771: 696: if (CanIgnoreCurrentASTNode()) return true;
-: 697: // We only care about classes that are actually defined.
473: 698: if (!decl || !decl->isThisDeclarationADefinition()) return true;
-: 699:
64: 700: InstantiateImplicitMethods(decl);
-: 701:
-: 702: // Check to see if there are any implicit constructors. Can be
-: 703: // several: implicit default constructor, implicit copy constructor.
64: 704: for (CXXRecordDecl::ctor_iterator it = decl->ctor_begin();
236: 705: it != decl->ctor_end(); ++it) {
86: 706: CXXConstructorDecl* ctor = *it;
144: 707: if (ctor->isImplicit() && !ctor->isDeleted()) {
58: 708: if (!TraverseImplicitDeclHelper(ctor))
#####: 709: return false;
58: 710: }
86: 711: }
-: 712:
-: 713: // Check the (single) destructor.
64: 714: bool hasImplicitDeclaredDestructor = (!decl->needsImplicitDestructor() &&
38: 715: !decl->hasUserDeclaredDestructor());
64: 716: if (hasImplicitDeclaredDestructor) {
31: 717: if (!TraverseImplicitDeclHelper(decl->getDestructor()))
#####: 718: return false;
31: 719: }
-: 720:
-: 721: // Check copy and move assignment operators.
64: 722: for (CXXRecordDecl::method_iterator it = decl->method_begin();
478: 723: it != decl->method_end(); ++it) {
207: 724: bool isAssignmentOperator = it->isCopyAssignmentOperator() ||
411: 725: it->isMoveAssignmentOperator();
210: 726: if (isAssignmentOperator && it->isImplicit()) {
1: 727: if (!TraverseImplicitDeclHelper(*it))
#####: 728: return false;
1: 729: }
207: 730: }
-: 731:
64: 732: return true;
975: 733: }
-: 734:
-: 735: //------------------------------------------------------------
-: 736: // (5) Add TraverseImplicitDestructorCall and HandleFunctionCall.
-: 737:
-: 738: // TraverseImplicitDestructorCall: This is a callback this class
-: 739: // introduces that is a first-class callback just like any AST-node
-: 740: // callback. It is used to cover two places where the compiler
-: 741: // destroys objects, but there's no written indication of that in
-: 742: // the text: (1) when a local variable or a temporary goes out of
-: 743: // scope (NOTE: in this case, we attribute the destruction to the
-: 744: // same line as the corresponding construction, not to where the
-: 745: // scope ends). (2) When a destructor destroys one of the fields of
-: 746: // a class. For instance: 'class Foo { MyClass b; }': In addition
-: 747: // to executing its body, Foo::~Foo calls MyClass::~Myclass on b.
-: 748: // Note we only call this if an actual destructor is being executed:
-: 749: // we don't call it when an int goes out of scope!
-: 750: //
-: 751: // HandleFunctionCall: A convenience callback that 'bundles'
-: 752: // the following Expr's, each of which causes one or more
-: 753: // function calls when evaluated (though most of them are
-: 754: // not a child of CallExpr):
-: 755: // * CallExpr (obviously)
-: 756: // * CXXMemberCallExpr
-: 757: // * CXXOperatorCallExpr -- a call to operatorXX()
-: 758: // * CXXConstructExpr -- calls a constructor to create an object,
-: 759: // and maybe a destructor when the object goes out of scope.
-: 760: // * CXXTemporaryObjectExpr -- subclass of CXXConstructExpr
-: 761: // * CXXNewExpr -- calls operator new and a constructor
-: 762: // * CXXDeleteExpr -- calls operator delete and a destructor
-: 763: // * DeclRefExpr -- if the declref is a function pointer, we
-: 764: // treat it as a function call, since it can act like one
-: 765: // in the future
-: 766: // * ImplicitDestructorCall -- calls a destructor
-: 767: // Each of these calls HandleFunctionCall for the function calls
-: 768: // it does. A subclass interested only in function calls, and
-: 769: // not exactly what expression caused them, can override
-: 770: // HandleFunctionCall. Note: subclasses should expect that
-: 771: // the first argument to HandleFunctionCall may be NULL (e.g. when
-: 772: // constructing a built-in type), in which case the handler should
-: 773: // immediately return.
-: 774:
-: 775: // If the function being called is a member of a class, parent_type
-: 776: // is the type of the method's owner (parent), as it is written in
-: 777: // the source. (We need the type-as-written so we can distinguish
-: 778: // explicitly-written template args from default template args.) We
-: 779: // also pass in the CallExpr (or CXXConstructExpr, etc). This may
-: 780: // be NULL if the function call is implicit.
1871: 781: bool HandleFunctionCall(clang::FunctionDecl* callee,
1871: 782: const clang::Type* parent_type,
1871: 783: const clang::Expr* calling_expr) {
2067: 784: if (!callee) return true;
1675: 785: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 786: errs() << AnnotatedName("FunctionCall")
#####: 787: << PrintablePtr(callee) << PrintableDecl(callee) << "\n";
#####: 788: }
1675: 789: return true;
1871: 790: }
-: 791:
304: 792: bool TraverseImplicitDestructorCall(clang::CXXDestructorDecl* decl,
304: 793: const Type* type_being_destroyed) {
304: 794: if (CanIgnoreCurrentASTNode()) return true;
304: 795: if (!decl) return true;
304: 796: if (ShouldPrintSymbolFromCurrentFile()) {
#####: 797: errs() << AnnotatedName("Destruction")
#####: 798: << PrintableType(type_being_destroyed) << "\n";
#####: 799: }
304: 800: return this->getDerived().HandleFunctionCall(decl, type_being_destroyed,
-: 801: static_cast<Expr*>(NULL));
304: 802: }
-: 803:
-: 804:
6713: 805: bool TraverseCallExpr(clang::CallExpr* expr) {
6713: 806: if (!Base::TraverseCallExpr(expr)) return false;
13030: 807: if (CanIgnoreCurrentASTNode()) return true;
792: 808: return this->getDerived().HandleFunctionCall(expr->getDirectCallee(),
396: 809: TypeOfParentIfMethod(expr),
-: 810: expr);
6713: 811: }
-: 812:
583: 813: bool TraverseCXXMemberCallExpr(clang::CXXMemberCallExpr* expr) {
583: 814: if (!Base::TraverseCXXMemberCallExpr(expr)) return false;
843: 815: if (CanIgnoreCurrentASTNode()) return true;
646: 816: return this->getDerived().HandleFunctionCall(expr->getDirectCallee(),
323: 817: TypeOfParentIfMethod(expr),
-: 818: expr);
583: 819: }
-: 820:
2896: 821: bool TraverseCXXOperatorCallExpr(clang::CXXOperatorCallExpr* expr) {
2896: 822: if (!Base::TraverseCXXOperatorCallExpr(expr)) return false;
5720: 823: if (CanIgnoreCurrentASTNode()) return true;
-: 824:
72: 825: const Type* parent_type = TypeOfParentIfMethod(expr);
-: 826: // If we're a free function -- bool operator==(MyClass a, MyClass b) --
-: 827: // we still want to have a parent_type, as if we were defined as
-: 828: // MyClass::operator==. So we go through the arguments and take the
-: 829: // first one that's a class, and associate the function with that.
72: 830: if (!parent_type) {
72: 831: if (const Expr* first_argument = GetFirstClassArgument(expr))
51: 832: parent_type = GetTypeOf(first_argument);
72: 833: }
72: 834: return this->getDerived().HandleFunctionCall(expr->getDirectCallee(),
-: 835: parent_type, expr);
2896: 836: }
-: 837:
579: 838: bool TraverseCXXConstructExpr(clang::CXXConstructExpr* expr) {
579: 839: if (!Base::TraverseCXXConstructExpr(expr)) return false;
771: 840: if (CanIgnoreCurrentASTNode()) return true;
-: 841:
774: 842: if (!this->getDerived().HandleFunctionCall(expr->getConstructor(),
387: 843: GetTypeOf(expr),
-: 844: expr))
#####: 845: return false;
-: 846:
-: 847: // When creating a local variable or a temporary, but not a pointer, the
-: 848: // constructor is also responsible for destruction (which happens
-: 849: // implicitly when the variable goes out of scope). Only when initializing
-: 850: // a field of a class does the constructor not have to worry
-: 851: // about destruction. It turns out it's easier to check for that.
387: 852: bool willCallImplicitDestructorOnLeavingScope =
387: 853: !IsCXXConstructExprInInitializer(current_ast_node()) &&
252: 854: !IsCXXConstructExprInNewExpr(current_ast_node());
387: 855: if (willCallImplicitDestructorOnLeavingScope) {
-: 856: // Create the destructor if it hasn't been lazily created yet.
235: 857: InstantiateImplicitMethods(expr->getConstructor()->getParent());
235: 858: if (const CXXDestructorDecl* dtor_decl = GetSiblingDestructorFor(expr)) {
470: 859: if (!this->getDerived().TraverseImplicitDestructorCall(
235: 860: const_cast<CXXDestructorDecl*>(dtor_decl), GetTypeOf(expr)))
#####: 861: return false;
235: 862: }
235: 863: }
387: 864: return true;
579: 865: }
-: 866:
71: 867: bool TraverseCXXTemporaryObjectExpr(clang::CXXTemporaryObjectExpr* expr) {
71: 868: if (!Base::TraverseCXXTemporaryObjectExpr(expr)) return false;
110: 869: if (CanIgnoreCurrentASTNode()) return true;
-: 870:
-: 871: // In this case, we *know* we're responsible for destruction as well.
32: 872: InstantiateImplicitMethods(expr->getConstructor()->getParent());
32: 873: CXXConstructorDecl* ctor_decl = expr->getConstructor();
32: 874: CXXDestructorDecl* dtor_decl =
32: 875: const_cast<CXXDestructorDecl*>(GetSiblingDestructorFor(expr));
32: 876: const Type* type = GetTypeOf(expr);
32: 877: return (this->getDerived().HandleFunctionCall(ctor_decl, type, expr) &&
32: 878: this->getDerived().HandleFunctionCall(dtor_decl, type, expr));
71: 879: }
-: 880:
129: 881: bool TraverseCXXNewExpr(clang::CXXNewExpr* expr) {
129: 882: if (!Base::TraverseCXXNewExpr(expr)) return false;
222: 883: if (CanIgnoreCurrentASTNode()) return true;
-: 884:
36: 885: const Type* parent_type = expr->getAllocatedType().getTypePtrOrNull();
-: 886: // 'new' calls operator new in addition to the ctor of the new-ed type.
36: 887: if (FunctionDecl* operator_new = expr->getOperatorNew()) {
-: 888: // If operator new is a method, it must (by the semantics of
-: 889: // per-class operator new) be a method on the class we're newing.
25: 890: const Type* op_parent = NULL;
25: 891: if (isa<CXXMethodDecl>(operator_new))
1: 892: op_parent = parent_type;
25: 893: if (!this->getDerived().HandleFunctionCall(operator_new, op_parent, expr))
#####: 894: return false;
25: 895: }
36: 896: return true;
129: 897: }
-: 898:
54: 899: bool TraverseCXXDeleteExpr(clang::CXXDeleteExpr* expr) {
54: 900: if (!Base::TraverseCXXDeleteExpr(expr)) return false;
-: 901:
72: 902: if (CanIgnoreCurrentASTNode()) return true;
-: 903:
36: 904: const Type* parent_type = expr->getDestroyedType().getTypePtrOrNull();
-: 905: // We call operator delete in addition to the dtor of the deleted type.
36: 906: if (FunctionDecl* operator_delete = expr->getOperatorDelete()) {
-: 907: // If operator delete is a method, it must (by the semantics of per-
-: 908: // class operator delete) be a method on the class we're deleting.
27: 909: const Type* op_parent = NULL;
27: 910: if (isa<CXXMethodDecl>(operator_delete))
1: 911: op_parent = parent_type;
27: 912: if (!this->getDerived().HandleFunctionCall(operator_delete, op_parent,
-: 913: expr))
#####: 914: return false;
27: 915: }
36: 916: const CXXDestructorDecl* dtor = GetDestructorForDeleteExpr(expr);
36: 917: return this->getDerived().HandleFunctionCall(
-: 918: const_cast<CXXDestructorDecl*>(dtor), parent_type, expr);
54: 919: }
-: 920:
-: 921: // This is to catch assigning template functions to function pointers.
-: 922: // For instance, 'MyFunctionPtr p = &TplFn<MyClass*>;': we need to
-: 923: // expand TplFn to see if it needs full type info for MyClass.
18592: 924: bool TraverseDeclRefExpr(clang::DeclRefExpr* expr) {
18592: 925: if (!Base::TraverseDeclRefExpr(expr)) return false;
35775: 926: if (CanIgnoreCurrentASTNode()) return true;
-: 927:
-: 928: // If it's a normal function call, that was already handled by a
-: 929: // CallExpr somewhere. We want only assignments.
1409: 930: if (current_ast_node()->template ParentIsA<CallExpr>() ||
1216: 931: (current_ast_node()->template ParentIsA<ImplicitCastExpr>() &&
673: 932: current_ast_node()->template AncestorIsA<CallExpr>(2))) {
540: 933: return true;
-: 934: }
-: 935:
869: 936: if (FunctionDecl* fn_decl = DynCastFrom(expr->getDecl())) {
-: 937: // If fn_decl has a class-name before it -- 'MyClass::method' --
-: 938: // it's a method pointer.
16: 939: const Type* parent_type = NULL;
24: 940: if (expr->getQualifier() && expr->getQualifier()->getAsType())
8: 941: parent_type = expr->getQualifier()->getAsType();
16: 942: if (!this->getDerived().HandleFunctionCall(fn_decl, parent_type, expr))
#####: 943: return false;
16: 944: }
869: 945: return true;
18592: 946: }
-: 947:
-: 948: protected:
1251: 949: CompilerInstance* compiler() { return compiler_; }
-: 950:
-: 951: private:
-: 952: template <typename T> friend class BaseAstVisitor;
-: 953: CompilerInstance* const compiler_;
-: 954:
-: 955: // The currently active decl/stmt/type/etc -- that is, the node
-: 956: // being currently visited in a Visit*() or Traverse*() method. The
-: 957: // advantage of ASTNode over the object passed in to Visit*() and
-: 958: // Traverse*() is ASTNode knows its parent.
-: 959: ASTNode* current_ast_node_;
-: 960:};
-: 961:
-: 962:
-: 963:// ----------------------------------------------------------------------
-: 964:// --- AstTreeFlattenerVisitor
-: 965:// ----------------------------------------------------------------------
-: 966://
-: 967:// This simple visitor just creates a set of all AST nodes (stored as
-: 968:// void*'s) seen while traversing via BaseAstVisitor.
-: 969:
2038: 970:class AstFlattenerVisitor : public BaseAstVisitor<AstFlattenerVisitor> {
-: 971: public:
-: 972: typedef BaseAstVisitor<AstFlattenerVisitor> Base;
-: 973:
-: 974: // We divide our set of nodes into category by type. For most AST
-: 975: // nodes, we can store just a pointer to the node. However, for
-: 976: // some AST nodes we don't get a pointer into the AST, we get a
-: 977: // temporary (stack-allocated) object, and have to store the full
-: 978: // object ourselves and use its operator== to test for equality.
-: 979: // These types each get their own set (or, usually, vector, since
-: 980: // the objects tend not to support operator< or hash<>()).
8266: 981: class NodeSet {
-: 982: public:
-: 983: // We could add more versions, but these are the only useful ones so far.
5510: 984: bool Contains(const Type* type) const {
5510: 985: return ContainsKey(others, type);
-: 986: }
2707: 987: bool Contains(const Decl* decl) const {
2707: 988: return ContainsKey(others, decl);
-: 989: }
13138: 990: bool Contains(const ASTNode& node) const {
13138: 991: if (const TypeLoc* tl = node.GetAs<TypeLoc>()) {
3766: 992: return ContainsValue(typelocs, *tl);
9372: 993: } else if (const NestedNameSpecifierLoc* nl
9372: 994: = node.GetAs<NestedNameSpecifierLoc>()) {
#####: 995: return ContainsValue(nnslocs, *nl);
9372: 996: } else if (const TemplateName* tn = node.GetAs<TemplateName>()) {
-: 997: // The best we can do is to compare the associated decl
#####: 998: if (tn->getAsTemplateDecl() == NULL)
#####: 999: return false; // be conservative if we can't compare decls
#####: 1000: for (Each<TemplateName> it(&tpl_names); it.AtEnd(); ++it) {
#####: 1001: if (it->getAsTemplateDecl() == tn->getAsTemplateDecl())
#####: 1002: return true;
#####: 1003: }
#####: 1004: return false;
9372: 1005: } else if (const TemplateArgument* ta = node.GetAs<TemplateArgument>()) {
-: 1006: // TODO(csilvers): figure out how to compare template arguments
-: 1007: (void)ta;
#####: 1008: return false;
9372: 1009: } else if (const TemplateArgumentLoc* tal =
9372: 1010: node.GetAs<TemplateArgumentLoc>()) {
-: 1011: // TODO(csilvers): figure out how to compare template argument-locs
-: 1012: (void)tal;
#####: 1013: return false;
-: 1014: } else {
9372: 1015: return ContainsKey(others, node.GetAs<void>());
-: 1016: }
13138: 1017: }
-: 1018:
667: 1019: void AddAll(const NodeSet& that) {
667: 1020: Extend(&typelocs, that.typelocs);
667: 1021: Extend(&nnslocs, that.nnslocs);
667: 1022: Extend(&tpl_names, that.tpl_names);
667: 1023: Extend(&tpl_args, that.tpl_args);
667: 1024: Extend(&tpl_arglocs, that.tpl_arglocs);
667: 1025: InsertAllInto(that.others, &others);
667: 1026: }
-: 1027:
-: 1028: // Needed since we're treated like an stl-like object.
-: 1029: bool empty() const {
2870: 1030: return (typelocs.empty() && nnslocs.empty() &&
2519: 1031: tpl_names.empty() && tpl_args.empty() &&
2518: 1032: tpl_arglocs.empty() && others.empty());
1610: 1033: }
-: 1034: void clear() {
565: 1035: typelocs.clear();
565: 1036: nnslocs.clear();
565: 1037: tpl_names.clear();
565: 1038: tpl_args.clear();
565: 1039: tpl_arglocs.clear();
565: 1040: others.clear();
565: 1041: }
-: 1042:
-: 1043: private:
-: 1044: friend class AstFlattenerVisitor;
-: 1045:
-: 1046: // It's ok not to check for duplicates; we're just traversing the tree.
1705: 1047: void Add(TypeLoc tl) { typelocs.push_back(tl); }
-: 1048: void Add(NestedNameSpecifierLoc nl) { nnslocs.push_back(nl); }
119: 1049: void Add(TemplateName tn) { tpl_names.push_back(tn); }
#####: 1050: void Add(TemplateArgument ta) { tpl_args.push_back(ta); }
180: 1051: void Add(TemplateArgumentLoc tal) { tpl_arglocs.push_back(tal); }
4696: 1052: void Add(const void* o) { others.insert(o); }
-: 1053:
-: 1054: vector<TypeLoc> typelocs;
-: 1055: vector<NestedNameSpecifierLoc> nnslocs;
-: 1056: vector<TemplateName> tpl_names;
-: 1057: vector<TemplateArgument> tpl_args;
-: 1058: vector<TemplateArgumentLoc> tpl_arglocs;
-: 1059: set<const void*> others;
-: 1060: };
-: 1061:
-: 1062: //------------------------------------------------------------
-: 1063: // Public interface:
-: 1064:
2038: 1065: explicit AstFlattenerVisitor(CompilerInstance* compiler) : Base(compiler) { }
-: 1066:
805: 1067: const NodeSet& GetNodesBelow(Decl* decl) {
2415: 1068: CHECK_(seen_nodes_.empty() && "Nodes should be clear before GetNodesBelow");
805: 1069: NodeSet* node_set = &nodeset_decl_cache_[decl];
805: 1070: if (node_set->empty()) {
405: 1071: if (decl->isImplicit()) {
#####: 1072: TraverseImplicitDeclHelper(dyn_cast_or_null<FunctionDecl>(decl));
#####: 1073: } else {
405: 1074: TraverseDecl(decl);
-: 1075: }
405: 1076: swap(*node_set, seen_nodes_); // move the seen_nodes_ into the cache
405: 1077: }
805: 1078: return *node_set; // returns the cache entry
-: 1079: }
-: 1080:
-: 1081: //------------------------------------------------------------
-: 1082: // Pure virtual methods that the base class requires.
-: 1083:
-: 1084: virtual bool CanIgnoreCurrentASTNode() const {
539: 1085: return false;
-: 1086: }
-: 1087: virtual bool ShouldPrintSymbolFromCurrentFile() const {
40: 1088: return false;
-: 1089: }
-: 1090: virtual string GetSymbolAnnotation() const {
#####: 1091: return "[Uninstantiated template AST-node] ";
-: 1092: }
-: 1093:
-: 1094: //------------------------------------------------------------
-: 1095: // Top-level handlers that construct the tree.
-: 1096:
898: 1097: bool VisitDecl(Decl*) { AddCurrentAstNodeAsPointer(); return true; }
1700: 1098: bool VisitStmt(Stmt*) { AddCurrentAstNodeAsPointer(); return true; }
1734: 1099: bool VisitType(Type*) { AddCurrentAstNodeAsPointer(); return true; }
1705: 1100: bool VisitTypeLoc(TypeLoc typeloc) {
3410: 1101: VERRS(7) << GetSymbolAnnotation() << PrintableTypeLoc(typeloc) << "\n";
1705: 1102: seen_nodes_.Add(typeloc);
1705: 1103: return true;
-: 1104: }
148: 1105: bool VisitNestedNameSpecifier(NestedNameSpecifier*) {
148: 1106: AddCurrentAstNodeAsPointer();
148: 1107: return true;
-: 1108: }
119: 1109: bool VisitTemplateName(TemplateName tpl_name) {
238: 1110: VERRS(7) << GetSymbolAnnotation()
#####: 1111: << PrintableTemplateName(tpl_name) << "\n";
119: 1112: seen_nodes_.Add(tpl_name);
119: 1113: return true;
-: 1114: }
#####: 1115: bool VisitTemplateArgument(const TemplateArgument& tpl_arg) {
#####: 1116: VERRS(7) << GetSymbolAnnotation()
#####: 1117: << PrintableTemplateArgument(tpl_arg) << "\n";
#####: 1118: seen_nodes_.Add(tpl_arg);
#####: 1119: return true;
-: 1120: }
180: 1121: bool VisitTemplateArgumentLoc(const TemplateArgumentLoc& tpl_argloc) {
360: 1122: VERRS(7) << GetSymbolAnnotation()
#####: 1123: << PrintableTemplateArgumentLoc(tpl_argloc) << "\n";
180: 1124: seen_nodes_.Add(tpl_argloc);
180: 1125: return true;
-: 1126: }
5: 1127: bool TraverseImplicitDestructorCall(clang::CXXDestructorDecl* decl,
5: 1128: const Type* type) {
10: 1129: VERRS(7) << GetSymbolAnnotation() << "[implicit dtor] "
-: 1130: << static_cast<void*>(decl)
#####: 1131: << (decl ? PrintableDecl(decl) : "NULL") << "\n";
5: 1132: AddAstNodeAsPointer(decl);
5: 1133: return Base::TraverseImplicitDestructorCall(decl, type);
-: 1134: }
211: 1135: bool HandleFunctionCall(clang::FunctionDecl* callee,
211: 1136: const clang::Type* parent_type,
211: 1137: const clang::Expr* calling_expr) {
422: 1138: VERRS(7) << GetSymbolAnnotation() << "[function call] "
-: 1139: << static_cast<void*>(callee)
#####: 1140: << (callee ? PrintableDecl(callee) : "NULL") << "\n";
211: 1141: AddAstNodeAsPointer(callee);
211: 1142: return Base::HandleFunctionCall(callee, parent_type, calling_expr);
-: 1143: }
-: 1144:
-: 1145: //------------------------------------------------------------
-: 1146: // Class logic.
-: 1147:
4696: 1148: void AddAstNodeAsPointer(const void* node) {
4696: 1149: seen_nodes_.Add(node);
4696: 1150: }
-: 1151:
-: 1152: void AddCurrentAstNodeAsPointer() {
4480: 1153: if (ShouldPrint(7)) {
#####: 1154: errs() << GetSymbolAnnotation() << current_ast_node()->GetAs<void>()
-: 1155: << " ";
#####: 1156: PrintASTNode(current_ast_node());
#####: 1157: errs() << "\n";
#####: 1158: }
4480: 1159: AddAstNodeAsPointer(current_ast_node()->GetAs<void>());
4480: 1160: }
-: 1161:
-: 1162: private:
-: 1163: NodeSet seen_nodes_;
-: 1164:
-: 1165: // Because we make a new AstFlattenerVisitor each time we flatten, we
-: 1166: // need to make this map static.
-: 1167: // TODO(csilvers): just have one flattener, so this needn't be static.
-: 1168: static map<const Decl*, NodeSet> nodeset_decl_cache_;
-: 1169:};
-: 1170:
-: 1171:map<const Decl*, AstFlattenerVisitor::NodeSet>
1: 1172:AstFlattenerVisitor::nodeset_decl_cache_;
-: 1173:
-: 1174:
-: 1175:// ----------------------------------------------------------------------
-: 1176:// --- VisitorState
-: 1177:// ----------------------------------------------------------------------
-: 1178://
-: 1179:// This is a simple struct holding data that IwyuBaseASTVisitor will
-: 1180:// need to access and manipulate. It's held separately from
-: 1181:// IwyuBaseASTVisitor because we want this information to be shared
-: 1182:// between the IwyuASTConsumer and the InstantiatedTemplateVisitor,
-: 1183:// each of which gets its own copy of IwyuBaseASTVisitor data. So to
-: 1184:// share data, we need to hold it somewhere else.
-: 1185:
-: 1186:struct VisitorState {
2: 1187: VisitorState(CompilerInstance* c, const IwyuPreprocessorInfo& ipi)
2: 1188: : compiler(c), preprocessor_info(ipi) {}
-: 1189:
-: 1190: CompilerInstance* const compiler;
-: 1191:
-: 1192: // Information gathered at preprocessor time, including #include info.
-: 1193: const IwyuPreprocessorInfo& preprocessor_info;
-: 1194:
-: 1195: // When we see an overloaded function that depends on a template
-: 1196: // parameter, we can't resolve the overload until the template
-: 1197: // is instantiated (e.g., MyFunc<int> in the following example):
-: 1198: // template<typename T> MyFunc() { OverloadedFunction(T()); }
-: 1199: // However, sometimes we can do iwyu even before resolving the
-: 1200: // overload, if *all* potential overloads live in the same file. We
-: 1201: // mark the location of such 'early-processed' functions here, so
-: 1202: // when we see the function again at template-instantiation time, we
-: 1203: // know not to do iwyu-checking on it again. (Since the actual
-: 1204: // function-call exprs are different between the uninstantiated and
-: 1205: // instantiated calls, we can't store the exprs themselves, but have
-: 1206: // to store their location.)
-: 1207: set<SourceLocation> processed_overload_locs;
-: 1208:
-: 1209: // When we see a using declaration, we want to keep track of what
-: 1210: // file it's in, because other files may depend on that using
-: 1211: // declaration to get the names of their types right. We want to
-: 1212: // make sure we don't replace an #include with a forward-declare
-: 1213: // when we might need the #include's using declaration.
-: 1214: // The key is the type being 'used', the FileEntry is the file
-: 1215: // that has the using decl. If there are multiple using decls
-: 1216: // for a file, we prefer the one that has NamedDecl in it.
-: 1217: multimap<const NamedDecl*, const UsingDecl*> using_declarations;
-: 1218:};
-: 1219:
-: 1220:
-: 1221:// ----------------------------------------------------------------------
-: 1222:// --- IwyuBaseAstVisitor
-: 1223:// ----------------------------------------------------------------------
-: 1224://
-: 1225:// We use two AST visitor classes to implement IWYU: IwyuAstConsumer
-: 1226:// is the main visitor that traverses the AST corresponding to what's
-: 1227:// actually written in the source code, and
-: 1228:// InstantiatedTemplateVisitor is for traversing template
-: 1229:// instantiations. This class template holds iwyu work that is be
-: 1230:// shared by both.
-: 1231:
-: 1232:template <class Derived>
-: 1233:class IwyuBaseAstVisitor : public BaseAstVisitor<Derived> {
-: 1234: public:
-: 1235: typedef BaseAstVisitor<Derived> Base;
-: 1236:
2: 1237: explicit IwyuBaseAstVisitor(VisitorState* visitor_state)
-: 1238: : Base(visitor_state->compiler),
2: 1239: visitor_state_(visitor_state) {}
-: 1240:
#####: 1241: virtual ~IwyuBaseAstVisitor() {}
-: 1242:
-: 1243: // To avoid having this-> pointers everywhere, we re-export Base's
-: 1244: // functions that we use in this class. This is a language nit(?)
-: 1245: // when a templated class subclasses from another templated class.
-: 1246: using Base::CanIgnoreCurrentASTNode;
-: 1247: using Base::CurrentLoc;
-: 1248: using Base::CurrentFileEntry;
-: 1249: using Base::PrintableCurrentLoc;
-: 1250: using Base::current_ast_node;
-: 1251:
-: 1252: //------------------------------------------------------------
-: 1253: // Pure virtual methods that a subclass must implement.
-: 1254:
-: 1255: // Returns true if we are not interested in iwyu information for the
-: 1256: // given type, where the type is *not* the current AST node.
-: 1257: // TODO(csilvers): check we're calling this consistent with its API.
-: 1258: virtual bool CanIgnoreType(const Type* type) const = 0;
-: 1259:
-: 1260: // Returns true if we are not interested in doing an iwyu check on
-: 1261: // the given decl, where the decl is *not* the current AST node.
-: 1262: // TODO(csilvers): check we're calling this consistent with its API.
-: 1263: virtual bool CanIgnoreDecl(const Decl* decl) const = 0;
-: 1264:
-: 1265: //------------------------------------------------------------
-: 1266: // IWYU logic.
-: 1267:
-: 1268: // Helper for MapPrivateDeclToPublicDecl. Returns true if the decl
-: 1269: // is a template specialization whose (written qualified) name matches
-: 1270: // the given name, has the given number of template arguments, and
-: 1271: // whose specified tpl argument is a type.
-: 1272: bool DeclIsTemplateWithNameAndNumArgsAndTypeArg(
12006: 1273: const Decl* decl, const string& name,
12006: 1274: size_t num_args, size_t type_arg_idx) const {
12006: 1275: const ClassTemplateSpecializationDecl* tpl_decl = DynCastFrom(decl);
12006: 1276: if (!tpl_decl)
7842: 1277: return false;
4164: 1278: const string actual_name = GetWrittenQualifiedNameAsString(tpl_decl);
4164: 1279: if (name != actual_name)
3941: 1280: return false;
223: 1281: const TemplateArgumentList& tpl_args = tpl_decl->getTemplateArgs();
223: 1282: if (tpl_args.size() != num_args)
#####: 1283: return false;
223: 1284: if (tpl_args.get(type_arg_idx).getKind() != TemplateArgument::Type)
#####: 1285: return false;
223: 1286: return true;
16170: 1287: }
-: 1288:
-: 1289: // This requires the above function to have been called on decl, first.
223: 1290: const Type* GetTplTypeArg(const Decl* decl, size_t type_arg_idx) const {
223: 1291: const ClassTemplateSpecializationDecl* tpl_decl = DynCastFrom(decl);
669: 1292: CHECK_(tpl_decl && "Must call DeclIsTemplateWithNameAndNumArgsAndTypeArg");
223: 1293: const TemplateArgumentList& tpl_args = tpl_decl->getTemplateArgs();
669: 1294: CHECK_(tpl_args.size() > type_arg_idx && "Invalid type_arg_idx");
669: 1295: CHECK_(tpl_args.get(type_arg_idx).getKind() == TemplateArgument::Type);
223: 1296: return tpl_args.get(type_arg_idx).getAsType().getTypePtr();
-: 1297: }
-: 1298:
-: 1299: // Some types, such as __gnu_cxx::__normal_iterator or std::__wrap_iter, are
-: 1300: // private types that should not be exposed to the user. Instead, they're
-: 1301: // exposed to the user via typedefs, like vector::iterator.
-: 1302: // Sometimes, the typedef gets lost (such as for find(myvec.begin(),
-: 1303: // myvec.end(), foo)), so we need to manually map back. We map
-: 1304: // __normal_iterator<foo, vector> to vector<> and __wrap_iter<foo> to foo,
-: 1305: // assuming that the vector<> class includes the typedef. Likewise, we map
-: 1306: // any free function taking a private iterator (such as operator==) the
-: 1307: // same way, assuming that that (templatized) function is instantiated
-: 1308: // as part of the vector class.
-: 1309: // We do something similar for _List_iterator and _List_const_iterator
-: 1310: // from GNU libstdc++, and for __list_iterator and __list_const_iterator
-: 1311: // from libc++. These private names are defined in stl_list.h and list
-: 1312: // respectively, so we don't need to re-map them, but we do want to re-map
-: 1313: // reverse_iterator<_List_iterator> to something in list header.
-: 1314: // If the input decl does not correspond to one of these private
-: 1315: // decls, we return NULL. This method is actually a helper for
-: 1316: // MapPrivateDeclToPublicDecl() and MapPrivateTypeToPublicType().
3962: 1317: const Type* MapPrivateDeclToPublicType(const NamedDecl* decl) const {
3962: 1318: const NamedDecl* class_decl = decl;
-: 1319: // If we're a member method, then the __normal_iterator or __wrap_iter will
-: 1320: // be the parent: __normal_iterator::operator=. If we're a free
-: 1321: // overloaded operator, then the __normal_iterator will be the
-: 1322: // first argument: operator==(__normal_iterator<...>& lhs, ...);
3962: 1323: if (const CXXMethodDecl* method_decl = DynCastFrom(class_decl)) {
1358: 1324: class_decl = method_decl->getParent();
3962: 1325: } else if (const FunctionDecl* fn = DynCastFrom(decl)) {
294: 1326: if (fn->isOverloadedOperator() && fn->getNumParams() >= 1) {
84: 1327: const Type* firstarg_type = fn->getParamDecl(0)->getType().getTypePtr();
84: 1328: firstarg_type = RemovePointersAndReferencesAsWritten(firstarg_type);
84: 1329: class_decl = TypeToDeclAsWritten(firstarg_type);
84: 1330: }
210: 1331: }
-: 1332:
-: 1333: // In addition to __normal_iterator<x> and __wrap_iter<x>, we want
-: 1334: // to handle reverse_iterator<__normal_iterator<x>>, and in the same way.
3962: 1335: if (DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1336: class_decl, "std::reverse_iterator", 1, 0)) {
30: 1337: const Type* reversed_iterator_type = GetTplTypeArg(class_decl, 0);
-: 1338: // Gets class_decl to be reversed iterator.
30: 1339: class_decl = TypeToDeclAsWritten(reversed_iterator_type);
-: 1340:
-: 1341: // If it's reverse_iterator<_List_iterator>, map to
-: 1342: // _List_iterator, which is defined in stl_list like we want. Also map
-: 1343: // reverse_iterator<__list_iterator> to __list_iterator which is defined
-: 1344: // in list.
30: 1345: if (DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1346: class_decl, "std::_List_iterator", 1, 0) ||
30: 1347: DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1348: class_decl, "std::_List_const_iterator", 1, 0) ||
30: 1349: DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1350: class_decl, "std::__list_iterator", 2, 0) ||
240: 1351: DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1352: class_decl, "std::__list_const_iterator", 2, 0)) {
#####: 1353: return reversed_iterator_type;
-: 1354: }
30: 1355: }
-: 1356:
3962: 1357: if (DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1358: class_decl, "__gnu_cxx::__normal_iterator", 2, 1)) {
#####: 1359: return GetTplTypeArg(class_decl, 1);
-: 1360: }
3962: 1361: if (DeclIsTemplateWithNameAndNumArgsAndTypeArg(
-: 1362: class_decl, "std::__wrap_iter", 1, 0)) {
193: 1363: return GetTplTypeArg(class_decl, 0);
-: 1364: }
-: 1365:
3769: 1366: return NULL;
3962: 1367: }
-: 1368:
3209: 1369: const NamedDecl* MapPrivateDeclToPublicDecl(const NamedDecl* decl) const {
3209: 1370: const Type* public_type = MapPrivateDeclToPublicType(decl);
3209: 1371: if (public_type)
145: 1372: return TypeToDeclAsWritten(public_type);
3064: 1373: return decl;
3209: 1374: }
-: 1375:
753: 1376: const Type* MapPrivateTypeToPublicType(const Type* type) const {
753: 1377: const NamedDecl* private_decl = TypeToDeclAsWritten(type);
753: 1378: const Type* public_type = MapPrivateDeclToPublicType(private_decl);
753: 1379: if (public_type)
48: 1380: return public_type;
705: 1381: return type;
753: 1382: }
-: 1383:
-: 1384: // Re-assign uses from macro authors to macro callers when possible.
-: 1385: // With macros, it can be very difficult to tell what types are the
-: 1386: // responsibility of the macro-caller, and which the macro-author. e.g.
-: 1387: // #define SIZE_IN_FOOS(ptr) ( sizeof(*ptr) / sizeof(Foo) )
-: 1388: // Here the type of *ptr is the responsibility of the caller, while the
-: 1389: // type of Foo is the responsibility of the author, even though the
-: 1390: // Exprs for *ptr and Foo are both located inside the macro (the Expr
-: 1391: // for ptr is located at the macro-calling site, but not for *ptr).
-: 1392: // To help us guess the owner, we use this rule: if the macro-file
-: 1393: // intends-to-provide the type, then we keep ownership of the type
-: 1394: // at the macro. Otherwise, we assume it's with the caller. This
-: 1395: // works well as long as the file defining the macro is well-behaved.
-: 1396: // This function should be called with a use-loc that is within
-: 1397: // an expanded macro (so the use-loc will point to either inside a
-: 1398: // macro definition, or to an argument to a macro call). If it
-: 1399: // points within a macro definition, and that macro-definition file
-: 1400: // does not mean to re-export the symbol being used, then we reassign
-: 1401: // use of the decl to the macro-caller.
2: 1402: SourceLocation GetUseLocationForMacroExpansion(SourceLocation use_loc,
2: 1403: const Decl* used_decl) {
6: 1404: CHECK_(IsInMacro(use_loc) && "Unexpected non-macro-expansion call");
4: 1405: if (!preprocessor_info().PublicHeaderIntendsToProvide(
2: 1406: GetFileEntry(use_loc), GetFileEntry(used_decl)))
1: 1407: return GetInstantiationLoc(use_loc);
1: 1408: return use_loc;
2: 1409: }
-: 1410:
-: 1411: // There are a few situations where iwyu is more restrictive than
-: 1412: // C++: where C++ allows a forward-declare but iwyu wants the full
-: 1413: // type. One is in a typedef: if you write 'typedef Foo MyTypedef',
-: 1414: // iwyu says that you are responsible for #including "foo.h", but
-: 1415: // the language allows a forward-declare. Another is for
-: 1416: // 'autocast': if your function has a parameter with a conversion
-: 1417: // (one-arg, not-explicit) constructor, iwyu requires that the
-: 1418: // function-author provides the full type of that parameter, but
-: 1419: // the language doesn't. (It's ok with all callers providing the
-: 1420: // full type instead.)
-: 1421: //
-: 1422: // In each of these situations, we allow the user to say that iwyu
-: 1423: // should not require #includes for these underlying types, but
-: 1424: // allow forward-declares instead. The author can do this by
-: 1425: // explicitly forward-declaring in the same file: for instance, they
-: 1426: // would do
-: 1427: // class Foo; typedef Foo MyTypedef; // can be on different lines :-)
-: 1428: // class AutocastType; void MyFunc(AutocastType); // but in same file
-: 1429: // If a definition- or declaration-site does this forward-declaring
-: 1430: // *and* does not directly #include the necessary file for Foo or
-: 1431: // AutocastType, we take that as a signal from the code-author that
-: 1432: // iwyu should relax its policies. These functions calculate the
-: 1433: // types (which may have many component-types if it's a templated
-: 1434: // type) for which the code-author has made this decision.
2708: 1435: bool CodeAuthorWantsJustAForwardDeclare(const Type* type,
2708: 1436: SourceLocation use_loc) {
2708: 1437: const NamedDecl* decl = TypeToDeclAsWritten(type);
2708: 1438: if (decl == NULL) // only class-types are candidates for returning true
1483: 1439: return false;
-: 1440:
-: 1441: // If we're a template specialization, we also accept
-: 1442: // forward-declarations of the underlying template (vector<T>, not
-: 1443: // vector<int>).
1225: 1444: set<const NamedDecl*> redecls = GetClassRedecls(decl);
1225: 1445: if (const ClassTemplateSpecializationDecl* spec_decl = DynCastFrom(decl)) {
262: 1446: InsertAllInto(GetClassRedecls(spec_decl->getSpecializedTemplate()),
-: 1447: &redecls);
262: 1448: }
-: 1449:
-: 1450: // Check if the author forward-declared the class in the same file.
1225: 1451: bool found_earlier_forward_declare_in_same_file = false;
6092: 1452: for (Each<const NamedDecl*> it(&redecls); !it.AtEnd(); ++it) {
833: 1453: if (IsBeforeInSameFile(*it, use_loc)) {
158: 1454: found_earlier_forward_declare_in_same_file = true;
158: 1455: break;
-: 1456: }
675: 1457: }
1225: 1458: if (!found_earlier_forward_declare_in_same_file)
1067: 1459: return false;
-: 1460:
-: 1461: // Check if the the author is not #including the file with the
-: 1462: // definition. PublicHeaderIntendsToProvide has exactly the
-: 1463: // semantics we want. Note if there's no definition anywhere, we
-: 1464: // say the author does not want the full type (which is a good
-: 1465: // thing, since there isn't one!)
158: 1466: if (const NamedDecl* dfn = GetDefinitionForClass(decl)) {
157: 1467: if (IsBeforeInSameFile(dfn, use_loc))
125: 1468: return false;
64: 1469: if (preprocessor_info().PublicHeaderIntendsToProvide(
32: 1470: GetFileEntry(use_loc), GetFileEntry(dfn))) {
26: 1471: return false;
-: 1472: }
6: 1473: }
-: 1474:
-: 1475: // OK, looks like the author has stated they don't want the fulll type.
7: 1476: return true;
3933: 1477: }
-: 1478:
-: 1479: const Type* GetUnderlyingType(const Type* type) {
-: 1480: if (const TypedefType* typedef_type = DynCastFrom(type)) {
-: 1481: return GetUnderlyingType(typedef_type->getDecl()->getUnderlyingType().getTypePtr());
-: 1482: }
-: 1483: return type;
-: 1484: }
-: 1485:
-: 1486: set<const Type*> GetCallerResponsibleTypesForTypedef(
119: 1487: const TypedefDecl* decl) {
119: 1488: set<const Type*> retval;
119: 1489: const Type* underlying_type = decl->getUnderlyingType().getTypePtr();
-: 1490: // If the underlying type is itself a typedef, we recurse.
119: 1491: if (const TypedefType* underlying_typedef = DynCastFrom(underlying_type)) {
4: 1492: if (const TypedefDecl* underlying_typedef_decl
4: 1493: = DynCastFrom(TypeToDeclAsWritten(underlying_typedef))) {
-: 1494: // TODO(csilvers): if one of the intermediate typedefs
-: 1495: // #includes the necessary definition of the 'final'
-: 1496: // underlying type, do we want to return the empty set here?
4: 1497: return GetCallerResponsibleTypesForTypedef(underlying_typedef_decl);
-: 1498: }
#####: 1499: }
-: 1500:
115: 1501: const Type* deref_type
115: 1502: = RemovePointersAndReferencesAsWritten(underlying_type);
115: 1503: if (CodeAuthorWantsJustAForwardDeclare(deref_type, GetLocation(decl))) {
1: 1504: retval.insert(deref_type);
-: 1505: // TODO(csilvers): include template type-args if appropriate.
-: 1506: // This requires doing an iwyu visit of the instantiated
-: 1507: // underlying type and seeing which type-args we require full
-: 1508: // use for. Also have to handle the case where the type-args
-: 1509: // are themselves templates. It will require pretty substantial
-: 1510: // iwyu surgery.
1: 1511: }
115: 1512: return retval;
119: 1513: }
-: 1514:
-: 1515: // ast_node is the node for the autocast CastExpr. We use it to get
-: 1516: // the parent CallExpr to figure out what function is being called.
-: 1517: set<const Type*> GetCallerResponsibleTypesForAutocast(
8: 1518: const ASTNode* ast_node) {
118: 1519: while (ast_node && !ast_node->IsA<CallExpr>())
47: 1520: ast_node = ast_node->parent();
24: 1521: CHECK_(ast_node && "Should only check Autocast if under a CallExpr");
8: 1522: const CallExpr* call_expr = ast_node->GetAs<CallExpr>();
8: 1523: const FunctionDecl* fn_decl = call_expr->getDirectCallee();
8: 1524: if (!fn_decl) // TODO(csilvers): what to do for fn ptrs and the like?
#####: 1525: return set<const Type*>();
-: 1526:
-: 1527: // Collect the non-explicit, one-arg constructor ('autocast') types.
8: 1528: set<const Type*> autocast_types;
21: 1529: for (FunctionDecl::param_const_iterator param = fn_decl->param_begin();
18: 1530: param != fn_decl->param_end(); ++param) {
5: 1531: const Type* param_type = GetTypeOf(*param);
5: 1532: if (HasImplicitConversionConstructor(param_type)) {
2: 1533: const Type* deref_param_type =
2: 1534: RemovePointersAndReferencesAsWritten(param_type);
2: 1535: autocast_types.insert(deref_param_type);
2: 1536: }
5: 1537: }
-: 1538:
-: 1539: // Now look at all the function decls that are visible from the
-: 1540: // call-location. We keep only the autocast params that *all*
-: 1541: // the function decl authors want the caller to be responsible
-: 1542: // for. We do this by elimination: start with all types, and
-: 1543: // remove them as we see authors providing the full type.
8: 1544: set<const Type*> retval = autocast_types;
8: 1545: for (FunctionDecl::redecl_iterator fn_redecl = fn_decl->redecls_begin();
26: 1546: fn_redecl != fn_decl->redecls_end(); ++fn_redecl) {
-: 1547: // Ignore function-decls that we can't see from the use-location.
18: 1548: if (!preprocessor_info().FileTransitivelyIncludes(
9: 1549: GetFileEntry(call_expr), GetFileEntry(*fn_redecl))) {
#####: 1550: continue;
-: 1551: }
9: 1552: for (set<const Type*>::iterator it = retval.begin();
11: 1553: it != retval.end(); ) {
2: 1554: if (!CodeAuthorWantsJustAForwardDeclare(*it, GetLocation(*fn_redecl))) {
-: 1555: // set<> has nice property that erasing doesn't invalidate iterators.
-: 1556:
2: 1557: retval.erase(it++);
2: 1558: } else {
#####: 1559: ++it;
-: 1560: }
2: 1561: }
9: 1562: }
-: 1563:
-: 1564: // TODO(csilvers): include template type-args of each entry of retval.
-: 1565:
8: 1566: return retval;
16: 1567: }
-: 1568:
-: 1569: set<const Type*> GetCallerResponsibleTypesForFnReturn(
1420: 1570: const FunctionDecl* decl) {
1420: 1571: set<const Type*> retval;
1420: 1572: const Type* return_type
1420: 1573: = RemoveElaboration(decl->getReturnType().getTypePtr());
1420: 1574: if (CodeAuthorWantsJustAForwardDeclare(return_type, GetLocation(decl))) {
#####: 1575: retval.insert(return_type);
-: 1576: // TODO(csilvers): include template type-args if appropriate.
#####: 1577: }
1420: 1578: return retval;
2840: 1579: }
-: 1580:
-: 1581: //------------------------------------------------------------
-: 1582: // Checkers, that tell iwyu_output about uses of symbols.
-: 1583: // We let, but don't require, subclasses to override these.
-: 1584:
-: 1585: // The comment, if not NULL, is extra text that is included along
-: 1586: // with the warning message that iwyu emits.
2911: 1587: virtual void ReportDeclUseWithComment(SourceLocation used_loc,
2911: 1588: const NamedDecl* decl,
2911: 1589: const char* comment) {
-: 1590: // Map private decls like __normal_iterator to their public counterpart.
2911: 1591: decl = MapPrivateDeclToPublicDecl(decl);
2911: 1592: if (CanIgnoreDecl(decl))
135: 1593: return;
-: 1594:
-: 1595: // Figure out the best location to attribute uses inside macros.
2776: 1596: if (IsInMacro(used_loc))
2: 1597: used_loc = GetUseLocationForMacroExpansion(used_loc, decl);
2776: 1598: const FileEntry* used_in = GetFileEntry(used_loc);
-: 1599:
5552: 1600: preprocessor_info().FileInfoFor(used_in)->ReportFullSymbolUse(
2776: 1601: used_loc, decl, IsNodeInsideCXXMethodBody(current_ast_node()),
-: 1602: comment);
-: 1603:
-: 1604: // Sometimes using a decl drags in a few other uses as well:
-: 1605:
-: 1606: // If we're a use that depends on a using declaration, make sure
-: 1607: // we #include the file with the using declaration.
-: 1608: // TODO(csilvers): check that our getQualifier() does not match
-: 1609: // the namespace of the decl. If we have 'using std::vector;' +
-: 1610: // 'std::vector<int> foo;' we don't actually care about the
-: 1611: // using-decl.
-: 1612: // TODO(csilvers): maybe just insert our own using declaration
-: 1613: // instead? We can call it "Use what you use". :-)
-: 1614: // TODO(csilvers): check for using statements and namespace aliases too.
2776: 1615: if (const UsingDecl* using_decl
2776: 1616: = GetUsingDeclarationOf(decl, GetDeclContext(current_ast_node()))) {
4: 1617: preprocessor_info().FileInfoFor(used_in)->ReportFullSymbolUse(
2: 1618: used_loc, using_decl, IsNodeInsideCXXMethodBody(current_ast_node()),
-: 1619: "(for using decl)");
2: 1620: }
-: 1621:
-: 1622: // For typedefs, the user of the type is sometimes the one
-: 1623: // responsible for the underlying type. We check if that is the
-: 1624: // case here, since we might be using a typedef type from
-: 1625: // anywhere. ('autocast' is similar, but is handled in
-: 1626: // VisitCastExpr; 'fn-return-type' is also similar and is
-: 1627: // handled in HandleFunctionCall.)
2776: 1628: if (const TypedefDecl* typedef_decl = DynCastFrom(decl)) {
-: 1629: // One exception: if this TypedefType is being used in another
-: 1630: // typedef (that is, 'typedef MyTypedef OtherTypdef'), then the
-: 1631: // user -- the other typedef -- is never responsible for the
-: 1632: // underlying type. Instead, users of that typedef are.
117: 1633: if (!current_ast_node()->template ParentIsA<TypedefDecl>()) {
115: 1634: const set<const Type*>& underlying_types
115: 1635: = GetCallerResponsibleTypesForTypedef(typedef_decl);
115: 1636: if (!underlying_types.empty()) {
2: 1637: VERRS(6) << "User, not author, of typedef "
#####: 1638: << typedef_decl->getQualifiedNameAsString()
-: 1639: << " owns the underlying type:\n";
-: 1640: // If any of the used types are themselves typedefs, this will
-: 1641: // result in a recursive expansion. Note we are careful to
-: 1642: // recurse inside this class, and not go back to subclasses.
5: 1643: for (Each<const Type*> it(&underlying_types); !it.AtEnd(); ++it)
1: 1644: IwyuBaseAstVisitor<Derived>::ReportTypeUseWithComment(used_loc, *it,
-: 1645: NULL);
1: 1646: }
115: 1647: }
117: 1648: }
2911: 1649: }
-: 1650:
-: 1651: // The comment, if not NULL, is extra text that is included along
-: 1652: // with the warning message that iwyu emits.
298: 1653: virtual void ReportDeclForwardDeclareUseWithComment(SourceLocation used_loc,
298: 1654: const NamedDecl* decl,
298: 1655: const char* comment) {
298: 1656: decl = MapPrivateDeclToPublicDecl(decl);
298: 1657: if (CanIgnoreDecl(decl))
#####: 1658: return;
-: 1659:
-: 1660: // Figure out the best location to attribute uses inside macros.
298: 1661: if (IsInMacro(used_loc))
#####: 1662: used_loc = GetUseLocationForMacroExpansion(used_loc, decl);
298: 1663: const FileEntry* used_in = GetFileEntry(used_loc);
-: 1664:
596: 1665: preprocessor_info().FileInfoFor(used_in)->ReportForwardDeclareUse(
298: 1666: used_loc, decl, IsNodeInsideCXXMethodBody(current_ast_node()),
-: 1667: comment);
-: 1668:
-: 1669: // If we're a use that depends on a using declaration, make sure
-: 1670: // we #include the file with the using declaration.
298: 1671: if (const UsingDecl* using_decl
298: 1672: = GetUsingDeclarationOf(decl, GetDeclContext(current_ast_node()))) {
8: 1673: preprocessor_info().FileInfoFor(used_in)->ReportFullSymbolUse(
4: 1674: used_loc, using_decl, IsNodeInsideCXXMethodBody(current_ast_node()),
-: 1675: "(for using decl)");
4: 1676: }
298: 1677: }
-: 1678:
-: 1679: // Like ReportDeclUse, but for the common case of no comment.
2285: 1680: void ReportDeclUse(SourceLocation used_loc, const NamedDecl* decl) {
2285: 1681: return ReportDeclUseWithComment(used_loc, decl, NULL);
-: 1682: }
-: 1683:
285: 1684: void ReportDeclForwardDeclareUse(SourceLocation used_loc,
285: 1685: const NamedDecl* decl) {
285: 1686: return ReportDeclForwardDeclareUseWithComment(used_loc, decl, NULL);
-: 1687: }
-: 1688:
290: 1689: void ReportDeclsUse(SourceLocation used_loc,
290: 1690: const set<const NamedDecl*>& decls) {
940: 1691: for (Each<const NamedDecl*> it(&decls); !it.AtEnd(); ++it)
35: 1692: ReportDeclUse(used_loc, *it);
290: 1693: }
-: 1694:
-: 1695: // Called when the given type is fully used at used_loc, regardless
-: 1696: // of the type being explicitly written in the source code or not.
-: 1697: // The comment, if not NULL, is extra text that is included along
-: 1698: // with the warning message that iwyu emits.
753: 1699: virtual void ReportTypeUseWithComment(SourceLocation used_loc,
753: 1700: const Type* type,
753: 1701: const char* comment) {
-: 1702: // TODO(csilvers): figure out if/when calling CanIgnoreType() is correct.
753: 1703: if (!type)
#####: 1704: return;
-: 1705:
-: 1706: // Map private types like __normal_iterator to their public counterpart.
753: 1707: type = MapPrivateTypeToPublicType(type);
-: 1708: // For the below, we want to be careful to call *our*
-: 1709: // ReportDeclUse(), not any of the ones in subclasses.
753: 1710: if (IsPointerOrReferenceAsWritten(type)) {
50: 1711: type = RemovePointersAndReferencesAsWritten(type);
50: 1712: if (const NamedDecl* decl = TypeToDeclAsWritten(type)) {
26: 1713: VERRS(6) << "(For pointer type " << PrintableType(type) << "):\n";
13: 1714: IwyuBaseAstVisitor<Derived>::ReportDeclForwardDeclareUseWithComment(
-: 1715: used_loc, decl, comment);
13: 1716: }
50: 1717: } else {
703: 1718: if (const NamedDecl* decl = TypeToDeclAsWritten(type)) {
626: 1719: decl = GetDefinitionAsWritten(decl);
626: 1720: std::string type_name = PrintableType(type);
626: 1721: if ((type_name == "class std::basic_string<char>")
626: 1722: || (type_name == "value_type")) {
#####: 1723: VERRS(6) << "Place for breakpoint\n";
#####: 1724: }
1252: 1725: VERRS(6) << "(For type " << PrintableType(type) << "):\n";
626: 1726: IwyuBaseAstVisitor<Derived>::ReportDeclUseWithComment(
-: 1727: used_loc, decl, comment);
626: 1728: }
-: 1729: }
753: 1730: }
-: 1731:
-: 1732: // Like ReportTypeUse, but for the common case of no comment.
746: 1733: void ReportTypeUse(SourceLocation used_loc, const Type* type) {
746: 1734: return ReportTypeUseWithComment(used_loc, type, NULL);
-: 1735: }
-: 1736:
290: 1737: void ReportTypesUse(SourceLocation used_loc, const set<const Type*>& types) {
1202: 1738: for (Each<const Type*> it(&types); !it.AtEnd(); ++it)
166: 1739: ReportTypeUse(used_loc, *it);
290: 1740: }
-: 1741:
-: 1742: //------------------------------------------------------------
-: 1743: // Visitors of types derived from clang::Decl.
-: 1744:
-: 1745: // Friend declarations only need their types forward-declared.
252: 1746: bool VisitFriendDecl(clang::FriendDecl* decl) {
416: 1747: if (CanIgnoreCurrentASTNode()) return true;
88: 1748: current_ast_node()->set_in_forward_declare_context(true);
88: 1749: return true;
252: 1750: }
-: 1751:
#####: 1752: bool VisitFriendTemplateDecl(clang::FriendTemplateDecl* decl) {
#####: 1753: if (CanIgnoreCurrentASTNode()) return true;
#####: 1754: current_ast_node()->set_in_forward_declare_context(true);
#####: 1755: return true;
#####: 1756: }
-: 1757:
-: 1758: // If you say 'typedef Foo Bar', C++ says you just need to
-: 1759: // forward-declare Foo. But iwyu would rather you fully define Foo,
-: 1760: // so all users of Bar don't have to. We make two exceptions:
-: 1761: // 1) The author of the typedef doesn't *want* to provide Foo, and
-: 1762: // is happy making all the callers do so. The author indicates
-: 1763: // this by explicitly forward-declaring Foo and not #including
-: 1764: // foo.h.
-: 1765: // 2) The typedef is a member of a templated class, and the
-: 1766: // underlying type is a template parameter:
-: 1767: // template<class T> struct C { typedef T value_type; };
-: 1768: // This is not a re-export because you need the type to
-: 1769: // access the typedef (via 'C<Someclass>::value_type'), so
-: 1770: // there's no need for the typedef-file to provide the type
-: 1771: // too. TODO(csilvers): this is patently wrong; figure out
-: 1772: // something better. We need something that doesn't require
-: 1773: // the full type info for creating a scoped_ptr<MyClass>.
-: 1774: // As an extension of (2), if the typedef is a template type that
-: 1775: // contains T as a template parameter, the typedef still re-exports
-: 1776: // the template type (it's not (2)), but the template parameter
-: 1777: // itself can be forward-declared, just as in (2). That is:
-: 1778: // template<class T> struct C { typedef pair<T,T> value_type; };
-: 1779: // iwyu will demand the full type of pair, but not of its template
-: 1780: // arguments. This is handled not here, but below, in
-: 1781: // VisitSubstTemplateTypeParmType.
2523: 1782: bool VisitTypedefDecl(clang::TypedefDecl* decl) {
4059: 1783: if (CanIgnoreCurrentASTNode()) return true;
987: 1784: const Type* underlying_type = decl->getUnderlyingType().getTypePtr();
987: 1785: const Type* deref_type
987: 1786: = RemovePointersAndReferencesAsWritten(underlying_type);
-: 1787:
987: 1788: if (CodeAuthorWantsJustAForwardDeclare(deref_type, GetLocation(decl)) ||
983: 1789: isa<SubstTemplateTypeParmType>(underlying_type)) {
181: 1790: current_ast_node()->set_in_forward_declare_context(true);
181: 1791: } else {
806: 1792: current_ast_node()->set_in_forward_declare_context(false);
-: 1793: }
-: 1794:
987: 1795: return Base::VisitTypedefDecl(decl);
2523: 1796: }
-: 1797:
-: 1798: // If we're a declared (not defined) function, all our types --
-: 1799: // return type and argument types -- are forward-declarable. The
-: 1800: // one exception required by the language is the throw types, which
-: 1801: // we clean up in VisitType().
-: 1802: // There are two more exceptions that iwyu imposes:
-: 1803: // (1) iwyu asks the function author to provide the full type
-: 1804: // information for the return type. That way the user doesn't
-: 1805: // have to.
-: 1806: // (2) If any of our function parameters have a type with a
-: 1807: // non-explicit, one-arg constructor, or is a const reference to
-: 1808: // such a type, mark that type as not forward declarable. The
-: 1809: // worry is that people might need the full type for the
-: 1810: // implicit conversion (the 'autocast'), for instance, passing
-: 1811: // in a char* to Fn(const StringPiece& foo) { ... }
-: 1812: // Both of these iwyu requirements can be overridden by the function
-: 1813: // author; for details, see CodeAuthorWantsJustAForwardDeclare.
6883: 1814: bool VisitFunctionDecl(clang::FunctionDecl* decl) {
12707: 1815: if (CanIgnoreCurrentASTNode()) return true;
-: 1816:
1059: 1817: if (!decl->isThisDeclarationADefinition()) {
-: 1818: // Make all our types forward-declarable...
252: 1819: current_ast_node()->set_in_forward_declare_context(true);
252: 1820: }
-: 1821:
-: 1822: // (The exceptions below don't apply to friend declarations; we
-: 1823: // never need full types for them.)
1059: 1824: if (IsFriendDecl(decl))
32: 1825: return true;
-: 1826:
-: 1827: // ...except the return value.
1027: 1828: const Type* return_type
1027: 1829: = RemoveElaboration(decl->getReturnType().getTypePtr());
1027: 1830: const bool is_responsible_for_return_type
1027: 1831: = (!CanIgnoreType(return_type) &&
183: 1832: !IsPointerOrReferenceAsWritten(return_type) &&
175: 1833: !CodeAuthorWantsJustAForwardDeclare(return_type, GetLocation(decl)));
-: 1834: // Don't bother to report here, when the language agrees with us
-: 1835: // we need the full type; that will be reported elsewhere, so
-: 1836: // reporting here would be double-counting.
1027: 1837: const bool type_use_reported_in_visit_function_type
1027: 1838: = (!current_ast_node()->in_forward_declare_context() ||
1254: 1839: !IsClassType(return_type));
1200: 1840: if (is_responsible_for_return_type &&
-: 1841: !type_use_reported_in_visit_function_type) {
2: 1842: ReportTypeUseWithComment(GetLocation(decl), return_type,
-: 1843: "(for fn return type)");
2: 1844: }
-: 1845:
-: 1846: // ...and non-explicit, one-arg ('autocast') constructor types.
2673: 1847: for (FunctionDecl::param_iterator param = decl->param_begin();
2265: 1848: param != decl->param_end(); ++param) {
619: 1849: const Type* param_type = GetTypeOf(*param);
619: 1850: if (!HasImplicitConversionConstructor(param_type))
565: 1851: continue;
54: 1852: const Type* deref_param_type =
54: 1853: RemovePointersAndReferencesAsWritten(param_type);
98: 1854: if (CanIgnoreType(param_type) && CanIgnoreType(deref_param_type))
37: 1855: continue;
-: 1856:
-: 1857: // TODO(csilvers): remove this 'if' check when we've resolved the
-: 1858: // clang bug where getTypeSourceInfo() can return NULL.
17: 1859: if ((*param)->getTypeSourceInfo()) {
9: 1860: const TypeLoc param_tl = (*param)->getTypeSourceInfo()->getTypeLoc();
-: 1861: // While iwyu requires the full type of autocast parameters,
-: 1862: // c++ does not. Function-writers can force iwyu to follow
-: 1863: // the language by explicitly forward-declaring the type.
-: 1864: // Check for that now, and don't require the full type.
18: 1865: if (CodeAuthorWantsJustAForwardDeclare(deref_param_type,
9: 1866: GetLocation(&param_tl)))
#####: 1867: continue;
-: 1868: // This is a 'full type required' check, to 'turn off' fwd decl.
-: 1869: // But don't bother to report in situations where we need the
-: 1870: // full type for other reasons; that's just double-reporting.
9: 1871: if (current_ast_node()->in_forward_declare_context() ||
6: 1872: IsPointerOrReferenceAsWritten(param_type)) {
4: 1873: ReportTypeUseWithComment(GetLocation(&param_tl), deref_param_type,
-: 1874: "(for autocast)");
4: 1875: }
9: 1876: } else {
16: 1877: VERRS(6) << "WARNING: NULL TypeSourceInfo for " << PrintableDecl(*param)
#####: 1878: << " (type " << PrintableType(param_type) << ")\n";
-: 1879: }
17: 1880: }
1027: 1881: return true;
6883: 1882: }
-: 1883:
-: 1884: // Special handling for C++ methods to detect covariant return types.
-: 1885: // These are defined as a derived class overriding a method with a different
-: 1886: // return type from the base.
4784: 1887: bool VisitCXXMethodDecl(CXXMethodDecl* method_decl) {
8676: 1888: if (CanIgnoreCurrentASTNode()) return true;
-: 1889:
892: 1890: if (HasCovariantReturnType(method_decl)) {
#####: 1891: const Type* return_type = RemovePointersAndReferencesAsWritten(
#####: 1892: method_decl->getReturnType().getTypePtr());
-: 1893:
#####: 1894: VERRS(3) << "Found covariant return type in "
#####: 1895: << method_decl->getQualifiedNameAsString()
-: 1896: << ", needs complete type of "
#####: 1897: << PrintableType(return_type)
-: 1898: << ".\n";
-: 1899:
#####: 1900: ReportTypeUse(CurrentLoc(), return_type);
#####: 1901: }
-: 1902:
892: 1903: return Base::VisitCXXMethodDecl(method_decl);
4784: 1904: }
-: 1905:
-: 1906: //------------------------------------------------------------
-: 1907: // Visitors of types derived from clang::Stmt.
-: 1908:
-: 1909: // Catch statements always require the full type to be visible,
-: 1910: // no matter if we're catching by value, reference or pointer.
86: 1911: bool VisitCXXCatchStmt(clang::CXXCatchStmt* stmt) {
172: 1912: if (CanIgnoreCurrentASTNode()) return true;
-: 1913:
#####: 1914: if (const Type* caught_type = stmt->getCaughtType().getTypePtrOrNull()) {
-: 1915: // Strip off pointers/references to get to the 'base' type.
#####: 1916: caught_type = RemovePointersAndReferencesAsWritten(caught_type);
#####: 1917: ReportTypeUse(CurrentLoc(), caught_type);
#####: 1918: } else {
-: 1919: // catch(...): no type to act on here.
-: 1920: }
-: 1921:
#####: 1922: return Base::VisitCXXCatchStmt(stmt);
86: 1923: }
-: 1924:
-: 1925: // When casting non-pointers, iwyu will do the right thing
-: 1926: // automatically, but sometimes when casting from one pointer to
-: 1927: // another, you still need the full type information of both types:
-: 1928: // for instance, when static-casting from a sub-class to a
-: 1929: // super-class. Testing shows this is true for static, dynamic
-: 1930: // casts, and implicit casts, but not for reinterpret casts, const
-: 1931: // casts, or C-style casts. (Functional casts like int(3.5) are
-: 1932: // treated the same as C-style casts.) clang helpfully provides a
-: 1933: // 'cast kind', which we use to determine when full types are
-: 1934: // needed. When we notice that the cast is a cast up or down a
-: 1935: // class hierarchy, we require full type info for both types even
-: 1936: // for C-style casts (though the language doesn't), to give the
-: 1937: // compiler a fighting chance of generating correct code.
6933: 1938: bool VisitCastExpr(clang::CastExpr* expr) {
12322: 1939: if (CanIgnoreCurrentASTNode()) return true;
1544: 1940: const Type* const from_type = GetTypeOf(expr->getSubExprAsWritten());
1544: 1941: const Type* const to_type = GetTypeOf(expr);
1544: 1942: const Type* const deref_from_type = RemovePointersAndReferences(from_type);
1544: 1943: const Type* const deref_to_type = RemovePointersAndReferences(to_type);
-: 1944:
-: 1945: // For all those casts that don't result in function calls
-: 1946: // (everything except a user-defined cast or a constructor cast),
-: 1947: // we only care about the need for full types when casting either
-: 1948: // a pointer to a pointer, or any type to a reference.
-: 1949: // Unfortunately, when casting to a reference, clang seems to
-: 1950: // strip the reference off of to_type, so we need a separate
-: 1951: // function call to tell.
1544: 1952: if (expr->getCastKind() != clang::CK_UserDefinedConversion &&
1514: 1953: expr->getCastKind() != clang::CK_ConstructorConversion) {
1494: 1954: if (!((from_type->hasPointerRepresentation() && // pointer or reference
479: 1955: to_type->hasPointerRepresentation()) ||
1036: 1956: IsCastToReferenceType(expr)))
934: 1957: return true; // we only care about ptr-to-ptr casts for this check
560: 1958: }
-: 1959:
1220: 1960: bool need_full_deref_from_type = false;
1220: 1961: bool need_full_deref_to_type = false;
-: 1962: // The list of kinds: http://clang.llvm.org/doxygen/namespaceclang.html
1220: 1963: switch (expr->getCastKind()) {
-: 1964: // This cast still isn't handled directly.
-: 1965: case clang::CK_Dependent:
#####: 1966: break;
-: 1967:
-: 1968: // These casts don't require any iwyu action.
-: 1969: case clang::CK_LValueToRValue:
-: 1970: case clang::CK_AtomicToNonAtomic:
-: 1971: case clang::CK_NonAtomicToAtomic:
-: 1972: case clang::CK_ReinterpretMemberPointer:
-: 1973: case clang::CK_BuiltinFnToFnPtr:
-: 1974: case clang::CK_ZeroToOCLEvent: // OpenCL event_t is a built-in type.
-: 1975: case clang::CK_AddressSpaceConversion: // Address spaces are associated
-: 1976: // with pointers, so no need for
-: 1977: // the full type.
298: 1978: break;
-: 1979:
-: 1980: // We shouldn't be seeing any of these kinds.
-: 1981: case clang::CK_ArrayToPointerDecay:
-: 1982: case clang::CK_FloatingCast:
-: 1983: case clang::CK_FloatingComplexCast:
-: 1984: case clang::CK_FloatingComplexToBoolean:
-: 1985: case clang::CK_FloatingComplexToIntegralComplex:
-: 1986: case clang::CK_FloatingComplexToReal:
-: 1987: case clang::CK_FloatingRealToComplex:
-: 1988: case clang::CK_FloatingToBoolean:
-: 1989: case clang::CK_FloatingToIntegral:
-: 1990: case clang::CK_FunctionToPointerDecay:
-: 1991: case clang::CK_IntegralCast:
-: 1992: case clang::CK_IntegralComplexCast:
-: 1993: case clang::CK_IntegralComplexToBoolean:
-: 1994: case clang::CK_IntegralComplexToFloatingComplex:
-: 1995: case clang::CK_IntegralComplexToReal:
-: 1996: case clang::CK_IntegralRealToComplex:
-: 1997: case clang::CK_IntegralToBoolean:
-: 1998: case clang::CK_IntegralToFloating:
-: 1999: case clang::CK_IntegralToPointer:
-: 2000: case clang::CK_MemberPointerToBoolean:
-: 2001: case clang::CK_NullToMemberPointer:
-: 2002: case clang::CK_NullToPointer:
-: 2003: case clang::CK_PointerToBoolean:
-: 2004: case clang::CK_PointerToIntegral:
-: 2005: case clang::CK_ToUnion:
-: 2006: case clang::CK_ToVoid:
-: 2007: // Due to a bug in clang, we sometimes get IntegralToPointer
-: 2008: // kinds for a cast that should be a NoOp kind:
-: 2009: // http://llvm.org/bugs/show_bug.cgi?id=8543
-: 2010: // It's possible clang mis-categorizes in other cases too. So
-: 2011: // I just log here, rather than asserting and possibly
-: 2012: // crashing iwyu.
#####: 2013: VERRS(3) << "WARNING: Unexpected cast that involves a non-pointer: "
#####: 2014: << expr->getCastKindName() << "\n";
#####: 2015: break;
-: 2016: case clang::CK_AnyPointerToBlockPointerCast:
-: 2017: case clang::CK_ARCConsumeObject:
-: 2018: case clang::CK_ARCExtendBlockObject:
-: 2019: case clang::CK_ARCProduceObject:
-: 2020: case clang::CK_ARCReclaimReturnedObject:
-: 2021: case clang::CK_BlockPointerToObjCPointerCast:
-: 2022: case clang::CK_CopyAndAutoreleaseBlockObject:
-: 2023: case clang::CK_CPointerToObjCPointerCast:
-: 2024: case clang::CK_ObjCObjectLValueCast:
-: 2025: case clang::CK_VectorSplat:
#####: 2026: CHECK_UNREACHABLE_(
-: 2027: "TODO(csilvers): for objc and clang lang extensions");
-: 2028: break;
-: 2029:
-: 2030: // Kinds for reinterpret_cast and const_cast, which need no full types.
-: 2031: case clang::CK_BitCast: // used for reinterpret_cast
-: 2032: case clang::CK_LValueBitCast: // used for reinterpret_cast
-: 2033: case clang::CK_NoOp: // used for const_cast, etc
153: 2034: break;
-: 2035:
-: 2036: // Need the full to-type so we can call its constructor.
-: 2037: case clang::CK_ConstructorConversion:
-: 2038: // 'Autocast' -- calling a one-arg, non-explicit constructor
-: 2039: // -- is a special case when it's done for a function call.
-: 2040: // iwyu requires the function-writer to provide the #include
-: 2041: // for the casted-to type, just so we don't have to require it
-: 2042: // here. *However*, the function-author can override this
-: 2043: // iwyu requirement, in which case we're responsible for the
-: 2044: // casted-to type. See IwyuBaseASTVisitor::VisitFunctionDecl.
20: 2045: if (!current_ast_node()->template HasAncestorOfType<CallExpr>() ||
56: 2046: ContainsKey(
8: 2047: GetCallerResponsibleTypesForAutocast(current_ast_node()),
-: 2048: deref_to_type)) {
12: 2049: need_full_deref_to_type = true;
12: 2050: }
20: 2051: break;
-: 2052: // Need the full from-type so we can call its 'operator <totype>()'.
-: 2053: case clang::CK_UserDefinedConversion:
30: 2054: need_full_deref_from_type = true;
30: 2055: break;
-: 2056:
-: 2057: // Kinds that cast up or down an inheritance hierarchy.
-: 2058: case clang::CK_BaseToDerived:
-: 2059: case clang::CK_BaseToDerivedMemberPointer:
-: 2060: // Just 'to' type is enough: full type for derived gets base type too.
4: 2061: need_full_deref_to_type = true;
4: 2062: break;
-: 2063: case clang::CK_DerivedToBase:
-: 2064: case clang::CK_UncheckedDerivedToBase:
-: 2065: case clang::CK_DerivedToBaseMemberPointer:
103: 2066: need_full_deref_from_type = true;
103: 2067: break;
-: 2068: case clang::CK_Dynamic:
-: 2069: // Usually dynamic casting is a base-to-derived cast, but it is
-: 2070: // possible to dynamic-cast between siblings, in which case we
-: 2071: // need both types.
2: 2072: need_full_deref_from_type = true;
2: 2073: need_full_deref_to_type = true;
2: 2074: break;
-: 2075: }
-: 2076:
-: 2077: // TODO(csilvers): test if we correctly say we use FooPtr for
-: 2078: // typedef Foo* FooPtr; ... static_cast<FooPtr>(...) ...
745: 2079: if (need_full_deref_from_type && !CanIgnoreType(deref_from_type)) {
47: 2080: ReportTypeUse(CurrentLoc(), deref_from_type);
47: 2081: }
628: 2082: if (need_full_deref_to_type && !CanIgnoreType(deref_to_type)) {
14: 2083: ReportTypeUse(CurrentLoc(), deref_to_type);
14: 2084: }
610: 2085: return true;
6933: 2086: }
-: 2087:
-: 2088: // Mark that we need the full type info for our base type -- the
-: 2089: // thing we're a member of -- and it's not just forward-declarable.
-: 2090: // For instance, for code 'Mytype* myvar; myvar->a;', we'll get a
-: 2091: // MemberExpr callback whose base has the type of myvar.
3289: 2092: bool VisitMemberExpr(clang::MemberExpr* expr) {
5964: 2093: if (CanIgnoreCurrentASTNode()) return true;
-: 2094:
614: 2095: const Expr* base_expr = expr->getBase()->IgnoreParenImpCasts();
614: 2096: const Type* base_type = GetTypeOf(base_expr);
1842: 2097: CHECK_(base_type && "Member's base does not have a type?");
-: 2098: //base_type = GetUnderlyingType(base_type);
614: 2099: const Type* deref_base_type // For myvar->a, base-type will have a *
1842: 2100: = expr->isArrow() ? RemovePointerFromType(base_type) : base_type;
1082: 2101: if (CanIgnoreType(base_type) && CanIgnoreType(deref_base_type))
410: 2102: return true;
-: 2103: // Technically, we should say the type is being used at the
-: 2104: // location of base_expr. That may be a different file than us in
-: 2105: // cases like MACRO.b(). However, while one can imagine
-: 2106: // situations where the base-type is the responsibility of the
-: 2107: // macro-author ('SOME_GLOBAL_OBJECT.a()'), the more common case
-: 2108: // is it's our responsibility ('CHECK_NOTNULL(x).a()'). Until we
-: 2109: // can better distinguish whether a macro body is an expression
-: 2110: // that's responsible for its type or not, we just assume it is.
-: 2111: // TODO(csilvers): fix when we can determine what the macro-text
-: 2112: // is responsible for and what we're responsible for.
-: 2113: // TODO(csilvers): we should be reporting a fwd-decl use for
-: 2114: // GetTypeOf(expr), not on deref_base_type.
204: 2115: ReportTypeUse(CurrentLoc(), deref_base_type);
204: 2116: return true;
3289: 2117: }
-: 2118:
-: 2119: // For a[4], report that we need the full type of *a (to get its
-: 2120: // size; otherwise the compiler can't tell the address of a[4]).
150: 2121: bool VisitArraySubscriptExpr(clang::ArraySubscriptExpr* expr) {
296: 2122: if (CanIgnoreCurrentASTNode()) return true;
-: 2123:
4: 2124: const Type* element_type = GetTypeOf(expr);
4: 2125: if (CanIgnoreType(element_type))
2: 2126: return true;
2: 2127: ReportTypeUse(CurrentLoc(), element_type);
2: 2128: return true;
150: 2129: }
-: 2130:
-: 2131: // Mark that we need the full type info for the thing we're taking
-: 2132: // sizeof of. Sometimes this is double-counting: for
-: 2133: // sizeof(some_type), RecursiveASTVisitor will visit some_type and
-: 2134: // say it needs the full type information there, and for
-: 2135: // sizeof(some_var), we'll report we need full type information when
-: 2136: // some_var is defined. But if the arg is a reference, nobody else
-: 2137: // will say we need full type info but us.
29: 2138: bool VisitUnaryExprOrTypeTraitExpr(clang::UnaryExprOrTypeTraitExpr* expr) {
29: 2139: if (CanIgnoreCurrentASTNode()) return true;
-: 2140:
-: 2141: // Calling sizeof on a reference-to-X is the same as calling it on X.
-: 2142: // If sizeof() takes a type, this is easy to check. If sizeof()
-: 2143: // takes an expr, it's hard to tell -- GetTypeOf(expr) 'sees through'
-: 2144: // references. Luckily, we want to see through references, so we
-: 2145: // just use the GetTypeOf().
29: 2146: if (expr->isArgumentType()) {
26: 2147: const TypeLoc& arg_tl = expr->getArgumentTypeInfo()->getTypeLoc();
26: 2148: if (const ReferenceType* reftype = DynCastFrom(arg_tl.getTypePtr())) {
#####: 2149: const Type* dereftype = reftype->getPointeeTypeAsWritten().getTypePtr();
#####: 2150: if (!CanIgnoreType(reftype) || !CanIgnoreType(dereftype))
#####: 2151: ReportTypeUse(GetLocation(&arg_tl), dereftype);
#####: 2152: } else {
-: 2153: // No need to report on non-ref types, RecursiveASTVisitor will get 'em.
-: 2154: }
26: 2155: } else {
3: 2156: const Expr* arg_expr = expr->getArgumentExpr();
3: 2157: const Type* dereftype = arg_expr->getType().getTypePtr();
3: 2158: if (!CanIgnoreType(dereftype))
-: 2159: // This reports even if the expr ends up not being a reference, but
-: 2160: // that's ok (if potentially redundant).
3: 2161: ReportTypeUse(GetLocation(arg_expr), dereftype);
-: 2162: }
29: 2163: return true;
29: 2164: }
-: 2165:
-: 2166: // We want to mark use of the base type For 'free function' operator
-: 2167: // overloads ('ostream& operator<<(ostream& o, int x)') just like we
-: 2168: // do for member functions ('ostream& ostream::operator<<(int x)')
-: 2169: // -- for iwyu purposes, 'x << 4' is just semantic sugar around
-: 2170: // x.operator<<(4).
2876: 2171: bool VisitCXXOperatorCallExpr(clang::CXXOperatorCallExpr* expr) {
5700: 2172: if (CanIgnoreCurrentASTNode()) return true;
-: 2173:
52: 2174: if (const Expr* owner_expr = GetFirstClassArgument(expr)) {
50: 2175: const Type* owner_type = GetTypeOf(owner_expr);
-: 2176: // Note we report the type use is the location of owner_expr
-: 2177: // (the 'a' in 'a << b' or the 'MACRO' in 'MACRO << b'), rather
-: 2178: // than our location (which is the '<<'). That way, we properly
-: 2179: // situate the owner when it's a macro.
50: 2180: if (!CanIgnoreType(owner_type))
33: 2181: ReportTypeUse(GetLocation(owner_expr), owner_type);
50: 2182: }
52: 2183: return true;
2876: 2184: }
-: 2185:
-: 2186: // We have to check the type being deleted is fully defined (the
-: 2187: // language doesn't require it, but bad things happen if it's not:
-: 2188: // the destructor isn't run).
48: 2189: bool VisitCXXDeleteExpr(clang::CXXDeleteExpr* expr) {
66: 2190: if (CanIgnoreCurrentASTNode()) return true;
-: 2191:
30: 2192: const Expr* delete_arg = expr->getArgument()->IgnoreParenImpCasts();
-: 2193: // We always delete a pointer, so do one dereference to get the
-: 2194: // actual type being deleted.
30: 2195: const Type* delete_ptr_type = GetTypeOf(delete_arg);
30: 2196: const Type* delete_type = RemovePointerFromType(delete_ptr_type);
41: 2197: if (CanIgnoreType(delete_ptr_type) && CanIgnoreType(delete_type))
2: 2198: return true;
-: 2199:
55: 2200: if (delete_type && !IsPointerOrReferenceAsWritten(delete_type))
25: 2201: ReportTypeUse(CurrentLoc(), delete_type);
-: 2202:
28: 2203: return true;
48: 2204: }
-: 2205:
-: 2206: // Handle the case of passing references to variadic functions
-: 2207: // (those with '...'). We need the full type information for the
-: 2208: // reference in that case, since compilers seem to just deref the
-: 2209: // var before passing it in. Note we subclass all the
-: 2210: // function-calling methods rather than HandleFunctionCall, because
-: 2211: // a) we need type-specific caller information anyway, and b)
-: 2212: // HandleFunctionCall isn't called for calls via function-pointers,
-: 2213: // which we want.
530: 2214: void ReportIfReferenceVararg(const Expr* const* args, unsigned num_args,
530: 2215: const FunctionProtoType* callee_type) {
1060: 2216: if (callee_type && callee_type->isVariadic()) {
3: 2217: const unsigned first_vararg_index = callee_type->getNumParams();
20: 2218: for (unsigned i = first_vararg_index; i < num_args; i++) {
-: 2219: // We only care about reporting for references, but it's ok if
-: 2220: // we catch a few non-ref types too (it's just redundant).
-: 2221: // All expressions that are references will have their
-: 2222: // valuekind be an LValue, so we use that as the test.
7: 2223: if (args[i]->getValueKind() == clang::VK_LValue) {
-: 2224: // The types of expressions 'see through' the reference to
-: 2225: // the underlying type, which is exactly what we want here.
#####: 2226: ReportTypeUse(CurrentLoc(), GetTypeOf(args[i]));
#####: 2227: }
7: 2228: }
3: 2229: }
530: 2230: }
254: 2231: void ReportIfReferenceVararg(const Expr* const* args, unsigned num_args,
254: 2232: const FunctionDecl* callee) {
254: 2233: if (callee) {
254: 2234: const FunctionProtoType* callee_type =
254: 2235: DynCastFrom(callee->getType().getTypePtr());
762: 2236: CHECK_(callee_type &&
-: 2237: "The type of a FunctionDecl must be a FunctionProtoType.");
254: 2238: ReportIfReferenceVararg(args, num_args, callee_type);
254: 2239: }
254: 2240: }
-: 2241:
-: 2242: // We only need visitors for CallExpr, ConstructExpr, and NewExpr
-: 2243: // (which also captures their subclasses). We can ignore DeleteExpr
-: 2244: // since destructors never have arguments. NewExpr we treat below,
-: 2245: // since it requires other checks as well.
10006: 2246: bool VisitCallExpr(clang::CallExpr* expr) {
19407: 2247: if (CanIgnoreCurrentASTNode()) return true;
-: 2248: // Nothing to do if the called function is an old K&R-style function.
605: 2249: const FunctionType* fn_type = GetCalleeFunctionType(expr);
605: 2250: if (const FunctionProtoType* fn_proto = DynCastFrom(fn_type))
276: 2251: ReportIfReferenceVararg(expr->getArgs(), expr->getNumArgs(), fn_proto);
605: 2252: return true;
10006: 2253: }
-: 2254:
454: 2255: bool VisitCXXConstructExpr(clang::CXXConstructExpr* expr) {
671: 2256: if (CanIgnoreCurrentASTNode()) return true;
474: 2257: ReportIfReferenceVararg(expr->getArgs(), expr->getNumArgs(),
237: 2258: expr->getConstructor());
237: 2259: return true;
454: 2260: }
-: 2261:
-: 2262: // An OverloadExpr is an overloaded function (or method) in an
-: 2263: // uninstantiated template, that can't be resolved until the
-: 2264: // template is instantiated. The simplest case is something like:
-: 2265: // void Foo(int) { ... }
-: 2266: // void Foo(float) { ... }
-: 2267: // template<typename T> Fn(T t) { Foo(t); }
-: 2268: // But by far the most common case is when the function-to-be-called
-: 2269: // is also a templated function:
-: 2270: // template<typename T> Fn1(T t) { ... }
-: 2271: // template<typename T> Fn2(T t) { Fn1(t); }
-: 2272: // In either case, we look at all the potential overloads. If they
-: 2273: // all exist in the same file -- which is pretty much always the
-: 2274: // case, especially with a template calling a template -- we can do
-: 2275: // an iwyu warning now, even without knowing the exact overload.
-: 2276: // In that case, we store the fact we warned, so we won't warn again
-: 2277: // when the template is instantiated.
-: 2278: // TODO(csilvers): to be really correct, we should report *every*
-: 2279: // overload that callers couldn't match via ADL.
4747: 2280: bool VisitOverloadExpr(clang::OverloadExpr* expr) {
-: 2281: // No CanIgnoreCurrentASTNode() check here! It's later in the function.
-: 2282:
-: 2283: // Make sure all overloads are in the same file.
4747: 2284: if (expr->decls_begin() == expr->decls_end()) // not sure this is possible
5: 2285: return true;
4742: 2286: const NamedDecl* first_decl = *expr->decls_begin();
4742: 2287: const FileEntry* first_decl_file_entry = GetFileEntry(first_decl);
4742: 2288: for (OverloadExpr::decls_iterator it = expr->decls_begin();
24712: 2289: it != expr->decls_end(); ++it) {
12280: 2290: if (GetFileEntry(*it) != first_decl_file_entry)
2295: 2291: return true;
9985: 2292: }
-: 2293:
-: 2294: // For now, we're only worried about function calls.
-: 2295: // TODO(csilvers): are there other kinds of overloads we need to check?
2447: 2296: const FunctionDecl* arbitrary_fn_decl = NULL;
2447: 2297: for (OverloadExpr::decls_iterator it = expr->decls_begin();
2447: 2298: it != expr->decls_end(); ++it) {
2447: 2299: const NamedDecl* decl = *it;
-: 2300: // Sometimes a UsingShadowDecl comes between us and the 'real' decl.
2447: 2301: if (const UsingShadowDecl* using_shadow_decl = DynCastFrom(decl))
33: 2302: decl = using_shadow_decl->getTargetDecl();
2447: 2303: if (const FunctionDecl* fn_decl = DynCastFrom(decl)) {
692: 2304: arbitrary_fn_decl = fn_decl;
692: 2305: break;
1755: 2306: } else if (const FunctionTemplateDecl* tpl_decl = DynCastFrom(decl)) {
1755: 2307: arbitrary_fn_decl = tpl_decl->getTemplatedDecl();
1755: 2308: break;
-: 2309: }
#####: 2310: }
-: 2311:
-: 2312: // If we're an overloaded operator, we can never do the iwyu check
-: 2313: // before instantiation-time, because we don't know if we might
-: 2314: // end up being the built-in form of the operator. (Even if the
-: 2315: // only operator==() we see is in foo.h, we don't need to #include
-: 2316: // foo.h if the only call to operator== we see is on two integers.)
4894: 2317: if (arbitrary_fn_decl && !arbitrary_fn_decl->isOverloadedOperator()) {
1625: 2318: AddProcessedOverloadLoc(CurrentLoc());
3250: 2319: VERRS(7) << "Adding to processed_overload_locs: "
#####: 2320: << PrintableCurrentLoc() << "\n";
-: 2321: // Because processed_overload_locs might be set in one visitor
-: 2322: // but used in another, each with a different definition of
-: 2323: // CanIgnoreCurrentASTNode(), we have to be conservative and set
-: 2324: // the has-considered flag always. But of course we only
-: 2325: // actually report the function use if CanIgnoreCurrentASTNode()
-: 2326: // is *currently* false.
1625: 2327: if (!CanIgnoreCurrentASTNode())
2: 2328: ReportDeclUse(CurrentLoc(), arbitrary_fn_decl);
1625: 2329: }
2447: 2330: return true;
4747: 2331: }
-: 2332:
-: 2333: // TODO(csilvers): handle some special cases when we're a
-: 2334: // CXXDependentScopeMemberExpr (e.g. vector<T>::resize().). If the
-: 2335: // base class is a TemplateSpecializationType, get its TemplateDecl
-: 2336: // and if all explicit specializations and patterns are defined in
-: 2337: // the same file, treat it as an expr with only one decl. May have
-: 2338: // trouble with methods defined in a different file than they're
-: 2339: // declared.
-: 2340:
-: 2341: // If getOperatorNew() returns NULL, it means the operator-new is
-: 2342: // overloaded, and technically we can't know which operator-new is
-: 2343: // being called until the template is instantiated. But if it looks
-: 2344: // like a placement-new, we handle it at template-writing time
-: 2345: // anyway.
122: 2346: bool VisitCXXNewExpr(clang::CXXNewExpr* expr) {
-: 2347: // Like in VisitOverloadExpr(), we update processed_overload_locs
-: 2348: // regardless of the value of CanIgnoreCurrentASTNode().
-: 2349:
-: 2350: // We say it's placement-new if the (lone) placment-arg is a
-: 2351: // pointer. Unfortunately, often clang will just say it's a
-: 2352: // dependent type. In that case, we can still say it's a pointer
-: 2353: // in the (common) case the placement arg looks like '&something'.
-: 2354: // (This is possibly wrong for classes that override operator&, but
-: 2355: // those classes deserve what they get.)
122: 2356: if (!expr->getOperatorNew() &&
94: 2357: expr->getNumPlacementArgs() == 1 &&
78: 2358: (GetTypeOf(expr->getPlacementArg(0))->isPointerType() ||
30: 2359: GetTypeOf(expr->getPlacementArg(0))->isArrayType() ||
29: 2360: IsAddressOf(expr->getPlacementArg(0)))) {
-: 2361: // Treat this like an OverloadExpr.
56: 2362: AddProcessedOverloadLoc(CurrentLoc());
112: 2363: VERRS(7) << "Adding to processed_overload_locs (placement-new): "
#####: 2364: << PrintableCurrentLoc() << "\n";
56: 2365: if (!CanIgnoreCurrentASTNode()) {
-: 2366: // We have to 'make up' a full file path for 'new'. We'll
-: 2367: // parse it to '<new>' before using, so any path that does
-: 2368: // that, and is clearly a c++ path, is fine; its exact
-: 2369: // contents don't matter that much.
3: 2370: const FileEntry* use_file = CurrentFileEntry();
6: 2371: preprocessor_info().FileInfoFor(use_file)->ReportFullSymbolUse(
3: 2372: CurrentLoc(), "<new>", "operator new");
3: 2373: }
56: 2374: }
-: 2375:
-: 2376: // We also need to do a varargs check, like for other function calls.
215: 2377: if (CanIgnoreCurrentASTNode()) return true;
-: 2378: // ... only if this NewExpr involves a constructor call.
29: 2379: const Expr* Init = expr->getInitializer();
29: 2380: if (const CXXConstructExpr* CCE =
29: 2381: dyn_cast_or_null<CXXConstructExpr>(Init)){
34: 2382: ReportIfReferenceVararg(CCE->getArgs(),
17: 2383: CCE->getNumArgs(),
17: 2384: CCE->getConstructor());
17: 2385: }
29: 2386: return true;
122: 2387: }
-: 2388:
-: 2389: // When we call (or potentially call) a function, do an IWYU check
-: 2390: // via ReportDeclUse() to make sure the definition of the function
-: 2391: // is properly #included.
1660: 2392: bool HandleFunctionCall(FunctionDecl* callee, const Type* parent_type,
1660: 2393: const clang::Expr* calling_expr) {
1660: 2394: if (!Base::HandleFunctionCall(callee, parent_type, calling_expr))
#####: 2395: return false;
4940: 2396: if (!callee || CanIgnoreCurrentASTNode() || CanIgnoreDecl(callee))
58: 2397: return true;
-: 2398: // We may have already been checked in a previous
-: 2399: // VisitOverloadExpr() call. Don't check again in that case.
1602: 2400: if (IsProcessedOverloadLoc(CurrentLoc()))
182: 2401: return true;
-: 2402:
1420: 2403: ReportDeclUse(CurrentLoc(), callee);
-: 2404:
-: 2405: // Usually the function-author is responsible for providing the
-: 2406: // full type information for the return type of the function, but
-: 2407: // in cases where it's not, we have to take responsibility.
-: 2408: // TODO(csilvers): check the fn argument types as well.
1420: 2409: const Type* return_type = callee->getReturnType().getTypePtr();
1420: 2410: if (ContainsKey(GetCallerResponsibleTypesForFnReturn(callee),
-: 2411: return_type)) {
#####: 2412: ReportTypeUse(CurrentLoc(), return_type);
#####: 2413: }
-: 2414:
1420: 2415: return true;
1660: 2416: }
-: 2417:
-: 2418: //------------------------------------------------------------
-: 2419: // Visitors of types derived from clang::Type.
-: 2420:
65894: 2421: bool VisitType(clang::Type* type) {
-: 2422: // In VisitFunctionDecl(), we say all children of function
-: 2423: // declarations are forward-declarable. This is true, *except*
-: 2424: // for the exception (throw) types. We clean that up here.
-: 2425: // TODO(csilvers): figure out how to do these two steps in one place.
65894: 2426: const FunctionProtoType* fn_type = NULL;
65894: 2427: if (!fn_type) {
65894: 2428: fn_type = current_ast_node()->template GetParentAs<FunctionProtoType>();
65894: 2429: }
65894: 2430: if (!fn_type) {
58494: 2431: if (const FunctionDecl* fn_decl
58494: 2432: = current_ast_node()->template GetParentAs<FunctionDecl>())
7290: 2433: fn_type = dyn_cast<FunctionProtoType>(GetTypeOf(fn_decl));
58494: 2434: }
65894: 2435: if (fn_type) {
14690: 2436: for (FunctionProtoType::exception_iterator it =
29411: 2437: fn_type->exception_begin();
14752: 2438: it != fn_type->exception_end(); ++it)
45: 2439: if (it->getTypePtr() == type) { // *we're* an exception decl
14: 2440: current_ast_node()->set_in_forward_declare_context(false);
14: 2441: break;
31: 2442: }
14690: 2443: }
-: 2444:
65894: 2445: return Base::VisitType(type);
-: 2446: }
-: 2447:
-: 2448: bool VisitTemplateSpecializationType(
1070: 2449: clang::TemplateSpecializationType* type) {
1110: 2450: if (CanIgnoreCurrentASTNode()) return true;
1884: 2451: if (CanIgnoreType(type)) return true;
-: 2452:
176: 2453: const NamedDecl* decl = TypeToDeclAsWritten(type);
-: 2454:
-: 2455: // If we are forward-declarable, so are our template arguments.
176: 2456: if (CanForwardDeclareType(current_ast_node())) {
39: 2457: ReportDeclForwardDeclareUse(CurrentLoc(), decl);
39: 2458: current_ast_node()->set_in_forward_declare_context(true);
39: 2459: } else {
137: 2460: ReportDeclUse(CurrentLoc(), decl);
-: 2461: }
-: 2462:
176: 2463: return true;
1070: 2464: }
-: 2465:
-: 2466: //------------------------------------------------------------
-: 2467: // Visitors defined by BaseAstVisitor.
-: 2468:
8707: 2469: bool VisitNestedNameSpecifier(NestedNameSpecifier* nns) {
8707: 2470: if (!Base::VisitNestedNameSpecifier(nns)) return false;
-: 2471: // If we're in an nns (e.g. the Foo in Foo::bar), we're never
-: 2472: // forward-declarable, even if we're part of a pointer type, or in
-: 2473: // a template argument, or whatever.
8707: 2474: current_ast_node()->set_in_forward_declare_context(false);
8707: 2475: return true;
8707: 2476: }
-: 2477:
-: 2478: // Template arguments are forward-declarable by default. However,
-: 2479: // default template template args shouldn't be: we're responsible for
-: 2480: // the full type info for default args. So no forward-declaring
-: 2481: // MyClass in 'template<template<typename A> class T = MyClass> C ...'
-: 2482: // We detect because MyClass's parent is TemplateTemplateParmDecl.
-: 2483: // TODO(csilvers): And not when they're a type that's in
-: 2484: // known_fully_used_tpl_type_args_. See if that solves the problem with
-: 2485: // I1_TemplateClass<std::vector<I1_Class> > i1_nested_templateclass(...)
12475: 2486: void DetermineForwardDeclareStatusForTemplateArg(ASTNode* ast_node) {
37425: 2487: CHECK_(ast_node->IsA<TemplateArgument>() &&
-: 2488: "Should only pass in a template arg to DFDSFTA");
-: 2489:
12475: 2490: if (!IsDefaultTemplateTemplateArg(ast_node)) {
12475: 2491: ast_node->set_in_forward_declare_context(true);
12475: 2492: return;
-: 2493: }
12475: 2494: }
-: 2495:
197: 2496: bool VisitTemplateArgument(const TemplateArgument& arg) {
197: 2497: if (!Base::VisitTemplateArgument(arg)) return false;
-: 2498: // Template arguments are forward-declarable...usually.
197: 2499: DetermineForwardDeclareStatusForTemplateArg(current_ast_node());
197: 2500: return true;
197: 2501: }
-: 2502:
12278: 2503: bool VisitTemplateArgumentLoc(const TemplateArgumentLoc& argloc) {
12278: 2504: if (!Base::VisitTemplateArgumentLoc(argloc)) return false;
-: 2505: // Template arguments are forward-declarable...usually.
12278: 2506: DetermineForwardDeclareStatusForTemplateArg(current_ast_node());
12278: 2507: return true;
12278: 2508: }
-: 2509:
-: 2510: //------------------------------------------------------------
-: 2511: // Helper routines for visiting and traversing. These helpers
-: 2512: // encode the logic of whether a particular type of object
-: 2513: // can be forward-declared or not.
-: 2514:
-: 2515: // TODO(csilvers): get rid of in_forward_declare_context() and make
-: 2516: // this the canonical place to figure out if we can forward-declare.
1704: 2517: bool CanForwardDeclareType(const ASTNode* ast_node) const {
5112: 2518: CHECK_(ast_node->IsA<Type>());
-: 2519: // Cannot forward-declare an enum even if it's in a forward-declare context.
-: 2520: // TODO(vsapsai): make enums forward-declarable in C++11.
1704: 2521: if (ast_node->IsA<EnumType>())
86: 2522: return false;
-: 2523: // If we're in a forward-declare context, well then, there you have it.
1618: 2524: if (ast_node->in_forward_declare_context())
254: 2525: return true;
-: 2526: // If we're in a typedef, we don't want to forward-declare even if
-: 2527: // we're a pointer. ('typedef Foo* Bar; Bar x; x->a' needs full
-: 2528: // type of Foo.)
1364: 2529: if (ast_node->ParentIsA<TypedefDecl>())
101: 2530: return false;
-: 2531:
-: 2532: // If we ourselves are a forward-decl -- that is, we're the type
-: 2533: // component of a forward-declaration (which would be our parent
-: 2534: // AST node) -- then we're forward-declarable by definition.
1263: 2535: if (const TagDecl* parent
1263: 2536: = current_ast_node()->template GetParentAs<TagDecl>()) {
25: 2537: if (IsForwardDecl(parent))
#####: 2538: return true;
25: 2539: }
-: 2540:
-: 2541: // Another place we disregard what the language allows: if we're
-: 2542: // a dependent type, in theory we can be forward-declared. But
-: 2543: // we require the full definition anyway, so all the template
-: 2544: // callers don't have to provide it instead. Thus we don't
-: 2545: // run the following commented-out code (left here for reference):
-: 2546: //if (ast_node->GetAs<TemplateSpecializationType>()->isDependentType())
-: 2547: // return false;
-: 2548:
-: 2549: // Read past elaborations like 'class' keyword or namespaces.
2626: 2550: while (ast_node->ParentIsA<ElaboratedType>()) {
100: 2551: ast_node = ast_node->parent();
100: 2552: }
-: 2553:
-: 2554: // Now there are two options: either we have a type or we have a declaration
-: 2555: // involving a type.
1263: 2556: const Type* parent_type = ast_node->GetParentAs<Type>();
1263: 2557: if (parent_type == NULL) {
-: 2558: // Since it's not a type, it must be a decl.
-: 2559: // Our target here is record members, all of which derive from ValueDecl.
1011: 2560: if (const ValueDecl *decl = ast_node->GetParentAs<ValueDecl>()) {
-: 2561: // We can shortcircuit static data member declarations immediately,
-: 2562: // they can always be forward-declared.
326: 2563: if (const VarDecl *var_decl = DynCastFrom(decl)) {
225: 2564: if (!var_decl->isThisDeclarationADefinition() &&
#####: 2565: var_decl->isStaticDataMember()) {
#####: 2566: return true;
-: 2567: }
225: 2568: }
-: 2569:
326: 2570: parent_type = GetTypeOf(decl);
326: 2571: }
1011: 2572: }
-: 2573:
-: 2574: // TODO(csilvers): should probably just be IsPointerOrReference
1841: 2575: return parent_type && IsPointerOrReferenceAsWritten(parent_type);
1704: 2576: }
-: 2577:
-: 2578: protected:
-: 2579: const IwyuPreprocessorInfo& preprocessor_info() const {
4526: 2580: return visitor_state_->preprocessor_info;
-: 2581: }
-: 2582:
426: 2583: void AddUsingDeclaration(const NamedDecl* target_decl, // what's being used
426: 2584: const UsingDecl* using_decl) {
426: 2585: visitor_state_->using_declarations.insert(make_pair(target_decl,
-: 2586: using_decl));
426: 2587: }
-: 2588:
-: 2589: private:
-: 2590: template <typename T> friend class IwyuBaseAstVisitor;
-: 2591:
1602: 2592: bool IsProcessedOverloadLoc(SourceLocation loc) const {
1602: 2593: return ContainsKey(visitor_state_->processed_overload_locs, loc);
-: 2594: }
-: 2595:
1681: 2596: void AddProcessedOverloadLoc(SourceLocation loc) {
1681: 2597: visitor_state_->processed_overload_locs.insert(loc);
1681: 2598: }
-: 2599:
3074: 2600: const UsingDecl* GetUsingDeclarationOf(const NamedDecl* decl,
3074: 2601: const DeclContext* using_context) {
-: 2602: // We look through all the using-decls of the given decl. We
-: 2603: // limit them to ones that are visible from the decl-context we're
-: 2604: // currently in (that is, what namespaces we're in). Of those, we
-: 2605: // pick the one that's in the same file as decl, if possible,
-: 2606: // otherwise we pick one arbitrarily.
3074: 2607: const UsingDecl* retval = NULL;
3074: 2608: vector<const UsingDecl*> using_decls
3074: 2609: = FindInMultiMap(visitor_state_->using_declarations, decl);
9262: 2610: for (Each<const UsingDecl*> it(&using_decls); !it.AtEnd(); ++it) {
20: 2611: if (!(*it)->getDeclContext()->Encloses(using_context))
14: 2612: continue;
12: 2613: if (GetFileEntry(decl) == GetFileEntry(*it) || // in same file, prefer
-: 2614: retval == NULL) { // not in same file, but better than nothing
6: 2615: retval = *it;
6: 2616: }
6: 2617: }
3074: 2618: return retval;
3074: 2619: }
-: 2620:
-: 2621: // Do not any variables here! If you do, they will not be shared
-: 2622: // between the normal iwyu ast visitor and the
-: 2623: // template-instantiation visitor, which is almost always a mistake.
-: 2624: // Instead, add them to the VisitorState struct, above.
-: 2625: VisitorState* const visitor_state_;
-: 2626:};
-: 2627:
-: 2628:
-: 2629:// ----------------------------------------------------------------------
-: 2630:// --- InstantiatedTemplateVisitor
-: 2631:// ----------------------------------------------------------------------
-: 2632://
-: 2633:// This class is used to find all template-specified types used in an
-: 2634:// instantiated template class, function, or method -- or rather, all
-: 2635:// such types that are used in a way that can't be forward-declared.
-: 2636:// That is, for
-: 2637:// template<class T, class U> int Myfunc() { T* t; U u; Thirdclass z; }
-: 2638:// if we saw an instantiation such as myfunc<Foo, Bar>, we would pass
-: 2639:// that instantiation to this traversal class, and it would report
-: 2640:// that Bar is used in a non-forward-declarable way. (It would not
-: 2641:// report Foo, which is used only in a forward-declarable way, and
-: 2642:// would not report Thirdclass, which is not a type specified in a
-: 2643:// template.)
-: 2644://
-: 2645:// This class has two main entry points: one for instantiated
-: 2646:// template functions and methods (including static methods,
-: 2647:// constructor calls, and operator overloads), and one for
-: 2648:// instantiated template classes.
-: 2649://
-: 2650:// In each case, it is given the appropriate node from the AST that
-: 2651:// captures the instantiation (a TemplateSpecializationType or
-: 2652:// CallExpr), and returns a set of Type* nodes of types that are used
-: 2653:// in a non-forward-declarable way. Note it's safe to call this even
-: 2654:// on non-templatized functions and classes; we'll just always return
-: 2655:// the empty set in that case.
-: 2656://
-: 2657:// The traversal of the AST is done via RecursiveASTVisitor, which uses
-: 2658:// CRTP (http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)
-: 2659:// TODO(csilvers): move this to its own file?
-: 2660:
#####: 2661:class InstantiatedTemplateVisitor
-: 2662: : public IwyuBaseAstVisitor<InstantiatedTemplateVisitor> {
-: 2663: public:
-: 2664: typedef IwyuBaseAstVisitor<InstantiatedTemplateVisitor> Base;
-: 2665:
2: 2666: InstantiatedTemplateVisitor(VisitorState* visitor_state)
1: 2667: : Base(visitor_state) {
1: 2668: Clear();
2: 2669: }
-: 2670:
-: 2671: //------------------------------------------------------------
-: 2672: // Public entry points
-: 2673:
-: 2674: // ScanInstantiatedFunction() looks through the template definition of
-: 2675: // the given function as well as the definitions of all functions
-: 2676: // called from it (directly or indirectly) and records all template
-: 2677: // type arguments fully used by them and all methods used by them.
-: 2678: // The "fully used type arguments" are a subset of
-: 2679: // tpl_type_args_of_interest, which are the types we care about, and
-: 2680: // usually explicitly written at the call site.
-: 2681: //
-: 2682: // ScanInstantiatedType() is similar, except that it looks through
-: 2683: // the definition of a class template instead of a statement.
-: 2684:
-: 2685: // resugar_map is a map from an unsugared (canonicalized) template
-: 2686: // type to the template type as written (or as close as we can find
-: 2687: // to it). If a type is not in resugar-map, it might be due to a
-: 2688: // recursive template call and encode a template type we don't care
-: 2689: // about ourselves. If it's in the resugar_map but with a NULL
-: 2690: // value, it's a default template parameter, that the
-: 2691: // template-caller may or may not be responsible for.
-: 2692: void ScanInstantiatedFunction(
426: 2693: const FunctionDecl* fn_decl, const Type* parent_type,
426: 2694: const ASTNode* caller_ast_node,
426: 2695: const map<const Type*, const Type*>& resugar_map) {
426: 2696: Clear();
426: 2697: caller_ast_node_ = caller_ast_node;
426: 2698: resugar_map_ = resugar_map;
-: 2699:
-: 2700: // Make sure that the caller didn't already put the decl on the ast-stack.
1278: 2701: CHECK_(caller_ast_node->GetAs<Decl>() != fn_decl && "AST node already set");
-: 2702: // caller_ast_node requires a non-const ASTNode, but our node is
-: 2703: // const. This cast is safe because we don't do anything with this
-: 2704: // node (instead, we immediately push a new node on top of it).
426: 2705: set_current_ast_node(const_cast<ASTNode*>(caller_ast_node));
-: 2706:
426: 2707: TraverseExpandedTemplateFunctionHelper(fn_decl, parent_type);
426: 2708: }
-: 2709:
-: 2710: // This isn't a Stmt, but sometimes we need to fully instantiate
-: 2711: // a template class to get at a field of it, for instance:
-: 2712: // MyClass<T>::size_type s;
-: 2713: void ScanInstantiatedType(
138: 2714: const Type* type, const ASTNode* caller_ast_node,
138: 2715: const map<const Type*, const Type*>& resugar_map) {
138: 2716: Clear();
138: 2717: caller_ast_node_ = caller_ast_node;
138: 2718: resugar_map_ = resugar_map;
-: 2719:
-: 2720: // Make sure that the caller didn't already put the type on the ast-stack.
414: 2721: CHECK_(caller_ast_node->GetAs<Type>() != type && "AST node already set");
-: 2722: // caller_ast_node requires a non-const ASTNode, but our node is
-: 2723: // const. This cast is safe because we don't do anything with this
-: 2724: // node (instead, we immediately push a new node on top of it).
138: 2725: set_current_ast_node(const_cast<ASTNode*>(caller_ast_node));
-: 2726:
-: 2727: // As in TraverseExpandedTemplateFunctionHelper, we ignore all AST nodes
-: 2728: // that will be reported when we traverse the uninstantiated type.
138: 2729: if (const NamedDecl* type_decl_as_written = TypeToDeclAsWritten(type)) {
138: 2730: AstFlattenerVisitor nodeset_getter(compiler());
138: 2731: nodes_to_ignore_ = nodeset_getter.GetNodesBelow(
-: 2732: const_cast<NamedDecl*>(type_decl_as_written));
138: 2733: }
-: 2734:
138: 2735: TraverseType(QualType(type, 0));
138: 2736: }
-: 2737:
-: 2738: //------------------------------------------------------------
-: 2739: // Implements virtual methods from Base.
-: 2740:
-: 2741: // When checking a template instantiation, we don't care where the
-: 2742: // template definition is, so we never have any reason to ignore a
-: 2743: // node.
-: 2744: virtual bool CanIgnoreCurrentASTNode() const {
-: 2745: // TODO(csilvers): call CanIgnoreType() if we're a type.
13138: 2746: return nodes_to_ignore_.Contains(*current_ast_node());
-: 2747: }
-: 2748:
-: 2749: // For template instantiations, we want to print the symbol even if
-: 2750: // it's not from the main compilation unit.
-: 2751: virtual bool ShouldPrintSymbolFromCurrentFile() const {
29138: 2752: return GlobalFlags().verbose >= 5;
-: 2753: }
-: 2754:
#####: 2755: virtual string GetSymbolAnnotation() const { return " in tpl"; }
-: 2756:
-: 2757: // We only care about types that would have been dependent in the
-: 2758: // uninstantiated template: that is, SubstTemplateTypeParmType types
-: 2759: // or types derived from them. We use nodes_to_ignore_ to select
-: 2760: // down to those. Even amongst subst-type, we only want ones in the
-: 2761: // resugar-map: the rest we have chosen to ignore for some reason.
5510: 2762: virtual bool CanIgnoreType(const Type* type) const {
5510: 2763: if (nodes_to_ignore_.Contains(type))
#####: 2764: return true;
-: 2765:
-: 2766: // If we're a default template argument, we should ignore the type
-: 2767: // if the template author intend-to-provide it, but otherwise we
-: 2768: // should not ignore it -- the caller is responsible for the type.
-: 2769: // This captures cases like hash_set<Foo>, where the caller is
-: 2770: // responsible for defining hash<Foo>.
-: 2771: // SomeInstantiatedTemplateIntendsToProvide handles the case we
-: 2772: // have a templated class that #includes "foo.h" and has a
-: 2773: // scoped_ptr<Foo>: we say the templated class provides Foo, even
-: 2774: // though it's scoped_ptr.h that's actually trying to call
-: 2775: // Foo::Foo and ::~Foo.
-: 2776: // TODO(csilvers): this isn't ideal: ideally we'd want
-: 2777: // 'TheInstantiatedTemplateForWhichTypeWasADefaultTemplateArgumentIntendsToProvide',
-: 2778: // but clang doesn't store that information.
5510: 2779: if (IsDefaultTemplateParameter(type))
237: 2780: return SomeInstantiatedTemplateIntendsToProvide(type);
-: 2781:
-: 2782: // If we're not in the resugar-map at all, we're not a type
-: 2783: // corresponding to the template being instantiated, so we
-: 2784: // can be ignored.
5273: 2785: type = RemoveSubstTemplateTypeParm(type);
5273: 2786: return !ContainsKey(resugar_map_, type);
5510: 2787: }
-: 2788:
-: 2789: // We ignore function calls in nodes_to_ignore_, which were already
-: 2790: // handled by the template-as-written, and function names that we
-: 2791: // are not responsible for because the template code is (for
-: 2792: // instance, we're not responsible for a vector's call to
-: 2793: // allocator::allocator(), because <vector> provides it for us).
2707: 2794: virtual bool CanIgnoreDecl(const Decl* decl) const {
2707: 2795: return nodes_to_ignore_.Contains(decl);
-: 2796: }
-: 2797:
-: 2798: // We always attribute type uses to the template instantiator. For
-: 2799: // decls, we do unless it looks like the template "intends to
-: 2800: // provide" the decl, by #including the file that defines the decl
-: 2801: // (if templates call other templates, we have to find the right
-: 2802: // template).
631: 2803: virtual void ReportDeclUseWithComment(SourceLocation used_loc,
631: 2804: const NamedDecl* decl,
631: 2805: const char* comment) {
631: 2806: const SourceLocation actual_used_loc = GetLocOfTemplateThatProvides(decl);
631: 2807: if (actual_used_loc.isValid()) {
-: 2808: // If a template is responsible for this decl, then we don't add
-: 2809: // it to the cache; the cache is only for decls that the
-: 2810: // original caller is responsible for.
537: 2811: Base::ReportDeclUseWithComment(actual_used_loc, decl, comment);
537: 2812: } else {
-: 2813: // Let all the currently active types and decls know about this
-: 2814: // report, so they can update their cache entries.
424: 2815: for (Each<CacheStoringScope*> it(&cache_storers_); !it.AtEnd(); ++it)
71: 2816: (*it)->NoteReportedDecl(decl);
94: 2817: Base::ReportDeclUseWithComment(caller_loc(), decl, comment);
-: 2818: }
631: 2819: }
-: 2820:
545: 2821: virtual void ReportTypeUseWithComment(SourceLocation used_loc,
545: 2822: const Type* type,
545: 2823: const char* comment) {
-: 2824: // clang desugars template types, so Foo<MyTypedef>() gets turned
-: 2825: // into Foo<UnderlyingType>(). Try to convert back.
545: 2826: type = ResugarType(type);
3159: 2827: for (Each<CacheStoringScope*> it(&cache_storers_); !it.AtEnd(); ++it)
762: 2828: (*it)->NoteReportedType(type);
545: 2829: Base::ReportTypeUseWithComment(caller_loc(), type, comment);
545: 2830: }
-: 2831:
-: 2832: //------------------------------------------------------------
-: 2833: // Overridden traverse-style methods from Base.
-: 2834:
-: 2835: // The 'convenience' HandleFunctionCall is perfect for us!
822: 2836: bool HandleFunctionCall(FunctionDecl* callee, const Type* parent_type,
822: 2837: const clang::Expr* calling_expr) {
822: 2838: if (const Type* resugared_type = ResugarType(parent_type))
678: 2839: parent_type = resugared_type;
822: 2840: if (!Base::HandleFunctionCall(callee, parent_type, calling_expr))
#####: 2841: return false;
2454: 2842: if (!callee || CanIgnoreCurrentASTNode() || CanIgnoreDecl(callee))
44: 2843: return true;
778: 2844: return TraverseExpandedTemplateFunctionHelper(callee, parent_type);
822: 2845: }
-: 2846:
24: 2847: bool TraverseUnaryExprOrTypeTraitExpr(clang::UnaryExprOrTypeTraitExpr* expr) {
24: 2848: if (!Base::TraverseUnaryExprOrTypeTraitExpr(expr)) return false;
24: 2849: if (CanIgnoreCurrentASTNode()) return true;
24: 2850: const Type* arg_type = expr->getTypeOfArgument().getTypePtr();
-: 2851: // Calling sizeof on a reference-to-X is the same as calling it on X.
24: 2852: if (const ReferenceType* reftype = DynCastFrom(arg_type)) {
#####: 2853: arg_type = reftype->getPointeeTypeAsWritten().getTypePtr();
#####: 2854: }
24: 2855: if (const TemplateSpecializationType* type = DynCastFrom(arg_type)) {
-: 2856: // Even though sizeof(MyClass<T>) only requires knowing how much
-: 2857: // storage MyClass<T> takes, the language seems to require that
-: 2858: // MyClass<T> be fully instantiated, even typedefs. (Try
-: 2859: // compiling 'template<class T> struct C { typedef typename T::a t; };
-: 2860: // class S; int main() { return sizeof(C<S>); }'.)
3: 2861: return TraverseDataAndTypeMembersOfClassHelper(type);
-: 2862: }
21: 2863: return true;
24: 2864: }
-: 2865:
-: 2866: bool TraverseTemplateSpecializationTypeHelper(
894: 2867: const clang::TemplateSpecializationType* type) {
934: 2868: if (CanIgnoreCurrentASTNode()) return true;
854: 2869: if (CanForwardDeclareType(current_ast_node()))
149: 2870: current_ast_node()->set_in_forward_declare_context(true);
854: 2871: return TraverseDataAndTypeMembersOfClassHelper(type);
894: 2872: }
-: 2873: bool TraverseTemplateSpecializationType(
173: 2874: clang::TemplateSpecializationType* type) {
173: 2875: if (!Base::TraverseTemplateSpecializationType(type)) return false;
173: 2876: return TraverseTemplateSpecializationTypeHelper(type);
173: 2877: }
-: 2878: bool TraverseTemplateSpecializationTypeLoc(
721: 2879: clang::TemplateSpecializationTypeLoc typeloc) {
721: 2880: if (!Base::TraverseTemplateSpecializationTypeLoc(typeloc)) return false;
721: 2881: return TraverseTemplateSpecializationTypeHelper(typeloc.getTypePtr());
721: 2882: }
-: 2883:
-: 2884: bool TraverseSubstTemplateTypeParmTypeHelper(
1172: 2885: const clang::SubstTemplateTypeParmType* type) {
1173: 2886: if (CanIgnoreCurrentASTNode()) return true;
1828: 2887: if (CanIgnoreType(type)) return true;
514: 2888: const Type* actual_type = ResugarType(type);
1542: 2889: CHECK_(actual_type && "If !CanIgnoreType(), we should be resugar-able");
514: 2890: return TraverseType(QualType(actual_type, 0));
1172: 2891: }
-: 2892: // When we see a template argument used inside an instantiated
-: 2893: // template, we want to explore the type recursively. For instance
-: 2894: // if we see Inner<Outer<Foo> >(), we want to recurse onto Foo.
-: 2895: bool TraverseSubstTemplateTypeParmType(
10: 2896: clang::SubstTemplateTypeParmType* type) {
10: 2897: if (!Base::TraverseSubstTemplateTypeParmType(type))
#####: 2898: return false;
10: 2899: return TraverseSubstTemplateTypeParmTypeHelper(type);
10: 2900: }
-: 2901: bool TraverseSubstTemplateTypeParmTypeLoc(
1162: 2902: clang::SubstTemplateTypeParmTypeLoc typeloc) {
1162: 2903: if (!Base::TraverseSubstTemplateTypeParmTypeLoc(typeloc))
#####: 2904: return false;
1162: 2905: return TraverseSubstTemplateTypeParmTypeHelper(typeloc.getTypePtr());
1162: 2906: }
-: 2907:
-: 2908: // These do the actual work of finding the types to return. Our
-: 2909: // task is made easier since (at least in theory), every time we
-: 2910: // instantiate a template type, the instantiation has type
-: 2911: // SubstTemplateTypeParmTypeLoc in the AST tree.
1172: 2912: bool VisitSubstTemplateTypeParmType(clang::SubstTemplateTypeParmType* type) {
1173: 2913: if (CanIgnoreCurrentASTNode()) return true;
1828: 2914: if (CanIgnoreType(type)) return true;
-: 2915:
-: 2916: // Figure out how this type was actually written. clang always
-: 2917: // canonicalizes SubstTemplateTypeParmType, losing typedef info, etc.
514: 2918: const Type* actual_type = ResugarType(type);
1542: 2919: CHECK_(actual_type && "If !CanIgnoreType(), we should be resugar-able");
-: 2920:
-: 2921: // TODO(csilvers): whenever we report a type use here, we want to
-: 2922: // do an iwyu check on this type (to see if sub-types are used).
-: 2923:
-: 2924: // If we're a nested-name-specifier class (the Foo in Foo::bar),
-: 2925: // we need our full type info no matter what the context (even if
-: 2926: // we're a pointer, or a template arg, or whatever).
-: 2927: // TODO(csilvers): consider encoding this logic via
-: 2928: // in_forward_declare_context. I think this will require changing
-: 2929: // in_forward_declare_context to yes/no/maybe.
514: 2930: if (current_ast_node()->ParentIsA<NestedNameSpecifier>()) {
5: 2931: ReportTypeUse(CurrentLoc(), actual_type);
5: 2932: return Base::VisitSubstTemplateTypeParmType(type);
-: 2933: }
-: 2934:
-: 2935: // If we're inside a typedef, we don't need our full type info --
-: 2936: // in this case we follow what the C++ language allows and let
-: 2937: // the underlying type of a typedef be forward-declared. This has
-: 2938: // the effect that code like:
-: 2939: // class MyClass;
-: 2940: // template<class T> struct Foo { typedef T value_type; ... }
-: 2941: // Foo<MyClass> f;
-: 2942: // does not make us require the full type of MyClass. The idea
-: 2943: // is that using Foo<MyClass>::value_type already requires the
-: 2944: // type for MyClass, so it doesn't make sense for the typedef
-: 2945: // to require it as well. TODO(csilvers): this doesn't really
-: 2946: // make any sense. Who figures out we need the full type if
-: 2947: // you do 'Foo<MyClass>::value_type m;'?
4935: 2948: for (const ASTNode* ast_node = current_ast_node();
3917: 2949: ast_node != caller_ast_node_; ast_node = ast_node->parent()) {
4026: 2950: if (ast_node->IsA<TypedefDecl>())
109: 2951: return Base::VisitSubstTemplateTypeParmType(type);
3917: 2952: }
-: 2953:
-: 2954: // sizeof(a reference type) is the same as sizeof(underlying type).
-: 2955: // We have to handle that specially here, or else we'll say the
-: 2956: // reference is forward-declarable, below.
400: 2957: if (current_ast_node()->ParentIsA<UnaryExprOrTypeTraitExpr>() &&
10: 2958: isa<ReferenceType>(actual_type)) {
#####: 2959: const ReferenceType* actual_reftype = cast<ReferenceType>(actual_type);
#####: 2960: ReportTypeUse(CurrentLoc(),
#####: 2961: actual_reftype->getPointeeTypeAsWritten().getTypePtr());
#####: 2962: return Base::VisitSubstTemplateTypeParmType(type);
-: 2963: }
-: 2964:
-: 2965: // If we're used in a forward-declare context (MyFunc<T>() { T* t; }),
-: 2966: // or are ourselves a pointer type (MyFunc<Myclass*>()),
-: 2967: // we don't need to do anything: we're fine being forward-declared.
400: 2968: if (current_ast_node()->in_forward_declare_context())
143: 2969: return Base::VisitSubstTemplateTypeParmType(type);
-: 2970:
257: 2971: if (current_ast_node()->ParentIsA<PointerType>() ||
176: 2972: current_ast_node()->ParentIsA<LValueReferenceType>() ||
162: 2973: IsPointerOrReferenceAsWritten(actual_type))
117: 2974: return Base::VisitSubstTemplateTypeParmType(type);
-: 2975:
-: 2976: // We attribute all uses in an instantiated template to the
-: 2977: // template's caller.
140: 2978: ReportTypeUse(caller_loc(), actual_type);
140: 2979: return Base::VisitSubstTemplateTypeParmType(type);
1172: 2980: }
-: 2981:
-: 2982: // If constructing an object, check the type we're constructing.
-: 2983: // Normally we'd see that type later, when traversing the return
-: 2984: // type of the constructor-decl, but if we wait for that, we'll lose
-: 2985: // any SubstTemplateTypeParmType's we have (we lose all
-: 2986: // SubstTemplateTypeParmType's going from Expr to Decl).
-: 2987: // TODO(csilvers): This should maybe move to HandleFunctionCall.
238: 2988: bool VisitCXXConstructExpr(clang::CXXConstructExpr* expr) {
252: 2989: if (CanIgnoreCurrentASTNode()) return true;
224: 2990: const Type* class_type = GetTypeOf(expr);
396: 2991: if (CanIgnoreType(class_type)) return true;
-: 2992:
-: 2993: // If the ctor type is a SubstTemplateTypeParmType, get the type-as-typed.
52: 2994: const Type* actual_type = ResugarType(class_type);
156: 2995: CHECK_(actual_type && "If !CanIgnoreType(), we should be resugar-able");
52: 2996: ReportTypeUse(caller_loc(), actual_type);
52: 2997: return Base::VisitCXXConstructExpr(expr);
238: 2998: }
-: 2999:
-: 3000: private:
-: 3001: // Clears the state of the visitor.
-: 3002: void Clear() {
565: 3003: caller_ast_node_ = NULL;
565: 3004: resugar_map_.clear();
565: 3005: traversed_decls_.clear();
565: 3006: nodes_to_ignore_.clear();
565: 3007: cache_storers_.clear();
565: 3008: }
-: 3009:
-: 3010: // If we see the instantiated template using a type or decl (such as
-: 3011: // std::allocator), we want to know if the author of the template is
-: 3012: // providing the type or decl, so the code using the instantiated
-: 3013: // template doesn't have to. For instance:
-: 3014: // vector<int, /*allocator<int>*/> v; // in foo.cc
-: 3015: // Does <vector> provide the definition of allocator<int>? If not,
-: 3016: // foo.cc will have to #include <allocator>.
-: 3017: // We say the template-as-written does provide the decl if it, or
-: 3018: // any other header seen since we started instantiating the
-: 3019: // template, sees it. The latter requirement is to deal with a
-: 3020: // situation like this: we have a templated class that #includes
-: 3021: // "foo.h" and has a scoped_ptr<Foo>; we say the templated class
-: 3022: // provides Foo, even though it's scoped_ptr.h that's actually
-: 3023: // trying to call Foo::Foo and Foo::~Foo.
868: 3024: SourceLocation GetLocOfTemplateThatProvides(const NamedDecl* decl) const {
868: 3025: if (!decl)
#####: 3026: return SourceLocation(); // an invalid source-loc
2295: 3027: for (const ASTNode* ast_node = current_ast_node();
559: 3028: ast_node != caller_ast_node_; ast_node = ast_node->parent()) {
2646: 3029: if (preprocessor_info().PublicHeaderIntendsToProvide(
1323: 3030: GetFileEntry(ast_node->GetLocation()),
1323: 3031: GetFileEntry(decl)))
764: 3032: return ast_node->GetLocation();
559: 3033: }
104: 3034: return SourceLocation(); // an invalid source-loc
868: 3035: }
-: 3036:
-: 3037: bool SomeInstantiatedTemplateIntendsToProvide(const NamedDecl* decl) const {
-: 3038: return GetLocOfTemplateThatProvides(decl).isValid();
-: 3039: }
237: 3040: bool SomeInstantiatedTemplateIntendsToProvide(const Type* type) const {
237: 3041: type = RemoveSubstTemplateTypeParm(type);
237: 3042: type = RemovePointersAndReferences(type); // get down to the decl
237: 3043: if (const NamedDecl* decl = TypeToDeclAsWritten(type))
237: 3044: return GetLocOfTemplateThatProvides(decl).isValid();
#####: 3045: return true; // we always provide non-decl types like int, etc.
237: 3046: }
-: 3047:
-: 3048: // For a SubstTemplateTypeParmType, says whether it corresponds to a
-: 3049: // default template parameter (one not explicitly specified when the
-: 3050: // class was instantiated) or not. We store this in resugar_map by
-: 3051: // having the value be NULL.
5510: 3052: bool IsDefaultTemplateParameter(const Type* type) const {
5510: 3053: type = RemoveSubstTemplateTypeParm(type);
5510: 3054: return ContainsKeyValue(resugar_map_, type, static_cast<Type*>(NULL));
-: 3055: }
-: 3056:
-: 3057: // clang desugars template types, so Foo<MyTypedef>() gets turned
-: 3058: // into Foo<UnderlyingType>(). We can 'resugar' using resugar_map_.
-: 3059: // If we're not in the resugar-map, then we weren't canonicalized,
-: 3060: // so we can just use the input type unchanged.
2447: 3061: const Type* ResugarType(const Type* type) const {
2447: 3062: type = RemoveSubstTemplateTypeParm(type);
-: 3063: // If we're the resugar-map but with a value of NULL, it means
-: 3064: // we're a default template arg, which means we don't have anything
-: 3065: // to resugar to. So just return the input type.
2447: 3066: if (ContainsKeyValue(resugar_map_, type, static_cast<const Type*>(NULL)))
38: 3067: return type;
2409: 3068: return GetOrDefault(resugar_map_, type, type);
2447: 3069: }
-: 3070:
1204: 3071: bool TraverseExpandedTemplateFunctionHelper(const FunctionDecl* fn_decl,
1204: 3072: const Type* parent_type) {
2408: 3073: if (!fn_decl || ContainsKey(traversed_decls_, fn_decl))
154: 3074: return true; // avoid recursion and repetition
1050: 3075: traversed_decls_.insert(fn_decl);
-: 3076:
-: 3077: // If we have cached the reporting done for this decl before,
-: 3078: // report again (but with the new caller_loc this time).
-: 3079: // Otherwise, for all reporting done in the rest of this scope,
-: 3080: // store in the cache for this function.
2100: 3081: if (ReplayUsesFromCache(*FunctionCallsFullUseCache(),
1050: 3082: fn_decl, caller_loc()))
169: 3083: return true;
-: 3084: // Make sure all the types we report in the recursive TraverseDecl
-: 3085: // calls, below, end up in the cache for fn_decl.
881: 3086: CacheStoringScope css(&cache_storers_, FunctionCallsFullUseCache(),
-: 3087: fn_decl, resugar_map_);
-: 3088:
-: 3089: // We want to ignore all nodes that are the same in this
-: 3090: // instantiated function as they are in the uninstantiated version
-: 3091: // of the function. The latter will be reported when we traverse
-: 3092: // the uninstantiated function, so we don't need to re-traverse
-: 3093: // them here.
881: 3094: AstFlattenerVisitor nodeset_getter(compiler());
-: 3095: // This gets to the decl for the (uninstantiated) template-as-written:
881: 3096: const FunctionDecl* decl_as_written
881: 3097: = fn_decl->getTemplateInstantiationPattern();
881: 3098: if (!decl_as_written) {
295: 3099: if (fn_decl->isImplicit()) { // TIP not set up for implicit methods
-: 3100: // TODO(csilvers): handle implicit template methods
214: 3101: } else { // not a templated decl
81: 3102: decl_as_written = fn_decl;
-: 3103: }
295: 3104: }
881: 3105: if (decl_as_written) {
667: 3106: FunctionDecl* const daw = const_cast<FunctionDecl*>(decl_as_written);
667: 3107: nodes_to_ignore_.AddAll(nodeset_getter.GetNodesBelow(daw));
667: 3108: }
-: 3109:
-: 3110: // We need to iterate over the function. We do so even if it's
-: 3111: // an implicit function.
881: 3112: if (fn_decl->isImplicit()) {
214: 3113: if (!TraverseImplicitDeclHelper(const_cast<FunctionDecl*>(fn_decl)))
#####: 3114: return false;
214: 3115: } else {
667: 3116: if (!TraverseDecl(const_cast<FunctionDecl*>(fn_decl)))
#####: 3117: return false;
-: 3118: }
-: 3119:
-: 3120: // If we're a constructor, we also need to construct the entire class,
-: 3121: // even typedefs that aren't used at construct time. Try compiling
-: 3122: // template<class T> struct C { typedef typename T::a t; };
-: 3123: // class S; int main() { C<S> c; }
881: 3124: if (isa<CXXConstructorDecl>(fn_decl)) {
780: 3125: CHECK_(parent_type && "How can a constructor have no parent?");
260: 3126: parent_type = RemoveElaboration(parent_type);
260: 3127: if (!TraverseDataAndTypeMembersOfClassHelper(
260: 3128: dyn_cast<TemplateSpecializationType>(parent_type)))
#####: 3129: return false;
260: 3130: }
881: 3131: return true;
2085: 3132: }
-: 3133:
-: 3134: // Does the actual recursing over data members and type members of
-: 3135: // the instantiated class. Unlike
-: 3136: // TraverseClassTemplateSpecializationDecl() in the base class, it
-: 3137: // does *not* traverse the methods.
-: 3138: bool TraverseDataAndTypeMembersOfClassHelper(
1117: 3139: const TemplateSpecializationType* type) {
1117: 3140: if (!type)
103: 3141: return true;
-: 3142:
-: 3143: // No point in doing traversal if we're forward-declared
1014: 3144: if (current_ast_node()->in_forward_declare_context())
154: 3145: return true;
-: 3146:
1720: 3147: while (type->isTypeAlias()) {
#####: 3148: type = DynCastFrom(type->getAliasedType().getTypePtr());
#####: 3149: if (!type)
#####: 3150: return true;
#####: 3151: }
-: 3152:
-: 3153: // If we're a dependent type, we only try to be analyzed if we're
-: 3154: // in the precomputed list -- in general, the only thing clang
-: 3155: // tells us about dependent types is their name (which is all we
-: 3156: // need for the precomputed list!). This means iwyu will properly
-: 3157: // analyze the use of SomeClass in code like 'map<T, SomeClass>',
-: 3158: // but not in 'MyMap<T, SomeClass>', since we have precomputed
-: 3159: // information about the STL map<>, but not the user type MyMap.
-: 3160: // TODO(csilvers): do better here.
860: 3161: if (type->isDependentType()) {
-: 3162: // TODO(csilvers): This is currently always a noop; need to fix
-: 3163: // GetTplTypeResugarMapForClassNoComponentTypes to do something
-: 3164: // useful for dependent types.
31: 3165: ReplayClassMemberUsesFromPrecomputedList(type); // best-effort
31: 3166: return true;
-: 3167: }
-: 3168:
829: 3169: const ClassTemplateSpecializationDecl* class_decl
829: 3170: = DynCastFrom(TypeToDeclAsWritten(type));
2487: 3171: CHECK_(class_decl && "TemplateSpecializationType is not a TplSpecDecl?");
829: 3172: if (ContainsKey(traversed_decls_, class_decl))
209: 3173: return true; // avoid recursion & repetition
620: 3174: traversed_decls_.insert(class_decl);
-: 3175:
-: 3176: // If we have cached the reporting done for this decl before,
-: 3177: // report again (but with the new caller_loc this time).
-: 3178: // Otherwise, for all reporting done in the rest of this scope,
-: 3179: // store in the cache for this function.
1240: 3180: if (ReplayUsesFromCache(*ClassMembersFullUseCache(),
620: 3181: class_decl, caller_loc()))
121: 3182: return true;
499: 3183: if (ReplayClassMemberUsesFromPrecomputedList(type))
50: 3184: return true;
-: 3185:
-: 3186: // Make sure all the types we report in the recursive TraverseDecl
-: 3187: // calls, below, end up in the cache for class_decl.
449: 3188: CacheStoringScope css(&cache_storers_, ClassMembersFullUseCache(),
-: 3189: class_decl, resugar_map_);
-: 3190:
449: 3191: for (DeclContext::decl_iterator it = class_decl->decls_begin();
8297: 3192: it != class_decl->decls_end(); ++it) {
6318: 3193: if (isa<CXXMethodDecl>(*it) || isa<FunctionTemplateDecl>(*it))
1840: 3194: continue;
2084: 3195: if (!TraverseDecl(*it))
#####: 3196: return false;
2084: 3197: }
-: 3198:
-: 3199: // Most methods on template classes are instantiated when they're
-: 3200: // called, and we don't need to deal with them here. But virtual
-: 3201: // methods are instantiated when the class's key method is
-: 3202: // instantiated, and since template classes rarely have a key
-: 3203: // method, it means they're instantiated whenever the class is
-: 3204: // instantiated. So we need to instantiate virtual methods here.
449: 3205: for (DeclContext::decl_iterator it = class_decl->decls_begin();
8297: 3206: it != class_decl->decls_end(); ++it) {
3924: 3207: if (const CXXMethodDecl* method_decl = DynCastFrom(*it)) {
1530: 3208: if (method_decl->isVirtual()) {
#####: 3209: if (!TraverseExpandedTemplateFunctionHelper(method_decl, type))
#####: 3210: return false;
#####: 3211: }
1530: 3212: }
3924: 3213: }
-: 3214:
449: 3215: return true;
1566: 3216: }
-: 3217:
-: 3218: //------------------------------------------------------------
-: 3219: // Cache methods. Caches hold the list of full uses found when we
-: 3220: // last instantiated a given decl, saving a lot of tree-walking if
-: 3221: // we have to do it again.
-: 3222:
-: 3223: // Returns true if we replayed uses, false if key isn't in the cache.
1670: 3224: bool ReplayUsesFromCache(const FullUseCache& cache, const NamedDecl* key,
1670: 3225: SourceLocation use_loc) {
1670: 3226: if (!cache.Contains(key, resugar_map_))
1380: 3227: return false;
580: 3228: VERRS(6) << "(Replaying full-use information from the cache for "
#####: 3229: << key->getQualifiedNameAsString() << ")\n";
290: 3230: ReportTypesUse(use_loc, cache.GetFullUseTypes(key, resugar_map_));
290: 3231: ReportDeclsUse(use_loc, cache.GetFullUseDecls(key, resugar_map_));
290: 3232: return true;
1670: 3233: }
-: 3234:
-: 3235: // We precompute (hard-code) results of calling
-: 3236: // TraverseDataAndTypeMembersOfClassHelper for some types (mostly
-: 3237: // STL types). This way we don't even need to traverse them once.
-: 3238: // Returns true iff we did appropriate reporting for this type.
-: 3239: bool ReplayClassMemberUsesFromPrecomputedList(
530: 3240: const TemplateSpecializationType* tpl_type) {
1060: 3241: if (current_ast_node() && current_ast_node()->in_forward_declare_context())
#####: 3242: return true; // never depend on any types if a fwd-decl
-: 3243:
530: 3244: const NamedDecl* tpl_decl = TypeToDeclAsWritten(tpl_type);
-: 3245:
-: 3246: // This says how the template-args are used by this hard-coded type
-: 3247: // (a set<>, or map<>, or ...), to avoid having to recurse into them.
530: 3248: const map<const Type*, const Type*>& resugar_map_for_precomputed_type =
530: 3249: FullUseCache::GetPrecomputedResugarMap(tpl_type);
-: 3250: // But we need to reconcile that with the types-of-interest, as
-: 3251: // stored in resugar_map_. To do this, we take only those entries
-: 3252: // from resugar_map_for_precomputed_type that are also present in
-: 3253: // resugar_map_. We consider type components, so if
-: 3254: // resugar_map_for_precomputed_type has less_than<Foo> or hash<Foo>,
-: 3255: // we'll add those in even if resugar_map_ only includes 'Foo'.
530: 3256: map<const Type*, const Type*> resugar_map;
530: 3257: for (Each<const Type*, const Type*> it(&resugar_map_for_precomputed_type);
1282: 3258: !it.AtEnd(); ++it) {
-: 3259: // TODO(csilvers): for default template args, it->first is sometimes
-: 3260: // a RecordType even when it's a template specialization. Figure out
-: 3261: // how to get the proper type components in that situation.
111: 3262: const set<const Type*> type_components = GetComponentsOfType(it->first);
111: 3263: if (ContainsAnyKey(resugar_map_, type_components)) {
104: 3264: resugar_map.insert(*it);
104: 3265: }
111: 3266: }
530: 3267: if (resugar_map.empty())
480: 3268: return false;
-: 3269:
100: 3270: VERRS(6) << "(Using pre-computed list of full-use information for "
#####: 3271: << tpl_decl->getQualifiedNameAsString() << ")\n";
-: 3272: // For entries with a non-NULL value, we report the value, which
-: 3273: // is the unsugared type, as being fully used. Entries with a
-: 3274: // NULL value are default template args, and we only report them
-: 3275: // if the template class doesn't intend-to-provide them.
358: 3276: for (Each<const Type*, const Type*> it(&resugar_map); !it.AtEnd(); ++it) {
104: 3277: const Type* resugared_type = NULL;
104: 3278: if (it->second) {
55: 3279: resugared_type = it->second;
55: 3280: } else {
49: 3281: const NamedDecl* resugared_decl = TypeToDeclAsWritten(it->first);
98: 3282: if (!preprocessor_info().PublicHeaderIntendsToProvide(
49: 3283: GetFileEntry(tpl_decl), GetFileEntry(resugared_decl)))
#####: 3284: resugared_type = it->first;
-: 3285: }
159: 3286: if (resugared_type && !resugared_type->isPointerType()) {
55: 3287: ReportTypeUse(caller_loc(), resugared_type);
-: 3288: // For a templated type, check the template args as well.
55: 3289: if (const TemplateSpecializationType* spec_type
55: 3290: = DynCastFrom(resugared_type)) {
#####: 3291: TraverseDataAndTypeMembersOfClassHelper(spec_type);
#####: 3292: }
55: 3293: }
104: 3294: }
50: 3295: return true;
1060: 3296: }
-: 3297:
-: 3298: //------------------------------------------------------------
-: 3299: // Member accessors.
-: 3300:
-: 3301: SourceLocation caller_loc() const {
2556: 3302: return caller_ast_node_->GetLocation();
-: 3303: }
-: 3304:
-: 3305: //------------------------------------------------------------
-: 3306: // Member variables.
-: 3307:
-: 3308: // The AST-chain when this template was instantiated.
-: 3309: const ASTNode* caller_ast_node_;
-: 3310:
-: 3311: // resugar_map is a map from an unsugared (canonicalized) template
-: 3312: // type to the template type as written (or as close as we can find
-: 3313: // to it). If a type is not in resugar-map, it might be due to a
-: 3314: // recursive template call and encode a template type we don't care
-: 3315: // about ourselves. If it's in the resugar_map but with a NULL
-: 3316: // value, it's a default template parameter, that the
-: 3317: // template-caller may or may not be responsible for.
-: 3318: map<const Type*, const Type*> resugar_map_;
-: 3319:
-: 3320: // Used to avoid recursion in the *Helper() methods.
-: 3321: set<const Decl*> traversed_decls_;
-: 3322:
-: 3323: AstFlattenerVisitor::NodeSet nodes_to_ignore_;
-: 3324:
-: 3325: // The current set of nodes we're updating cache entries for.
-: 3326: set<CacheStoringScope*> cache_storers_;
-: 3327:}; // class InstantiatedTemplateVisitor
-: 3328:
-: 3329:
-: 3330:// ----------------------------------------------------------------------
-: 3331:// --- IwyuAstConsumer
-: 3332:// ----------------------------------------------------------------------
-: 3333://
-: 3334:// This class listens to Clang's events as the AST is generated.
-: 3335://
-: 3336:// The traversal of the AST is done via RecursiveASTVisitor, which uses
-: 3337:// CRTP (http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern)
-: 3338:
#####: 3339:class IwyuAstConsumer
-: 3340: : public ASTConsumer, public IwyuBaseAstVisitor<IwyuAstConsumer> {
-: 3341: public:
-: 3342: typedef IwyuBaseAstVisitor<IwyuAstConsumer> Base;
-: 3343:
2: 3344: IwyuAstConsumer(VisitorState* visitor_state)
-: 3345: : Base(visitor_state),
2: 3346: instantiated_template_visitor_(visitor_state) {}
-: 3347:
-: 3348: //------------------------------------------------------------
-: 3349: // Implements pure virtual methods from Base.
-: 3350:
-: 3351: // Returns true if we are not interested in symbols used in used_in
-: 3352: // for whatever reason. For instance, we can ignore nodes that are
-: 3353: // neither in the file we're compiling nor in its associated .h file.
-: 3354: virtual bool CanIgnoreCurrentASTNode() const {
-: 3355: // If we're outside of foo.{h,cc} and the set of check_also files,
-: 3356: // just ignore.
112192: 3357: if (CanIgnoreLocation(current_ast_node()->GetLocation()))
106401: 3358: return true;
-: 3359:
-: 3360: // If we're a field of a typedef type, ignore us: our rule is that
-: 3361: // the author of the typedef is responsible for everything
-: 3362: // involving the typedef.
5791: 3363: if (IsMemberOfATypedef(current_ast_node()))
10: 3364: return true;
-: 3365:
-: 3366: // TODO(csilvers): if we're a type, call CanIgnoreType().
-: 3367:
5781: 3368: return false;
177975: 3369: }
-: 3370:
-: 3371: // We print symbols from files in the main compilation unit (foo.cc,
-: 3372: // foo.h, foo-inl.h) if the debug level is 5 or 6, for non-system
-: 3373: // files if the debug level is 7, and all files if the debug level
-: 3374: // is 8 or more.
-: 3375: virtual bool ShouldPrintSymbolFromCurrentFile() const {
237401: 3376: return ShouldPrintSymbolFromFile(CurrentFileEntry());
237401: 3377: }
-: 3378:
#####: 3379: virtual string GetSymbolAnnotation() const { return ""; }
-: 3380:
-: 3381: // We are interested in all types for iwyu checking.
1088: 3382: virtual bool CanIgnoreType(const Type* type) const {
544: 3383: return type == NULL;
544: 3384: }
-: 3385:
6740: 3386: virtual bool CanIgnoreDecl(const Decl* decl) const {
3782: 3387: return decl == NULL;
2958: 3388: }
-: 3389:
-: 3390: //------------------------------------------------------------
-: 3391: // Parser event handlers. Clang will call them to notify this
-: 3392: // ASTConsumer as it parses the source code. See class ASTConsumer in
-: 3393: // clang/AST/ASTConsumer.h
-: 3394: // for all the handlers we can override.
-: 3395:
-: 3396: // Called once at the beginning of the compilation.
1: 3397: virtual void Initialize(ASTContext& context) {} // NOLINT
-: 3398:
-: 3399: // Called once at the end of the compilation.
1: 3400: virtual void HandleTranslationUnit(ASTContext& context) { // NOLINT
-: 3401: // TODO(csilvers): automatically detect preprocessing is done, somehow.
1: 3402: const_cast<IwyuPreprocessorInfo*>(&preprocessor_info())->
-: 3403: HandlePreprocessingDone();
-: 3404:
-: 3405: // We run a separate pass to force parsing of late-parsed function
-: 3406: // templates.
1: 3407: ParseFunctionTemplates(context.getTranslationUnitDecl());
-: 3408:
1: 3409: TraverseDecl(context.getTranslationUnitDecl());
-: 3410:
-: 3411: // We have to calculate the .h files before the .cc file, since
-: 3412: // the .cc file inherits #includes from the .h files, and we
-: 3413: // need to figure out what those #includes are going to be.
1: 3414: size_t num_edits = 0;
1: 3415: const FileEntry* const main_file = preprocessor_info().main_file();
1: 3416: const set<const FileEntry*>* const files_to_report_iwyu_violations_for
1: 3417: = preprocessor_info().files_to_report_iwyu_violations_for();
1: 3418: for (Each<const FileEntry*> file(files_to_report_iwyu_violations_for);
8: 3419: !file.AtEnd(); ++file) {
3: 3420: if (*file == main_file)
1: 3421: continue;
6: 3422: CHECK_(preprocessor_info().FileInfoFor(*file));
2: 3423: num_edits += preprocessor_info().FileInfoFor(*file)
-: 3424: ->CalculateAndReportIwyuViolations();
2: 3425: }
3: 3426: CHECK_(preprocessor_info().FileInfoFor(main_file));
1: 3427: num_edits += preprocessor_info().FileInfoFor(main_file)
-: 3428: ->CalculateAndReportIwyuViolations();
-: 3429:
-: 3430: // We need to force the compile to fail so we can re-run.
1: 3431: exit(EXIT_SUCCESS_OFFSET + num_edits);
#####: 3432: }
-: 3433:
1: 3434: void ParseFunctionTemplates(TranslationUnitDecl* decl) {
1: 3435: set<FunctionDecl*> late_parsed_decls = GetLateParsedFunctionDecls(decl);
1: 3436: clang::Sema& sema = compiler()->getSema();
-: 3437:
-: 3438: // If we have any late-parsed functions, make sure the
-: 3439: // -fdelayed-template-parsing flag is on. Otherwise we don't know where
-: 3440: // they came from.
4: 3441: CHECK_((compiler()->getLangOpts().DelayedTemplateParsing ||
-: 3442: late_parsed_decls.empty()) &&
-: 3443: "Should not have late-parsed decls without "
-: 3444: "-fdelayed-template-parsing.");
-: 3445:
4: 3446: for (const FunctionDecl* fd : late_parsed_decls) {
#####: 3447: CHECK_(fd->isLateTemplateParsed());
-: 3448:
#####: 3449: if (CanIgnoreLocation(GetLocation(fd)))
#####: 3450: continue;
-: 3451:
-: 3452: // Force parsing and AST building of the yet-uninstantiated function
-: 3453: // template body.
#####: 3454: clang::LateParsedTemplate* lpt = sema.LateParsedTemplateMap[fd];
#####: 3455: sema.LateTemplateParser(sema.OpaqueParser, *lpt);
#####: 3456: }
1: 3457: }
-: 3458:
-: 3459: //------------------------------------------------------------
-: 3460: // AST visitors. We start by adding a visitor callback for
-: 3461: // most of the subclasses of Decl/Stmt/Type listed in:
-: 3462: // clang/AST/DeclNodes.def
-: 3463: // clang/AST/StmtNodes.td
-: 3464: // clang/AST/TypeNodes.def
-: 3465: // We exclude only:
-: 3466: // 1) abstract declarations and types with no logic (e.g. NamedDecl)
-: 3467: // 2) ObjC declarations, statements, and types (e.g. ObjcIvarDecl)
-: 3468: // RecursiveASTVisitor defines specialized visitors for each specific
-: 3469: // math operation (MulAssign, OffsetOf, etc). We don't override
-: 3470: // those callbacks, but use their default behavior, which is to call
-: 3471: // back to VisitUnaryOperator, VisitBinaryOperator, etc.
-: 3472: //
-: 3473: // Over time, as we understand when a callback is called and
-: 3474: // which can be ignored by iwyu, we will pare down the list.
-: 3475: // Each of these returns a bool: false if we want to abort the
-: 3476: // traversal (we never do). For Visit*(), we can abort early if
-: 3477: // we're not in the main compilation-unit, since we only ever give
-: 3478: // iwyu warnings on symbols in those files.
-: 3479:
-: 3480: // --- Visitors of types derived from clang::Decl.
-: 3481:
1: 3482: bool VisitNamespaceAliasDecl(clang::NamespaceAliasDecl* decl) {
1: 3483: if (CanIgnoreCurrentASTNode()) return true;
1: 3484: ReportDeclUse(CurrentLoc(), decl->getNamespace());
1: 3485: return Base::VisitNamespaceAliasDecl(decl);
1: 3486: }
-: 3487:
268: 3488: bool VisitUsingDecl(clang::UsingDecl* decl) {
-: 3489: // If somebody in a different file tries to use one of these decls
-: 3490: // with the shortened name, then they had better #include us in
-: 3491: // order to get our using declaration. We store the necessary
-: 3492: // information here. Note: we have to store this even if this is
-: 3493: // an ast node we would otherwise ignore, since other AST nodes
-: 3494: // (which we might not ignore) can depend on it.
268: 3495: for (UsingDecl::shadow_iterator it = decl->shadow_begin();
1120: 3496: it != decl->shadow_end(); ++it) {
426: 3497: AddUsingDeclaration((*it)->getTargetDecl(), decl);
426: 3498: }
-: 3499:
532: 3500: if (CanIgnoreCurrentASTNode()) return true;
-: 3501:
-: 3502: // The shadow decls hold the declarations for the var/fn/etc we're
-: 3503: // using. (There may be more than one if, say, we're using an
-: 3504: // overloaded function.) We check to make sure nothing we're
-: 3505: // using is an iwyu violation.
4: 3506: for (UsingDecl::shadow_iterator it = decl->shadow_begin();
12: 3507: it != decl->shadow_end(); ++it) {
4: 3508: ReportDeclForwardDeclareUse(CurrentLoc(), (*it)->getTargetDecl());
4: 3509: }
-: 3510:
4: 3511: return Base::VisitUsingDecl(decl);
268: 3512: }
-: 3513:
1378: 3514: bool VisitTagDecl(clang::TagDecl* decl) {
2681: 3515: if (CanIgnoreCurrentASTNode()) return true;
-: 3516:
75: 3517: if (IsForwardDecl(decl)) {
-: 3518: // If we're a templated class, make sure we add the whole template.
19: 3519: const NamedDecl* decl_to_fwd_declare = decl;
19: 3520: if (const CXXRecordDecl* cxx_decl = DynCastFrom(decl))
19: 3521: if (cxx_decl->getDescribedClassTemplate())
24: 3522: decl_to_fwd_declare = cxx_decl->getDescribedClassTemplate();
-: 3523:
-: 3524: // We've found a forward-declaration. We'll report we've found
-: 3525: // it, but we also want to report if we know already that we
-: 3526: // should keep this forward-declaration around (and not consider
-: 3527: // it for deletion if it's never used). There are a few
-: 3528: // situations we can do this, described below.
19: 3529: bool definitely_keep_fwd_decl = false;
-: 3530:
-: 3531: // (1) If the forward-decl has a linkage spec ('extern "C"')
-: 3532: // then it can't be removed, since that information probably
-: 3533: // isn't encoded anywhere else.
-: 3534: // (Surprisingly classes can have linkage specs! -- they are
-: 3535: // applied to all static methods of the class. See
-: 3536: // http://msdn.microsoft.com/en-us/library/ms882260.aspx.)
19: 3537: if (current_ast_node()->ParentIsA<LinkageSpecDecl>()) {
1: 3538: definitely_keep_fwd_decl = true;
-: 3539:
-: 3540: // (2) GCC-style __attributes__ work the same way: we can't assume
-: 3541: // that attributes are consistent between declarations, so we can't
-: 3542: // remove a decl with attributes unless they're inherited, i.e. propagated
-: 3543: // from another redeclaration as opposed to explicitly written.
19: 3544: } else if (decl->hasAttrs()) {
#####: 3545: for (Each<const Attr*> it(&decl->getAttrs()); !it.AtEnd(); ++it) {
#####: 3546: if (!(*it)->isInherited()) {
#####: 3547: definitely_keep_fwd_decl = true;
#####: 3548: break;
-: 3549: }
#####: 3550: }
-: 3551:
-: 3552: // (3) If we're a nested class ("class A { class SubA; };"),
-: 3553: // then we can't necessary be removed either, since we're part
-: 3554: // of the public API of the enclosing class -- it's illegal to
-: 3555: // have a nested class and not at least declare it in the
-: 3556: // enclosing class. If the nested class is actually defined in
-: 3557: // the enclosing class, then we're fine; if not, we need to keep
-: 3558: // the first forward-declaration.
18: 3559: } else if (IsNestedClassAsWritten(current_ast_node())) {
5: 3560: if (!decl->getDefinition() || decl->getDefinition()->isOutOfLine()) {
-: 3561: // TODO(kimgr): Member class redeclarations are illegal, per C++
-: 3562: // standard DR85, so this check for first redecl can be removed.
-: 3563: // Nested classes should always be definitely kept. More details here:
-: 3564: // http://comments.gmane.org/gmane.comp.compilers.clang.scm/74782
-: 3565: // GCC and MSVC both still allow redeclarations of nested classes,
-: 3566: // though, so it seems hygienic to remove all but one.
3: 3567: if (const NamedDecl* first_decl = GetFirstRedecl(decl)) {
-: 3568: // Check if we're the decl with the smallest line number.
3: 3569: if (decl == first_decl)
3: 3570: definitely_keep_fwd_decl = true;
3: 3571: }
3: 3572: }
3: 3573: }
-: 3574:
19: 3575: preprocessor_info().FileInfoFor(CurrentFileEntry())->AddForwardDeclare(
-: 3576: decl_to_fwd_declare, definitely_keep_fwd_decl);
19: 3577: }
75: 3578: return Base::VisitTagDecl(decl);
1378: 3579: }
-: 3580:
-: 3581: // If you specialize a template, you need a declaration of the
-: 3582: // template you're specializing. That is, for code like this:
-: 3583: // template <class T> struct Foo;
-: 3584: // template<> struct Foo<int> { ... };
-: 3585: // we don't want iwyu to recommend removing the 'forward declare' of Foo.
-: 3586: bool VisitClassTemplateSpecializationDecl(
483: 3587: clang::ClassTemplateSpecializationDecl* decl) {
961: 3588: if (CanIgnoreCurrentASTNode()) return true;
5: 3589: ClassTemplateDecl* specialized_decl = decl->getSpecializedTemplate();
5: 3590: ReportDeclForwardDeclareUse(CurrentLoc(), specialized_decl);
5: 3591: return Base::VisitClassTemplateSpecializationDecl(decl);
483: 3592: }
-: 3593:
-: 3594: // If you say 'typedef Foo Bar', then clients can use Bar however
-: 3595: // they want without having to worry about #including anything
-: 3596: // except you. That puts you on the hook for all the #includes that
-: 3597: // Bar might need, for *anything* one might want to do to a Bar.
-: 3598: // TODO(csilvers): we can probably relax this rule in .cc files.
-: 3599: // TODO(csilvers): this should really move into IwyuBaseASTVisitor
-: 3600: // (that way we'll correctly identify need for hash<> in hash_set).
-: 3601: // This is a Traverse*() because Visit*() can't call HandleFunctionCall().
1569: 3602: bool TraverseTypedefDecl(clang::TypedefDecl* decl) {
-: 3603: // Before we go up the tree, make sure the parents know we don't
-: 3604: // forward-declare the underlying type of a typedef decl.
1569: 3605: current_ast_node()->set_in_forward_declare_context(false);
1569: 3606: if (!Base::TraverseTypedefDecl(decl))
#####: 3607: return false;
3105: 3608: if (CanIgnoreCurrentASTNode()) return true;
-: 3609:
33: 3610: const Type* underlying_type = decl->getUnderlyingType().getTypePtr();
33: 3611: const Decl* underlying_decl = TypeToDeclAsWritten(underlying_type);
-: 3612:
-: 3613: // We simulate a user calling all the methods in a class.
33: 3614: if (const CXXRecordDecl* record_decl = DynCastFrom(underlying_decl)) {
17: 3615: for (DeclContext::decl_iterator it = record_decl->decls_begin();
665: 3616: it != record_decl->decls_end(); ++it) {
324: 3617: FunctionDecl* fn_decl = NULL;
324: 3618: if (CXXMethodDecl* method_decl = DynCastFrom(*it)) {
199: 3619: fn_decl = method_decl;
324: 3620: } else if (FunctionTemplateDecl* tpl_decl = DynCastFrom(*it)) {
22: 3621: fn_decl = tpl_decl->getTemplatedDecl(); // templated method decl
22: 3622: } else {
103: 3623: continue; // not a method or static method
-: 3624: }
221: 3625: if (!this->getDerived().HandleFunctionCall(
-: 3626: fn_decl, underlying_type, static_cast<Expr*>(NULL)))
#####: 3627: return false;
221: 3628: }
17: 3629: }
-: 3630: // We don't have to simulate a user instantiating the type, because
-: 3631: // RecursiveASTVisitor.h will recurse on the typedef'ed type for us.
33: 3632: return true;
1569: 3633: }
-: 3634:
-: 3635: // --- Visitors of types derived from clang::Stmt.
-: 3636:
-: 3637: // Called whenever a variable, function, enum, etc is used.
17591: 3638: bool VisitDeclRefExpr(clang::DeclRefExpr* expr) {
34749: 3639: if (CanIgnoreCurrentASTNode()) return true;
433: 3640: ReportDeclUse(CurrentLoc(), expr->getDecl());
433: 3641: return Base::VisitDeclRefExpr(expr);
17591: 3642: }
-: 3643:
-: 3644: // This Expr is for sizeof(), alignof() and similar. The compiler
-: 3645: // fully instantiates a template class before taking the size of it.
-: 3646: // So so do we.
217: 3647: bool VisitUnaryExprOrTypeTraitExpr(clang::UnaryExprOrTypeTraitExpr* expr) {
429: 3648: if (CanIgnoreCurrentASTNode()) return true;
-: 3649:
5: 3650: const Type* arg_type = expr->getTypeOfArgument().getTypePtr();
-: 3651: // Calling sizeof on a reference-to-X is the same as calling it on X.
5: 3652: if (const ReferenceType* reftype = DynCastFrom(arg_type)) {
#####: 3653: arg_type = reftype->getPointeeTypeAsWritten().getTypePtr();
#####: 3654: }
5: 3655: if (!IsTemplatizedType(arg_type))
4: 3656: return Base::VisitUnaryExprOrTypeTraitExpr(expr);
-: 3657:
1: 3658: const map<const Type*, const Type*> resugar_map
1: 3659: = GetTplTypeResugarMapForClass(arg_type);
2: 3660: instantiated_template_visitor_.ScanInstantiatedType(
1: 3661: arg_type, current_ast_node(), resugar_map);
-: 3662:
1: 3663: return Base::VisitUnaryExprOrTypeTraitExpr(expr);
218: 3664: }
-: 3665:
-: 3666: // --- Visitors of types derived from clang::Type.
-: 3667:
9956: 3668: bool VisitTypedefType(clang::TypedefType* type) {
19845: 3669: if (CanIgnoreCurrentASTNode()) return true;
-: 3670: // TypedefType::getDecl() returns the place where the typedef is defined.
67: 3671: if (CanForwardDeclareType(current_ast_node())) {
14: 3672: ReportDeclForwardDeclareUse(CurrentLoc(), type->getDecl());
14: 3673: } else {
53: 3674: ReportDeclUse(CurrentLoc(), type->getDecl());
-: 3675: }
67: 3676: return Base::VisitTypedefType(type);
9956: 3677: }
-: 3678:
-: 3679: // This is a superclass of RecordType and CXXRecordType.
2797: 3680: bool VisitTagType(clang::TagType* type) {
5163: 3681: if (CanIgnoreCurrentASTNode()) return true;
-: 3682:
-: 3683: // If we're forward-declarable, then no complicated checking is
-: 3684: // needed: just forward-declare.
431: 3685: if (CanForwardDeclareType(current_ast_node())) {
230: 3686: current_ast_node()->set_in_forward_declare_context(true);
230: 3687: if (compiler()->getLangOpts().CPlusPlus) {
-: 3688: // In C++, if we're already elaborated ('class Foo x') but not
-: 3689: // namespace-qualified ('class ns::Foo x') there's no need even to
-: 3690: // forward-declare.
-: 3691: // Note that enums are never forward-declarable, so elaborated enums are
-: 3692: // short-circuited in CanForwardDeclareType.
230: 3693: const ASTNode* parent = current_ast_node()->parent();
239: 3694: if (!IsElaborationNode(parent) || IsNamespaceQualifiedNode(parent))
223: 3695: ReportDeclForwardDeclareUse(CurrentLoc(), type->getDecl());
230: 3696: } else {
-: 3697: // In C, all struct references are elaborated, so we really never need
-: 3698: // to forward-declare. But there's one case where an elaborated struct
-: 3699: // decl in a parameter list causes Clang to warn about constrained
-: 3700: // visibility, so we recommend forward declaration to avoid the warning.
-: 3701: // E.g.
-: 3702: // void init(struct mystruct* s);
-: 3703: // warning: declaration of 'struct mystruct' will not be visible
-: 3704: // outside of this function [-Wvisibility]
#####: 3705: if (current_ast_node()->HasAncestorOfType<ParmVarDecl>())
#####: 3706: ReportDeclForwardDeclareUse(CurrentLoc(), type->getDecl());
-: 3707: }
230: 3708: return Base::VisitTagType(type);
-: 3709: }
-: 3710:
-: 3711: // OK, seems to be a use that requires the full type.
201: 3712: ReportDeclUse(CurrentLoc(), type->getDecl());
201: 3713: return Base::VisitTagType(type);
2797: 3714: }
-: 3715:
-: 3716: // Like for CXXConstructExpr, etc., we sometimes need to instantiate
-: 3717: // a class when looking at TemplateSpecializationType -- for instance,
-: 3718: // when we need to access a class typedef: MyClass<A>::value_type.
-: 3719: bool VisitTemplateSpecializationType(
5661: 3720: clang::TemplateSpecializationType* type) {
11146: 3721: if (CanIgnoreCurrentASTNode()) return true;
-: 3722:
-: 3723: // If we're not in a forward-declare context, use of a template
-: 3724: // specialization requires having the full type information.
176: 3725: if (!CanForwardDeclareType(current_ast_node())) {
137: 3726: const map<const Type*, const Type*> resugar_map
137: 3727: = GetTplTypeResugarMapForClass(type);
-: 3728: // ScanInstantiatedType requires that type not already be on the
-: 3729: // ast-stack that it sees, but in our case it will be. So we
-: 3730: // pass in the parent-node.
137: 3731: const ASTNode* ast_parent = current_ast_node()->parent();
137: 3732: instantiated_template_visitor_.ScanInstantiatedType(
-: 3733: type, ast_parent, resugar_map);
137: 3734: }
-: 3735:
176: 3736: return Base::VisitTemplateSpecializationType(type);
5661: 3737: }
-: 3738:
-: 3739: // --- Visitors defined by BaseASTVisitor (not RecursiveASTVisitor).
-: 3740:
5664: 3741: bool VisitTemplateName(TemplateName template_name) {
11149: 3742: if (CanIgnoreCurrentASTNode()) return true;
179: 3743: if (!Base::VisitTemplateName(template_name)) return false;
-: 3744: // The only time we can see a TemplateName not in the
-: 3745: // context of a TemplateSpecializationType is when it's
-: 3746: // the default argument of a template template arg:
-: 3747: // template<template<class T> class A = TplNameWithoutTST> class Foo ...
-: 3748: // So that's the only case we need to handle here.
-: 3749: // TODO(csilvers): check if this is really forward-declarable or
-: 3750: // not. You *could* do something like: 'template<template<class
-: 3751: // T> class A = Foo> class C { A<int>* x; };' and never
-: 3752: // dereference x, but that's pretty unlikely. So for now, we just
-: 3753: // assume these default template template args always need full
-: 3754: // type info.
179: 3755: if (IsDefaultTemplateTemplateArg(current_ast_node())) {
3: 3756: current_ast_node()->set_in_forward_declare_context(false);
3: 3757: ReportDeclUse(CurrentLoc(), template_name.getAsTemplateDecl());
3: 3758: }
179: 3759: return true;
5664: 3760: }
-: 3761:
-: 3762: // For expressions that require us to instantiate a template
-: 3763: // (CallExpr of a template function, or CXXConstructExpr of a
-: 3764: // template class, etc), we need to instantiate the template and
-: 3765: // check IWYU status of the template parameters *in the template
-: 3766: // code* (so for 'MyFunc<T>() { T t; ... }', the contents of
-: 3767: // MyFunc<MyClass> add an iwyu requirement on MyClass).
838: 3768: bool HandleFunctionCall(FunctionDecl* callee, const Type* parent_type,
838: 3769: const clang::Expr* calling_expr) {
838: 3770: if (!Base::HandleFunctionCall(callee, parent_type, calling_expr))
#####: 3771: return false;
2486: 3772: if (!callee || CanIgnoreCurrentASTNode() || CanIgnoreDecl(callee))
14: 3773: return true;
-: 3774:
1580: 3775: if (!IsTemplatizedFunctionDecl(callee) && !IsTemplatizedType(parent_type))
398: 3776: return true;
-: 3777:
426: 3778: map<const Type*, const Type*> resugar_map
426: 3779: = GetTplTypeResugarMapForFunction(callee, calling_expr);
-: 3780:
426: 3781: if (parent_type) { // means we're a method of a class
398: 3782: InsertAllInto(GetTplTypeResugarMapForClass(parent_type), &resugar_map);
398: 3783: }
-: 3784:
852: 3785: instantiated_template_visitor_.ScanInstantiatedFunction(
-: 3786: callee, parent_type,
426: 3787: current_ast_node(), resugar_map);
426: 3788: return true;
1264: 3789: }
-: 3790:
-: 3791: private:
-: 3792: // Class we call to handle instantiated template functions and classes.
-: 3793: InstantiatedTemplateVisitor instantiated_template_visitor_;
-: 3794:}; // class IwyuAstConsumer
-: 3795:
-: 3796:// We use an ASTFrontendAction to hook up IWYU with Clang.
2: 3797:class IwyuAction : public ASTFrontendAction {
-: 3798: protected:
-: 3799: virtual std::unique_ptr<ASTConsumer> CreateASTConsumer(
1: 3800: CompilerInstance& compiler, // NOLINT
1: 3801: llvm::StringRef /* dummy */) {
-: 3802: // Do this first thing after getting our hands on a CompilerInstance.
2: 3803: InitGlobals(&compiler.getSourceManager(),
1: 3804: &compiler.getPreprocessor().getHeaderSearchInfo());
-: 3805:
1: 3806: IwyuPreprocessorInfo* const preprocessor_consumer =
-: 3807: new IwyuPreprocessorInfo();
1: 3808: compiler.getPreprocessor().addPPCallbacks(
-: 3809: std::unique_ptr<PPCallbacks>(preprocessor_consumer));
3: 3810: compiler.getPreprocessor().addCommentHandler(preprocessor_consumer);
-: 3811:
1: 3812: VisitorState* const visitor_state
-: 3813: = new VisitorState(&compiler, *preprocessor_consumer);
1: 3814: return std::unique_ptr<IwyuAstConsumer>(new IwyuAstConsumer(visitor_state));
-: 3815: }
-: 3816:};
-: 3817:
-: 3818:
-: 3819:} // namespace include_what_you_use
-: 3820:
-: 3821:#include "iwyu_driver.h"
-: 3822:#include "clang/Frontend/FrontendAction.h"
-: 3823:#include "llvm/Support/ManagedStatic.h"
-: 3824:#include "llvm/Support/TargetSelect.h"
-: 3825:
-: 3826:using include_what_you_use::OptionsParser;
-: 3827:using include_what_you_use::IwyuAction;
-: 3828:using include_what_you_use::CreateCompilerInstance;
-: 3829:
1: 3830:int main(int argc, char **argv) {
-: 3831: // Must initialize X86 target to be able to parse Microsoft inline
-: 3832: // assembly. We do this unconditionally, because it allows an IWYU
-: 3833: // built for non-X86 targets to parse MS inline asm without choking.
1: 3834: LLVMInitializeX86TargetInfo();
1: 3835: LLVMInitializeX86TargetMC();
1: 3836: LLVMInitializeX86AsmParser();
-: 3837:
-: 3838: // The command line should look like
-: 3839: // path/to/iwyu -Xiwyu --verbose=4 [-Xiwyu --other_iwyu_flag]... CLANG_FLAGS... foo.cc
1: 3840: OptionsParser options_parser(argc, argv);
-: 3841:
2: 3842: std::unique_ptr<clang::CompilerInstance> compiler(CreateCompilerInstance(
1: 3843: options_parser.clang_argc(), options_parser.clang_argv()));
1: 3844: if (compiler) {
-: 3845: // Create and execute the frontend to generate an LLVM bitcode module.
1: 3846: std::unique_ptr<clang::ASTFrontendAction> action(new IwyuAction);
1: 3847: compiler->ExecuteAction(*action);
1: 3848: }
-: 3849:
#####: 3850: llvm::llvm_shutdown();
-: 3851:
-: 3852: // We always return a failure exit code, to indicate we didn't
-: 3853: // successfully compile (produce a .o for) the source files we were
-: 3854: // given.
#####: 3855: return 1;
#####: 3856:}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment