BugReporter.cpp 106 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083
  1. //===- BugReporter.cpp - Generate PathDiagnostics for bugs ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines BugReporter, a utility class for generating
  10. // PathDiagnostics.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclBase.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ParentMap.h"
  20. #include "clang/AST/Stmt.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtObjC.h"
  23. #include "clang/Analysis/AnalysisDeclContext.h"
  24. #include "clang/Analysis/CFG.h"
  25. #include "clang/Analysis/CFGStmtMap.h"
  26. #include "clang/Analysis/ProgramPoint.h"
  27. #include "clang/Basic/LLVM.h"
  28. #include "clang/Basic/SourceLocation.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  31. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
  32. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  33. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  34. #include "clang/StaticAnalyzer/Core/Checker.h"
  35. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  36. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  37. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  38. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  39. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  40. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  41. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  42. #include "llvm/ADT/ArrayRef.h"
  43. #include "llvm/ADT/DenseMap.h"
  44. #include "llvm/ADT/DenseSet.h"
  45. #include "llvm/ADT/FoldingSet.h"
  46. #include "llvm/ADT/None.h"
  47. #include "llvm/ADT/Optional.h"
  48. #include "llvm/ADT/STLExtras.h"
  49. #include "llvm/ADT/SmallPtrSet.h"
  50. #include "llvm/ADT/SmallString.h"
  51. #include "llvm/ADT/SmallVector.h"
  52. #include "llvm/ADT/Statistic.h"
  53. #include "llvm/ADT/StringRef.h"
  54. #include "llvm/ADT/iterator_range.h"
  55. #include "llvm/Support/Casting.h"
  56. #include "llvm/Support/Compiler.h"
  57. #include "llvm/Support/ErrorHandling.h"
  58. #include "llvm/Support/MemoryBuffer.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include <algorithm>
  61. #include <cassert>
  62. #include <cstddef>
  63. #include <iterator>
  64. #include <memory>
  65. #include <queue>
  66. #include <string>
  67. #include <tuple>
  68. #include <utility>
  69. #include <vector>
  70. using namespace clang;
  71. using namespace ento;
  72. #define DEBUG_TYPE "BugReporter"
  73. STATISTIC(MaxBugClassSize,
  74. "The maximum number of bug reports in the same equivalence class");
  75. STATISTIC(MaxValidBugClassSize,
  76. "The maximum number of bug reports in the same equivalence class "
  77. "where at least one report is valid (not suppressed)");
  78. BugReporterVisitor::~BugReporterVisitor() = default;
  79. void BugReporterContext::anchor() {}
  80. //===----------------------------------------------------------------------===//
  81. // PathDiagnosticBuilder and its associated routines and helper objects.
  82. //===----------------------------------------------------------------------===//
  83. namespace {
  84. /// A (CallPiece, node assiciated with its CallEnter) pair.
  85. using CallWithEntry =
  86. std::pair<PathDiagnosticCallPiece *, const ExplodedNode *>;
  87. using CallWithEntryStack = SmallVector<CallWithEntry, 6>;
  88. /// Map from each node to the diagnostic pieces visitors emit for them.
  89. using VisitorsDiagnosticsTy =
  90. llvm::DenseMap<const ExplodedNode *, std::vector<PathDiagnosticPieceRef>>;
  91. /// A map from PathDiagnosticPiece to the LocationContext of the inlined
  92. /// function call it represents.
  93. using LocationContextMap =
  94. llvm::DenseMap<const PathPieces *, const LocationContext *>;
  95. /// A helper class that contains everything needed to construct a
  96. /// PathDiagnostic object. It does no much more then providing convenient
  97. /// getters and some well placed asserts for extra security.
  98. class PathDiagnosticConstruct {
  99. /// The consumer we're constructing the bug report for.
  100. const PathDiagnosticConsumer *Consumer;
  101. /// Our current position in the bug path, which is owned by
  102. /// PathDiagnosticBuilder.
  103. const ExplodedNode *CurrentNode;
  104. /// A mapping from parts of the bug path (for example, a function call, which
  105. /// would span backwards from a CallExit to a CallEnter with the nodes in
  106. /// between them) with the location contexts it is associated with.
  107. LocationContextMap LCM;
  108. const SourceManager &SM;
  109. public:
  110. /// We keep stack of calls to functions as we're ascending the bug path.
  111. /// TODO: PathDiagnostic has a stack doing the same thing, shouldn't we use
  112. /// that instead?
  113. CallWithEntryStack CallStack;
  114. /// The bug report we're constructing. For ease of use, this field is kept
  115. /// public, though some "shortcut" getters are provided for commonly used
  116. /// methods of PathDiagnostic.
  117. std::unique_ptr<PathDiagnostic> PD;
  118. public:
  119. PathDiagnosticConstruct(const PathDiagnosticConsumer *PDC,
  120. const ExplodedNode *ErrorNode, const BugReport *R);
  121. /// \returns the location context associated with the current position in the
  122. /// bug path.
  123. const LocationContext *getCurrLocationContext() const {
  124. assert(CurrentNode && "Already reached the root!");
  125. return CurrentNode->getLocationContext();
  126. }
  127. /// Same as getCurrLocationContext (they should always return the same
  128. /// location context), but works after reaching the root of the bug path as
  129. /// well.
  130. const LocationContext *getLocationContextForActivePath() const {
  131. return LCM.find(&PD->getActivePath())->getSecond();
  132. }
  133. const ExplodedNode *getCurrentNode() const { return CurrentNode; }
  134. /// Steps the current node to its predecessor.
  135. /// \returns whether we reached the root of the bug path.
  136. bool ascendToPrevNode() {
  137. CurrentNode = CurrentNode->getFirstPred();
  138. return static_cast<bool>(CurrentNode);
  139. }
  140. const ParentMap &getParentMap() const {
  141. return getCurrLocationContext()->getParentMap();
  142. }
  143. const SourceManager &getSourceManager() const { return SM; }
  144. const Stmt *getParent(const Stmt *S) const {
  145. return getParentMap().getParent(S);
  146. }
  147. void updateLocCtxMap(const PathPieces *Path, const LocationContext *LC) {
  148. assert(Path && LC);
  149. LCM[Path] = LC;
  150. }
  151. const LocationContext *getLocationContextFor(const PathPieces *Path) const {
  152. assert(LCM.count(Path) &&
  153. "Failed to find the context associated with these pieces!");
  154. return LCM.find(Path)->getSecond();
  155. }
  156. bool isInLocCtxMap(const PathPieces *Path) const { return LCM.count(Path); }
  157. PathPieces &getActivePath() { return PD->getActivePath(); }
  158. PathPieces &getMutablePieces() { return PD->getMutablePieces(); }
  159. bool shouldAddPathEdges() const { return Consumer->shouldAddPathEdges(); }
  160. bool shouldGenerateDiagnostics() const {
  161. return Consumer->shouldGenerateDiagnostics();
  162. }
  163. bool supportsLogicalOpControlFlow() const {
  164. return Consumer->supportsLogicalOpControlFlow();
  165. }
  166. };
  167. /// Contains every contextual information needed for constructing a
  168. /// PathDiagnostic object for a given bug report. This class and its fields are
  169. /// immutable, and passes a BugReportConstruct object around during the
  170. /// construction.
  171. class PathDiagnosticBuilder : public BugReporterContext {
  172. /// A linear path from the error node to the root.
  173. std::unique_ptr<const ExplodedGraph> BugPath;
  174. /// The bug report we're describing. Visitors create their diagnostics with
  175. /// them being the last entities being able to modify it (for example,
  176. /// changing interestingness here would cause inconsistencies as to how this
  177. /// file and visitors construct diagnostics), hence its const.
  178. const BugReport *R;
  179. /// The leaf of the bug path. This isn't the same as the bug reports error
  180. /// node, which refers to the *original* graph, not the bug path.
  181. const ExplodedNode *const ErrorNode;
  182. /// The diagnostic pieces visitors emitted, which is expected to be collected
  183. /// by the time this builder is constructed.
  184. std::unique_ptr<const VisitorsDiagnosticsTy> VisitorsDiagnostics;
  185. public:
  186. /// Find a non-invalidated report for a given equivalence class, and returns
  187. /// a PathDiagnosticBuilder able to construct bug reports for different
  188. /// consumers. Returns None if no valid report is found.
  189. static Optional<PathDiagnosticBuilder>
  190. findValidReport(ArrayRef<BugReport *> &bugReports,
  191. PathSensitiveBugReporter &Reporter);
  192. PathDiagnosticBuilder(
  193. BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
  194. BugReport *r, const ExplodedNode *ErrorNode,
  195. std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics);
  196. /// This function is responsible for generating diagnostic pieces that are
  197. /// *not* provided by bug report visitors.
  198. /// These diagnostics may differ depending on the consumer's settings,
  199. /// and are therefore constructed separately for each consumer.
  200. ///
  201. /// There are two path diagnostics generation modes: with adding edges (used
  202. /// for plists) and without (used for HTML and text). When edges are added,
  203. /// the path is modified to insert artificially generated edges.
  204. /// Otherwise, more detailed diagnostics is emitted for block edges,
  205. /// explaining the transitions in words.
  206. std::unique_ptr<PathDiagnostic>
  207. generate(const PathDiagnosticConsumer *PDC) const;
  208. private:
  209. void generatePathDiagnosticsForNode(PathDiagnosticConstruct &C,
  210. PathDiagnosticLocation &PrevLoc) const;
  211. void generateMinimalDiagForBlockEdge(PathDiagnosticConstruct &C,
  212. BlockEdge BE) const;
  213. PathDiagnosticPieceRef
  214. generateDiagForGotoOP(const PathDiagnosticConstruct &C, const Stmt *S,
  215. PathDiagnosticLocation &Start) const;
  216. PathDiagnosticPieceRef
  217. generateDiagForSwitchOP(const PathDiagnosticConstruct &C, const CFGBlock *Dst,
  218. PathDiagnosticLocation &Start) const;
  219. PathDiagnosticPieceRef
  220. generateDiagForBinaryOP(const PathDiagnosticConstruct &C, const Stmt *T,
  221. const CFGBlock *Src, const CFGBlock *DstC) const;
  222. PathDiagnosticLocation
  223. ExecutionContinues(const PathDiagnosticConstruct &C) const;
  224. PathDiagnosticLocation
  225. ExecutionContinues(llvm::raw_string_ostream &os,
  226. const PathDiagnosticConstruct &C) const;
  227. const BugReport *getBugReport() const { return R; }
  228. };
  229. } // namespace
  230. //===----------------------------------------------------------------------===//
  231. // Helper routines for walking the ExplodedGraph and fetching statements.
  232. //===----------------------------------------------------------------------===//
  233. static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
  234. for (N = N->getFirstPred(); N; N = N->getFirstPred())
  235. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  236. return S;
  237. return nullptr;
  238. }
  239. static inline const Stmt*
  240. GetCurrentOrPreviousStmt(const ExplodedNode *N) {
  241. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  242. return S;
  243. return GetPreviousStmt(N);
  244. }
  245. //===----------------------------------------------------------------------===//
  246. // Diagnostic cleanup.
  247. //===----------------------------------------------------------------------===//
  248. static PathDiagnosticEventPiece *
  249. eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
  250. PathDiagnosticEventPiece *Y) {
  251. // Prefer diagnostics that come from ConditionBRVisitor over
  252. // those that came from TrackConstraintBRVisitor,
  253. // unless the one from ConditionBRVisitor is
  254. // its generic fallback diagnostic.
  255. const void *tagPreferred = ConditionBRVisitor::getTag();
  256. const void *tagLesser = TrackConstraintBRVisitor::getTag();
  257. if (X->getLocation() != Y->getLocation())
  258. return nullptr;
  259. if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
  260. return ConditionBRVisitor::isPieceMessageGeneric(X) ? Y : X;
  261. if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
  262. return ConditionBRVisitor::isPieceMessageGeneric(Y) ? X : Y;
  263. return nullptr;
  264. }
  265. /// An optimization pass over PathPieces that removes redundant diagnostics
  266. /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both
  267. /// BugReporterVisitors use different methods to generate diagnostics, with
  268. /// one capable of emitting diagnostics in some cases but not in others. This
  269. /// can lead to redundant diagnostic pieces at the same point in a path.
  270. static void removeRedundantMsgs(PathPieces &path) {
  271. unsigned N = path.size();
  272. if (N < 2)
  273. return;
  274. // NOTE: this loop intentionally is not using an iterator. Instead, we
  275. // are streaming the path and modifying it in place. This is done by
  276. // grabbing the front, processing it, and if we decide to keep it append
  277. // it to the end of the path. The entire path is processed in this way.
  278. for (unsigned i = 0; i < N; ++i) {
  279. auto piece = std::move(path.front());
  280. path.pop_front();
  281. switch (piece->getKind()) {
  282. case PathDiagnosticPiece::Call:
  283. removeRedundantMsgs(cast<PathDiagnosticCallPiece>(*piece).path);
  284. break;
  285. case PathDiagnosticPiece::Macro:
  286. removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(*piece).subPieces);
  287. break;
  288. case PathDiagnosticPiece::Event: {
  289. if (i == N-1)
  290. break;
  291. if (auto *nextEvent =
  292. dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
  293. auto *event = cast<PathDiagnosticEventPiece>(piece.get());
  294. // Check to see if we should keep one of the two pieces. If we
  295. // come up with a preference, record which piece to keep, and consume
  296. // another piece from the path.
  297. if (auto *pieceToKeep =
  298. eventsDescribeSameCondition(event, nextEvent)) {
  299. piece = std::move(pieceToKeep == event ? piece : path.front());
  300. path.pop_front();
  301. ++i;
  302. }
  303. }
  304. break;
  305. }
  306. case PathDiagnosticPiece::ControlFlow:
  307. case PathDiagnosticPiece::Note:
  308. case PathDiagnosticPiece::PopUp:
  309. break;
  310. }
  311. path.push_back(std::move(piece));
  312. }
  313. }
  314. /// Recursively scan through a path and prune out calls and macros pieces
  315. /// that aren't needed. Return true if afterwards the path contains
  316. /// "interesting stuff" which means it shouldn't be pruned from the parent path.
  317. static bool removeUnneededCalls(const PathDiagnosticConstruct &C,
  318. PathPieces &pieces, const BugReport *R,
  319. bool IsInteresting = false) {
  320. bool containsSomethingInteresting = IsInteresting;
  321. const unsigned N = pieces.size();
  322. for (unsigned i = 0 ; i < N ; ++i) {
  323. // Remove the front piece from the path. If it is still something we
  324. // want to keep once we are done, we will push it back on the end.
  325. auto piece = std::move(pieces.front());
  326. pieces.pop_front();
  327. switch (piece->getKind()) {
  328. case PathDiagnosticPiece::Call: {
  329. auto &call = cast<PathDiagnosticCallPiece>(*piece);
  330. // Check if the location context is interesting.
  331. if (!removeUnneededCalls(
  332. C, call.path, R,
  333. R->isInteresting(C.getLocationContextFor(&call.path))))
  334. continue;
  335. containsSomethingInteresting = true;
  336. break;
  337. }
  338. case PathDiagnosticPiece::Macro: {
  339. auto &macro = cast<PathDiagnosticMacroPiece>(*piece);
  340. if (!removeUnneededCalls(C, macro.subPieces, R, IsInteresting))
  341. continue;
  342. containsSomethingInteresting = true;
  343. break;
  344. }
  345. case PathDiagnosticPiece::Event: {
  346. auto &event = cast<PathDiagnosticEventPiece>(*piece);
  347. // We never throw away an event, but we do throw it away wholesale
  348. // as part of a path if we throw the entire path away.
  349. containsSomethingInteresting |= !event.isPrunable();
  350. break;
  351. }
  352. case PathDiagnosticPiece::ControlFlow:
  353. case PathDiagnosticPiece::Note:
  354. case PathDiagnosticPiece::PopUp:
  355. break;
  356. }
  357. pieces.push_back(std::move(piece));
  358. }
  359. return containsSomethingInteresting;
  360. }
  361. /// Same logic as above to remove extra pieces.
  362. static void removePopUpNotes(PathPieces &Path) {
  363. for (unsigned int i = 0; i < Path.size(); ++i) {
  364. auto Piece = std::move(Path.front());
  365. Path.pop_front();
  366. if (!isa<PathDiagnosticPopUpPiece>(*Piece))
  367. Path.push_back(std::move(Piece));
  368. }
  369. }
  370. /// Returns true if the given decl has been implicitly given a body, either by
  371. /// the analyzer or by the compiler proper.
  372. static bool hasImplicitBody(const Decl *D) {
  373. assert(D);
  374. return D->isImplicit() || !D->hasBody();
  375. }
  376. /// Recursively scan through a path and make sure that all call pieces have
  377. /// valid locations.
  378. static void
  379. adjustCallLocations(PathPieces &Pieces,
  380. PathDiagnosticLocation *LastCallLocation = nullptr) {
  381. for (const auto &I : Pieces) {
  382. auto *Call = dyn_cast<PathDiagnosticCallPiece>(I.get());
  383. if (!Call)
  384. continue;
  385. if (LastCallLocation) {
  386. bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
  387. if (CallerIsImplicit || !Call->callEnter.asLocation().isValid())
  388. Call->callEnter = *LastCallLocation;
  389. if (CallerIsImplicit || !Call->callReturn.asLocation().isValid())
  390. Call->callReturn = *LastCallLocation;
  391. }
  392. // Recursively clean out the subclass. Keep this call around if
  393. // it contains any informative diagnostics.
  394. PathDiagnosticLocation *ThisCallLocation;
  395. if (Call->callEnterWithin.asLocation().isValid() &&
  396. !hasImplicitBody(Call->getCallee()))
  397. ThisCallLocation = &Call->callEnterWithin;
  398. else
  399. ThisCallLocation = &Call->callEnter;
  400. assert(ThisCallLocation && "Outermost call has an invalid location");
  401. adjustCallLocations(Call->path, ThisCallLocation);
  402. }
  403. }
  404. /// Remove edges in and out of C++ default initializer expressions. These are
  405. /// for fields that have in-class initializers, as opposed to being initialized
  406. /// explicitly in a constructor or braced list.
  407. static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
  408. for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
  409. if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
  410. removeEdgesToDefaultInitializers(C->path);
  411. if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
  412. removeEdgesToDefaultInitializers(M->subPieces);
  413. if (auto *CF = dyn_cast<PathDiagnosticControlFlowPiece>(I->get())) {
  414. const Stmt *Start = CF->getStartLocation().asStmt();
  415. const Stmt *End = CF->getEndLocation().asStmt();
  416. if (Start && isa<CXXDefaultInitExpr>(Start)) {
  417. I = Pieces.erase(I);
  418. continue;
  419. } else if (End && isa<CXXDefaultInitExpr>(End)) {
  420. PathPieces::iterator Next = std::next(I);
  421. if (Next != E) {
  422. if (auto *NextCF =
  423. dyn_cast<PathDiagnosticControlFlowPiece>(Next->get())) {
  424. NextCF->setStartLocation(CF->getStartLocation());
  425. }
  426. }
  427. I = Pieces.erase(I);
  428. continue;
  429. }
  430. }
  431. I++;
  432. }
  433. }
  434. /// Remove all pieces with invalid locations as these cannot be serialized.
  435. /// We might have pieces with invalid locations as a result of inlining Body
  436. /// Farm generated functions.
  437. static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
  438. for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
  439. if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
  440. removePiecesWithInvalidLocations(C->path);
  441. if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
  442. removePiecesWithInvalidLocations(M->subPieces);
  443. if (!(*I)->getLocation().isValid() ||
  444. !(*I)->getLocation().asLocation().isValid()) {
  445. I = Pieces.erase(I);
  446. continue;
  447. }
  448. I++;
  449. }
  450. }
  451. PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(
  452. const PathDiagnosticConstruct &C) const {
  453. if (const Stmt *S = PathDiagnosticLocation::getNextStmt(C.getCurrentNode()))
  454. return PathDiagnosticLocation(S, getSourceManager(),
  455. C.getCurrLocationContext());
  456. return PathDiagnosticLocation::createDeclEnd(C.getCurrLocationContext(),
  457. getSourceManager());
  458. }
  459. PathDiagnosticLocation PathDiagnosticBuilder::ExecutionContinues(
  460. llvm::raw_string_ostream &os, const PathDiagnosticConstruct &C) const {
  461. // Slow, but probably doesn't matter.
  462. if (os.str().empty())
  463. os << ' ';
  464. const PathDiagnosticLocation &Loc = ExecutionContinues(C);
  465. if (Loc.asStmt())
  466. os << "Execution continues on line "
  467. << getSourceManager().getExpansionLineNumber(Loc.asLocation())
  468. << '.';
  469. else {
  470. os << "Execution jumps to the end of the ";
  471. const Decl *D = C.getCurrLocationContext()->getDecl();
  472. if (isa<ObjCMethodDecl>(D))
  473. os << "method";
  474. else if (isa<FunctionDecl>(D))
  475. os << "function";
  476. else {
  477. assert(isa<BlockDecl>(D));
  478. os << "anonymous block";
  479. }
  480. os << '.';
  481. }
  482. return Loc;
  483. }
  484. static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
  485. if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
  486. return PM.getParentIgnoreParens(S);
  487. const Stmt *Parent = PM.getParentIgnoreParens(S);
  488. if (!Parent)
  489. return nullptr;
  490. switch (Parent->getStmtClass()) {
  491. case Stmt::ForStmtClass:
  492. case Stmt::DoStmtClass:
  493. case Stmt::WhileStmtClass:
  494. case Stmt::ObjCForCollectionStmtClass:
  495. case Stmt::CXXForRangeStmtClass:
  496. return Parent;
  497. default:
  498. break;
  499. }
  500. return nullptr;
  501. }
  502. static PathDiagnosticLocation
  503. getEnclosingStmtLocation(const Stmt *S, const LocationContext *LC,
  504. bool allowNestedContexts = false) {
  505. if (!S)
  506. return {};
  507. const SourceManager &SMgr = LC->getDecl()->getASTContext().getSourceManager();
  508. while (const Stmt *Parent = getEnclosingParent(S, LC->getParentMap())) {
  509. switch (Parent->getStmtClass()) {
  510. case Stmt::BinaryOperatorClass: {
  511. const auto *B = cast<BinaryOperator>(Parent);
  512. if (B->isLogicalOp())
  513. return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC);
  514. break;
  515. }
  516. case Stmt::CompoundStmtClass:
  517. case Stmt::StmtExprClass:
  518. return PathDiagnosticLocation(S, SMgr, LC);
  519. case Stmt::ChooseExprClass:
  520. // Similar to '?' if we are referring to condition, just have the edge
  521. // point to the entire choose expression.
  522. if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
  523. return PathDiagnosticLocation(Parent, SMgr, LC);
  524. else
  525. return PathDiagnosticLocation(S, SMgr, LC);
  526. case Stmt::BinaryConditionalOperatorClass:
  527. case Stmt::ConditionalOperatorClass:
  528. // For '?', if we are referring to condition, just have the edge point
  529. // to the entire '?' expression.
  530. if (allowNestedContexts ||
  531. cast<AbstractConditionalOperator>(Parent)->getCond() == S)
  532. return PathDiagnosticLocation(Parent, SMgr, LC);
  533. else
  534. return PathDiagnosticLocation(S, SMgr, LC);
  535. case Stmt::CXXForRangeStmtClass:
  536. if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
  537. return PathDiagnosticLocation(S, SMgr, LC);
  538. break;
  539. case Stmt::DoStmtClass:
  540. return PathDiagnosticLocation(S, SMgr, LC);
  541. case Stmt::ForStmtClass:
  542. if (cast<ForStmt>(Parent)->getBody() == S)
  543. return PathDiagnosticLocation(S, SMgr, LC);
  544. break;
  545. case Stmt::IfStmtClass:
  546. if (cast<IfStmt>(Parent)->getCond() != S)
  547. return PathDiagnosticLocation(S, SMgr, LC);
  548. break;
  549. case Stmt::ObjCForCollectionStmtClass:
  550. if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
  551. return PathDiagnosticLocation(S, SMgr, LC);
  552. break;
  553. case Stmt::WhileStmtClass:
  554. if (cast<WhileStmt>(Parent)->getCond() != S)
  555. return PathDiagnosticLocation(S, SMgr, LC);
  556. break;
  557. default:
  558. break;
  559. }
  560. S = Parent;
  561. }
  562. assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
  563. return PathDiagnosticLocation(S, SMgr, LC);
  564. }
  565. //===----------------------------------------------------------------------===//
  566. // "Minimal" path diagnostic generation algorithm.
  567. //===----------------------------------------------------------------------===//
  568. /// If the piece contains a special message, add it to all the call pieces on
  569. /// the active stack. For exampler, my_malloc allocated memory, so MallocChecker
  570. /// will construct an event at the call to malloc(), and add a stack hint that
  571. /// an allocated memory was returned. We'll use this hint to construct a message
  572. /// when returning from the call to my_malloc
  573. ///
  574. /// void *my_malloc() { return malloc(sizeof(int)); }
  575. /// void fishy() {
  576. /// void *ptr = my_malloc(); // returned allocated memory
  577. /// } // leak
  578. static void updateStackPiecesWithMessage(PathDiagnosticPiece &P,
  579. const CallWithEntryStack &CallStack) {
  580. if (auto *ep = dyn_cast<PathDiagnosticEventPiece>(&P)) {
  581. if (ep->hasCallStackHint())
  582. for (const auto &I : CallStack) {
  583. PathDiagnosticCallPiece *CP = I.first;
  584. const ExplodedNode *N = I.second;
  585. std::string stackMsg = ep->getCallStackMessage(N);
  586. // The last message on the path to final bug is the most important
  587. // one. Since we traverse the path backwards, do not add the message
  588. // if one has been previously added.
  589. if (!CP->hasCallStackMessage())
  590. CP->setCallStackMessage(stackMsg);
  591. }
  592. }
  593. }
  594. static void CompactMacroExpandedPieces(PathPieces &path,
  595. const SourceManager& SM);
  596. PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForSwitchOP(
  597. const PathDiagnosticConstruct &C, const CFGBlock *Dst,
  598. PathDiagnosticLocation &Start) const {
  599. const SourceManager &SM = getSourceManager();
  600. // Figure out what case arm we took.
  601. std::string sbuf;
  602. llvm::raw_string_ostream os(sbuf);
  603. PathDiagnosticLocation End;
  604. if (const Stmt *S = Dst->getLabel()) {
  605. End = PathDiagnosticLocation(S, SM, C.getCurrLocationContext());
  606. switch (S->getStmtClass()) {
  607. default:
  608. os << "No cases match in the switch statement. "
  609. "Control jumps to line "
  610. << End.asLocation().getExpansionLineNumber();
  611. break;
  612. case Stmt::DefaultStmtClass:
  613. os << "Control jumps to the 'default' case at line "
  614. << End.asLocation().getExpansionLineNumber();
  615. break;
  616. case Stmt::CaseStmtClass: {
  617. os << "Control jumps to 'case ";
  618. const auto *Case = cast<CaseStmt>(S);
  619. const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
  620. // Determine if it is an enum.
  621. bool GetRawInt = true;
  622. if (const auto *DR = dyn_cast<DeclRefExpr>(LHS)) {
  623. // FIXME: Maybe this should be an assertion. Are there cases
  624. // were it is not an EnumConstantDecl?
  625. const auto *D = dyn_cast<EnumConstantDecl>(DR->getDecl());
  626. if (D) {
  627. GetRawInt = false;
  628. os << *D;
  629. }
  630. }
  631. if (GetRawInt)
  632. os << LHS->EvaluateKnownConstInt(getASTContext());
  633. os << ":' at line " << End.asLocation().getExpansionLineNumber();
  634. break;
  635. }
  636. }
  637. } else {
  638. os << "'Default' branch taken. ";
  639. End = ExecutionContinues(os, C);
  640. }
  641. return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  642. os.str());
  643. }
  644. PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForGotoOP(
  645. const PathDiagnosticConstruct &C, const Stmt *S,
  646. PathDiagnosticLocation &Start) const {
  647. std::string sbuf;
  648. llvm::raw_string_ostream os(sbuf);
  649. const PathDiagnosticLocation &End =
  650. getEnclosingStmtLocation(S, C.getCurrLocationContext());
  651. os << "Control jumps to line " << End.asLocation().getExpansionLineNumber();
  652. return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str());
  653. }
  654. PathDiagnosticPieceRef PathDiagnosticBuilder::generateDiagForBinaryOP(
  655. const PathDiagnosticConstruct &C, const Stmt *T, const CFGBlock *Src,
  656. const CFGBlock *Dst) const {
  657. const SourceManager &SM = getSourceManager();
  658. const auto *B = cast<BinaryOperator>(T);
  659. std::string sbuf;
  660. llvm::raw_string_ostream os(sbuf);
  661. os << "Left side of '";
  662. PathDiagnosticLocation Start, End;
  663. if (B->getOpcode() == BO_LAnd) {
  664. os << "&&"
  665. << "' is ";
  666. if (*(Src->succ_begin() + 1) == Dst) {
  667. os << "false";
  668. End = PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
  669. Start =
  670. PathDiagnosticLocation::createOperatorLoc(B, SM);
  671. } else {
  672. os << "true";
  673. Start =
  674. PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
  675. End = ExecutionContinues(C);
  676. }
  677. } else {
  678. assert(B->getOpcode() == BO_LOr);
  679. os << "||"
  680. << "' is ";
  681. if (*(Src->succ_begin() + 1) == Dst) {
  682. os << "false";
  683. Start =
  684. PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
  685. End = ExecutionContinues(C);
  686. } else {
  687. os << "true";
  688. End = PathDiagnosticLocation(B->getLHS(), SM, C.getCurrLocationContext());
  689. Start =
  690. PathDiagnosticLocation::createOperatorLoc(B, SM);
  691. }
  692. }
  693. return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  694. os.str());
  695. }
  696. void PathDiagnosticBuilder::generateMinimalDiagForBlockEdge(
  697. PathDiagnosticConstruct &C, BlockEdge BE) const {
  698. const SourceManager &SM = getSourceManager();
  699. const LocationContext *LC = C.getCurrLocationContext();
  700. const CFGBlock *Src = BE.getSrc();
  701. const CFGBlock *Dst = BE.getDst();
  702. const Stmt *T = Src->getTerminatorStmt();
  703. if (!T)
  704. return;
  705. auto Start = PathDiagnosticLocation::createBegin(T, SM, LC);
  706. switch (T->getStmtClass()) {
  707. default:
  708. break;
  709. case Stmt::GotoStmtClass:
  710. case Stmt::IndirectGotoStmtClass: {
  711. if (const Stmt *S = PathDiagnosticLocation::getNextStmt(C.getCurrentNode()))
  712. C.getActivePath().push_front(generateDiagForGotoOP(C, S, Start));
  713. break;
  714. }
  715. case Stmt::SwitchStmtClass: {
  716. C.getActivePath().push_front(generateDiagForSwitchOP(C, Dst, Start));
  717. break;
  718. }
  719. case Stmt::BreakStmtClass:
  720. case Stmt::ContinueStmtClass: {
  721. std::string sbuf;
  722. llvm::raw_string_ostream os(sbuf);
  723. PathDiagnosticLocation End = ExecutionContinues(os, C);
  724. C.getActivePath().push_front(
  725. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
  726. break;
  727. }
  728. // Determine control-flow for ternary '?'.
  729. case Stmt::BinaryConditionalOperatorClass:
  730. case Stmt::ConditionalOperatorClass: {
  731. std::string sbuf;
  732. llvm::raw_string_ostream os(sbuf);
  733. os << "'?' condition is ";
  734. if (*(Src->succ_begin() + 1) == Dst)
  735. os << "false";
  736. else
  737. os << "true";
  738. PathDiagnosticLocation End = ExecutionContinues(C);
  739. if (const Stmt *S = End.asStmt())
  740. End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
  741. C.getActivePath().push_front(
  742. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
  743. break;
  744. }
  745. // Determine control-flow for short-circuited '&&' and '||'.
  746. case Stmt::BinaryOperatorClass: {
  747. if (!C.supportsLogicalOpControlFlow())
  748. break;
  749. C.getActivePath().push_front(generateDiagForBinaryOP(C, T, Src, Dst));
  750. break;
  751. }
  752. case Stmt::DoStmtClass:
  753. if (*(Src->succ_begin()) == Dst) {
  754. std::string sbuf;
  755. llvm::raw_string_ostream os(sbuf);
  756. os << "Loop condition is true. ";
  757. PathDiagnosticLocation End = ExecutionContinues(os, C);
  758. if (const Stmt *S = End.asStmt())
  759. End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
  760. C.getActivePath().push_front(
  761. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  762. os.str()));
  763. } else {
  764. PathDiagnosticLocation End = ExecutionContinues(C);
  765. if (const Stmt *S = End.asStmt())
  766. End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
  767. C.getActivePath().push_front(
  768. std::make_shared<PathDiagnosticControlFlowPiece>(
  769. Start, End, "Loop condition is false. Exiting loop"));
  770. }
  771. break;
  772. case Stmt::WhileStmtClass:
  773. case Stmt::ForStmtClass:
  774. if (*(Src->succ_begin() + 1) == Dst) {
  775. std::string sbuf;
  776. llvm::raw_string_ostream os(sbuf);
  777. os << "Loop condition is false. ";
  778. PathDiagnosticLocation End = ExecutionContinues(os, C);
  779. if (const Stmt *S = End.asStmt())
  780. End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
  781. C.getActivePath().push_front(
  782. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  783. os.str()));
  784. } else {
  785. PathDiagnosticLocation End = ExecutionContinues(C);
  786. if (const Stmt *S = End.asStmt())
  787. End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
  788. C.getActivePath().push_front(
  789. std::make_shared<PathDiagnosticControlFlowPiece>(
  790. Start, End, "Loop condition is true. Entering loop body"));
  791. }
  792. break;
  793. case Stmt::IfStmtClass: {
  794. PathDiagnosticLocation End = ExecutionContinues(C);
  795. if (const Stmt *S = End.asStmt())
  796. End = getEnclosingStmtLocation(S, C.getCurrLocationContext());
  797. if (*(Src->succ_begin() + 1) == Dst)
  798. C.getActivePath().push_front(
  799. std::make_shared<PathDiagnosticControlFlowPiece>(
  800. Start, End, "Taking false branch"));
  801. else
  802. C.getActivePath().push_front(
  803. std::make_shared<PathDiagnosticControlFlowPiece>(
  804. Start, End, "Taking true branch"));
  805. break;
  806. }
  807. }
  808. }
  809. //===----------------------------------------------------------------------===//
  810. // Functions for determining if a loop was executed 0 times.
  811. //===----------------------------------------------------------------------===//
  812. static bool isLoop(const Stmt *Term) {
  813. switch (Term->getStmtClass()) {
  814. case Stmt::ForStmtClass:
  815. case Stmt::WhileStmtClass:
  816. case Stmt::ObjCForCollectionStmtClass:
  817. case Stmt::CXXForRangeStmtClass:
  818. return true;
  819. default:
  820. // Note that we intentionally do not include do..while here.
  821. return false;
  822. }
  823. }
  824. static bool isJumpToFalseBranch(const BlockEdge *BE) {
  825. const CFGBlock *Src = BE->getSrc();
  826. assert(Src->succ_size() == 2);
  827. return (*(Src->succ_begin()+1) == BE->getDst());
  828. }
  829. static bool isContainedByStmt(const ParentMap &PM, const Stmt *S,
  830. const Stmt *SubS) {
  831. while (SubS) {
  832. if (SubS == S)
  833. return true;
  834. SubS = PM.getParent(SubS);
  835. }
  836. return false;
  837. }
  838. static const Stmt *getStmtBeforeCond(const ParentMap &PM, const Stmt *Term,
  839. const ExplodedNode *N) {
  840. while (N) {
  841. Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
  842. if (SP) {
  843. const Stmt *S = SP->getStmt();
  844. if (!isContainedByStmt(PM, Term, S))
  845. return S;
  846. }
  847. N = N->getFirstPred();
  848. }
  849. return nullptr;
  850. }
  851. static bool isInLoopBody(const ParentMap &PM, const Stmt *S, const Stmt *Term) {
  852. const Stmt *LoopBody = nullptr;
  853. switch (Term->getStmtClass()) {
  854. case Stmt::CXXForRangeStmtClass: {
  855. const auto *FR = cast<CXXForRangeStmt>(Term);
  856. if (isContainedByStmt(PM, FR->getInc(), S))
  857. return true;
  858. if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
  859. return true;
  860. LoopBody = FR->getBody();
  861. break;
  862. }
  863. case Stmt::ForStmtClass: {
  864. const auto *FS = cast<ForStmt>(Term);
  865. if (isContainedByStmt(PM, FS->getInc(), S))
  866. return true;
  867. LoopBody = FS->getBody();
  868. break;
  869. }
  870. case Stmt::ObjCForCollectionStmtClass: {
  871. const auto *FC = cast<ObjCForCollectionStmt>(Term);
  872. LoopBody = FC->getBody();
  873. break;
  874. }
  875. case Stmt::WhileStmtClass:
  876. LoopBody = cast<WhileStmt>(Term)->getBody();
  877. break;
  878. default:
  879. return false;
  880. }
  881. return isContainedByStmt(PM, LoopBody, S);
  882. }
  883. /// Adds a sanitized control-flow diagnostic edge to a path.
  884. static void addEdgeToPath(PathPieces &path,
  885. PathDiagnosticLocation &PrevLoc,
  886. PathDiagnosticLocation NewLoc) {
  887. if (!NewLoc.isValid())
  888. return;
  889. SourceLocation NewLocL = NewLoc.asLocation();
  890. if (NewLocL.isInvalid())
  891. return;
  892. if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) {
  893. PrevLoc = NewLoc;
  894. return;
  895. }
  896. // Ignore self-edges, which occur when there are multiple nodes at the same
  897. // statement.
  898. if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt())
  899. return;
  900. path.push_front(
  901. std::make_shared<PathDiagnosticControlFlowPiece>(NewLoc, PrevLoc));
  902. PrevLoc = NewLoc;
  903. }
  904. /// A customized wrapper for CFGBlock::getTerminatorCondition()
  905. /// which returns the element for ObjCForCollectionStmts.
  906. static const Stmt *getTerminatorCondition(const CFGBlock *B) {
  907. const Stmt *S = B->getTerminatorCondition();
  908. if (const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(S))
  909. return FS->getElement();
  910. return S;
  911. }
  912. constexpr llvm::StringLiteral StrEnteringLoop = "Entering loop body";
  913. constexpr llvm::StringLiteral StrLoopBodyZero = "Loop body executed 0 times";
  914. constexpr llvm::StringLiteral StrLoopRangeEmpty =
  915. "Loop body skipped when range is empty";
  916. constexpr llvm::StringLiteral StrLoopCollectionEmpty =
  917. "Loop body skipped when collection is empty";
  918. static std::unique_ptr<FilesToLineNumsMap>
  919. findExecutedLines(const SourceManager &SM, const ExplodedNode *N);
  920. void PathDiagnosticBuilder::generatePathDiagnosticsForNode(
  921. PathDiagnosticConstruct &C, PathDiagnosticLocation &PrevLoc) const {
  922. ProgramPoint P = C.getCurrentNode()->getLocation();
  923. const SourceManager &SM = getSourceManager();
  924. // Have we encountered an entrance to a call? It may be
  925. // the case that we have not encountered a matching
  926. // call exit before this point. This means that the path
  927. // terminated within the call itself.
  928. if (auto CE = P.getAs<CallEnter>()) {
  929. if (C.shouldAddPathEdges()) {
  930. // Add an edge to the start of the function.
  931. const StackFrameContext *CalleeLC = CE->getCalleeContext();
  932. const Decl *D = CalleeLC->getDecl();
  933. // Add the edge only when the callee has body. We jump to the beginning
  934. // of the *declaration*, however we expect it to be followed by the
  935. // body. This isn't the case for autosynthesized property accessors in
  936. // Objective-C. No need for a similar extra check for CallExit points
  937. // because the exit edge comes from a statement (i.e. return),
  938. // not from declaration.
  939. if (D->hasBody())
  940. addEdgeToPath(C.getActivePath(), PrevLoc,
  941. PathDiagnosticLocation::createBegin(D, SM));
  942. }
  943. // Did we visit an entire call?
  944. bool VisitedEntireCall = C.PD->isWithinCall();
  945. C.PD->popActivePath();
  946. PathDiagnosticCallPiece *Call;
  947. if (VisitedEntireCall) {
  948. Call = cast<PathDiagnosticCallPiece>(C.getActivePath().front().get());
  949. } else {
  950. // The path terminated within a nested location context, create a new
  951. // call piece to encapsulate the rest of the path pieces.
  952. const Decl *Caller = CE->getLocationContext()->getDecl();
  953. Call = PathDiagnosticCallPiece::construct(C.getActivePath(), Caller);
  954. assert(C.getActivePath().size() == 1 &&
  955. C.getActivePath().front().get() == Call);
  956. // Since we just transferred the path over to the call piece, reset the
  957. // mapping of the active path to the current location context.
  958. assert(C.isInLocCtxMap(&C.getActivePath()) &&
  959. "When we ascend to a previously unvisited call, the active path's "
  960. "address shouldn't change, but rather should be compacted into "
  961. "a single CallEvent!");
  962. C.updateLocCtxMap(&C.getActivePath(), C.getCurrLocationContext());
  963. // Record the location context mapping for the path within the call.
  964. assert(!C.isInLocCtxMap(&Call->path) &&
  965. "When we ascend to a previously unvisited call, this must be the "
  966. "first time we encounter the caller context!");
  967. C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
  968. }
  969. Call->setCallee(*CE, SM);
  970. // Update the previous location in the active path.
  971. PrevLoc = Call->getLocation();
  972. if (!C.CallStack.empty()) {
  973. assert(C.CallStack.back().first == Call);
  974. C.CallStack.pop_back();
  975. }
  976. return;
  977. }
  978. assert(C.getCurrLocationContext() == C.getLocationContextForActivePath() &&
  979. "The current position in the bug path is out of sync with the "
  980. "location context associated with the active path!");
  981. // Have we encountered an exit from a function call?
  982. if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
  983. // We are descending into a call (backwards). Construct
  984. // a new call piece to contain the path pieces for that call.
  985. auto Call = PathDiagnosticCallPiece::construct(*CE, SM);
  986. // Record the mapping from call piece to LocationContext.
  987. assert(!C.isInLocCtxMap(&Call->path) &&
  988. "We just entered a call, this must've been the first time we "
  989. "encounter its context!");
  990. C.updateLocCtxMap(&Call->path, CE->getCalleeContext());
  991. if (C.shouldAddPathEdges()) {
  992. // Add the edge to the return site.
  993. addEdgeToPath(C.getActivePath(), PrevLoc, Call->callReturn);
  994. PrevLoc.invalidate();
  995. }
  996. auto *P = Call.get();
  997. C.getActivePath().push_front(std::move(Call));
  998. // Make the contents of the call the active path for now.
  999. C.PD->pushActivePath(&P->path);
  1000. C.CallStack.push_back(CallWithEntry(P, C.getCurrentNode()));
  1001. return;
  1002. }
  1003. if (auto PS = P.getAs<PostStmt>()) {
  1004. if (!C.shouldAddPathEdges())
  1005. return;
  1006. // Add an edge. If this is an ObjCForCollectionStmt do
  1007. // not add an edge here as it appears in the CFG both
  1008. // as a terminator and as a terminator condition.
  1009. if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
  1010. PathDiagnosticLocation L =
  1011. PathDiagnosticLocation(PS->getStmt(), SM, C.getCurrLocationContext());
  1012. addEdgeToPath(C.getActivePath(), PrevLoc, L);
  1013. }
  1014. } else if (auto BE = P.getAs<BlockEdge>()) {
  1015. if (!C.shouldAddPathEdges()) {
  1016. generateMinimalDiagForBlockEdge(C, *BE);
  1017. return;
  1018. }
  1019. // Are we jumping to the head of a loop? Add a special diagnostic.
  1020. if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
  1021. PathDiagnosticLocation L(Loop, SM, C.getCurrLocationContext());
  1022. const Stmt *Body = nullptr;
  1023. if (const auto *FS = dyn_cast<ForStmt>(Loop))
  1024. Body = FS->getBody();
  1025. else if (const auto *WS = dyn_cast<WhileStmt>(Loop))
  1026. Body = WS->getBody();
  1027. else if (const auto *OFS = dyn_cast<ObjCForCollectionStmt>(Loop)) {
  1028. Body = OFS->getBody();
  1029. } else if (const auto *FRS = dyn_cast<CXXForRangeStmt>(Loop)) {
  1030. Body = FRS->getBody();
  1031. }
  1032. // do-while statements are explicitly excluded here
  1033. auto p = std::make_shared<PathDiagnosticEventPiece>(
  1034. L, "Looping back to the head "
  1035. "of the loop");
  1036. p->setPrunable(true);
  1037. addEdgeToPath(C.getActivePath(), PrevLoc, p->getLocation());
  1038. C.getActivePath().push_front(std::move(p));
  1039. if (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  1040. addEdgeToPath(C.getActivePath(), PrevLoc,
  1041. PathDiagnosticLocation::createEndBrace(CS, SM));
  1042. }
  1043. }
  1044. const CFGBlock *BSrc = BE->getSrc();
  1045. const ParentMap &PM = C.getParentMap();
  1046. if (const Stmt *Term = BSrc->getTerminatorStmt()) {
  1047. // Are we jumping past the loop body without ever executing the
  1048. // loop (because the condition was false)?
  1049. if (isLoop(Term)) {
  1050. const Stmt *TermCond = getTerminatorCondition(BSrc);
  1051. bool IsInLoopBody = isInLoopBody(
  1052. PM, getStmtBeforeCond(PM, TermCond, C.getCurrentNode()), Term);
  1053. StringRef str;
  1054. if (isJumpToFalseBranch(&*BE)) {
  1055. if (!IsInLoopBody) {
  1056. if (isa<ObjCForCollectionStmt>(Term)) {
  1057. str = StrLoopCollectionEmpty;
  1058. } else if (isa<CXXForRangeStmt>(Term)) {
  1059. str = StrLoopRangeEmpty;
  1060. } else {
  1061. str = StrLoopBodyZero;
  1062. }
  1063. }
  1064. } else {
  1065. str = StrEnteringLoop;
  1066. }
  1067. if (!str.empty()) {
  1068. PathDiagnosticLocation L(TermCond ? TermCond : Term, SM,
  1069. C.getCurrLocationContext());
  1070. auto PE = std::make_shared<PathDiagnosticEventPiece>(L, str);
  1071. PE->setPrunable(true);
  1072. addEdgeToPath(C.getActivePath(), PrevLoc, PE->getLocation());
  1073. C.getActivePath().push_front(std::move(PE));
  1074. }
  1075. } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
  1076. isa<GotoStmt>(Term)) {
  1077. PathDiagnosticLocation L(Term, SM, C.getCurrLocationContext());
  1078. addEdgeToPath(C.getActivePath(), PrevLoc, L);
  1079. }
  1080. }
  1081. }
  1082. }
  1083. static std::unique_ptr<PathDiagnostic>
  1084. generateEmptyDiagnosticForReport(const BugReport *R, const SourceManager &SM) {
  1085. const BugType &BT = R->getBugType();
  1086. return std::make_unique<PathDiagnostic>(
  1087. R->getBugType().getCheckName(), R->getDeclWithIssue(),
  1088. R->getBugType().getName(), R->getDescription(),
  1089. R->getShortDescription(/*UseFallback=*/false), BT.getCategory(),
  1090. R->getUniqueingLocation(), R->getUniqueingDecl(),
  1091. findExecutedLines(SM, R->getErrorNode()));
  1092. }
  1093. static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
  1094. if (!S)
  1095. return nullptr;
  1096. while (true) {
  1097. S = PM.getParentIgnoreParens(S);
  1098. if (!S)
  1099. break;
  1100. if (isa<FullExpr>(S) ||
  1101. isa<CXXBindTemporaryExpr>(S) ||
  1102. isa<SubstNonTypeTemplateParmExpr>(S))
  1103. continue;
  1104. break;
  1105. }
  1106. return S;
  1107. }
  1108. static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
  1109. switch (S->getStmtClass()) {
  1110. case Stmt::BinaryOperatorClass: {
  1111. const auto *BO = cast<BinaryOperator>(S);
  1112. if (!BO->isLogicalOp())
  1113. return false;
  1114. return BO->getLHS() == Cond || BO->getRHS() == Cond;
  1115. }
  1116. case Stmt::IfStmtClass:
  1117. return cast<IfStmt>(S)->getCond() == Cond;
  1118. case Stmt::ForStmtClass:
  1119. return cast<ForStmt>(S)->getCond() == Cond;
  1120. case Stmt::WhileStmtClass:
  1121. return cast<WhileStmt>(S)->getCond() == Cond;
  1122. case Stmt::DoStmtClass:
  1123. return cast<DoStmt>(S)->getCond() == Cond;
  1124. case Stmt::ChooseExprClass:
  1125. return cast<ChooseExpr>(S)->getCond() == Cond;
  1126. case Stmt::IndirectGotoStmtClass:
  1127. return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
  1128. case Stmt::SwitchStmtClass:
  1129. return cast<SwitchStmt>(S)->getCond() == Cond;
  1130. case Stmt::BinaryConditionalOperatorClass:
  1131. return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
  1132. case Stmt::ConditionalOperatorClass: {
  1133. const auto *CO = cast<ConditionalOperator>(S);
  1134. return CO->getCond() == Cond ||
  1135. CO->getLHS() == Cond ||
  1136. CO->getRHS() == Cond;
  1137. }
  1138. case Stmt::ObjCForCollectionStmtClass:
  1139. return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
  1140. case Stmt::CXXForRangeStmtClass: {
  1141. const auto *FRS = cast<CXXForRangeStmt>(S);
  1142. return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
  1143. }
  1144. default:
  1145. return false;
  1146. }
  1147. }
  1148. static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
  1149. if (const auto *FS = dyn_cast<ForStmt>(FL))
  1150. return FS->getInc() == S || FS->getInit() == S;
  1151. if (const auto *FRS = dyn_cast<CXXForRangeStmt>(FL))
  1152. return FRS->getInc() == S || FRS->getRangeStmt() == S ||
  1153. FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
  1154. return false;
  1155. }
  1156. using OptimizedCallsSet = llvm::DenseSet<const PathDiagnosticCallPiece *>;
  1157. /// Adds synthetic edges from top-level statements to their subexpressions.
  1158. ///
  1159. /// This avoids a "swoosh" effect, where an edge from a top-level statement A
  1160. /// points to a sub-expression B.1 that's not at the start of B. In these cases,
  1161. /// we'd like to see an edge from A to B, then another one from B to B.1.
  1162. static void addContextEdges(PathPieces &pieces, const LocationContext *LC) {
  1163. const ParentMap &PM = LC->getParentMap();
  1164. PathPieces::iterator Prev = pieces.end();
  1165. for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
  1166. Prev = I, ++I) {
  1167. auto *Piece = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1168. if (!Piece)
  1169. continue;
  1170. PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
  1171. SmallVector<PathDiagnosticLocation, 4> SrcContexts;
  1172. PathDiagnosticLocation NextSrcContext = SrcLoc;
  1173. const Stmt *InnerStmt = nullptr;
  1174. while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
  1175. SrcContexts.push_back(NextSrcContext);
  1176. InnerStmt = NextSrcContext.asStmt();
  1177. NextSrcContext = getEnclosingStmtLocation(InnerStmt, LC,
  1178. /*allowNested=*/true);
  1179. }
  1180. // Repeatedly split the edge as necessary.
  1181. // This is important for nested logical expressions (||, &&, ?:) where we
  1182. // want to show all the levels of context.
  1183. while (true) {
  1184. const Stmt *Dst = Piece->getEndLocation().getStmtOrNull();
  1185. // We are looking at an edge. Is the destination within a larger
  1186. // expression?
  1187. PathDiagnosticLocation DstContext =
  1188. getEnclosingStmtLocation(Dst, LC, /*allowNested=*/true);
  1189. if (!DstContext.isValid() || DstContext.asStmt() == Dst)
  1190. break;
  1191. // If the source is in the same context, we're already good.
  1192. if (llvm::find(SrcContexts, DstContext) != SrcContexts.end())
  1193. break;
  1194. // Update the subexpression node to point to the context edge.
  1195. Piece->setStartLocation(DstContext);
  1196. // Try to extend the previous edge if it's at the same level as the source
  1197. // context.
  1198. if (Prev != E) {
  1199. auto *PrevPiece = dyn_cast<PathDiagnosticControlFlowPiece>(Prev->get());
  1200. if (PrevPiece) {
  1201. if (const Stmt *PrevSrc =
  1202. PrevPiece->getStartLocation().getStmtOrNull()) {
  1203. const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
  1204. if (PrevSrcParent ==
  1205. getStmtParent(DstContext.getStmtOrNull(), PM)) {
  1206. PrevPiece->setEndLocation(DstContext);
  1207. break;
  1208. }
  1209. }
  1210. }
  1211. }
  1212. // Otherwise, split the current edge into a context edge and a
  1213. // subexpression edge. Note that the context statement may itself have
  1214. // context.
  1215. auto P =
  1216. std::make_shared<PathDiagnosticControlFlowPiece>(SrcLoc, DstContext);
  1217. Piece = P.get();
  1218. I = pieces.insert(I, std::move(P));
  1219. }
  1220. }
  1221. }
  1222. /// Move edges from a branch condition to a branch target
  1223. /// when the condition is simple.
  1224. ///
  1225. /// This restructures some of the work of addContextEdges. That function
  1226. /// creates edges this may destroy, but they work together to create a more
  1227. /// aesthetically set of edges around branches. After the call to
  1228. /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
  1229. /// the branch to the branch condition, and (3) an edge from the branch
  1230. /// condition to the branch target. We keep (1), but may wish to remove (2)
  1231. /// and move the source of (3) to the branch if the branch condition is simple.
  1232. static void simplifySimpleBranches(PathPieces &pieces) {
  1233. for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
  1234. const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1235. if (!PieceI)
  1236. continue;
  1237. const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
  1238. const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
  1239. if (!s1Start || !s1End)
  1240. continue;
  1241. PathPieces::iterator NextI = I; ++NextI;
  1242. if (NextI == E)
  1243. break;
  1244. PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
  1245. while (true) {
  1246. if (NextI == E)
  1247. break;
  1248. const auto *EV = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
  1249. if (EV) {
  1250. StringRef S = EV->getString();
  1251. if (S == StrEnteringLoop || S == StrLoopBodyZero ||
  1252. S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
  1253. ++NextI;
  1254. continue;
  1255. }
  1256. break;
  1257. }
  1258. PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1259. break;
  1260. }
  1261. if (!PieceNextI)
  1262. continue;
  1263. const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
  1264. const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
  1265. if (!s2Start || !s2End || s1End != s2Start)
  1266. continue;
  1267. // We only perform this transformation for specific branch kinds.
  1268. // We don't want to do this for do..while, for example.
  1269. if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) ||
  1270. isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) ||
  1271. isa<CXXForRangeStmt>(s1Start)))
  1272. continue;
  1273. // Is s1End the branch condition?
  1274. if (!isConditionForTerminator(s1Start, s1End))
  1275. continue;
  1276. // Perform the hoisting by eliminating (2) and changing the start
  1277. // location of (3).
  1278. PieceNextI->setStartLocation(PieceI->getStartLocation());
  1279. I = pieces.erase(I);
  1280. }
  1281. }
  1282. /// Returns the number of bytes in the given (character-based) SourceRange.
  1283. ///
  1284. /// If the locations in the range are not on the same line, returns None.
  1285. ///
  1286. /// Note that this does not do a precise user-visible character or column count.
  1287. static Optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
  1288. SourceRange Range) {
  1289. SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
  1290. SM.getExpansionRange(Range.getEnd()).getEnd());
  1291. FileID FID = SM.getFileID(ExpansionRange.getBegin());
  1292. if (FID != SM.getFileID(ExpansionRange.getEnd()))
  1293. return None;
  1294. bool Invalid;
  1295. const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid);
  1296. if (Invalid)
  1297. return None;
  1298. unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
  1299. unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
  1300. StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
  1301. // We're searching the raw bytes of the buffer here, which might include
  1302. // escaped newlines and such. That's okay; we're trying to decide whether the
  1303. // SourceRange is covering a large or small amount of space in the user's
  1304. // editor.
  1305. if (Snippet.find_first_of("\r\n") != StringRef::npos)
  1306. return None;
  1307. // This isn't Unicode-aware, but it doesn't need to be.
  1308. return Snippet.size();
  1309. }
  1310. /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
  1311. static Optional<size_t> getLengthOnSingleLine(const SourceManager &SM,
  1312. const Stmt *S) {
  1313. return getLengthOnSingleLine(SM, S->getSourceRange());
  1314. }
  1315. /// Eliminate two-edge cycles created by addContextEdges().
  1316. ///
  1317. /// Once all the context edges are in place, there are plenty of cases where
  1318. /// there's a single edge from a top-level statement to a subexpression,
  1319. /// followed by a single path note, and then a reverse edge to get back out to
  1320. /// the top level. If the statement is simple enough, the subexpression edges
  1321. /// just add noise and make it harder to understand what's going on.
  1322. ///
  1323. /// This function only removes edges in pairs, because removing only one edge
  1324. /// might leave other edges dangling.
  1325. ///
  1326. /// This will not remove edges in more complicated situations:
  1327. /// - if there is more than one "hop" leading to or from a subexpression.
  1328. /// - if there is an inlined call between the edges instead of a single event.
  1329. /// - if the whole statement is large enough that having subexpression arrows
  1330. /// might be helpful.
  1331. static void removeContextCycles(PathPieces &Path, const SourceManager &SM) {
  1332. for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
  1333. // Pattern match the current piece and its successor.
  1334. const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1335. if (!PieceI) {
  1336. ++I;
  1337. continue;
  1338. }
  1339. const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
  1340. const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
  1341. PathPieces::iterator NextI = I; ++NextI;
  1342. if (NextI == E)
  1343. break;
  1344. const auto *PieceNextI =
  1345. dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1346. if (!PieceNextI) {
  1347. if (isa<PathDiagnosticEventPiece>(NextI->get())) {
  1348. ++NextI;
  1349. if (NextI == E)
  1350. break;
  1351. PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1352. }
  1353. if (!PieceNextI) {
  1354. ++I;
  1355. continue;
  1356. }
  1357. }
  1358. const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
  1359. const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
  1360. if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
  1361. const size_t MAX_SHORT_LINE_LENGTH = 80;
  1362. Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
  1363. if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
  1364. Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
  1365. if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
  1366. Path.erase(I);
  1367. I = Path.erase(NextI);
  1368. continue;
  1369. }
  1370. }
  1371. }
  1372. ++I;
  1373. }
  1374. }
  1375. /// Return true if X is contained by Y.
  1376. static bool lexicalContains(const ParentMap &PM, const Stmt *X, const Stmt *Y) {
  1377. while (X) {
  1378. if (X == Y)
  1379. return true;
  1380. X = PM.getParent(X);
  1381. }
  1382. return false;
  1383. }
  1384. // Remove short edges on the same line less than 3 columns in difference.
  1385. static void removePunyEdges(PathPieces &path, const SourceManager &SM,
  1386. const ParentMap &PM) {
  1387. bool erased = false;
  1388. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
  1389. erased ? I : ++I) {
  1390. erased = false;
  1391. const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1392. if (!PieceI)
  1393. continue;
  1394. const Stmt *start = PieceI->getStartLocation().getStmtOrNull();
  1395. const Stmt *end = PieceI->getEndLocation().getStmtOrNull();
  1396. if (!start || !end)
  1397. continue;
  1398. const Stmt *endParent = PM.getParent(end);
  1399. if (!endParent)
  1400. continue;
  1401. if (isConditionForTerminator(end, endParent))
  1402. continue;
  1403. SourceLocation FirstLoc = start->getBeginLoc();
  1404. SourceLocation SecondLoc = end->getBeginLoc();
  1405. if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
  1406. continue;
  1407. if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
  1408. std::swap(SecondLoc, FirstLoc);
  1409. SourceRange EdgeRange(FirstLoc, SecondLoc);
  1410. Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
  1411. // If the statements are on different lines, continue.
  1412. if (!ByteWidth)
  1413. continue;
  1414. const size_t MAX_PUNY_EDGE_LENGTH = 2;
  1415. if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
  1416. // FIXME: There are enough /bytes/ between the endpoints of the edge, but
  1417. // there might not be enough /columns/. A proper user-visible column count
  1418. // is probably too expensive, though.
  1419. I = path.erase(I);
  1420. erased = true;
  1421. continue;
  1422. }
  1423. }
  1424. }
  1425. static void removeIdenticalEvents(PathPieces &path) {
  1426. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
  1427. const auto *PieceI = dyn_cast<PathDiagnosticEventPiece>(I->get());
  1428. if (!PieceI)
  1429. continue;
  1430. PathPieces::iterator NextI = I; ++NextI;
  1431. if (NextI == E)
  1432. return;
  1433. const auto *PieceNextI = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
  1434. if (!PieceNextI)
  1435. continue;
  1436. // Erase the second piece if it has the same exact message text.
  1437. if (PieceI->getString() == PieceNextI->getString()) {
  1438. path.erase(NextI);
  1439. }
  1440. }
  1441. }
  1442. static bool optimizeEdges(const PathDiagnosticConstruct &C, PathPieces &path,
  1443. OptimizedCallsSet &OCS) {
  1444. bool hasChanges = false;
  1445. const LocationContext *LC = C.getLocationContextFor(&path);
  1446. assert(LC);
  1447. const ParentMap &PM = LC->getParentMap();
  1448. const SourceManager &SM = C.getSourceManager();
  1449. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
  1450. // Optimize subpaths.
  1451. if (auto *CallI = dyn_cast<PathDiagnosticCallPiece>(I->get())) {
  1452. // Record the fact that a call has been optimized so we only do the
  1453. // effort once.
  1454. if (!OCS.count(CallI)) {
  1455. while (optimizeEdges(C, CallI->path, OCS)) {
  1456. }
  1457. OCS.insert(CallI);
  1458. }
  1459. ++I;
  1460. continue;
  1461. }
  1462. // Pattern match the current piece and its successor.
  1463. auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1464. if (!PieceI) {
  1465. ++I;
  1466. continue;
  1467. }
  1468. const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
  1469. const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
  1470. const Stmt *level1 = getStmtParent(s1Start, PM);
  1471. const Stmt *level2 = getStmtParent(s1End, PM);
  1472. PathPieces::iterator NextI = I; ++NextI;
  1473. if (NextI == E)
  1474. break;
  1475. const auto *PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1476. if (!PieceNextI) {
  1477. ++I;
  1478. continue;
  1479. }
  1480. const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
  1481. const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
  1482. const Stmt *level3 = getStmtParent(s2Start, PM);
  1483. const Stmt *level4 = getStmtParent(s2End, PM);
  1484. // Rule I.
  1485. //
  1486. // If we have two consecutive control edges whose end/begin locations
  1487. // are at the same level (e.g. statements or top-level expressions within
  1488. // a compound statement, or siblings share a single ancestor expression),
  1489. // then merge them if they have no interesting intermediate event.
  1490. //
  1491. // For example:
  1492. //
  1493. // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
  1494. // parent is '1'. Here 'x.y.z' represents the hierarchy of statements.
  1495. //
  1496. // NOTE: this will be limited later in cases where we add barriers
  1497. // to prevent this optimization.
  1498. if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
  1499. PieceI->setEndLocation(PieceNextI->getEndLocation());
  1500. path.erase(NextI);
  1501. hasChanges = true;
  1502. continue;
  1503. }
  1504. // Rule II.
  1505. //
  1506. // Eliminate edges between subexpressions and parent expressions
  1507. // when the subexpression is consumed.
  1508. //
  1509. // NOTE: this will be limited later in cases where we add barriers
  1510. // to prevent this optimization.
  1511. if (s1End && s1End == s2Start && level2) {
  1512. bool removeEdge = false;
  1513. // Remove edges into the increment or initialization of a
  1514. // loop that have no interleaving event. This means that
  1515. // they aren't interesting.
  1516. if (isIncrementOrInitInForLoop(s1End, level2))
  1517. removeEdge = true;
  1518. // Next only consider edges that are not anchored on
  1519. // the condition of a terminator. This are intermediate edges
  1520. // that we might want to trim.
  1521. else if (!isConditionForTerminator(level2, s1End)) {
  1522. // Trim edges on expressions that are consumed by
  1523. // the parent expression.
  1524. if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
  1525. removeEdge = true;
  1526. }
  1527. // Trim edges where a lexical containment doesn't exist.
  1528. // For example:
  1529. //
  1530. // X -> Y -> Z
  1531. //
  1532. // If 'Z' lexically contains Y (it is an ancestor) and
  1533. // 'X' does not lexically contain Y (it is a descendant OR
  1534. // it has no lexical relationship at all) then trim.
  1535. //
  1536. // This can eliminate edges where we dive into a subexpression
  1537. // and then pop back out, etc.
  1538. else if (s1Start && s2End &&
  1539. lexicalContains(PM, s2Start, s2End) &&
  1540. !lexicalContains(PM, s1End, s1Start)) {
  1541. removeEdge = true;
  1542. }
  1543. // Trim edges from a subexpression back to the top level if the
  1544. // subexpression is on a different line.
  1545. //
  1546. // A.1 -> A -> B
  1547. // becomes
  1548. // A.1 -> B
  1549. //
  1550. // These edges just look ugly and don't usually add anything.
  1551. else if (s1Start && s2End &&
  1552. lexicalContains(PM, s1Start, s1End)) {
  1553. SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
  1554. PieceI->getStartLocation().asLocation());
  1555. if (!getLengthOnSingleLine(SM, EdgeRange).hasValue())
  1556. removeEdge = true;
  1557. }
  1558. }
  1559. if (removeEdge) {
  1560. PieceI->setEndLocation(PieceNextI->getEndLocation());
  1561. path.erase(NextI);
  1562. hasChanges = true;
  1563. continue;
  1564. }
  1565. }
  1566. // Optimize edges for ObjC fast-enumeration loops.
  1567. //
  1568. // (X -> collection) -> (collection -> element)
  1569. //
  1570. // becomes:
  1571. //
  1572. // (X -> element)
  1573. if (s1End == s2Start) {
  1574. const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(level3);
  1575. if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
  1576. s2End == FS->getElement()) {
  1577. PieceI->setEndLocation(PieceNextI->getEndLocation());
  1578. path.erase(NextI);
  1579. hasChanges = true;
  1580. continue;
  1581. }
  1582. }
  1583. // No changes at this index? Move to the next one.
  1584. ++I;
  1585. }
  1586. if (!hasChanges) {
  1587. // Adjust edges into subexpressions to make them more uniform
  1588. // and aesthetically pleasing.
  1589. addContextEdges(path, LC);
  1590. // Remove "cyclical" edges that include one or more context edges.
  1591. removeContextCycles(path, SM);
  1592. // Hoist edges originating from branch conditions to branches
  1593. // for simple branches.
  1594. simplifySimpleBranches(path);
  1595. // Remove any puny edges left over after primary optimization pass.
  1596. removePunyEdges(path, SM, PM);
  1597. // Remove identical events.
  1598. removeIdenticalEvents(path);
  1599. }
  1600. return hasChanges;
  1601. }
  1602. /// Drop the very first edge in a path, which should be a function entry edge.
  1603. ///
  1604. /// If the first edge is not a function entry edge (say, because the first
  1605. /// statement had an invalid source location), this function does nothing.
  1606. // FIXME: We should just generate invalid edges anyway and have the optimizer
  1607. // deal with them.
  1608. static void dropFunctionEntryEdge(const PathDiagnosticConstruct &C,
  1609. PathPieces &Path) {
  1610. const auto *FirstEdge =
  1611. dyn_cast<PathDiagnosticControlFlowPiece>(Path.front().get());
  1612. if (!FirstEdge)
  1613. return;
  1614. const Decl *D = C.getLocationContextFor(&Path)->getDecl();
  1615. PathDiagnosticLocation EntryLoc =
  1616. PathDiagnosticLocation::createBegin(D, C.getSourceManager());
  1617. if (FirstEdge->getStartLocation() != EntryLoc)
  1618. return;
  1619. Path.pop_front();
  1620. }
  1621. /// Populate executes lines with lines containing at least one diagnostics.
  1622. static void updateExecutedLinesWithDiagnosticPieces(PathDiagnostic &PD) {
  1623. PathPieces path = PD.path.flatten(/*ShouldFlattenMacros=*/true);
  1624. FilesToLineNumsMap &ExecutedLines = PD.getExecutedLines();
  1625. for (const auto &P : path) {
  1626. FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
  1627. FileID FID = Loc.getFileID();
  1628. unsigned LineNo = Loc.getLineNumber();
  1629. assert(FID.isValid());
  1630. ExecutedLines[FID].insert(LineNo);
  1631. }
  1632. }
  1633. PathDiagnosticConstruct::PathDiagnosticConstruct(
  1634. const PathDiagnosticConsumer *PDC, const ExplodedNode *ErrorNode,
  1635. const BugReport *R)
  1636. : Consumer(PDC), CurrentNode(ErrorNode),
  1637. SM(CurrentNode->getCodeDecl().getASTContext().getSourceManager()),
  1638. PD(generateEmptyDiagnosticForReport(R, getSourceManager())) {
  1639. LCM[&PD->getActivePath()] = ErrorNode->getLocationContext();
  1640. }
  1641. PathDiagnosticBuilder::PathDiagnosticBuilder(
  1642. BugReporterContext BRC, std::unique_ptr<ExplodedGraph> BugPath,
  1643. BugReport *r, const ExplodedNode *ErrorNode,
  1644. std::unique_ptr<VisitorsDiagnosticsTy> VisitorsDiagnostics)
  1645. : BugReporterContext(BRC), BugPath(std::move(BugPath)), R(r),
  1646. ErrorNode(ErrorNode),
  1647. VisitorsDiagnostics(std::move(VisitorsDiagnostics)) {}
  1648. std::unique_ptr<PathDiagnostic>
  1649. PathDiagnosticBuilder::generate(const PathDiagnosticConsumer *PDC) const {
  1650. PathDiagnosticConstruct Construct(PDC, ErrorNode, R);
  1651. const SourceManager &SM = getSourceManager();
  1652. const BugReport *R = getBugReport();
  1653. const AnalyzerOptions &Opts = getAnalyzerOptions();
  1654. StringRef ErrorTag = ErrorNode->getLocation().getTag()->getTagDescription();
  1655. // See whether we need to silence the checker/package.
  1656. // FIXME: This will not work if the report was emitted with an incorrect tag.
  1657. for (const std::string &CheckerOrPackage : Opts.SilencedCheckersAndPackages) {
  1658. if (ErrorTag.startswith(CheckerOrPackage))
  1659. return nullptr;
  1660. }
  1661. if (!PDC->shouldGenerateDiagnostics())
  1662. return generateEmptyDiagnosticForReport(R, getSourceManager());
  1663. // Construct the final (warning) event for the bug report.
  1664. auto EndNotes = VisitorsDiagnostics->find(ErrorNode);
  1665. PathDiagnosticPieceRef LastPiece;
  1666. if (EndNotes != VisitorsDiagnostics->end()) {
  1667. assert(!EndNotes->second.empty());
  1668. LastPiece = EndNotes->second[0];
  1669. } else {
  1670. LastPiece = BugReporterVisitor::getDefaultEndPath(*this, ErrorNode,
  1671. *getBugReport());
  1672. }
  1673. Construct.PD->setEndOfPath(LastPiece);
  1674. PathDiagnosticLocation PrevLoc = Construct.PD->getLocation();
  1675. // From the error node to the root, ascend the bug path and construct the bug
  1676. // report.
  1677. while (Construct.ascendToPrevNode()) {
  1678. generatePathDiagnosticsForNode(Construct, PrevLoc);
  1679. auto VisitorNotes = VisitorsDiagnostics->find(Construct.getCurrentNode());
  1680. if (VisitorNotes == VisitorsDiagnostics->end())
  1681. continue;
  1682. // This is a workaround due to inability to put shared PathDiagnosticPiece
  1683. // into a FoldingSet.
  1684. std::set<llvm::FoldingSetNodeID> DeduplicationSet;
  1685. // Add pieces from custom visitors.
  1686. for (const PathDiagnosticPieceRef &Note : VisitorNotes->second) {
  1687. llvm::FoldingSetNodeID ID;
  1688. Note->Profile(ID);
  1689. if (!DeduplicationSet.insert(ID).second)
  1690. continue;
  1691. if (PDC->shouldAddPathEdges())
  1692. addEdgeToPath(Construct.getActivePath(), PrevLoc, Note->getLocation());
  1693. updateStackPiecesWithMessage(*Note, Construct.CallStack);
  1694. Construct.getActivePath().push_front(Note);
  1695. }
  1696. }
  1697. if (PDC->shouldAddPathEdges()) {
  1698. // Add an edge to the start of the function.
  1699. // We'll prune it out later, but it helps make diagnostics more uniform.
  1700. const StackFrameContext *CalleeLC =
  1701. Construct.getLocationContextForActivePath()->getStackFrame();
  1702. const Decl *D = CalleeLC->getDecl();
  1703. addEdgeToPath(Construct.getActivePath(), PrevLoc,
  1704. PathDiagnosticLocation::createBegin(D, SM));
  1705. }
  1706. // Finally, prune the diagnostic path of uninteresting stuff.
  1707. if (!Construct.PD->path.empty()) {
  1708. if (R->shouldPrunePath() && Opts.ShouldPrunePaths) {
  1709. bool stillHasNotes =
  1710. removeUnneededCalls(Construct, Construct.getMutablePieces(), R);
  1711. assert(stillHasNotes);
  1712. (void)stillHasNotes;
  1713. }
  1714. // Remove pop-up notes if needed.
  1715. if (!Opts.ShouldAddPopUpNotes)
  1716. removePopUpNotes(Construct.getMutablePieces());
  1717. // Redirect all call pieces to have valid locations.
  1718. adjustCallLocations(Construct.getMutablePieces());
  1719. removePiecesWithInvalidLocations(Construct.getMutablePieces());
  1720. if (PDC->shouldAddPathEdges()) {
  1721. // Reduce the number of edges from a very conservative set
  1722. // to an aesthetically pleasing subset that conveys the
  1723. // necessary information.
  1724. OptimizedCallsSet OCS;
  1725. while (optimizeEdges(Construct, Construct.getMutablePieces(), OCS)) {
  1726. }
  1727. // Drop the very first function-entry edge. It's not really necessary
  1728. // for top-level functions.
  1729. dropFunctionEntryEdge(Construct, Construct.getMutablePieces());
  1730. }
  1731. // Remove messages that are basically the same, and edges that may not
  1732. // make sense.
  1733. // We have to do this after edge optimization in the Extensive mode.
  1734. removeRedundantMsgs(Construct.getMutablePieces());
  1735. removeEdgesToDefaultInitializers(Construct.getMutablePieces());
  1736. }
  1737. if (Opts.ShouldDisplayMacroExpansions)
  1738. CompactMacroExpandedPieces(Construct.getMutablePieces(), SM);
  1739. return std::move(Construct.PD);
  1740. }
  1741. //===----------------------------------------------------------------------===//
  1742. // Methods for BugType and subclasses.
  1743. //===----------------------------------------------------------------------===//
  1744. void BugType::anchor() {}
  1745. void BuiltinBug::anchor() {}
  1746. //===----------------------------------------------------------------------===//
  1747. // Methods for BugReport and subclasses.
  1748. //===----------------------------------------------------------------------===//
  1749. void BugReport::addVisitor(std::unique_ptr<BugReporterVisitor> visitor) {
  1750. if (!visitor)
  1751. return;
  1752. llvm::FoldingSetNodeID ID;
  1753. visitor->Profile(ID);
  1754. void *InsertPos = nullptr;
  1755. if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
  1756. return;
  1757. }
  1758. Callbacks.push_back(std::move(visitor));
  1759. }
  1760. void BugReport::clearVisitors() {
  1761. Callbacks.clear();
  1762. }
  1763. const Decl *BugReport::getDeclWithIssue() const {
  1764. if (DeclWithIssue)
  1765. return DeclWithIssue;
  1766. const ExplodedNode *N = getErrorNode();
  1767. if (!N)
  1768. return nullptr;
  1769. const LocationContext *LC = N->getLocationContext();
  1770. return LC->getStackFrame()->getDecl();
  1771. }
  1772. void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
  1773. hash.AddPointer(&BT);
  1774. hash.AddString(Description);
  1775. PathDiagnosticLocation UL = getUniqueingLocation();
  1776. if (UL.isValid()) {
  1777. UL.Profile(hash);
  1778. } else if (Location.isValid()) {
  1779. Location.Profile(hash);
  1780. } else {
  1781. assert(ErrorNode);
  1782. hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
  1783. }
  1784. for (SourceRange range : Ranges) {
  1785. if (!range.isValid())
  1786. continue;
  1787. hash.AddInteger(range.getBegin().getRawEncoding());
  1788. hash.AddInteger(range.getEnd().getRawEncoding());
  1789. }
  1790. }
  1791. template <class T>
  1792. static void insertToInterestingnessMap(
  1793. llvm::DenseMap<T, bugreporter::TrackingKind> &InterestingnessMap, T Val,
  1794. bugreporter::TrackingKind TKind) {
  1795. auto Result = InterestingnessMap.insert({Val, TKind});
  1796. if (Result.second)
  1797. return;
  1798. // Even if this symbol/region was already marked as interesting as a
  1799. // condition, if we later mark it as interesting again but with
  1800. // thorough tracking, overwrite it. Entities marked with thorough
  1801. // interestiness are the most important (or most interesting, if you will),
  1802. // and we wouldn't like to downplay their importance.
  1803. switch (TKind) {
  1804. case bugreporter::TrackingKind::Thorough:
  1805. Result.first->getSecond() = bugreporter::TrackingKind::Thorough;
  1806. return;
  1807. case bugreporter::TrackingKind::Condition:
  1808. return;
  1809. }
  1810. llvm_unreachable(
  1811. "BugReport::markInteresting currently can only handle 2 different "
  1812. "tracking kinds! Please define what tracking kind should this entitiy"
  1813. "have, if it was already marked as interesting with a different kind!");
  1814. }
  1815. void BugReport::markInteresting(SymbolRef sym,
  1816. bugreporter::TrackingKind TKind) {
  1817. if (!sym)
  1818. return;
  1819. insertToInterestingnessMap(InterestingSymbols, sym, TKind);
  1820. if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
  1821. markInteresting(meta->getRegion(), TKind);
  1822. }
  1823. void BugReport::markInteresting(const MemRegion *R,
  1824. bugreporter::TrackingKind TKind) {
  1825. if (!R)
  1826. return;
  1827. R = R->getBaseRegion();
  1828. insertToInterestingnessMap(InterestingRegions, R, TKind);
  1829. if (const auto *SR = dyn_cast<SymbolicRegion>(R))
  1830. markInteresting(SR->getSymbol(), TKind);
  1831. }
  1832. void BugReport::markInteresting(SVal V, bugreporter::TrackingKind TKind) {
  1833. markInteresting(V.getAsRegion(), TKind);
  1834. markInteresting(V.getAsSymbol(), TKind);
  1835. }
  1836. void BugReport::markInteresting(const LocationContext *LC) {
  1837. if (!LC)
  1838. return;
  1839. InterestingLocationContexts.insert(LC);
  1840. }
  1841. Optional<bugreporter::TrackingKind>
  1842. BugReport::getInterestingnessKind(SVal V) const {
  1843. auto RKind = getInterestingnessKind(V.getAsRegion());
  1844. auto SKind = getInterestingnessKind(V.getAsSymbol());
  1845. if (!RKind)
  1846. return SKind;
  1847. if (!SKind)
  1848. return RKind;
  1849. // If either is marked with throrough tracking, return that, we wouldn't like
  1850. // to downplay a note's importance by 'only' mentioning it as a condition.
  1851. switch(*RKind) {
  1852. case bugreporter::TrackingKind::Thorough:
  1853. return RKind;
  1854. case bugreporter::TrackingKind::Condition:
  1855. return SKind;
  1856. }
  1857. llvm_unreachable(
  1858. "BugReport::getInterestingnessKind currently can only handle 2 different "
  1859. "tracking kinds! Please define what tracking kind should we return here "
  1860. "when the kind of getAsRegion() and getAsSymbol() is different!");
  1861. return None;
  1862. }
  1863. Optional<bugreporter::TrackingKind>
  1864. BugReport::getInterestingnessKind(SymbolRef sym) const {
  1865. if (!sym)
  1866. return None;
  1867. // We don't currently consider metadata symbols to be interesting
  1868. // even if we know their region is interesting. Is that correct behavior?
  1869. auto It = InterestingSymbols.find(sym);
  1870. if (It == InterestingSymbols.end())
  1871. return None;
  1872. return It->getSecond();
  1873. }
  1874. Optional<bugreporter::TrackingKind>
  1875. BugReport::getInterestingnessKind(const MemRegion *R) const {
  1876. if (!R)
  1877. return None;
  1878. R = R->getBaseRegion();
  1879. auto It = InterestingRegions.find(R);
  1880. if (It != InterestingRegions.end())
  1881. return It->getSecond();
  1882. if (const auto *SR = dyn_cast<SymbolicRegion>(R))
  1883. return getInterestingnessKind(SR->getSymbol());
  1884. return None;
  1885. }
  1886. bool BugReport::isInteresting(SVal V) const {
  1887. return getInterestingnessKind(V).hasValue();
  1888. }
  1889. bool BugReport::isInteresting(SymbolRef sym) const {
  1890. return getInterestingnessKind(sym).hasValue();
  1891. }
  1892. bool BugReport::isInteresting(const MemRegion *R) const {
  1893. return getInterestingnessKind(R).hasValue();
  1894. }
  1895. bool BugReport::isInteresting(const LocationContext *LC) const {
  1896. if (!LC)
  1897. return false;
  1898. return InterestingLocationContexts.count(LC);
  1899. }
  1900. const Stmt *BugReport::getStmt() const {
  1901. if (!ErrorNode)
  1902. return nullptr;
  1903. ProgramPoint ProgP = ErrorNode->getLocation();
  1904. const Stmt *S = nullptr;
  1905. if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
  1906. CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
  1907. if (BE->getBlock() == &Exit)
  1908. S = GetPreviousStmt(ErrorNode);
  1909. }
  1910. if (!S)
  1911. S = PathDiagnosticLocation::getStmt(ErrorNode);
  1912. return S;
  1913. }
  1914. llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() const {
  1915. // If no custom ranges, add the range of the statement corresponding to
  1916. // the error node.
  1917. if (Ranges.empty()) {
  1918. if (dyn_cast_or_null<Expr>(getStmt()))
  1919. return llvm::make_range(&ErrorNodeRange, &ErrorNodeRange + 1);
  1920. return llvm::make_range(ranges_iterator(), ranges_iterator());
  1921. }
  1922. // User-specified absence of range info.
  1923. if (Ranges.size() == 1 && !Ranges.begin()->isValid())
  1924. return llvm::make_range(ranges_iterator(), ranges_iterator());
  1925. return llvm::make_range(Ranges.begin(), Ranges.end());
  1926. }
  1927. PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
  1928. if (ErrorNode) {
  1929. assert(!Location.isValid() &&
  1930. "Either Location or ErrorNode should be specified but not both.");
  1931. return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
  1932. }
  1933. assert(Location.isValid());
  1934. return Location;
  1935. }
  1936. //===----------------------------------------------------------------------===//
  1937. // Methods for BugReporter and subclasses.
  1938. //===----------------------------------------------------------------------===//
  1939. const ExplodedGraph &PathSensitiveBugReporter::getGraph() const {
  1940. return Eng.getGraph();
  1941. }
  1942. ProgramStateManager &PathSensitiveBugReporter::getStateManager() const {
  1943. return Eng.getStateManager();
  1944. }
  1945. BugReporter::~BugReporter() {
  1946. // Make sure reports are flushed.
  1947. assert(StrBugTypes.empty() &&
  1948. "Destroying BugReporter before diagnostics are emitted!");
  1949. // Free the bug reports we are tracking.
  1950. for (const auto I : EQClassesVector)
  1951. delete I;
  1952. }
  1953. void BugReporter::FlushReports() {
  1954. // We need to flush reports in deterministic order to ensure the order
  1955. // of the reports is consistent between runs.
  1956. for (const auto EQ : EQClassesVector)
  1957. FlushReport(*EQ);
  1958. // BugReporter owns and deletes only BugTypes created implicitly through
  1959. // EmitBasicReport.
  1960. // FIXME: There are leaks from checkers that assume that the BugTypes they
  1961. // create will be destroyed by the BugReporter.
  1962. llvm::DeleteContainerSeconds(StrBugTypes);
  1963. }
  1964. //===----------------------------------------------------------------------===//
  1965. // PathDiagnostics generation.
  1966. //===----------------------------------------------------------------------===//
  1967. namespace {
  1968. /// A wrapper around an ExplodedGraph that contains a single path from the root
  1969. /// to the error node.
  1970. class BugPathInfo {
  1971. public:
  1972. std::unique_ptr<ExplodedGraph> BugPath;
  1973. BugReport *Report;
  1974. const ExplodedNode *ErrorNode;
  1975. };
  1976. /// A wrapper around an ExplodedGraph whose leafs are all error nodes. Can
  1977. /// conveniently retrieve bug paths from a single error node to the root.
  1978. class BugPathGetter {
  1979. std::unique_ptr<ExplodedGraph> TrimmedGraph;
  1980. using PriorityMapTy = llvm::DenseMap<const ExplodedNode *, unsigned>;
  1981. /// Assign each node with its distance from the root.
  1982. PriorityMapTy PriorityMap;
  1983. /// Since the getErrorNode() or BugReport refers to the original ExplodedGraph,
  1984. /// we need to pair it to the error node of the constructed trimmed graph.
  1985. using ReportNewNodePair = std::pair<BugReport *, const ExplodedNode *>;
  1986. SmallVector<ReportNewNodePair, 32> ReportNodes;
  1987. BugPathInfo CurrentBugPath;
  1988. /// A helper class for sorting ExplodedNodes by priority.
  1989. template <bool Descending>
  1990. class PriorityCompare {
  1991. const PriorityMapTy &PriorityMap;
  1992. public:
  1993. PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
  1994. bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
  1995. PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
  1996. PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
  1997. PriorityMapTy::const_iterator E = PriorityMap.end();
  1998. if (LI == E)
  1999. return Descending;
  2000. if (RI == E)
  2001. return !Descending;
  2002. return Descending ? LI->second > RI->second
  2003. : LI->second < RI->second;
  2004. }
  2005. bool operator()(const ReportNewNodePair &LHS,
  2006. const ReportNewNodePair &RHS) const {
  2007. return (*this)(LHS.second, RHS.second);
  2008. }
  2009. };
  2010. public:
  2011. BugPathGetter(const ExplodedGraph *OriginalGraph,
  2012. ArrayRef<BugReport *> &bugReports);
  2013. BugPathInfo *getNextBugPath();
  2014. };
  2015. } // namespace
  2016. BugPathGetter::BugPathGetter(const ExplodedGraph *OriginalGraph,
  2017. ArrayRef<BugReport *> &bugReports) {
  2018. SmallVector<const ExplodedNode *, 32> Nodes;
  2019. for (const auto I : bugReports) {
  2020. assert(I->isValid() &&
  2021. "We only allow BugReporterVisitors and BugReporter itself to "
  2022. "invalidate reports!");
  2023. Nodes.emplace_back(I->getErrorNode());
  2024. }
  2025. // The trimmed graph is created in the body of the constructor to ensure
  2026. // that the DenseMaps have been initialized already.
  2027. InterExplodedGraphMap ForwardMap;
  2028. TrimmedGraph = OriginalGraph->trim(Nodes, &ForwardMap);
  2029. // Find the (first) error node in the trimmed graph. We just need to consult
  2030. // the node map which maps from nodes in the original graph to nodes
  2031. // in the new graph.
  2032. llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
  2033. for (BugReport *Report : bugReports) {
  2034. const ExplodedNode *NewNode = ForwardMap.lookup(Report->getErrorNode());
  2035. assert(NewNode &&
  2036. "Failed to construct a trimmed graph that contains this error "
  2037. "node!");
  2038. ReportNodes.emplace_back(Report, NewNode);
  2039. RemainingNodes.insert(NewNode);
  2040. }
  2041. assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
  2042. // Perform a forward BFS to find all the shortest paths.
  2043. std::queue<const ExplodedNode *> WS;
  2044. assert(TrimmedGraph->num_roots() == 1);
  2045. WS.push(*TrimmedGraph->roots_begin());
  2046. unsigned Priority = 0;
  2047. while (!WS.empty()) {
  2048. const ExplodedNode *Node = WS.front();
  2049. WS.pop();
  2050. PriorityMapTy::iterator PriorityEntry;
  2051. bool IsNew;
  2052. std::tie(PriorityEntry, IsNew) = PriorityMap.insert({Node, Priority});
  2053. ++Priority;
  2054. if (!IsNew) {
  2055. assert(PriorityEntry->second <= Priority);
  2056. continue;
  2057. }
  2058. if (RemainingNodes.erase(Node))
  2059. if (RemainingNodes.empty())
  2060. break;
  2061. for (const ExplodedNode *Succ : Node->succs())
  2062. WS.push(Succ);
  2063. }
  2064. // Sort the error paths from longest to shortest.
  2065. llvm::sort(ReportNodes, PriorityCompare<true>(PriorityMap));
  2066. }
  2067. BugPathInfo *BugPathGetter::getNextBugPath() {
  2068. if (ReportNodes.empty())
  2069. return nullptr;
  2070. const ExplodedNode *OrigN;
  2071. std::tie(CurrentBugPath.Report, OrigN) = ReportNodes.pop_back_val();
  2072. assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
  2073. "error node not accessible from root");
  2074. // Create a new graph with a single path. This is the graph that will be
  2075. // returned to the caller.
  2076. auto GNew = std::make_unique<ExplodedGraph>();
  2077. // Now walk from the error node up the BFS path, always taking the
  2078. // predeccessor with the lowest number.
  2079. ExplodedNode *Succ = nullptr;
  2080. while (true) {
  2081. // Create the equivalent node in the new graph with the same state
  2082. // and location.
  2083. ExplodedNode *NewN = GNew->createUncachedNode(
  2084. OrigN->getLocation(), OrigN->getState(), OrigN->isSink());
  2085. // Link up the new node with the previous node.
  2086. if (Succ)
  2087. Succ->addPredecessor(NewN, *GNew);
  2088. else
  2089. CurrentBugPath.ErrorNode = NewN;
  2090. Succ = NewN;
  2091. // Are we at the final node?
  2092. if (OrigN->pred_empty()) {
  2093. GNew->addRoot(NewN);
  2094. break;
  2095. }
  2096. // Find the next predeccessor node. We choose the node that is marked
  2097. // with the lowest BFS number.
  2098. OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
  2099. PriorityCompare<false>(PriorityMap));
  2100. }
  2101. CurrentBugPath.BugPath = std::move(GNew);
  2102. return &CurrentBugPath;
  2103. }
  2104. /// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
  2105. /// object and collapses PathDiagosticPieces that are expanded by macros.
  2106. static void CompactMacroExpandedPieces(PathPieces &path,
  2107. const SourceManager& SM) {
  2108. using MacroStackTy = std::vector<
  2109. std::pair<std::shared_ptr<PathDiagnosticMacroPiece>, SourceLocation>>;
  2110. using PiecesTy = std::vector<PathDiagnosticPieceRef>;
  2111. MacroStackTy MacroStack;
  2112. PiecesTy Pieces;
  2113. for (PathPieces::const_iterator I = path.begin(), E = path.end();
  2114. I != E; ++I) {
  2115. const auto &piece = *I;
  2116. // Recursively compact calls.
  2117. if (auto *call = dyn_cast<PathDiagnosticCallPiece>(&*piece)) {
  2118. CompactMacroExpandedPieces(call->path, SM);
  2119. }
  2120. // Get the location of the PathDiagnosticPiece.
  2121. const FullSourceLoc Loc = piece->getLocation().asLocation();
  2122. // Determine the instantiation location, which is the location we group
  2123. // related PathDiagnosticPieces.
  2124. SourceLocation InstantiationLoc = Loc.isMacroID() ?
  2125. SM.getExpansionLoc(Loc) :
  2126. SourceLocation();
  2127. if (Loc.isFileID()) {
  2128. MacroStack.clear();
  2129. Pieces.push_back(piece);
  2130. continue;
  2131. }
  2132. assert(Loc.isMacroID());
  2133. // Is the PathDiagnosticPiece within the same macro group?
  2134. if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
  2135. MacroStack.back().first->subPieces.push_back(piece);
  2136. continue;
  2137. }
  2138. // We aren't in the same group. Are we descending into a new macro
  2139. // or are part of an old one?
  2140. std::shared_ptr<PathDiagnosticMacroPiece> MacroGroup;
  2141. SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
  2142. SM.getExpansionLoc(Loc) :
  2143. SourceLocation();
  2144. // Walk the entire macro stack.
  2145. while (!MacroStack.empty()) {
  2146. if (InstantiationLoc == MacroStack.back().second) {
  2147. MacroGroup = MacroStack.back().first;
  2148. break;
  2149. }
  2150. if (ParentInstantiationLoc == MacroStack.back().second) {
  2151. MacroGroup = MacroStack.back().first;
  2152. break;
  2153. }
  2154. MacroStack.pop_back();
  2155. }
  2156. if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
  2157. // Create a new macro group and add it to the stack.
  2158. auto NewGroup = std::make_shared<PathDiagnosticMacroPiece>(
  2159. PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
  2160. if (MacroGroup)
  2161. MacroGroup->subPieces.push_back(NewGroup);
  2162. else {
  2163. assert(InstantiationLoc.isFileID());
  2164. Pieces.push_back(NewGroup);
  2165. }
  2166. MacroGroup = NewGroup;
  2167. MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
  2168. }
  2169. // Finally, add the PathDiagnosticPiece to the group.
  2170. MacroGroup->subPieces.push_back(piece);
  2171. }
  2172. // Now take the pieces and construct a new PathDiagnostic.
  2173. path.clear();
  2174. path.insert(path.end(), Pieces.begin(), Pieces.end());
  2175. }
  2176. /// Generate notes from all visitors.
  2177. /// Notes associated with {@code ErrorNode} are generated using
  2178. /// {@code getEndPath}, and the rest are generated with {@code VisitNode}.
  2179. static std::unique_ptr<VisitorsDiagnosticsTy>
  2180. generateVisitorsDiagnostics(BugReport *R, const ExplodedNode *ErrorNode,
  2181. BugReporterContext &BRC) {
  2182. std::unique_ptr<VisitorsDiagnosticsTy> Notes =
  2183. std::make_unique<VisitorsDiagnosticsTy>();
  2184. BugReport::VisitorList visitors;
  2185. // Run visitors on all nodes starting from the node *before* the last one.
  2186. // The last node is reserved for notes generated with {@code getEndPath}.
  2187. const ExplodedNode *NextNode = ErrorNode->getFirstPred();
  2188. while (NextNode) {
  2189. // At each iteration, move all visitors from report to visitor list. This is
  2190. // important, because the Profile() functions of the visitors make sure that
  2191. // a visitor isn't added multiple times for the same node, but it's fine
  2192. // to add the a visitor with Profile() for different nodes (e.g. tracking
  2193. // a region at different points of the symbolic execution).
  2194. for (std::unique_ptr<BugReporterVisitor> &Visitor : R->visitors())
  2195. visitors.push_back(std::move(Visitor));
  2196. R->clearVisitors();
  2197. const ExplodedNode *Pred = NextNode->getFirstPred();
  2198. if (!Pred) {
  2199. PathDiagnosticPieceRef LastPiece;
  2200. for (auto &V : visitors) {
  2201. V->finalizeVisitor(BRC, ErrorNode, *R);
  2202. if (auto Piece = V->getEndPath(BRC, ErrorNode, *R)) {
  2203. assert(!LastPiece &&
  2204. "There can only be one final piece in a diagnostic.");
  2205. assert(Piece->getKind() == PathDiagnosticPiece::Kind::Event &&
  2206. "The final piece must contain a message!");
  2207. LastPiece = std::move(Piece);
  2208. (*Notes)[ErrorNode].push_back(LastPiece);
  2209. }
  2210. }
  2211. break;
  2212. }
  2213. for (auto &V : visitors) {
  2214. auto P = V->VisitNode(NextNode, BRC, *R);
  2215. if (P)
  2216. (*Notes)[NextNode].push_back(std::move(P));
  2217. }
  2218. if (!R->isValid())
  2219. break;
  2220. NextNode = Pred;
  2221. }
  2222. return Notes;
  2223. }
  2224. Optional<PathDiagnosticBuilder>
  2225. PathDiagnosticBuilder::findValidReport(ArrayRef<BugReport *> &bugReports,
  2226. PathSensitiveBugReporter &Reporter) {
  2227. BugPathGetter BugGraph(&Reporter.getGraph(), bugReports);
  2228. while (BugPathInfo *BugPath = BugGraph.getNextBugPath()) {
  2229. // Find the BugReport with the original location.
  2230. BugReport *R = BugPath->Report;
  2231. assert(R && "No original report found for sliced graph.");
  2232. assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
  2233. const ExplodedNode *ErrorNode = BugPath->ErrorNode;
  2234. // Register refutation visitors first, if they mark the bug invalid no
  2235. // further analysis is required
  2236. R->addVisitor(std::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
  2237. // Register additional node visitors.
  2238. R->addVisitor(std::make_unique<NilReceiverBRVisitor>());
  2239. R->addVisitor(std::make_unique<ConditionBRVisitor>());
  2240. R->addVisitor(std::make_unique<TagVisitor>());
  2241. BugReporterContext BRC(Reporter);
  2242. // Run all visitors on a given graph, once.
  2243. std::unique_ptr<VisitorsDiagnosticsTy> visitorNotes =
  2244. generateVisitorsDiagnostics(R, ErrorNode, BRC);
  2245. if (R->isValid()) {
  2246. if (Reporter.getAnalyzerOptions().ShouldCrosscheckWithZ3) {
  2247. // If crosscheck is enabled, remove all visitors, add the refutation
  2248. // visitor and check again
  2249. R->clearVisitors();
  2250. R->addVisitor(std::make_unique<FalsePositiveRefutationBRVisitor>());
  2251. // We don't overrite the notes inserted by other visitors because the
  2252. // refutation manager does not add any new note to the path
  2253. generateVisitorsDiagnostics(R, BugPath->ErrorNode, BRC);
  2254. }
  2255. // Check if the bug is still valid
  2256. if (R->isValid())
  2257. return PathDiagnosticBuilder(
  2258. std::move(BRC), std::move(BugPath->BugPath), BugPath->Report,
  2259. BugPath->ErrorNode, std::move(visitorNotes));
  2260. }
  2261. }
  2262. return {};
  2263. }
  2264. std::unique_ptr<DiagnosticForConsumerMapTy>
  2265. PathSensitiveBugReporter::generatePathDiagnostics(
  2266. ArrayRef<PathDiagnosticConsumer *> consumers,
  2267. ArrayRef<BugReport *> &bugReports) {
  2268. assert(!bugReports.empty());
  2269. auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
  2270. Optional<PathDiagnosticBuilder> PDB =
  2271. PathDiagnosticBuilder::findValidReport(bugReports, *this);
  2272. if (PDB) {
  2273. for (PathDiagnosticConsumer *PC : consumers) {
  2274. if (std::unique_ptr<PathDiagnostic> PD = PDB->generate(PC)) {
  2275. (*Out)[PC] = std::move(PD);
  2276. }
  2277. }
  2278. }
  2279. return Out;
  2280. }
  2281. void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
  2282. if (const ExplodedNode *E = R->getErrorNode()) {
  2283. // An error node must either be a sink or have a tag, otherwise
  2284. // it could get reclaimed before the path diagnostic is created.
  2285. assert((E->isSink() || E->getLocation().getTag()) &&
  2286. "Error node must either be a sink or have a tag");
  2287. const AnalysisDeclContext *DeclCtx =
  2288. E->getLocationContext()->getAnalysisDeclContext();
  2289. // The source of autosynthesized body can be handcrafted AST or a model
  2290. // file. The locations from handcrafted ASTs have no valid source locations
  2291. // and have to be discarded. Locations from model files should be preserved
  2292. // for processing and reporting.
  2293. if (DeclCtx->isBodyAutosynthesized() &&
  2294. !DeclCtx->isBodyAutosynthesizedFromModelFile())
  2295. return;
  2296. }
  2297. bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
  2298. assert(ValidSourceLoc);
  2299. // If we mess up in a release build, we'd still prefer to just drop the bug
  2300. // instead of trying to go on.
  2301. if (!ValidSourceLoc)
  2302. return;
  2303. // Compute the bug report's hash to determine its equivalence class.
  2304. llvm::FoldingSetNodeID ID;
  2305. R->Profile(ID);
  2306. // Lookup the equivance class. If there isn't one, create it.
  2307. void *InsertPos;
  2308. BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
  2309. if (!EQ) {
  2310. EQ = new BugReportEquivClass(std::move(R));
  2311. EQClasses.InsertNode(EQ, InsertPos);
  2312. EQClassesVector.push_back(EQ);
  2313. } else
  2314. EQ->AddReport(std::move(R));
  2315. }
  2316. //===----------------------------------------------------------------------===//
  2317. // Emitting reports in equivalence classes.
  2318. //===----------------------------------------------------------------------===//
  2319. namespace {
  2320. struct FRIEC_WLItem {
  2321. const ExplodedNode *N;
  2322. ExplodedNode::const_succ_iterator I, E;
  2323. FRIEC_WLItem(const ExplodedNode *n)
  2324. : N(n), I(N->succ_begin()), E(N->succ_end()) {}
  2325. };
  2326. } // namespace
  2327. static BugReport *
  2328. FindReportInEquivalenceClass(BugReportEquivClass& EQ,
  2329. SmallVectorImpl<BugReport*> &bugReports) {
  2330. BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
  2331. assert(I != E);
  2332. const BugType& BT = I->getBugType();
  2333. // If we don't need to suppress any of the nodes because they are
  2334. // post-dominated by a sink, simply add all the nodes in the equivalence class
  2335. // to 'Nodes'. Any of the reports will serve as a "representative" report.
  2336. if (!BT.isSuppressOnSink()) {
  2337. BugReport *R = &*I;
  2338. for (auto &I : EQ) {
  2339. const ExplodedNode *N = I.getErrorNode();
  2340. if (N) {
  2341. R = &I;
  2342. bugReports.push_back(R);
  2343. }
  2344. }
  2345. return R;
  2346. }
  2347. // For bug reports that should be suppressed when all paths are post-dominated
  2348. // by a sink node, iterate through the reports in the equivalence class
  2349. // until we find one that isn't post-dominated (if one exists). We use a
  2350. // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
  2351. // this as a recursive function, but we don't want to risk blowing out the
  2352. // stack for very long paths.
  2353. BugReport *exampleReport = nullptr;
  2354. for (; I != E; ++I) {
  2355. const ExplodedNode *errorNode = I->getErrorNode();
  2356. if (!errorNode)
  2357. continue;
  2358. if (errorNode->isSink()) {
  2359. llvm_unreachable(
  2360. "BugType::isSuppressSink() should not be 'true' for sink end nodes");
  2361. }
  2362. // No successors? By definition this nodes isn't post-dominated by a sink.
  2363. if (errorNode->succ_empty()) {
  2364. bugReports.push_back(&*I);
  2365. if (!exampleReport)
  2366. exampleReport = &*I;
  2367. continue;
  2368. }
  2369. // See if we are in a no-return CFG block. If so, treat this similarly
  2370. // to being post-dominated by a sink. This works better when the analysis
  2371. // is incomplete and we have never reached the no-return function call(s)
  2372. // that we'd inevitably bump into on this path.
  2373. if (const CFGBlock *ErrorB = errorNode->getCFGBlock())
  2374. if (ErrorB->isInevitablySinking())
  2375. continue;
  2376. // At this point we know that 'N' is not a sink and it has at least one
  2377. // successor. Use a DFS worklist to find a non-sink end-of-path node.
  2378. using WLItem = FRIEC_WLItem;
  2379. using DFSWorkList = SmallVector<WLItem, 10>;
  2380. llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
  2381. DFSWorkList WL;
  2382. WL.push_back(errorNode);
  2383. Visited[errorNode] = 1;
  2384. while (!WL.empty()) {
  2385. WLItem &WI = WL.back();
  2386. assert(!WI.N->succ_empty());
  2387. for (; WI.I != WI.E; ++WI.I) {
  2388. const ExplodedNode *Succ = *WI.I;
  2389. // End-of-path node?
  2390. if (Succ->succ_empty()) {
  2391. // If we found an end-of-path node that is not a sink.
  2392. if (!Succ->isSink()) {
  2393. bugReports.push_back(&*I);
  2394. if (!exampleReport)
  2395. exampleReport = &*I;
  2396. WL.clear();
  2397. break;
  2398. }
  2399. // Found a sink? Continue on to the next successor.
  2400. continue;
  2401. }
  2402. // Mark the successor as visited. If it hasn't been explored,
  2403. // enqueue it to the DFS worklist.
  2404. unsigned &mark = Visited[Succ];
  2405. if (!mark) {
  2406. mark = 1;
  2407. WL.push_back(Succ);
  2408. break;
  2409. }
  2410. }
  2411. // The worklist may have been cleared at this point. First
  2412. // check if it is empty before checking the last item.
  2413. if (!WL.empty() && &WL.back() == &WI)
  2414. WL.pop_back();
  2415. }
  2416. }
  2417. // ExampleReport will be NULL if all the nodes in the equivalence class
  2418. // were post-dominated by sinks.
  2419. return exampleReport;
  2420. }
  2421. void BugReporter::FlushReport(BugReportEquivClass& EQ) {
  2422. SmallVector<BugReport*, 10> bugReports;
  2423. BugReport *report = FindReportInEquivalenceClass(EQ, bugReports);
  2424. if (!report)
  2425. return;
  2426. ArrayRef<PathDiagnosticConsumer*> Consumers = getPathDiagnosticConsumers();
  2427. std::unique_ptr<DiagnosticForConsumerMapTy> Diagnostics =
  2428. generateDiagnosticForConsumerMap(report, Consumers, bugReports);
  2429. for (auto &P : *Diagnostics) {
  2430. PathDiagnosticConsumer *Consumer = P.first;
  2431. std::unique_ptr<PathDiagnostic> &PD = P.second;
  2432. // If the path is empty, generate a single step path with the location
  2433. // of the issue.
  2434. if (PD->path.empty()) {
  2435. PathDiagnosticLocation L = report->getLocation(getSourceManager());
  2436. auto piece = std::make_unique<PathDiagnosticEventPiece>(
  2437. L, report->getDescription());
  2438. for (SourceRange Range : report->getRanges())
  2439. piece->addRange(Range);
  2440. PD->setEndOfPath(std::move(piece));
  2441. }
  2442. PathPieces &Pieces = PD->getMutablePieces();
  2443. if (getAnalyzerOptions().ShouldDisplayNotesAsEvents) {
  2444. // For path diagnostic consumers that don't support extra notes,
  2445. // we may optionally convert those to path notes.
  2446. for (auto I = report->getNotes().rbegin(),
  2447. E = report->getNotes().rend(); I != E; ++I) {
  2448. PathDiagnosticNotePiece *Piece = I->get();
  2449. auto ConvertedPiece = std::make_shared<PathDiagnosticEventPiece>(
  2450. Piece->getLocation(), Piece->getString());
  2451. for (const auto &R: Piece->getRanges())
  2452. ConvertedPiece->addRange(R);
  2453. Pieces.push_front(std::move(ConvertedPiece));
  2454. }
  2455. } else {
  2456. for (auto I = report->getNotes().rbegin(),
  2457. E = report->getNotes().rend(); I != E; ++I)
  2458. Pieces.push_front(*I);
  2459. }
  2460. updateExecutedLinesWithDiagnosticPieces(*PD);
  2461. Consumer->HandlePathDiagnostic(std::move(PD));
  2462. }
  2463. }
  2464. /// Insert all lines participating in the function signature \p Signature
  2465. /// into \p ExecutedLines.
  2466. static void populateExecutedLinesWithFunctionSignature(
  2467. const Decl *Signature, const SourceManager &SM,
  2468. FilesToLineNumsMap &ExecutedLines) {
  2469. SourceRange SignatureSourceRange;
  2470. const Stmt* Body = Signature->getBody();
  2471. if (const auto FD = dyn_cast<FunctionDecl>(Signature)) {
  2472. SignatureSourceRange = FD->getSourceRange();
  2473. } else if (const auto OD = dyn_cast<ObjCMethodDecl>(Signature)) {
  2474. SignatureSourceRange = OD->getSourceRange();
  2475. } else {
  2476. return;
  2477. }
  2478. SourceLocation Start = SignatureSourceRange.getBegin();
  2479. SourceLocation End = Body ? Body->getSourceRange().getBegin()
  2480. : SignatureSourceRange.getEnd();
  2481. if (!Start.isValid() || !End.isValid())
  2482. return;
  2483. unsigned StartLine = SM.getExpansionLineNumber(Start);
  2484. unsigned EndLine = SM.getExpansionLineNumber(End);
  2485. FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
  2486. for (unsigned Line = StartLine; Line <= EndLine; Line++)
  2487. ExecutedLines[FID].insert(Line);
  2488. }
  2489. static void populateExecutedLinesWithStmt(
  2490. const Stmt *S, const SourceManager &SM,
  2491. FilesToLineNumsMap &ExecutedLines) {
  2492. SourceLocation Loc = S->getSourceRange().getBegin();
  2493. if (!Loc.isValid())
  2494. return;
  2495. SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
  2496. FileID FID = SM.getFileID(ExpansionLoc);
  2497. unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
  2498. ExecutedLines[FID].insert(LineNo);
  2499. }
  2500. /// \return all executed lines including function signatures on the path
  2501. /// starting from \p N.
  2502. static std::unique_ptr<FilesToLineNumsMap>
  2503. findExecutedLines(const SourceManager &SM, const ExplodedNode *N) {
  2504. auto ExecutedLines = std::make_unique<FilesToLineNumsMap>();
  2505. while (N) {
  2506. if (N->getFirstPred() == nullptr) {
  2507. // First node: show signature of the entrance point.
  2508. const Decl *D = N->getLocationContext()->getDecl();
  2509. populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
  2510. } else if (auto CE = N->getLocationAs<CallEnter>()) {
  2511. // Inlined function: show signature.
  2512. const Decl* D = CE->getCalleeContext()->getDecl();
  2513. populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
  2514. } else if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) {
  2515. populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
  2516. // Show extra context for some parent kinds.
  2517. const Stmt *P = N->getParentMap().getParent(S);
  2518. // The path exploration can die before the node with the associated
  2519. // return statement is generated, but we do want to show the whole
  2520. // return.
  2521. if (const auto *RS = dyn_cast_or_null<ReturnStmt>(P)) {
  2522. populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
  2523. P = N->getParentMap().getParent(RS);
  2524. }
  2525. if (P && (isa<SwitchCase>(P) || isa<LabelStmt>(P)))
  2526. populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
  2527. }
  2528. N = N->getFirstPred();
  2529. }
  2530. return ExecutedLines;
  2531. }
  2532. std::unique_ptr<DiagnosticForConsumerMapTy>
  2533. BugReporter::generateDiagnosticForConsumerMap(
  2534. BugReport *report, ArrayRef<PathDiagnosticConsumer *> consumers,
  2535. ArrayRef<BugReport *> bugReports) {
  2536. if (!report->isPathSensitive()) {
  2537. auto Out = std::make_unique<DiagnosticForConsumerMapTy>();
  2538. for (auto *Consumer : consumers)
  2539. (*Out)[Consumer] = generateEmptyDiagnosticForReport(report,
  2540. getSourceManager());
  2541. return Out;
  2542. }
  2543. // Generate the full path sensitive diagnostic, using the generation scheme
  2544. // specified by the PathDiagnosticConsumer. Note that we have to generate
  2545. // path diagnostics even for consumers which do not support paths, because
  2546. // the BugReporterVisitors may mark this bug as a false positive.
  2547. assert(!bugReports.empty());
  2548. MaxBugClassSize.updateMax(bugReports.size());
  2549. std::unique_ptr<DiagnosticForConsumerMapTy> Out =
  2550. generatePathDiagnostics(consumers, bugReports);
  2551. if (Out->empty())
  2552. return Out;
  2553. MaxValidBugClassSize.updateMax(bugReports.size());
  2554. // Examine the report and see if the last piece is in a header. Reset the
  2555. // report location to the last piece in the main source file.
  2556. const AnalyzerOptions &Opts = getAnalyzerOptions();
  2557. for (auto const &P : *Out)
  2558. if (Opts.ShouldReportIssuesInMainSourceFile && !Opts.AnalyzeAll)
  2559. P.second->resetDiagnosticLocationToMainFile();
  2560. return Out;
  2561. }
  2562. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  2563. const CheckerBase *Checker,
  2564. StringRef Name, StringRef Category,
  2565. StringRef Str, PathDiagnosticLocation Loc,
  2566. ArrayRef<SourceRange> Ranges) {
  2567. EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
  2568. Loc, Ranges);
  2569. }
  2570. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  2571. CheckName CheckName,
  2572. StringRef name, StringRef category,
  2573. StringRef str, PathDiagnosticLocation Loc,
  2574. ArrayRef<SourceRange> Ranges) {
  2575. // 'BT' is owned by BugReporter.
  2576. BugType *BT = getBugTypeForName(CheckName, name, category);
  2577. auto R = std::make_unique<BugReport>(*BT, str, Loc);
  2578. R->setDeclWithIssue(DeclWithIssue);
  2579. for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
  2580. I != E; ++I)
  2581. R->addRange(*I);
  2582. emitReport(std::move(R));
  2583. }
  2584. BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
  2585. StringRef category) {
  2586. SmallString<136> fullDesc;
  2587. llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
  2588. << ":" << category;
  2589. BugType *&BT = StrBugTypes[fullDesc];
  2590. if (!BT)
  2591. BT = new BugType(CheckName, name, category);
  2592. return BT;
  2593. }