BugReporter.cpp 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  1. // BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- C++ -*--//
  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. // This file defines BugReporter, a utility class for generating
  11. // PathDiagnostics.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  15. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/Analysis/CFG.h"
  19. #include "clang/AST/DeclObjC.h"
  20. #include "clang/AST/Expr.h"
  21. #include "clang/AST/ParentMap.h"
  22. #include "clang/AST/StmtObjC.h"
  23. #include "clang/Basic/SourceManager.h"
  24. #include "clang/Analysis/ProgramPoint.h"
  25. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "llvm/ADT/DenseMap.h"
  28. #include "llvm/ADT/SmallString.h"
  29. #include "llvm/ADT/STLExtras.h"
  30. #include "llvm/ADT/OwningPtr.h"
  31. #include <queue>
  32. using namespace clang;
  33. using namespace ento;
  34. BugReporterVisitor::~BugReporterVisitor() {}
  35. void BugReporterContext::anchor() {}
  36. //===----------------------------------------------------------------------===//
  37. // Helper routines for walking the ExplodedGraph and fetching statements.
  38. //===----------------------------------------------------------------------===//
  39. static inline const Stmt *GetStmt(const ProgramPoint &P) {
  40. if (const StmtPoint* SP = dyn_cast<StmtPoint>(&P))
  41. return SP->getStmt();
  42. else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P))
  43. return BE->getSrc()->getTerminator();
  44. return 0;
  45. }
  46. static inline const ExplodedNode*
  47. GetPredecessorNode(const ExplodedNode *N) {
  48. return N->pred_empty() ? NULL : *(N->pred_begin());
  49. }
  50. static inline const ExplodedNode*
  51. GetSuccessorNode(const ExplodedNode *N) {
  52. return N->succ_empty() ? NULL : *(N->succ_begin());
  53. }
  54. static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
  55. for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
  56. if (const Stmt *S = GetStmt(N->getLocation()))
  57. return S;
  58. return 0;
  59. }
  60. static const Stmt *GetNextStmt(const ExplodedNode *N) {
  61. for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
  62. if (const Stmt *S = GetStmt(N->getLocation())) {
  63. // Check if the statement is '?' or '&&'/'||'. These are "merges",
  64. // not actual statement points.
  65. switch (S->getStmtClass()) {
  66. case Stmt::ChooseExprClass:
  67. case Stmt::BinaryConditionalOperatorClass: continue;
  68. case Stmt::ConditionalOperatorClass: continue;
  69. case Stmt::BinaryOperatorClass: {
  70. BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
  71. if (Op == BO_LAnd || Op == BO_LOr)
  72. continue;
  73. break;
  74. }
  75. default:
  76. break;
  77. }
  78. return S;
  79. }
  80. return 0;
  81. }
  82. static inline const Stmt*
  83. GetCurrentOrPreviousStmt(const ExplodedNode *N) {
  84. if (const Stmt *S = GetStmt(N->getLocation()))
  85. return S;
  86. return GetPreviousStmt(N);
  87. }
  88. static inline const Stmt*
  89. GetCurrentOrNextStmt(const ExplodedNode *N) {
  90. if (const Stmt *S = GetStmt(N->getLocation()))
  91. return S;
  92. return GetNextStmt(N);
  93. }
  94. //===----------------------------------------------------------------------===//
  95. // PathDiagnosticBuilder and its associated routines and helper objects.
  96. //===----------------------------------------------------------------------===//
  97. typedef llvm::DenseMap<const ExplodedNode*,
  98. const ExplodedNode*> NodeBackMap;
  99. namespace {
  100. class NodeMapClosure : public BugReport::NodeResolver {
  101. NodeBackMap& M;
  102. public:
  103. NodeMapClosure(NodeBackMap *m) : M(*m) {}
  104. ~NodeMapClosure() {}
  105. const ExplodedNode *getOriginalNode(const ExplodedNode *N) {
  106. NodeBackMap::iterator I = M.find(N);
  107. return I == M.end() ? 0 : I->second;
  108. }
  109. };
  110. class PathDiagnosticBuilder : public BugReporterContext {
  111. BugReport *R;
  112. PathDiagnosticConsumer *PDC;
  113. OwningPtr<ParentMap> PM;
  114. NodeMapClosure NMC;
  115. public:
  116. PathDiagnosticBuilder(GRBugReporter &br,
  117. BugReport *r, NodeBackMap *Backmap,
  118. PathDiagnosticConsumer *pdc)
  119. : BugReporterContext(br),
  120. R(r), PDC(pdc), NMC(Backmap) {}
  121. PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
  122. PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
  123. const ExplodedNode *N);
  124. BugReport *getBugReport() { return R; }
  125. Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
  126. const LocationContext* getLocationContext() {
  127. return R->getErrorNode()->getLocationContext();
  128. }
  129. ParentMap& getParentMap() { return R->getErrorNode()->getParentMap(); }
  130. const Stmt *getParent(const Stmt *S) {
  131. return getParentMap().getParent(S);
  132. }
  133. virtual NodeMapClosure& getNodeResolver() { return NMC; }
  134. PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
  135. PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
  136. return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
  137. }
  138. bool supportsLogicalOpControlFlow() const {
  139. return PDC ? PDC->supportsLogicalOpControlFlow() : true;
  140. }
  141. };
  142. } // end anonymous namespace
  143. PathDiagnosticLocation
  144. PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
  145. if (const Stmt *S = GetNextStmt(N))
  146. return PathDiagnosticLocation(S, getSourceManager(), getLocationContext());
  147. return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
  148. getSourceManager());
  149. }
  150. PathDiagnosticLocation
  151. PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
  152. const ExplodedNode *N) {
  153. // Slow, but probably doesn't matter.
  154. if (os.str().empty())
  155. os << ' ';
  156. const PathDiagnosticLocation &Loc = ExecutionContinues(N);
  157. if (Loc.asStmt())
  158. os << "Execution continues on line "
  159. << getSourceManager().getExpansionLineNumber(Loc.asLocation())
  160. << '.';
  161. else {
  162. os << "Execution jumps to the end of the ";
  163. const Decl *D = N->getLocationContext()->getDecl();
  164. if (isa<ObjCMethodDecl>(D))
  165. os << "method";
  166. else if (isa<FunctionDecl>(D))
  167. os << "function";
  168. else {
  169. assert(isa<BlockDecl>(D));
  170. os << "anonymous block";
  171. }
  172. os << '.';
  173. }
  174. return Loc;
  175. }
  176. static bool IsNested(const Stmt *S, ParentMap &PM) {
  177. if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
  178. return true;
  179. const Stmt *Parent = PM.getParentIgnoreParens(S);
  180. if (Parent)
  181. switch (Parent->getStmtClass()) {
  182. case Stmt::ForStmtClass:
  183. case Stmt::DoStmtClass:
  184. case Stmt::WhileStmtClass:
  185. return true;
  186. default:
  187. break;
  188. }
  189. return false;
  190. }
  191. PathDiagnosticLocation
  192. PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
  193. assert(S && "Null Stmt *passed to getEnclosingStmtLocation");
  194. ParentMap &P = getParentMap();
  195. SourceManager &SMgr = getSourceManager();
  196. const LocationContext *LC = getLocationContext();
  197. while (IsNested(S, P)) {
  198. const Stmt *Parent = P.getParentIgnoreParens(S);
  199. if (!Parent)
  200. break;
  201. switch (Parent->getStmtClass()) {
  202. case Stmt::BinaryOperatorClass: {
  203. const BinaryOperator *B = cast<BinaryOperator>(Parent);
  204. if (B->isLogicalOp())
  205. return PathDiagnosticLocation(S, SMgr, LC);
  206. break;
  207. }
  208. case Stmt::CompoundStmtClass:
  209. case Stmt::StmtExprClass:
  210. return PathDiagnosticLocation(S, SMgr, LC);
  211. case Stmt::ChooseExprClass:
  212. // Similar to '?' if we are referring to condition, just have the edge
  213. // point to the entire choose expression.
  214. if (cast<ChooseExpr>(Parent)->getCond() == S)
  215. return PathDiagnosticLocation(Parent, SMgr, LC);
  216. else
  217. return PathDiagnosticLocation(S, SMgr, LC);
  218. case Stmt::BinaryConditionalOperatorClass:
  219. case Stmt::ConditionalOperatorClass:
  220. // For '?', if we are referring to condition, just have the edge point
  221. // to the entire '?' expression.
  222. if (cast<AbstractConditionalOperator>(Parent)->getCond() == S)
  223. return PathDiagnosticLocation(Parent, SMgr, LC);
  224. else
  225. return PathDiagnosticLocation(S, SMgr, LC);
  226. case Stmt::DoStmtClass:
  227. return PathDiagnosticLocation(S, SMgr, LC);
  228. case Stmt::ForStmtClass:
  229. if (cast<ForStmt>(Parent)->getBody() == S)
  230. return PathDiagnosticLocation(S, SMgr, LC);
  231. break;
  232. case Stmt::IfStmtClass:
  233. if (cast<IfStmt>(Parent)->getCond() != S)
  234. return PathDiagnosticLocation(S, SMgr, LC);
  235. break;
  236. case Stmt::ObjCForCollectionStmtClass:
  237. if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
  238. return PathDiagnosticLocation(S, SMgr, LC);
  239. break;
  240. case Stmt::WhileStmtClass:
  241. if (cast<WhileStmt>(Parent)->getCond() != S)
  242. return PathDiagnosticLocation(S, SMgr, LC);
  243. break;
  244. default:
  245. break;
  246. }
  247. S = Parent;
  248. }
  249. assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
  250. // Special case: DeclStmts can appear in for statement declarations, in which
  251. // case the ForStmt is the context.
  252. if (isa<DeclStmt>(S)) {
  253. if (const Stmt *Parent = P.getParent(S)) {
  254. switch (Parent->getStmtClass()) {
  255. case Stmt::ForStmtClass:
  256. case Stmt::ObjCForCollectionStmtClass:
  257. return PathDiagnosticLocation(Parent, SMgr, LC);
  258. default:
  259. break;
  260. }
  261. }
  262. }
  263. else if (isa<BinaryOperator>(S)) {
  264. // Special case: the binary operator represents the initialization
  265. // code in a for statement (this can happen when the variable being
  266. // initialized is an old variable.
  267. if (const ForStmt *FS =
  268. dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
  269. if (FS->getInit() == S)
  270. return PathDiagnosticLocation(FS, SMgr, LC);
  271. }
  272. }
  273. return PathDiagnosticLocation(S, SMgr, LC);
  274. }
  275. //===----------------------------------------------------------------------===//
  276. // ScanNotableSymbols: closure-like callback for scanning Store bindings.
  277. //===----------------------------------------------------------------------===//
  278. static const VarDecl* GetMostRecentVarDeclBinding(const ExplodedNode *N,
  279. ProgramStateManager& VMgr,
  280. SVal X) {
  281. for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
  282. ProgramPoint P = N->getLocation();
  283. if (!isa<PostStmt>(P))
  284. continue;
  285. const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
  286. if (!DR)
  287. continue;
  288. SVal Y = N->getState()->getSVal(DR, N->getLocationContext());
  289. if (X != Y)
  290. continue;
  291. const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  292. if (!VD)
  293. continue;
  294. return VD;
  295. }
  296. return 0;
  297. }
  298. namespace {
  299. class NotableSymbolHandler
  300. : public StoreManager::BindingsHandler {
  301. SymbolRef Sym;
  302. ProgramStateRef PrevSt;
  303. const Stmt *S;
  304. ProgramStateManager& VMgr;
  305. const ExplodedNode *Pred;
  306. PathDiagnostic& PD;
  307. BugReporter& BR;
  308. public:
  309. NotableSymbolHandler(SymbolRef sym,
  310. ProgramStateRef prevst,
  311. const Stmt *s,
  312. ProgramStateManager& vmgr,
  313. const ExplodedNode *pred,
  314. PathDiagnostic& pd,
  315. BugReporter& br)
  316. : Sym(sym),
  317. PrevSt(prevst),
  318. S(s),
  319. VMgr(vmgr),
  320. Pred(pred),
  321. PD(pd),
  322. BR(br) {}
  323. bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
  324. SVal V) {
  325. SymbolRef ScanSym = V.getAsSymbol();
  326. if (ScanSym != Sym)
  327. return true;
  328. // Check if the previous state has this binding.
  329. SVal X = PrevSt->getSVal(loc::MemRegionVal(R));
  330. if (X == V) // Same binding?
  331. return true;
  332. // Different binding. Only handle assignments for now. We don't pull
  333. // this check out of the loop because we will eventually handle other
  334. // cases.
  335. VarDecl *VD = 0;
  336. if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
  337. if (!B->isAssignmentOp())
  338. return true;
  339. // What variable did we assign to?
  340. DeclRefExpr *DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
  341. if (!DR)
  342. return true;
  343. VD = dyn_cast<VarDecl>(DR->getDecl());
  344. }
  345. else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
  346. // FIXME: Eventually CFGs won't have DeclStmts. Right now we
  347. // assume that each DeclStmt has a single Decl. This invariant
  348. // holds by construction in the CFG.
  349. VD = dyn_cast<VarDecl>(*DS->decl_begin());
  350. }
  351. if (!VD)
  352. return true;
  353. // What is the most recently referenced variable with this binding?
  354. const VarDecl *MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
  355. if (!MostRecent)
  356. return true;
  357. // Create the diagnostic.
  358. if (Loc::isLocType(VD->getType())) {
  359. SmallString<64> buf;
  360. llvm::raw_svector_ostream os(buf);
  361. os << '\'' << *VD << "' now aliases '" << *MostRecent << '\'';
  362. PathDiagnosticLocation L =
  363. PathDiagnosticLocation::createBegin(S, BR.getSourceManager(),
  364. Pred->getLocationContext());
  365. PD.push_front(new PathDiagnosticEventPiece(L, os.str()));
  366. }
  367. return true;
  368. }
  369. };
  370. }
  371. static void HandleNotableSymbol(const ExplodedNode *N,
  372. const Stmt *S,
  373. SymbolRef Sym, BugReporter& BR,
  374. PathDiagnostic& PD) {
  375. const ExplodedNode *Pred = N->pred_empty() ? 0 : *N->pred_begin();
  376. ProgramStateRef PrevSt = Pred ? Pred->getState() : 0;
  377. if (!PrevSt)
  378. return;
  379. // Look at the region bindings of the current state that map to the
  380. // specified symbol. Are any of them not in the previous state?
  381. ProgramStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
  382. NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
  383. cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
  384. }
  385. namespace {
  386. class ScanNotableSymbols
  387. : public StoreManager::BindingsHandler {
  388. llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
  389. const ExplodedNode *N;
  390. const Stmt *S;
  391. GRBugReporter& BR;
  392. PathDiagnostic& PD;
  393. public:
  394. ScanNotableSymbols(const ExplodedNode *n, const Stmt *s,
  395. GRBugReporter& br, PathDiagnostic& pd)
  396. : N(n), S(s), BR(br), PD(pd) {}
  397. bool HandleBinding(StoreManager& SMgr, Store store,
  398. const MemRegion* R, SVal V) {
  399. SymbolRef ScanSym = V.getAsSymbol();
  400. if (!ScanSym)
  401. return true;
  402. if (!BR.isNotable(ScanSym))
  403. return true;
  404. if (AlreadyProcessed.count(ScanSym))
  405. return true;
  406. AlreadyProcessed.insert(ScanSym);
  407. HandleNotableSymbol(N, S, ScanSym, BR, PD);
  408. return true;
  409. }
  410. };
  411. } // end anonymous namespace
  412. //===----------------------------------------------------------------------===//
  413. // "Minimal" path diagnostic generation algorithm.
  414. //===----------------------------------------------------------------------===//
  415. static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
  416. static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
  417. PathDiagnosticBuilder &PDB,
  418. const ExplodedNode *N) {
  419. SourceManager& SMgr = PDB.getSourceManager();
  420. const LocationContext *LC = PDB.getLocationContext();
  421. const ExplodedNode *NextNode = N->pred_empty()
  422. ? NULL : *(N->pred_begin());
  423. while (NextNode) {
  424. N = NextNode;
  425. NextNode = GetPredecessorNode(N);
  426. ProgramPoint P = N->getLocation();
  427. if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
  428. const CFGBlock *Src = BE->getSrc();
  429. const CFGBlock *Dst = BE->getDst();
  430. const Stmt *T = Src->getTerminator();
  431. if (!T)
  432. continue;
  433. PathDiagnosticLocation Start =
  434. PathDiagnosticLocation::createBegin(T, SMgr,
  435. N->getLocationContext());
  436. switch (T->getStmtClass()) {
  437. default:
  438. break;
  439. case Stmt::GotoStmtClass:
  440. case Stmt::IndirectGotoStmtClass: {
  441. const Stmt *S = GetNextStmt(N);
  442. if (!S)
  443. continue;
  444. std::string sbuf;
  445. llvm::raw_string_ostream os(sbuf);
  446. const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
  447. os << "Control jumps to line "
  448. << End.asLocation().getExpansionLineNumber();
  449. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  450. os.str()));
  451. break;
  452. }
  453. case Stmt::SwitchStmtClass: {
  454. // Figure out what case arm we took.
  455. std::string sbuf;
  456. llvm::raw_string_ostream os(sbuf);
  457. if (const Stmt *S = Dst->getLabel()) {
  458. PathDiagnosticLocation End(S, SMgr, LC);
  459. switch (S->getStmtClass()) {
  460. default:
  461. os << "No cases match in the switch statement. "
  462. "Control jumps to line "
  463. << End.asLocation().getExpansionLineNumber();
  464. break;
  465. case Stmt::DefaultStmtClass:
  466. os << "Control jumps to the 'default' case at line "
  467. << End.asLocation().getExpansionLineNumber();
  468. break;
  469. case Stmt::CaseStmtClass: {
  470. os << "Control jumps to 'case ";
  471. const CaseStmt *Case = cast<CaseStmt>(S);
  472. const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
  473. // Determine if it is an enum.
  474. bool GetRawInt = true;
  475. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
  476. // FIXME: Maybe this should be an assertion. Are there cases
  477. // were it is not an EnumConstantDecl?
  478. const EnumConstantDecl *D =
  479. dyn_cast<EnumConstantDecl>(DR->getDecl());
  480. if (D) {
  481. GetRawInt = false;
  482. os << *D;
  483. }
  484. }
  485. if (GetRawInt)
  486. os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
  487. os << ":' at line "
  488. << End.asLocation().getExpansionLineNumber();
  489. break;
  490. }
  491. }
  492. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  493. os.str()));
  494. }
  495. else {
  496. os << "'Default' branch taken. ";
  497. const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
  498. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  499. os.str()));
  500. }
  501. break;
  502. }
  503. case Stmt::BreakStmtClass:
  504. case Stmt::ContinueStmtClass: {
  505. std::string sbuf;
  506. llvm::raw_string_ostream os(sbuf);
  507. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  508. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  509. os.str()));
  510. break;
  511. }
  512. // Determine control-flow for ternary '?'.
  513. case Stmt::BinaryConditionalOperatorClass:
  514. case Stmt::ConditionalOperatorClass: {
  515. std::string sbuf;
  516. llvm::raw_string_ostream os(sbuf);
  517. os << "'?' condition is ";
  518. if (*(Src->succ_begin()+1) == Dst)
  519. os << "false";
  520. else
  521. os << "true";
  522. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  523. if (const Stmt *S = End.asStmt())
  524. End = PDB.getEnclosingStmtLocation(S);
  525. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  526. os.str()));
  527. break;
  528. }
  529. // Determine control-flow for short-circuited '&&' and '||'.
  530. case Stmt::BinaryOperatorClass: {
  531. if (!PDB.supportsLogicalOpControlFlow())
  532. break;
  533. const BinaryOperator *B = cast<BinaryOperator>(T);
  534. std::string sbuf;
  535. llvm::raw_string_ostream os(sbuf);
  536. os << "Left side of '";
  537. if (B->getOpcode() == BO_LAnd) {
  538. os << "&&" << "' is ";
  539. if (*(Src->succ_begin()+1) == Dst) {
  540. os << "false";
  541. PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
  542. PathDiagnosticLocation Start =
  543. PathDiagnosticLocation::createOperatorLoc(B, SMgr);
  544. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  545. os.str()));
  546. }
  547. else {
  548. os << "true";
  549. PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
  550. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  551. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  552. os.str()));
  553. }
  554. }
  555. else {
  556. assert(B->getOpcode() == BO_LOr);
  557. os << "||" << "' is ";
  558. if (*(Src->succ_begin()+1) == Dst) {
  559. os << "false";
  560. PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
  561. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  562. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  563. os.str()));
  564. }
  565. else {
  566. os << "true";
  567. PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
  568. PathDiagnosticLocation Start =
  569. PathDiagnosticLocation::createOperatorLoc(B, SMgr);
  570. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  571. os.str()));
  572. }
  573. }
  574. break;
  575. }
  576. case Stmt::DoStmtClass: {
  577. if (*(Src->succ_begin()) == Dst) {
  578. std::string sbuf;
  579. llvm::raw_string_ostream os(sbuf);
  580. os << "Loop condition is true. ";
  581. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  582. if (const Stmt *S = End.asStmt())
  583. End = PDB.getEnclosingStmtLocation(S);
  584. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  585. os.str()));
  586. }
  587. else {
  588. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  589. if (const Stmt *S = End.asStmt())
  590. End = PDB.getEnclosingStmtLocation(S);
  591. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  592. "Loop condition is false. Exiting loop"));
  593. }
  594. break;
  595. }
  596. case Stmt::WhileStmtClass:
  597. case Stmt::ForStmtClass: {
  598. if (*(Src->succ_begin()+1) == Dst) {
  599. std::string sbuf;
  600. llvm::raw_string_ostream os(sbuf);
  601. os << "Loop condition is false. ";
  602. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  603. if (const Stmt *S = End.asStmt())
  604. End = PDB.getEnclosingStmtLocation(S);
  605. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  606. os.str()));
  607. }
  608. else {
  609. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  610. if (const Stmt *S = End.asStmt())
  611. End = PDB.getEnclosingStmtLocation(S);
  612. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  613. "Loop condition is true. Entering loop body"));
  614. }
  615. break;
  616. }
  617. case Stmt::IfStmtClass: {
  618. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  619. if (const Stmt *S = End.asStmt())
  620. End = PDB.getEnclosingStmtLocation(S);
  621. if (*(Src->succ_begin()+1) == Dst)
  622. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  623. "Taking false branch"));
  624. else
  625. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  626. "Taking true branch"));
  627. break;
  628. }
  629. }
  630. }
  631. if (NextNode) {
  632. // Add diagnostic pieces from custom visitors.
  633. BugReport *R = PDB.getBugReport();
  634. for (BugReport::visitor_iterator I = R->visitor_begin(),
  635. E = R->visitor_end(); I!=E; ++I) {
  636. if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R))
  637. PD.push_front(p);
  638. }
  639. }
  640. if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
  641. // Scan the region bindings, and see if a "notable" symbol has a new
  642. // lval binding.
  643. ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
  644. PDB.getStateManager().iterBindings(N->getState(), SNS);
  645. }
  646. }
  647. // After constructing the full PathDiagnostic, do a pass over it to compact
  648. // PathDiagnosticPieces that occur within a macro.
  649. CompactPathDiagnostic(PD, PDB.getSourceManager());
  650. }
  651. //===----------------------------------------------------------------------===//
  652. // "Extensive" PathDiagnostic generation.
  653. //===----------------------------------------------------------------------===//
  654. static bool IsControlFlowExpr(const Stmt *S) {
  655. const Expr *E = dyn_cast<Expr>(S);
  656. if (!E)
  657. return false;
  658. E = E->IgnoreParenCasts();
  659. if (isa<AbstractConditionalOperator>(E))
  660. return true;
  661. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
  662. if (B->isLogicalOp())
  663. return true;
  664. return false;
  665. }
  666. namespace {
  667. class ContextLocation : public PathDiagnosticLocation {
  668. bool IsDead;
  669. public:
  670. ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
  671. : PathDiagnosticLocation(L), IsDead(isdead) {}
  672. void markDead() { IsDead = true; }
  673. bool isDead() const { return IsDead; }
  674. };
  675. class EdgeBuilder {
  676. std::vector<ContextLocation> CLocs;
  677. typedef std::vector<ContextLocation>::iterator iterator;
  678. PathDiagnostic &PD;
  679. PathDiagnosticBuilder &PDB;
  680. PathDiagnosticLocation PrevLoc;
  681. bool IsConsumedExpr(const PathDiagnosticLocation &L);
  682. bool containsLocation(const PathDiagnosticLocation &Container,
  683. const PathDiagnosticLocation &Containee);
  684. PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
  685. PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
  686. bool firstCharOnly = false) {
  687. if (const Stmt *S = L.asStmt()) {
  688. const Stmt *Original = S;
  689. while (1) {
  690. // Adjust the location for some expressions that are best referenced
  691. // by one of their subexpressions.
  692. switch (S->getStmtClass()) {
  693. default:
  694. break;
  695. case Stmt::ParenExprClass:
  696. case Stmt::GenericSelectionExprClass:
  697. S = cast<Expr>(S)->IgnoreParens();
  698. firstCharOnly = true;
  699. continue;
  700. case Stmt::BinaryConditionalOperatorClass:
  701. case Stmt::ConditionalOperatorClass:
  702. S = cast<AbstractConditionalOperator>(S)->getCond();
  703. firstCharOnly = true;
  704. continue;
  705. case Stmt::ChooseExprClass:
  706. S = cast<ChooseExpr>(S)->getCond();
  707. firstCharOnly = true;
  708. continue;
  709. case Stmt::BinaryOperatorClass:
  710. S = cast<BinaryOperator>(S)->getLHS();
  711. firstCharOnly = true;
  712. continue;
  713. }
  714. break;
  715. }
  716. if (S != Original)
  717. L = PathDiagnosticLocation(S, L.getManager(), PDB.getLocationContext());
  718. }
  719. if (firstCharOnly)
  720. L = PathDiagnosticLocation::createSingleLocation(L);
  721. return L;
  722. }
  723. void popLocation() {
  724. if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
  725. // For contexts, we only one the first character as the range.
  726. rawAddEdge(cleanUpLocation(CLocs.back(), true));
  727. }
  728. CLocs.pop_back();
  729. }
  730. public:
  731. EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
  732. : PD(pd), PDB(pdb) {
  733. // If the PathDiagnostic already has pieces, add the enclosing statement
  734. // of the first piece as a context as well.
  735. if (!PD.empty()) {
  736. PrevLoc = PD.begin()->getLocation();
  737. if (const Stmt *S = PrevLoc.asStmt())
  738. addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
  739. }
  740. }
  741. ~EdgeBuilder() {
  742. while (!CLocs.empty()) popLocation();
  743. // Finally, add an initial edge from the start location of the first
  744. // statement (if it doesn't already exist).
  745. PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
  746. PDB.getLocationContext(),
  747. PDB.getSourceManager());
  748. if (L.isValid())
  749. rawAddEdge(L);
  750. }
  751. void flushLocations() {
  752. while (!CLocs.empty())
  753. popLocation();
  754. PrevLoc = PathDiagnosticLocation();
  755. }
  756. void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
  757. void rawAddEdge(PathDiagnosticLocation NewLoc);
  758. void addContext(const Stmt *S);
  759. void addExtendedContext(const Stmt *S);
  760. };
  761. } // end anonymous namespace
  762. PathDiagnosticLocation
  763. EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
  764. if (const Stmt *S = L.asStmt()) {
  765. if (IsControlFlowExpr(S))
  766. return L;
  767. return PDB.getEnclosingStmtLocation(S);
  768. }
  769. return L;
  770. }
  771. bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
  772. const PathDiagnosticLocation &Containee) {
  773. if (Container == Containee)
  774. return true;
  775. if (Container.asDecl())
  776. return true;
  777. if (const Stmt *S = Containee.asStmt())
  778. if (const Stmt *ContainerS = Container.asStmt()) {
  779. while (S) {
  780. if (S == ContainerS)
  781. return true;
  782. S = PDB.getParent(S);
  783. }
  784. return false;
  785. }
  786. // Less accurate: compare using source ranges.
  787. SourceRange ContainerR = Container.asRange();
  788. SourceRange ContaineeR = Containee.asRange();
  789. SourceManager &SM = PDB.getSourceManager();
  790. SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
  791. SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
  792. SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
  793. SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
  794. unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
  795. unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
  796. unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
  797. unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
  798. assert(ContainerBegLine <= ContainerEndLine);
  799. assert(ContaineeBegLine <= ContaineeEndLine);
  800. return (ContainerBegLine <= ContaineeBegLine &&
  801. ContainerEndLine >= ContaineeEndLine &&
  802. (ContainerBegLine != ContaineeBegLine ||
  803. SM.getExpansionColumnNumber(ContainerRBeg) <=
  804. SM.getExpansionColumnNumber(ContaineeRBeg)) &&
  805. (ContainerEndLine != ContaineeEndLine ||
  806. SM.getExpansionColumnNumber(ContainerREnd) >=
  807. SM.getExpansionColumnNumber(ContainerREnd)));
  808. }
  809. void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
  810. if (!PrevLoc.isValid()) {
  811. PrevLoc = NewLoc;
  812. return;
  813. }
  814. const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
  815. const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
  816. if (NewLocClean.asLocation() == PrevLocClean.asLocation())
  817. return;
  818. // FIXME: Ignore intra-macro edges for now.
  819. if (NewLocClean.asLocation().getExpansionLoc() ==
  820. PrevLocClean.asLocation().getExpansionLoc())
  821. return;
  822. PD.push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
  823. PrevLoc = NewLoc;
  824. }
  825. void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
  826. if (!alwaysAdd && NewLoc.asLocation().isMacroID())
  827. return;
  828. const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
  829. while (!CLocs.empty()) {
  830. ContextLocation &TopContextLoc = CLocs.back();
  831. // Is the top location context the same as the one for the new location?
  832. if (TopContextLoc == CLoc) {
  833. if (alwaysAdd) {
  834. if (IsConsumedExpr(TopContextLoc) &&
  835. !IsControlFlowExpr(TopContextLoc.asStmt()))
  836. TopContextLoc.markDead();
  837. rawAddEdge(NewLoc);
  838. }
  839. return;
  840. }
  841. if (containsLocation(TopContextLoc, CLoc)) {
  842. if (alwaysAdd) {
  843. rawAddEdge(NewLoc);
  844. if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
  845. CLocs.push_back(ContextLocation(CLoc, true));
  846. return;
  847. }
  848. }
  849. CLocs.push_back(CLoc);
  850. return;
  851. }
  852. // Context does not contain the location. Flush it.
  853. popLocation();
  854. }
  855. // If we reach here, there is no enclosing context. Just add the edge.
  856. rawAddEdge(NewLoc);
  857. }
  858. bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
  859. if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
  860. return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
  861. return false;
  862. }
  863. void EdgeBuilder::addExtendedContext(const Stmt *S) {
  864. if (!S)
  865. return;
  866. const Stmt *Parent = PDB.getParent(S);
  867. while (Parent) {
  868. if (isa<CompoundStmt>(Parent))
  869. Parent = PDB.getParent(Parent);
  870. else
  871. break;
  872. }
  873. if (Parent) {
  874. switch (Parent->getStmtClass()) {
  875. case Stmt::DoStmtClass:
  876. case Stmt::ObjCAtSynchronizedStmtClass:
  877. addContext(Parent);
  878. default:
  879. break;
  880. }
  881. }
  882. addContext(S);
  883. }
  884. void EdgeBuilder::addContext(const Stmt *S) {
  885. if (!S)
  886. return;
  887. PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.getLocationContext());
  888. while (!CLocs.empty()) {
  889. const PathDiagnosticLocation &TopContextLoc = CLocs.back();
  890. // Is the top location context the same as the one for the new location?
  891. if (TopContextLoc == L)
  892. return;
  893. if (containsLocation(TopContextLoc, L)) {
  894. CLocs.push_back(L);
  895. return;
  896. }
  897. // Context does not contain the location. Flush it.
  898. popLocation();
  899. }
  900. CLocs.push_back(L);
  901. }
  902. static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
  903. PathDiagnosticBuilder &PDB,
  904. const ExplodedNode *N) {
  905. EdgeBuilder EB(PD, PDB);
  906. const SourceManager& SM = PDB.getSourceManager();
  907. const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin());
  908. while (NextNode) {
  909. N = NextNode;
  910. NextNode = GetPredecessorNode(N);
  911. ProgramPoint P = N->getLocation();
  912. do {
  913. if (const CallExit *CE = dyn_cast<CallExit>(&P)) {
  914. const StackFrameContext *LCtx =
  915. CE->getLocationContext()->getCurrentStackFrame();
  916. PathDiagnosticLocation Loc(LCtx->getCallSite(),
  917. PDB.getSourceManager(),
  918. LCtx);
  919. EB.addEdge(Loc, true);
  920. EB.flushLocations();
  921. break;
  922. }
  923. // Was the predecessor in a different stack frame?
  924. if (NextNode &&
  925. !isa<CallExit>(NextNode->getLocation()) &&
  926. NextNode->getLocationContext()->getCurrentStackFrame() !=
  927. N->getLocationContext()->getCurrentStackFrame()) {
  928. EB.flushLocations();
  929. }
  930. // Block edges.
  931. if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
  932. const CFGBlock &Blk = *BE->getSrc();
  933. const Stmt *Term = Blk.getTerminator();
  934. // Are we jumping to the head of a loop? Add a special diagnostic.
  935. if (const Stmt *Loop = BE->getDst()->getLoopTarget()) {
  936. PathDiagnosticLocation L(Loop, SM, PDB.getLocationContext());
  937. const CompoundStmt *CS = NULL;
  938. if (!Term) {
  939. if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
  940. CS = dyn_cast<CompoundStmt>(FS->getBody());
  941. else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
  942. CS = dyn_cast<CompoundStmt>(WS->getBody());
  943. }
  944. PathDiagnosticEventPiece *p =
  945. new PathDiagnosticEventPiece(L,
  946. "Looping back to the head of the loop");
  947. EB.addEdge(p->getLocation(), true);
  948. PD.push_front(p);
  949. if (CS) {
  950. PathDiagnosticLocation BL =
  951. PathDiagnosticLocation::createEndBrace(CS, SM);
  952. EB.addEdge(BL);
  953. }
  954. }
  955. if (Term)
  956. EB.addContext(Term);
  957. break;
  958. }
  959. if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
  960. if (const CFGStmt *S = BE->getFirstElement().getAs<CFGStmt>()) {
  961. const Stmt *stmt = S->getStmt();
  962. if (IsControlFlowExpr(stmt)) {
  963. // Add the proper context for '&&', '||', and '?'.
  964. EB.addContext(stmt);
  965. }
  966. else
  967. EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
  968. }
  969. break;
  970. }
  971. } while (0);
  972. if (!NextNode)
  973. continue;
  974. // Add pieces from custom visitors.
  975. BugReport *R = PDB.getBugReport();
  976. for (BugReport::visitor_iterator I = R->visitor_begin(),
  977. E = R->visitor_end(); I!=E; ++I) {
  978. if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
  979. const PathDiagnosticLocation &Loc = p->getLocation();
  980. EB.addEdge(Loc, true);
  981. PD.push_front(p);
  982. if (const Stmt *S = Loc.asStmt())
  983. EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
  984. }
  985. }
  986. }
  987. }
  988. //===----------------------------------------------------------------------===//
  989. // Methods for BugType and subclasses.
  990. //===----------------------------------------------------------------------===//
  991. BugType::~BugType() { }
  992. void BugType::FlushReports(BugReporter &BR) {}
  993. void BuiltinBug::anchor() {}
  994. //===----------------------------------------------------------------------===//
  995. // Methods for BugReport and subclasses.
  996. //===----------------------------------------------------------------------===//
  997. void BugReport::NodeResolver::anchor() {}
  998. void BugReport::addVisitor(BugReporterVisitor* visitor) {
  999. if (!visitor)
  1000. return;
  1001. llvm::FoldingSetNodeID ID;
  1002. visitor->Profile(ID);
  1003. void *InsertPos;
  1004. if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
  1005. delete visitor;
  1006. return;
  1007. }
  1008. CallbacksSet.InsertNode(visitor, InsertPos);
  1009. Callbacks = F.add(visitor, Callbacks);
  1010. }
  1011. BugReport::~BugReport() {
  1012. for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) {
  1013. delete *I;
  1014. }
  1015. }
  1016. void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
  1017. hash.AddPointer(&BT);
  1018. hash.AddString(Description);
  1019. if (Location.isValid()) {
  1020. Location.Profile(hash);
  1021. } else {
  1022. assert(ErrorNode);
  1023. hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
  1024. }
  1025. for (SmallVectorImpl<SourceRange>::const_iterator I =
  1026. Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  1027. const SourceRange range = *I;
  1028. if (!range.isValid())
  1029. continue;
  1030. hash.AddInteger(range.getBegin().getRawEncoding());
  1031. hash.AddInteger(range.getEnd().getRawEncoding());
  1032. }
  1033. }
  1034. const Stmt *BugReport::getStmt() const {
  1035. if (!ErrorNode)
  1036. return 0;
  1037. ProgramPoint ProgP = ErrorNode->getLocation();
  1038. const Stmt *S = NULL;
  1039. if (BlockEntrance *BE = dyn_cast<BlockEntrance>(&ProgP)) {
  1040. CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
  1041. if (BE->getBlock() == &Exit)
  1042. S = GetPreviousStmt(ErrorNode);
  1043. }
  1044. if (!S)
  1045. S = GetStmt(ProgP);
  1046. return S;
  1047. }
  1048. std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
  1049. BugReport::getRanges() {
  1050. // If no custom ranges, add the range of the statement corresponding to
  1051. // the error node.
  1052. if (Ranges.empty()) {
  1053. if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
  1054. addRange(E->getSourceRange());
  1055. else
  1056. return std::make_pair(ranges_iterator(), ranges_iterator());
  1057. }
  1058. // User-specified absence of range info.
  1059. if (Ranges.size() == 1 && !Ranges.begin()->isValid())
  1060. return std::make_pair(ranges_iterator(), ranges_iterator());
  1061. return std::make_pair(Ranges.begin(), Ranges.end());
  1062. }
  1063. PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
  1064. if (ErrorNode) {
  1065. assert(!Location.isValid() &&
  1066. "Either Location or ErrorNode should be specified but not both.");
  1067. if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) {
  1068. const LocationContext *LC = ErrorNode->getLocationContext();
  1069. // For member expressions, return the location of the '.' or '->'.
  1070. if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
  1071. return PathDiagnosticLocation::createMemberLoc(ME, SM);
  1072. // For binary operators, return the location of the operator.
  1073. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
  1074. return PathDiagnosticLocation::createOperatorLoc(B, SM);
  1075. return PathDiagnosticLocation::createBegin(S, SM, LC);
  1076. }
  1077. } else {
  1078. assert(Location.isValid());
  1079. return Location;
  1080. }
  1081. return PathDiagnosticLocation();
  1082. }
  1083. //===----------------------------------------------------------------------===//
  1084. // Methods for BugReporter and subclasses.
  1085. //===----------------------------------------------------------------------===//
  1086. BugReportEquivClass::~BugReportEquivClass() {
  1087. for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
  1088. }
  1089. GRBugReporter::~GRBugReporter() { }
  1090. BugReporterData::~BugReporterData() {}
  1091. ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
  1092. ProgramStateManager&
  1093. GRBugReporter::getStateManager() { return Eng.getStateManager(); }
  1094. BugReporter::~BugReporter() {
  1095. FlushReports();
  1096. // Free the bug reports we are tracking.
  1097. typedef std::vector<BugReportEquivClass *> ContTy;
  1098. for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
  1099. I != E; ++I) {
  1100. delete *I;
  1101. }
  1102. }
  1103. void BugReporter::FlushReports() {
  1104. if (BugTypes.isEmpty())
  1105. return;
  1106. // First flush the warnings for each BugType. This may end up creating new
  1107. // warnings and new BugTypes.
  1108. // FIXME: Only NSErrorChecker needs BugType's FlushReports.
  1109. // Turn NSErrorChecker into a proper checker and remove this.
  1110. SmallVector<const BugType*, 16> bugTypes;
  1111. for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
  1112. bugTypes.push_back(*I);
  1113. for (SmallVector<const BugType*, 16>::iterator
  1114. I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
  1115. const_cast<BugType*>(*I)->FlushReports(*this);
  1116. typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
  1117. for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
  1118. BugReportEquivClass& EQ = *EI;
  1119. FlushReport(EQ);
  1120. }
  1121. // BugReporter owns and deletes only BugTypes created implicitly through
  1122. // EmitBasicReport.
  1123. // FIXME: There are leaks from checkers that assume that the BugTypes they
  1124. // create will be destroyed by the BugReporter.
  1125. for (llvm::StringMap<BugType*>::iterator
  1126. I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I)
  1127. delete I->second;
  1128. // Remove all references to the BugType objects.
  1129. BugTypes = F.getEmptySet();
  1130. }
  1131. //===----------------------------------------------------------------------===//
  1132. // PathDiagnostics generation.
  1133. //===----------------------------------------------------------------------===//
  1134. static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
  1135. std::pair<ExplodedNode*, unsigned> >
  1136. MakeReportGraph(const ExplodedGraph* G,
  1137. SmallVectorImpl<const ExplodedNode*> &nodes) {
  1138. // Create the trimmed graph. It will contain the shortest paths from the
  1139. // error nodes to the root. In the new graph we should only have one
  1140. // error node unless there are two or more error nodes with the same minimum
  1141. // path length.
  1142. ExplodedGraph* GTrim;
  1143. InterExplodedGraphMap* NMap;
  1144. llvm::DenseMap<const void*, const void*> InverseMap;
  1145. llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(),
  1146. &InverseMap);
  1147. // Create owning pointers for GTrim and NMap just to ensure that they are
  1148. // released when this function exists.
  1149. OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
  1150. OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
  1151. // Find the (first) error node in the trimmed graph. We just need to consult
  1152. // the node map (NMap) which maps from nodes in the original graph to nodes
  1153. // in the new graph.
  1154. std::queue<const ExplodedNode*> WS;
  1155. typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
  1156. IndexMapTy IndexMap;
  1157. for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) {
  1158. const ExplodedNode *originalNode = nodes[nodeIndex];
  1159. if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) {
  1160. WS.push(N);
  1161. IndexMap[originalNode] = nodeIndex;
  1162. }
  1163. }
  1164. assert(!WS.empty() && "No error node found in the trimmed graph.");
  1165. // Create a new (third!) graph with a single path. This is the graph
  1166. // that will be returned to the caller.
  1167. ExplodedGraph *GNew = new ExplodedGraph();
  1168. // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
  1169. // to the root node, and then construct a new graph that contains only
  1170. // a single path.
  1171. llvm::DenseMap<const void*,unsigned> Visited;
  1172. unsigned cnt = 0;
  1173. const ExplodedNode *Root = 0;
  1174. while (!WS.empty()) {
  1175. const ExplodedNode *Node = WS.front();
  1176. WS.pop();
  1177. if (Visited.find(Node) != Visited.end())
  1178. continue;
  1179. Visited[Node] = cnt++;
  1180. if (Node->pred_empty()) {
  1181. Root = Node;
  1182. break;
  1183. }
  1184. for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
  1185. E=Node->pred_end(); I!=E; ++I)
  1186. WS.push(*I);
  1187. }
  1188. assert(Root);
  1189. // Now walk from the root down the BFS path, always taking the successor
  1190. // with the lowest number.
  1191. ExplodedNode *Last = 0, *First = 0;
  1192. NodeBackMap *BM = new NodeBackMap();
  1193. unsigned NodeIndex = 0;
  1194. for ( const ExplodedNode *N = Root ;;) {
  1195. // Lookup the number associated with the current node.
  1196. llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
  1197. assert(I != Visited.end());
  1198. // Create the equivalent node in the new graph with the same state
  1199. // and location.
  1200. ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState());
  1201. // Store the mapping to the original node.
  1202. llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
  1203. assert(IMitr != InverseMap.end() && "No mapping to original node.");
  1204. (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
  1205. // Link up the new node with the previous node.
  1206. if (Last)
  1207. NewN->addPredecessor(Last, *GNew);
  1208. Last = NewN;
  1209. // Are we at the final node?
  1210. IndexMapTy::iterator IMI =
  1211. IndexMap.find((const ExplodedNode*)(IMitr->second));
  1212. if (IMI != IndexMap.end()) {
  1213. First = NewN;
  1214. NodeIndex = IMI->second;
  1215. break;
  1216. }
  1217. // Find the next successor node. We choose the node that is marked
  1218. // with the lowest DFS number.
  1219. ExplodedNode::const_succ_iterator SI = N->succ_begin();
  1220. ExplodedNode::const_succ_iterator SE = N->succ_end();
  1221. N = 0;
  1222. for (unsigned MinVal = 0; SI != SE; ++SI) {
  1223. I = Visited.find(*SI);
  1224. if (I == Visited.end())
  1225. continue;
  1226. if (!N || I->second < MinVal) {
  1227. N = *SI;
  1228. MinVal = I->second;
  1229. }
  1230. }
  1231. assert(N);
  1232. }
  1233. assert(First);
  1234. return std::make_pair(std::make_pair(GNew, BM),
  1235. std::make_pair(First, NodeIndex));
  1236. }
  1237. /// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
  1238. /// and collapses PathDiagosticPieces that are expanded by macros.
  1239. static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
  1240. typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
  1241. MacroStackTy;
  1242. typedef std::vector<PathDiagnosticPiece*>
  1243. PiecesTy;
  1244. MacroStackTy MacroStack;
  1245. PiecesTy Pieces;
  1246. for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
  1247. // Get the location of the PathDiagnosticPiece.
  1248. const FullSourceLoc Loc = I->getLocation().asLocation();
  1249. // Determine the instantiation location, which is the location we group
  1250. // related PathDiagnosticPieces.
  1251. SourceLocation InstantiationLoc = Loc.isMacroID() ?
  1252. SM.getExpansionLoc(Loc) :
  1253. SourceLocation();
  1254. if (Loc.isFileID()) {
  1255. MacroStack.clear();
  1256. Pieces.push_back(&*I);
  1257. continue;
  1258. }
  1259. assert(Loc.isMacroID());
  1260. // Is the PathDiagnosticPiece within the same macro group?
  1261. if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
  1262. MacroStack.back().first->push_back(&*I);
  1263. continue;
  1264. }
  1265. // We aren't in the same group. Are we descending into a new macro
  1266. // or are part of an old one?
  1267. PathDiagnosticMacroPiece *MacroGroup = 0;
  1268. SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
  1269. SM.getExpansionLoc(Loc) :
  1270. SourceLocation();
  1271. // Walk the entire macro stack.
  1272. while (!MacroStack.empty()) {
  1273. if (InstantiationLoc == MacroStack.back().second) {
  1274. MacroGroup = MacroStack.back().first;
  1275. break;
  1276. }
  1277. if (ParentInstantiationLoc == MacroStack.back().second) {
  1278. MacroGroup = MacroStack.back().first;
  1279. break;
  1280. }
  1281. MacroStack.pop_back();
  1282. }
  1283. if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
  1284. // Create a new macro group and add it to the stack.
  1285. PathDiagnosticMacroPiece *NewGroup =
  1286. new PathDiagnosticMacroPiece(
  1287. PathDiagnosticLocation::createSingleLocation(I->getLocation()));
  1288. if (MacroGroup)
  1289. MacroGroup->push_back(NewGroup);
  1290. else {
  1291. assert(InstantiationLoc.isFileID());
  1292. Pieces.push_back(NewGroup);
  1293. }
  1294. MacroGroup = NewGroup;
  1295. MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
  1296. }
  1297. // Finally, add the PathDiagnosticPiece to the group.
  1298. MacroGroup->push_back(&*I);
  1299. }
  1300. // Now take the pieces and construct a new PathDiagnostic.
  1301. PD.resetPath(false);
  1302. for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
  1303. if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
  1304. if (!MP->containsEvent()) {
  1305. delete MP;
  1306. continue;
  1307. }
  1308. PD.push_back(*I);
  1309. }
  1310. }
  1311. void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
  1312. SmallVectorImpl<BugReport *> &bugReports) {
  1313. assert(!bugReports.empty());
  1314. SmallVector<const ExplodedNode *, 10> errorNodes;
  1315. for (SmallVectorImpl<BugReport*>::iterator I = bugReports.begin(),
  1316. E = bugReports.end(); I != E; ++I) {
  1317. errorNodes.push_back((*I)->getErrorNode());
  1318. }
  1319. // Construct a new graph that contains only a single path from the error
  1320. // node to a root.
  1321. const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
  1322. std::pair<ExplodedNode*, unsigned> >&
  1323. GPair = MakeReportGraph(&getGraph(), errorNodes);
  1324. // Find the BugReport with the original location.
  1325. assert(GPair.second.second < bugReports.size());
  1326. BugReport *R = bugReports[GPair.second.second];
  1327. assert(R && "No original report found for sliced graph.");
  1328. OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
  1329. OwningPtr<NodeBackMap> BackMap(GPair.first.second);
  1330. const ExplodedNode *N = GPair.second.first;
  1331. // Start building the path diagnostic...
  1332. PathDiagnosticBuilder PDB(*this, R, BackMap.get(),
  1333. getPathDiagnosticConsumer());
  1334. // Register additional node visitors.
  1335. R->addVisitor(new NilReceiverBRVisitor());
  1336. R->addVisitor(new ConditionBRVisitor());
  1337. // If inlining is turning out, emit diagnostics for CallEnter and
  1338. // CallExit at the top level.
  1339. bool showTopLevel = Eng.getAnalysisManager().shouldInlineCall();
  1340. R->addVisitor(new CallEnterExitBRVisitor(showTopLevel));
  1341. // Generate the very last diagnostic piece - the piece is visible before
  1342. // the trace is expanded.
  1343. PathDiagnosticPiece *LastPiece = 0;
  1344. for (BugReport::visitor_iterator I = R->visitor_begin(),
  1345. E = R->visitor_end(); I!=E; ++I) {
  1346. if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) {
  1347. assert (!LastPiece &&
  1348. "There can only be one final piece in a diagnostic.");
  1349. LastPiece = Piece;
  1350. }
  1351. }
  1352. if (!LastPiece)
  1353. LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
  1354. if (LastPiece)
  1355. PD.push_back(LastPiece);
  1356. else
  1357. return;
  1358. switch (PDB.getGenerationScheme()) {
  1359. case PathDiagnosticConsumer::Extensive:
  1360. GenerateExtensivePathDiagnostic(PD, PDB, N);
  1361. break;
  1362. case PathDiagnosticConsumer::Minimal:
  1363. GenerateMinimalPathDiagnostic(PD, PDB, N);
  1364. break;
  1365. }
  1366. }
  1367. void BugReporter::Register(BugType *BT) {
  1368. BugTypes = F.add(BugTypes, BT);
  1369. }
  1370. void BugReporter::EmitReport(BugReport* R) {
  1371. // Compute the bug report's hash to determine its equivalence class.
  1372. llvm::FoldingSetNodeID ID;
  1373. R->Profile(ID);
  1374. // Lookup the equivance class. If there isn't one, create it.
  1375. BugType& BT = R->getBugType();
  1376. Register(&BT);
  1377. void *InsertPos;
  1378. BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
  1379. if (!EQ) {
  1380. EQ = new BugReportEquivClass(R);
  1381. EQClasses.InsertNode(EQ, InsertPos);
  1382. EQClassesVector.push_back(EQ);
  1383. }
  1384. else
  1385. EQ->AddReport(R);
  1386. }
  1387. //===----------------------------------------------------------------------===//
  1388. // Emitting reports in equivalence classes.
  1389. //===----------------------------------------------------------------------===//
  1390. namespace {
  1391. struct FRIEC_WLItem {
  1392. const ExplodedNode *N;
  1393. ExplodedNode::const_succ_iterator I, E;
  1394. FRIEC_WLItem(const ExplodedNode *n)
  1395. : N(n), I(N->succ_begin()), E(N->succ_end()) {}
  1396. };
  1397. }
  1398. static BugReport *
  1399. FindReportInEquivalenceClass(BugReportEquivClass& EQ,
  1400. SmallVectorImpl<BugReport*> &bugReports) {
  1401. BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
  1402. assert(I != E);
  1403. BugReport *R = *I;
  1404. BugType& BT = R->getBugType();
  1405. // If we don't need to suppress any of the nodes because they are
  1406. // post-dominated by a sink, simply add all the nodes in the equivalence class
  1407. // to 'Nodes'. Any of the reports will serve as a "representative" report.
  1408. if (!BT.isSuppressOnSink()) {
  1409. for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
  1410. const ExplodedNode *N = I->getErrorNode();
  1411. if (N) {
  1412. R = *I;
  1413. bugReports.push_back(R);
  1414. }
  1415. }
  1416. return R;
  1417. }
  1418. // For bug reports that should be suppressed when all paths are post-dominated
  1419. // by a sink node, iterate through the reports in the equivalence class
  1420. // until we find one that isn't post-dominated (if one exists). We use a
  1421. // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
  1422. // this as a recursive function, but we don't want to risk blowing out the
  1423. // stack for very long paths.
  1424. BugReport *exampleReport = 0;
  1425. for (; I != E; ++I) {
  1426. R = *I;
  1427. const ExplodedNode *errorNode = R->getErrorNode();
  1428. if (!errorNode)
  1429. continue;
  1430. if (errorNode->isSink()) {
  1431. llvm_unreachable(
  1432. "BugType::isSuppressSink() should not be 'true' for sink end nodes");
  1433. }
  1434. // No successors? By definition this nodes isn't post-dominated by a sink.
  1435. if (errorNode->succ_empty()) {
  1436. bugReports.push_back(R);
  1437. if (!exampleReport)
  1438. exampleReport = R;
  1439. continue;
  1440. }
  1441. // At this point we know that 'N' is not a sink and it has at least one
  1442. // successor. Use a DFS worklist to find a non-sink end-of-path node.
  1443. typedef FRIEC_WLItem WLItem;
  1444. typedef SmallVector<WLItem, 10> DFSWorkList;
  1445. llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
  1446. DFSWorkList WL;
  1447. WL.push_back(errorNode);
  1448. Visited[errorNode] = 1;
  1449. while (!WL.empty()) {
  1450. WLItem &WI = WL.back();
  1451. assert(!WI.N->succ_empty());
  1452. for (; WI.I != WI.E; ++WI.I) {
  1453. const ExplodedNode *Succ = *WI.I;
  1454. // End-of-path node?
  1455. if (Succ->succ_empty()) {
  1456. // If we found an end-of-path node that is not a sink.
  1457. if (!Succ->isSink()) {
  1458. bugReports.push_back(R);
  1459. if (!exampleReport)
  1460. exampleReport = R;
  1461. WL.clear();
  1462. break;
  1463. }
  1464. // Found a sink? Continue on to the next successor.
  1465. continue;
  1466. }
  1467. // Mark the successor as visited. If it hasn't been explored,
  1468. // enqueue it to the DFS worklist.
  1469. unsigned &mark = Visited[Succ];
  1470. if (!mark) {
  1471. mark = 1;
  1472. WL.push_back(Succ);
  1473. break;
  1474. }
  1475. }
  1476. // The worklist may have been cleared at this point. First
  1477. // check if it is empty before checking the last item.
  1478. if (!WL.empty() && &WL.back() == &WI)
  1479. WL.pop_back();
  1480. }
  1481. }
  1482. // ExampleReport will be NULL if all the nodes in the equivalence class
  1483. // were post-dominated by sinks.
  1484. return exampleReport;
  1485. }
  1486. //===----------------------------------------------------------------------===//
  1487. // DiagnosticCache. This is a hack to cache analyzer diagnostics. It
  1488. // uses global state, which eventually should go elsewhere.
  1489. //===----------------------------------------------------------------------===//
  1490. namespace {
  1491. class DiagCacheItem : public llvm::FoldingSetNode {
  1492. llvm::FoldingSetNodeID ID;
  1493. public:
  1494. DiagCacheItem(BugReport *R, PathDiagnostic *PD) {
  1495. R->Profile(ID);
  1496. PD->Profile(ID);
  1497. }
  1498. void Profile(llvm::FoldingSetNodeID &id) {
  1499. id = ID;
  1500. }
  1501. llvm::FoldingSetNodeID &getID() { return ID; }
  1502. };
  1503. }
  1504. static bool IsCachedDiagnostic(BugReport *R, PathDiagnostic *PD) {
  1505. // FIXME: Eventually this diagnostic cache should reside in something
  1506. // like AnalysisManager instead of being a static variable. This is
  1507. // really unsafe in the long term.
  1508. typedef llvm::FoldingSet<DiagCacheItem> DiagnosticCache;
  1509. static DiagnosticCache DC;
  1510. void *InsertPos;
  1511. DiagCacheItem *Item = new DiagCacheItem(R, PD);
  1512. if (DC.FindNodeOrInsertPos(Item->getID(), InsertPos)) {
  1513. delete Item;
  1514. return true;
  1515. }
  1516. DC.InsertNode(Item, InsertPos);
  1517. return false;
  1518. }
  1519. void BugReporter::FlushReport(BugReportEquivClass& EQ) {
  1520. SmallVector<BugReport*, 10> bugReports;
  1521. BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
  1522. if (!exampleReport)
  1523. return;
  1524. PathDiagnosticConsumer* PD = getPathDiagnosticConsumer();
  1525. // FIXME: Make sure we use the 'R' for the path that was actually used.
  1526. // Probably doesn't make a difference in practice.
  1527. BugType& BT = exampleReport->getBugType();
  1528. OwningPtr<PathDiagnostic>
  1529. D(new PathDiagnostic(exampleReport->getBugType().getName(),
  1530. !PD || PD->useVerboseDescription()
  1531. ? exampleReport->getDescription()
  1532. : exampleReport->getShortDescription(),
  1533. BT.getCategory()));
  1534. if (!bugReports.empty())
  1535. GeneratePathDiagnostic(*D.get(), bugReports);
  1536. if (IsCachedDiagnostic(exampleReport, D.get()))
  1537. return;
  1538. // Get the meta data.
  1539. const BugReport::ExtraTextList &Meta =
  1540. exampleReport->getExtraText();
  1541. for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
  1542. e = Meta.end(); i != e; ++i) {
  1543. D->addMeta(*i);
  1544. }
  1545. // Emit a summary diagnostic to the regular Diagnostics engine.
  1546. BugReport::ranges_iterator Beg, End;
  1547. llvm::tie(Beg, End) = exampleReport->getRanges();
  1548. DiagnosticsEngine &Diag = getDiagnostic();
  1549. // Search the description for '%', as that will be interpretted as a
  1550. // format character by FormatDiagnostics.
  1551. StringRef desc = exampleReport->getShortDescription();
  1552. unsigned ErrorDiag;
  1553. {
  1554. SmallString<512> TmpStr;
  1555. llvm::raw_svector_ostream Out(TmpStr);
  1556. for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I)
  1557. if (*I == '%')
  1558. Out << "%%";
  1559. else
  1560. Out << *I;
  1561. Out.flush();
  1562. ErrorDiag = Diag.getCustomDiagID(DiagnosticsEngine::Warning, TmpStr);
  1563. }
  1564. {
  1565. DiagnosticBuilder diagBuilder = Diag.Report(
  1566. exampleReport->getLocation(getSourceManager()).asLocation(), ErrorDiag);
  1567. for (BugReport::ranges_iterator I = Beg; I != End; ++I)
  1568. diagBuilder << *I;
  1569. }
  1570. // Emit a full diagnostic for the path if we have a PathDiagnosticConsumer.
  1571. if (!PD)
  1572. return;
  1573. if (D->empty()) {
  1574. PathDiagnosticPiece *piece = new PathDiagnosticEventPiece(
  1575. exampleReport->getLocation(getSourceManager()),
  1576. exampleReport->getDescription());
  1577. for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
  1578. D->push_back(piece);
  1579. }
  1580. PD->HandlePathDiagnostic(D.take());
  1581. }
  1582. void BugReporter::EmitBasicReport(StringRef name, StringRef str,
  1583. PathDiagnosticLocation Loc,
  1584. SourceRange* RBeg, unsigned NumRanges) {
  1585. EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
  1586. }
  1587. void BugReporter::EmitBasicReport(StringRef name,
  1588. StringRef category,
  1589. StringRef str, PathDiagnosticLocation Loc,
  1590. SourceRange* RBeg, unsigned NumRanges) {
  1591. // 'BT' is owned by BugReporter.
  1592. BugType *BT = getBugTypeForName(name, category);
  1593. BugReport *R = new BugReport(*BT, str, Loc);
  1594. for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
  1595. EmitReport(R);
  1596. }
  1597. BugType *BugReporter::getBugTypeForName(StringRef name,
  1598. StringRef category) {
  1599. SmallString<136> fullDesc;
  1600. llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
  1601. llvm::StringMapEntry<BugType *> &
  1602. entry = StrBugTypes.GetOrCreateValue(fullDesc);
  1603. BugType *BT = entry.getValue();
  1604. if (!BT) {
  1605. BT = new BugType(name, category);
  1606. entry.setValue(BT);
  1607. }
  1608. return BT;
  1609. }