BugReporter.cpp 59 KB

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