BugReporter.cpp 59 KB

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