BugReporter.cpp 118 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551
  1. // BugReporter.cpp - Generate PathDiagnostics for Bugs ------------*- C++ -*--//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines BugReporter, a utility class for generating
  11. // PathDiagnostics.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  15. #include "clang/AST/ASTContext.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/StmtCXX.h"
  21. #include "clang/AST/StmtObjC.h"
  22. #include "clang/Analysis/CFG.h"
  23. #include "clang/Analysis/ProgramPoint.h"
  24. #include "clang/Basic/SourceManager.h"
  25. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  26. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  27. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  28. #include "llvm/ADT/DenseMap.h"
  29. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  30. #include "llvm/ADT/STLExtras.h"
  31. #include "llvm/ADT/SmallString.h"
  32. #include "llvm/ADT/Statistic.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include <memory>
  35. #include <queue>
  36. using namespace clang;
  37. using namespace ento;
  38. #define DEBUG_TYPE "BugReporter"
  39. STATISTIC(MaxBugClassSize,
  40. "The maximum number of bug reports in the same equivalence class");
  41. STATISTIC(MaxValidBugClassSize,
  42. "The maximum number of bug reports in the same equivalence class "
  43. "where at least one report is valid (not suppressed)");
  44. BugReporterVisitor::~BugReporterVisitor() {}
  45. void BugReporterContext::anchor() {}
  46. //===----------------------------------------------------------------------===//
  47. // Helper routines for walking the ExplodedGraph and fetching statements.
  48. //===----------------------------------------------------------------------===//
  49. static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
  50. for (N = N->getFirstPred(); N; N = N->getFirstPred())
  51. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  52. return S;
  53. return nullptr;
  54. }
  55. static inline const Stmt*
  56. GetCurrentOrPreviousStmt(const ExplodedNode *N) {
  57. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  58. return S;
  59. return GetPreviousStmt(N);
  60. }
  61. //===----------------------------------------------------------------------===//
  62. // Diagnostic cleanup.
  63. //===----------------------------------------------------------------------===//
  64. static PathDiagnosticEventPiece *
  65. eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
  66. PathDiagnosticEventPiece *Y) {
  67. // Prefer diagnostics that come from ConditionBRVisitor over
  68. // those that came from TrackConstraintBRVisitor.
  69. const void *tagPreferred = ConditionBRVisitor::getTag();
  70. const void *tagLesser = TrackConstraintBRVisitor::getTag();
  71. if (X->getLocation() != Y->getLocation())
  72. return nullptr;
  73. if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
  74. return X;
  75. if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
  76. return Y;
  77. return nullptr;
  78. }
  79. /// An optimization pass over PathPieces that removes redundant diagnostics
  80. /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both
  81. /// BugReporterVisitors use different methods to generate diagnostics, with
  82. /// one capable of emitting diagnostics in some cases but not in others. This
  83. /// can lead to redundant diagnostic pieces at the same point in a path.
  84. static void removeRedundantMsgs(PathPieces &path) {
  85. unsigned N = path.size();
  86. if (N < 2)
  87. return;
  88. // NOTE: this loop intentionally is not using an iterator. Instead, we
  89. // are streaming the path and modifying it in place. This is done by
  90. // grabbing the front, processing it, and if we decide to keep it append
  91. // it to the end of the path. The entire path is processed in this way.
  92. for (unsigned i = 0; i < N; ++i) {
  93. IntrusiveRefCntPtr<PathDiagnosticPiece> piece(path.front());
  94. path.pop_front();
  95. switch (piece->getKind()) {
  96. case clang::ento::PathDiagnosticPiece::Call:
  97. removeRedundantMsgs(cast<PathDiagnosticCallPiece>(piece)->path);
  98. break;
  99. case clang::ento::PathDiagnosticPiece::Macro:
  100. removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(piece)->subPieces);
  101. break;
  102. case clang::ento::PathDiagnosticPiece::ControlFlow:
  103. break;
  104. case clang::ento::PathDiagnosticPiece::Event: {
  105. if (i == N-1)
  106. break;
  107. if (PathDiagnosticEventPiece *nextEvent =
  108. dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
  109. PathDiagnosticEventPiece *event =
  110. cast<PathDiagnosticEventPiece>(piece);
  111. // Check to see if we should keep one of the two pieces. If we
  112. // come up with a preference, record which piece to keep, and consume
  113. // another piece from the path.
  114. if (PathDiagnosticEventPiece *pieceToKeep =
  115. eventsDescribeSameCondition(event, nextEvent)) {
  116. piece = pieceToKeep;
  117. path.pop_front();
  118. ++i;
  119. }
  120. }
  121. break;
  122. }
  123. }
  124. path.push_back(piece);
  125. }
  126. }
  127. /// A map from PathDiagnosticPiece to the LocationContext of the inlined
  128. /// function call it represents.
  129. typedef llvm::DenseMap<const PathPieces *, const LocationContext *>
  130. LocationContextMap;
  131. /// Recursively scan through a path and prune out calls and macros pieces
  132. /// that aren't needed. Return true if afterwards the path contains
  133. /// "interesting stuff" which means it shouldn't be pruned from the parent path.
  134. static bool removeUnneededCalls(PathPieces &pieces, BugReport *R,
  135. LocationContextMap &LCM) {
  136. bool containsSomethingInteresting = false;
  137. const unsigned N = pieces.size();
  138. for (unsigned i = 0 ; i < N ; ++i) {
  139. // Remove the front piece from the path. If it is still something we
  140. // want to keep once we are done, we will push it back on the end.
  141. IntrusiveRefCntPtr<PathDiagnosticPiece> piece(pieces.front());
  142. pieces.pop_front();
  143. switch (piece->getKind()) {
  144. case PathDiagnosticPiece::Call: {
  145. PathDiagnosticCallPiece *call = cast<PathDiagnosticCallPiece>(piece);
  146. // Check if the location context is interesting.
  147. assert(LCM.count(&call->path));
  148. if (R->isInteresting(LCM[&call->path])) {
  149. containsSomethingInteresting = true;
  150. break;
  151. }
  152. if (!removeUnneededCalls(call->path, R, LCM))
  153. continue;
  154. containsSomethingInteresting = true;
  155. break;
  156. }
  157. case PathDiagnosticPiece::Macro: {
  158. PathDiagnosticMacroPiece *macro = cast<PathDiagnosticMacroPiece>(piece);
  159. if (!removeUnneededCalls(macro->subPieces, R, LCM))
  160. continue;
  161. containsSomethingInteresting = true;
  162. break;
  163. }
  164. case PathDiagnosticPiece::Event: {
  165. PathDiagnosticEventPiece *event = cast<PathDiagnosticEventPiece>(piece);
  166. // We never throw away an event, but we do throw it away wholesale
  167. // as part of a path if we throw the entire path away.
  168. containsSomethingInteresting |= !event->isPrunable();
  169. break;
  170. }
  171. case PathDiagnosticPiece::ControlFlow:
  172. break;
  173. }
  174. pieces.push_back(piece);
  175. }
  176. return containsSomethingInteresting;
  177. }
  178. /// Returns true if the given decl has been implicitly given a body, either by
  179. /// the analyzer or by the compiler proper.
  180. static bool hasImplicitBody(const Decl *D) {
  181. assert(D);
  182. return D->isImplicit() || !D->hasBody();
  183. }
  184. /// Recursively scan through a path and make sure that all call pieces have
  185. /// valid locations.
  186. static void
  187. adjustCallLocations(PathPieces &Pieces,
  188. PathDiagnosticLocation *LastCallLocation = nullptr) {
  189. for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E; ++I) {
  190. PathDiagnosticCallPiece *Call = dyn_cast<PathDiagnosticCallPiece>(*I);
  191. if (!Call) {
  192. assert((*I)->getLocation().asLocation().isValid());
  193. continue;
  194. }
  195. if (LastCallLocation) {
  196. bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
  197. if (CallerIsImplicit || !Call->callEnter.asLocation().isValid())
  198. Call->callEnter = *LastCallLocation;
  199. if (CallerIsImplicit || !Call->callReturn.asLocation().isValid())
  200. Call->callReturn = *LastCallLocation;
  201. }
  202. // Recursively clean out the subclass. Keep this call around if
  203. // it contains any informative diagnostics.
  204. PathDiagnosticLocation *ThisCallLocation;
  205. if (Call->callEnterWithin.asLocation().isValid() &&
  206. !hasImplicitBody(Call->getCallee()))
  207. ThisCallLocation = &Call->callEnterWithin;
  208. else
  209. ThisCallLocation = &Call->callEnter;
  210. assert(ThisCallLocation && "Outermost call has an invalid location");
  211. adjustCallLocations(Call->path, ThisCallLocation);
  212. }
  213. }
  214. /// Remove edges in and out of C++ default initializer expressions. These are
  215. /// for fields that have in-class initializers, as opposed to being initialized
  216. /// explicitly in a constructor or braced list.
  217. static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
  218. for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
  219. if (PathDiagnosticCallPiece *C = dyn_cast<PathDiagnosticCallPiece>(*I))
  220. removeEdgesToDefaultInitializers(C->path);
  221. if (PathDiagnosticMacroPiece *M = dyn_cast<PathDiagnosticMacroPiece>(*I))
  222. removeEdgesToDefaultInitializers(M->subPieces);
  223. if (PathDiagnosticControlFlowPiece *CF =
  224. dyn_cast<PathDiagnosticControlFlowPiece>(*I)) {
  225. const Stmt *Start = CF->getStartLocation().asStmt();
  226. const Stmt *End = CF->getEndLocation().asStmt();
  227. if (Start && isa<CXXDefaultInitExpr>(Start)) {
  228. I = Pieces.erase(I);
  229. continue;
  230. } else if (End && isa<CXXDefaultInitExpr>(End)) {
  231. PathPieces::iterator Next = std::next(I);
  232. if (Next != E) {
  233. if (PathDiagnosticControlFlowPiece *NextCF =
  234. dyn_cast<PathDiagnosticControlFlowPiece>(*Next)) {
  235. NextCF->setStartLocation(CF->getStartLocation());
  236. }
  237. }
  238. I = Pieces.erase(I);
  239. continue;
  240. }
  241. }
  242. I++;
  243. }
  244. }
  245. /// Remove all pieces with invalid locations as these cannot be serialized.
  246. /// We might have pieces with invalid locations as a result of inlining Body
  247. /// Farm generated functions.
  248. static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
  249. for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
  250. if (PathDiagnosticCallPiece *C = dyn_cast<PathDiagnosticCallPiece>(*I))
  251. removePiecesWithInvalidLocations(C->path);
  252. if (PathDiagnosticMacroPiece *M = dyn_cast<PathDiagnosticMacroPiece>(*I))
  253. removePiecesWithInvalidLocations(M->subPieces);
  254. if (!(*I)->getLocation().isValid() ||
  255. !(*I)->getLocation().asLocation().isValid()) {
  256. I = Pieces.erase(I);
  257. continue;
  258. }
  259. I++;
  260. }
  261. }
  262. //===----------------------------------------------------------------------===//
  263. // PathDiagnosticBuilder and its associated routines and helper objects.
  264. //===----------------------------------------------------------------------===//
  265. namespace {
  266. class NodeMapClosure : public BugReport::NodeResolver {
  267. InterExplodedGraphMap &M;
  268. public:
  269. NodeMapClosure(InterExplodedGraphMap &m) : M(m) {}
  270. const ExplodedNode *getOriginalNode(const ExplodedNode *N) override {
  271. return M.lookup(N);
  272. }
  273. };
  274. class PathDiagnosticBuilder : public BugReporterContext {
  275. BugReport *R;
  276. PathDiagnosticConsumer *PDC;
  277. NodeMapClosure NMC;
  278. public:
  279. const LocationContext *LC;
  280. PathDiagnosticBuilder(GRBugReporter &br,
  281. BugReport *r, InterExplodedGraphMap &Backmap,
  282. PathDiagnosticConsumer *pdc)
  283. : BugReporterContext(br),
  284. R(r), PDC(pdc), NMC(Backmap), LC(r->getErrorNode()->getLocationContext())
  285. {}
  286. PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
  287. PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
  288. const ExplodedNode *N);
  289. BugReport *getBugReport() { return R; }
  290. Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
  291. ParentMap& getParentMap() { return LC->getParentMap(); }
  292. const Stmt *getParent(const Stmt *S) {
  293. return getParentMap().getParent(S);
  294. }
  295. NodeMapClosure& getNodeResolver() override { return NMC; }
  296. PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
  297. PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
  298. return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Extensive;
  299. }
  300. bool supportsLogicalOpControlFlow() const {
  301. return PDC ? PDC->supportsLogicalOpControlFlow() : true;
  302. }
  303. };
  304. } // end anonymous namespace
  305. PathDiagnosticLocation
  306. PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
  307. if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N))
  308. return PathDiagnosticLocation(S, getSourceManager(), LC);
  309. return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
  310. getSourceManager());
  311. }
  312. PathDiagnosticLocation
  313. PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
  314. const ExplodedNode *N) {
  315. // Slow, but probably doesn't matter.
  316. if (os.str().empty())
  317. os << ' ';
  318. const PathDiagnosticLocation &Loc = ExecutionContinues(N);
  319. if (Loc.asStmt())
  320. os << "Execution continues on line "
  321. << getSourceManager().getExpansionLineNumber(Loc.asLocation())
  322. << '.';
  323. else {
  324. os << "Execution jumps to the end of the ";
  325. const Decl *D = N->getLocationContext()->getDecl();
  326. if (isa<ObjCMethodDecl>(D))
  327. os << "method";
  328. else if (isa<FunctionDecl>(D))
  329. os << "function";
  330. else {
  331. assert(isa<BlockDecl>(D));
  332. os << "anonymous block";
  333. }
  334. os << '.';
  335. }
  336. return Loc;
  337. }
  338. static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
  339. if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
  340. return PM.getParentIgnoreParens(S);
  341. const Stmt *Parent = PM.getParentIgnoreParens(S);
  342. if (!Parent)
  343. return nullptr;
  344. switch (Parent->getStmtClass()) {
  345. case Stmt::ForStmtClass:
  346. case Stmt::DoStmtClass:
  347. case Stmt::WhileStmtClass:
  348. case Stmt::ObjCForCollectionStmtClass:
  349. case Stmt::CXXForRangeStmtClass:
  350. return Parent;
  351. default:
  352. break;
  353. }
  354. return nullptr;
  355. }
  356. static PathDiagnosticLocation
  357. getEnclosingStmtLocation(const Stmt *S, SourceManager &SMgr, const ParentMap &P,
  358. const LocationContext *LC, bool allowNestedContexts) {
  359. if (!S)
  360. return PathDiagnosticLocation();
  361. while (const Stmt *Parent = getEnclosingParent(S, P)) {
  362. switch (Parent->getStmtClass()) {
  363. case Stmt::BinaryOperatorClass: {
  364. const BinaryOperator *B = cast<BinaryOperator>(Parent);
  365. if (B->isLogicalOp())
  366. return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC);
  367. break;
  368. }
  369. case Stmt::CompoundStmtClass:
  370. case Stmt::StmtExprClass:
  371. return PathDiagnosticLocation(S, SMgr, LC);
  372. case Stmt::ChooseExprClass:
  373. // Similar to '?' if we are referring to condition, just have the edge
  374. // point to the entire choose expression.
  375. if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
  376. return PathDiagnosticLocation(Parent, SMgr, LC);
  377. else
  378. return PathDiagnosticLocation(S, SMgr, LC);
  379. case Stmt::BinaryConditionalOperatorClass:
  380. case Stmt::ConditionalOperatorClass:
  381. // For '?', if we are referring to condition, just have the edge point
  382. // to the entire '?' expression.
  383. if (allowNestedContexts ||
  384. cast<AbstractConditionalOperator>(Parent)->getCond() == S)
  385. return PathDiagnosticLocation(Parent, SMgr, LC);
  386. else
  387. return PathDiagnosticLocation(S, SMgr, LC);
  388. case Stmt::CXXForRangeStmtClass:
  389. if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
  390. return PathDiagnosticLocation(S, SMgr, LC);
  391. break;
  392. case Stmt::DoStmtClass:
  393. return PathDiagnosticLocation(S, SMgr, LC);
  394. case Stmt::ForStmtClass:
  395. if (cast<ForStmt>(Parent)->getBody() == S)
  396. return PathDiagnosticLocation(S, SMgr, LC);
  397. break;
  398. case Stmt::IfStmtClass:
  399. if (cast<IfStmt>(Parent)->getCond() != S)
  400. return PathDiagnosticLocation(S, SMgr, LC);
  401. break;
  402. case Stmt::ObjCForCollectionStmtClass:
  403. if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
  404. return PathDiagnosticLocation(S, SMgr, LC);
  405. break;
  406. case Stmt::WhileStmtClass:
  407. if (cast<WhileStmt>(Parent)->getCond() != S)
  408. return PathDiagnosticLocation(S, SMgr, LC);
  409. break;
  410. default:
  411. break;
  412. }
  413. S = Parent;
  414. }
  415. assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
  416. return PathDiagnosticLocation(S, SMgr, LC);
  417. }
  418. PathDiagnosticLocation
  419. PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
  420. assert(S && "Null Stmt passed to getEnclosingStmtLocation");
  421. return ::getEnclosingStmtLocation(S, getSourceManager(), getParentMap(), LC,
  422. /*allowNestedContexts=*/false);
  423. }
  424. //===----------------------------------------------------------------------===//
  425. // "Visitors only" path diagnostic generation algorithm.
  426. //===----------------------------------------------------------------------===//
  427. static bool GenerateVisitorsOnlyPathDiagnostic(
  428. PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
  429. ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
  430. // All path generation skips the very first node (the error node).
  431. // This is because there is special handling for the end-of-path note.
  432. N = N->getFirstPred();
  433. if (!N)
  434. return true;
  435. BugReport *R = PDB.getBugReport();
  436. while (const ExplodedNode *Pred = N->getFirstPred()) {
  437. for (auto &V : visitors) {
  438. // Visit all the node pairs, but throw the path pieces away.
  439. PathDiagnosticPiece *Piece = V->VisitNode(N, Pred, PDB, *R);
  440. delete Piece;
  441. }
  442. N = Pred;
  443. }
  444. return R->isValid();
  445. }
  446. //===----------------------------------------------------------------------===//
  447. // "Minimal" path diagnostic generation algorithm.
  448. //===----------------------------------------------------------------------===//
  449. typedef std::pair<PathDiagnosticCallPiece*, const ExplodedNode*> StackDiagPair;
  450. typedef SmallVector<StackDiagPair, 6> StackDiagVector;
  451. static void updateStackPiecesWithMessage(PathDiagnosticPiece *P,
  452. StackDiagVector &CallStack) {
  453. // If the piece contains a special message, add it to all the call
  454. // pieces on the active stack.
  455. if (PathDiagnosticEventPiece *ep =
  456. dyn_cast<PathDiagnosticEventPiece>(P)) {
  457. if (ep->hasCallStackHint())
  458. for (StackDiagVector::iterator I = CallStack.begin(),
  459. E = CallStack.end(); I != E; ++I) {
  460. PathDiagnosticCallPiece *CP = I->first;
  461. const ExplodedNode *N = I->second;
  462. std::string stackMsg = ep->getCallStackMessage(N);
  463. // The last message on the path to final bug is the most important
  464. // one. Since we traverse the path backwards, do not add the message
  465. // if one has been previously added.
  466. if (!CP->hasCallStackMessage())
  467. CP->setCallStackMessage(stackMsg);
  468. }
  469. }
  470. }
  471. static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM);
  472. static bool GenerateMinimalPathDiagnostic(
  473. PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
  474. LocationContextMap &LCM,
  475. ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
  476. SourceManager& SMgr = PDB.getSourceManager();
  477. const LocationContext *LC = PDB.LC;
  478. const ExplodedNode *NextNode = N->pred_empty()
  479. ? nullptr : *(N->pred_begin());
  480. StackDiagVector CallStack;
  481. while (NextNode) {
  482. N = NextNode;
  483. PDB.LC = N->getLocationContext();
  484. NextNode = N->getFirstPred();
  485. ProgramPoint P = N->getLocation();
  486. do {
  487. if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
  488. PathDiagnosticCallPiece *C =
  489. PathDiagnosticCallPiece::construct(N, *CE, SMgr);
  490. // Record the mapping from call piece to LocationContext.
  491. LCM[&C->path] = CE->getCalleeContext();
  492. PD.getActivePath().push_front(C);
  493. PD.pushActivePath(&C->path);
  494. CallStack.push_back(StackDiagPair(C, N));
  495. break;
  496. }
  497. if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
  498. // Flush all locations, and pop the active path.
  499. bool VisitedEntireCall = PD.isWithinCall();
  500. PD.popActivePath();
  501. // Either we just added a bunch of stuff to the top-level path, or
  502. // we have a previous CallExitEnd. If the former, it means that the
  503. // path terminated within a function call. We must then take the
  504. // current contents of the active path and place it within
  505. // a new PathDiagnosticCallPiece.
  506. PathDiagnosticCallPiece *C;
  507. if (VisitedEntireCall) {
  508. C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
  509. } else {
  510. const Decl *Caller = CE->getLocationContext()->getDecl();
  511. C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
  512. // Record the mapping from call piece to LocationContext.
  513. LCM[&C->path] = CE->getCalleeContext();
  514. }
  515. C->setCallee(*CE, SMgr);
  516. if (!CallStack.empty()) {
  517. assert(CallStack.back().first == C);
  518. CallStack.pop_back();
  519. }
  520. break;
  521. }
  522. if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
  523. const CFGBlock *Src = BE->getSrc();
  524. const CFGBlock *Dst = BE->getDst();
  525. const Stmt *T = Src->getTerminator();
  526. if (!T)
  527. break;
  528. PathDiagnosticLocation Start =
  529. PathDiagnosticLocation::createBegin(T, SMgr,
  530. N->getLocationContext());
  531. switch (T->getStmtClass()) {
  532. default:
  533. break;
  534. case Stmt::GotoStmtClass:
  535. case Stmt::IndirectGotoStmtClass: {
  536. const Stmt *S = PathDiagnosticLocation::getNextStmt(N);
  537. if (!S)
  538. break;
  539. std::string sbuf;
  540. llvm::raw_string_ostream os(sbuf);
  541. const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
  542. os << "Control jumps to line "
  543. << End.asLocation().getExpansionLineNumber();
  544. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  545. Start, End, os.str()));
  546. break;
  547. }
  548. case Stmt::SwitchStmtClass: {
  549. // Figure out what case arm we took.
  550. std::string sbuf;
  551. llvm::raw_string_ostream os(sbuf);
  552. if (const Stmt *S = Dst->getLabel()) {
  553. PathDiagnosticLocation End(S, SMgr, LC);
  554. switch (S->getStmtClass()) {
  555. default:
  556. os << "No cases match in the switch statement. "
  557. "Control jumps to line "
  558. << End.asLocation().getExpansionLineNumber();
  559. break;
  560. case Stmt::DefaultStmtClass:
  561. os << "Control jumps to the 'default' case at line "
  562. << End.asLocation().getExpansionLineNumber();
  563. break;
  564. case Stmt::CaseStmtClass: {
  565. os << "Control jumps to 'case ";
  566. const CaseStmt *Case = cast<CaseStmt>(S);
  567. const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
  568. // Determine if it is an enum.
  569. bool GetRawInt = true;
  570. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
  571. // FIXME: Maybe this should be an assertion. Are there cases
  572. // were it is not an EnumConstantDecl?
  573. const EnumConstantDecl *D =
  574. dyn_cast<EnumConstantDecl>(DR->getDecl());
  575. if (D) {
  576. GetRawInt = false;
  577. os << *D;
  578. }
  579. }
  580. if (GetRawInt)
  581. os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
  582. os << ":' at line "
  583. << End.asLocation().getExpansionLineNumber();
  584. break;
  585. }
  586. }
  587. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  588. Start, End, os.str()));
  589. }
  590. else {
  591. os << "'Default' branch taken. ";
  592. const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
  593. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  594. Start, End, os.str()));
  595. }
  596. break;
  597. }
  598. case Stmt::BreakStmtClass:
  599. case Stmt::ContinueStmtClass: {
  600. std::string sbuf;
  601. llvm::raw_string_ostream os(sbuf);
  602. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  603. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  604. Start, End, os.str()));
  605. break;
  606. }
  607. // Determine control-flow for ternary '?'.
  608. case Stmt::BinaryConditionalOperatorClass:
  609. case Stmt::ConditionalOperatorClass: {
  610. std::string sbuf;
  611. llvm::raw_string_ostream os(sbuf);
  612. os << "'?' condition is ";
  613. if (*(Src->succ_begin()+1) == Dst)
  614. os << "false";
  615. else
  616. os << "true";
  617. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  618. if (const Stmt *S = End.asStmt())
  619. End = PDB.getEnclosingStmtLocation(S);
  620. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  621. Start, End, os.str()));
  622. break;
  623. }
  624. // Determine control-flow for short-circuited '&&' and '||'.
  625. case Stmt::BinaryOperatorClass: {
  626. if (!PDB.supportsLogicalOpControlFlow())
  627. break;
  628. const BinaryOperator *B = cast<BinaryOperator>(T);
  629. std::string sbuf;
  630. llvm::raw_string_ostream os(sbuf);
  631. os << "Left side of '";
  632. if (B->getOpcode() == BO_LAnd) {
  633. os << "&&" << "' is ";
  634. if (*(Src->succ_begin()+1) == Dst) {
  635. os << "false";
  636. PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
  637. PathDiagnosticLocation Start =
  638. PathDiagnosticLocation::createOperatorLoc(B, SMgr);
  639. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  640. Start, End, os.str()));
  641. }
  642. else {
  643. os << "true";
  644. PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
  645. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  646. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  647. Start, End, os.str()));
  648. }
  649. }
  650. else {
  651. assert(B->getOpcode() == BO_LOr);
  652. os << "||" << "' is ";
  653. if (*(Src->succ_begin()+1) == Dst) {
  654. os << "false";
  655. PathDiagnosticLocation Start(B->getLHS(), SMgr, LC);
  656. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  657. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  658. Start, End, os.str()));
  659. }
  660. else {
  661. os << "true";
  662. PathDiagnosticLocation End(B->getLHS(), SMgr, LC);
  663. PathDiagnosticLocation Start =
  664. PathDiagnosticLocation::createOperatorLoc(B, SMgr);
  665. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  666. Start, End, os.str()));
  667. }
  668. }
  669. break;
  670. }
  671. case Stmt::DoStmtClass: {
  672. if (*(Src->succ_begin()) == Dst) {
  673. std::string sbuf;
  674. llvm::raw_string_ostream os(sbuf);
  675. os << "Loop condition is true. ";
  676. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  677. if (const Stmt *S = End.asStmt())
  678. End = PDB.getEnclosingStmtLocation(S);
  679. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  680. Start, End, os.str()));
  681. }
  682. else {
  683. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  684. if (const Stmt *S = End.asStmt())
  685. End = PDB.getEnclosingStmtLocation(S);
  686. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  687. Start, End, "Loop condition is false. Exiting loop"));
  688. }
  689. break;
  690. }
  691. case Stmt::WhileStmtClass:
  692. case Stmt::ForStmtClass: {
  693. if (*(Src->succ_begin()+1) == Dst) {
  694. std::string sbuf;
  695. llvm::raw_string_ostream os(sbuf);
  696. os << "Loop condition is false. ";
  697. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  698. if (const Stmt *S = End.asStmt())
  699. End = PDB.getEnclosingStmtLocation(S);
  700. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  701. Start, End, os.str()));
  702. }
  703. else {
  704. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  705. if (const Stmt *S = End.asStmt())
  706. End = PDB.getEnclosingStmtLocation(S);
  707. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  708. Start, End, "Loop condition is true. Entering loop body"));
  709. }
  710. break;
  711. }
  712. case Stmt::IfStmtClass: {
  713. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  714. if (const Stmt *S = End.asStmt())
  715. End = PDB.getEnclosingStmtLocation(S);
  716. if (*(Src->succ_begin()+1) == Dst)
  717. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  718. Start, End, "Taking false branch"));
  719. else
  720. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(
  721. Start, End, "Taking true branch"));
  722. break;
  723. }
  724. }
  725. }
  726. } while(0);
  727. if (NextNode) {
  728. // Add diagnostic pieces from custom visitors.
  729. BugReport *R = PDB.getBugReport();
  730. for (auto &V : visitors) {
  731. if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *R)) {
  732. PD.getActivePath().push_front(p);
  733. updateStackPiecesWithMessage(p, CallStack);
  734. }
  735. }
  736. }
  737. }
  738. if (!PDB.getBugReport()->isValid())
  739. return false;
  740. // After constructing the full PathDiagnostic, do a pass over it to compact
  741. // PathDiagnosticPieces that occur within a macro.
  742. CompactPathDiagnostic(PD.getMutablePieces(), PDB.getSourceManager());
  743. return true;
  744. }
  745. //===----------------------------------------------------------------------===//
  746. // "Extensive" PathDiagnostic generation.
  747. //===----------------------------------------------------------------------===//
  748. static bool IsControlFlowExpr(const Stmt *S) {
  749. const Expr *E = dyn_cast<Expr>(S);
  750. if (!E)
  751. return false;
  752. E = E->IgnoreParenCasts();
  753. if (isa<AbstractConditionalOperator>(E))
  754. return true;
  755. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
  756. if (B->isLogicalOp())
  757. return true;
  758. return false;
  759. }
  760. namespace {
  761. class ContextLocation : public PathDiagnosticLocation {
  762. bool IsDead;
  763. public:
  764. ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
  765. : PathDiagnosticLocation(L), IsDead(isdead) {}
  766. void markDead() { IsDead = true; }
  767. bool isDead() const { return IsDead; }
  768. };
  769. static PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
  770. const LocationContext *LC,
  771. bool firstCharOnly = false) {
  772. if (const Stmt *S = L.asStmt()) {
  773. const Stmt *Original = S;
  774. while (1) {
  775. // Adjust the location for some expressions that are best referenced
  776. // by one of their subexpressions.
  777. switch (S->getStmtClass()) {
  778. default:
  779. break;
  780. case Stmt::ParenExprClass:
  781. case Stmt::GenericSelectionExprClass:
  782. S = cast<Expr>(S)->IgnoreParens();
  783. firstCharOnly = true;
  784. continue;
  785. case Stmt::BinaryConditionalOperatorClass:
  786. case Stmt::ConditionalOperatorClass:
  787. S = cast<AbstractConditionalOperator>(S)->getCond();
  788. firstCharOnly = true;
  789. continue;
  790. case Stmt::ChooseExprClass:
  791. S = cast<ChooseExpr>(S)->getCond();
  792. firstCharOnly = true;
  793. continue;
  794. case Stmt::BinaryOperatorClass:
  795. S = cast<BinaryOperator>(S)->getLHS();
  796. firstCharOnly = true;
  797. continue;
  798. }
  799. break;
  800. }
  801. if (S != Original)
  802. L = PathDiagnosticLocation(S, L.getManager(), LC);
  803. }
  804. if (firstCharOnly)
  805. L = PathDiagnosticLocation::createSingleLocation(L);
  806. return L;
  807. }
  808. class EdgeBuilder {
  809. std::vector<ContextLocation> CLocs;
  810. typedef std::vector<ContextLocation>::iterator iterator;
  811. PathDiagnostic &PD;
  812. PathDiagnosticBuilder &PDB;
  813. PathDiagnosticLocation PrevLoc;
  814. bool IsConsumedExpr(const PathDiagnosticLocation &L);
  815. bool containsLocation(const PathDiagnosticLocation &Container,
  816. const PathDiagnosticLocation &Containee);
  817. PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
  818. void popLocation() {
  819. if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
  820. // For contexts, we only one the first character as the range.
  821. rawAddEdge(cleanUpLocation(CLocs.back(), PDB.LC, true));
  822. }
  823. CLocs.pop_back();
  824. }
  825. public:
  826. EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
  827. : PD(pd), PDB(pdb) {
  828. // If the PathDiagnostic already has pieces, add the enclosing statement
  829. // of the first piece as a context as well.
  830. if (!PD.path.empty()) {
  831. PrevLoc = (*PD.path.begin())->getLocation();
  832. if (const Stmt *S = PrevLoc.asStmt())
  833. addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
  834. }
  835. }
  836. ~EdgeBuilder() {
  837. while (!CLocs.empty()) popLocation();
  838. // Finally, add an initial edge from the start location of the first
  839. // statement (if it doesn't already exist).
  840. PathDiagnosticLocation L = PathDiagnosticLocation::createDeclBegin(
  841. PDB.LC,
  842. PDB.getSourceManager());
  843. if (L.isValid())
  844. rawAddEdge(L);
  845. }
  846. void flushLocations() {
  847. while (!CLocs.empty())
  848. popLocation();
  849. PrevLoc = PathDiagnosticLocation();
  850. }
  851. void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false,
  852. bool IsPostJump = false);
  853. void rawAddEdge(PathDiagnosticLocation NewLoc);
  854. void addContext(const Stmt *S);
  855. void addContext(const PathDiagnosticLocation &L);
  856. void addExtendedContext(const Stmt *S);
  857. };
  858. } // end anonymous namespace
  859. PathDiagnosticLocation
  860. EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
  861. if (const Stmt *S = L.asStmt()) {
  862. if (IsControlFlowExpr(S))
  863. return L;
  864. return PDB.getEnclosingStmtLocation(S);
  865. }
  866. return L;
  867. }
  868. bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
  869. const PathDiagnosticLocation &Containee) {
  870. if (Container == Containee)
  871. return true;
  872. if (Container.asDecl())
  873. return true;
  874. if (const Stmt *S = Containee.asStmt())
  875. if (const Stmt *ContainerS = Container.asStmt()) {
  876. while (S) {
  877. if (S == ContainerS)
  878. return true;
  879. S = PDB.getParent(S);
  880. }
  881. return false;
  882. }
  883. // Less accurate: compare using source ranges.
  884. SourceRange ContainerR = Container.asRange();
  885. SourceRange ContaineeR = Containee.asRange();
  886. SourceManager &SM = PDB.getSourceManager();
  887. SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
  888. SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
  889. SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
  890. SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
  891. unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
  892. unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
  893. unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
  894. unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
  895. assert(ContainerBegLine <= ContainerEndLine);
  896. assert(ContaineeBegLine <= ContaineeEndLine);
  897. return (ContainerBegLine <= ContaineeBegLine &&
  898. ContainerEndLine >= ContaineeEndLine &&
  899. (ContainerBegLine != ContaineeBegLine ||
  900. SM.getExpansionColumnNumber(ContainerRBeg) <=
  901. SM.getExpansionColumnNumber(ContaineeRBeg)) &&
  902. (ContainerEndLine != ContaineeEndLine ||
  903. SM.getExpansionColumnNumber(ContainerREnd) >=
  904. SM.getExpansionColumnNumber(ContaineeREnd)));
  905. }
  906. void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
  907. if (!PrevLoc.isValid()) {
  908. PrevLoc = NewLoc;
  909. return;
  910. }
  911. const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc, PDB.LC);
  912. const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc, PDB.LC);
  913. if (PrevLocClean.asLocation().isInvalid()) {
  914. PrevLoc = NewLoc;
  915. return;
  916. }
  917. if (NewLocClean.asLocation() == PrevLocClean.asLocation())
  918. return;
  919. // FIXME: Ignore intra-macro edges for now.
  920. if (NewLocClean.asLocation().getExpansionLoc() ==
  921. PrevLocClean.asLocation().getExpansionLoc())
  922. return;
  923. PD.getActivePath().push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
  924. PrevLoc = NewLoc;
  925. }
  926. void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd,
  927. bool IsPostJump) {
  928. if (!alwaysAdd && NewLoc.asLocation().isMacroID())
  929. return;
  930. const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
  931. while (!CLocs.empty()) {
  932. ContextLocation &TopContextLoc = CLocs.back();
  933. // Is the top location context the same as the one for the new location?
  934. if (TopContextLoc == CLoc) {
  935. if (alwaysAdd) {
  936. if (IsConsumedExpr(TopContextLoc))
  937. TopContextLoc.markDead();
  938. rawAddEdge(NewLoc);
  939. }
  940. if (IsPostJump)
  941. TopContextLoc.markDead();
  942. return;
  943. }
  944. if (containsLocation(TopContextLoc, CLoc)) {
  945. if (alwaysAdd) {
  946. rawAddEdge(NewLoc);
  947. if (IsConsumedExpr(CLoc)) {
  948. CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/true));
  949. return;
  950. }
  951. }
  952. CLocs.push_back(ContextLocation(CLoc, /*IsDead=*/IsPostJump));
  953. return;
  954. }
  955. // Context does not contain the location. Flush it.
  956. popLocation();
  957. }
  958. // If we reach here, there is no enclosing context. Just add the edge.
  959. rawAddEdge(NewLoc);
  960. }
  961. bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
  962. if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
  963. return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
  964. return false;
  965. }
  966. void EdgeBuilder::addExtendedContext(const Stmt *S) {
  967. if (!S)
  968. return;
  969. const Stmt *Parent = PDB.getParent(S);
  970. while (Parent) {
  971. if (isa<CompoundStmt>(Parent))
  972. Parent = PDB.getParent(Parent);
  973. else
  974. break;
  975. }
  976. if (Parent) {
  977. switch (Parent->getStmtClass()) {
  978. case Stmt::DoStmtClass:
  979. case Stmt::ObjCAtSynchronizedStmtClass:
  980. addContext(Parent);
  981. default:
  982. break;
  983. }
  984. }
  985. addContext(S);
  986. }
  987. void EdgeBuilder::addContext(const Stmt *S) {
  988. if (!S)
  989. return;
  990. PathDiagnosticLocation L(S, PDB.getSourceManager(), PDB.LC);
  991. addContext(L);
  992. }
  993. void EdgeBuilder::addContext(const PathDiagnosticLocation &L) {
  994. while (!CLocs.empty()) {
  995. const PathDiagnosticLocation &TopContextLoc = CLocs.back();
  996. // Is the top location context the same as the one for the new location?
  997. if (TopContextLoc == L)
  998. return;
  999. if (containsLocation(TopContextLoc, L)) {
  1000. CLocs.push_back(L);
  1001. return;
  1002. }
  1003. // Context does not contain the location. Flush it.
  1004. popLocation();
  1005. }
  1006. CLocs.push_back(L);
  1007. }
  1008. // Cone-of-influence: support the reverse propagation of "interesting" symbols
  1009. // and values by tracing interesting calculations backwards through evaluated
  1010. // expressions along a path. This is probably overly complicated, but the idea
  1011. // is that if an expression computed an "interesting" value, the child
  1012. // expressions are are also likely to be "interesting" as well (which then
  1013. // propagates to the values they in turn compute). This reverse propagation
  1014. // is needed to track interesting correlations across function call boundaries,
  1015. // where formal arguments bind to actual arguments, etc. This is also needed
  1016. // because the constraint solver sometimes simplifies certain symbolic values
  1017. // into constants when appropriate, and this complicates reasoning about
  1018. // interesting values.
  1019. typedef llvm::DenseSet<const Expr *> InterestingExprs;
  1020. static void reversePropagateIntererstingSymbols(BugReport &R,
  1021. InterestingExprs &IE,
  1022. const ProgramState *State,
  1023. const Expr *Ex,
  1024. const LocationContext *LCtx) {
  1025. SVal V = State->getSVal(Ex, LCtx);
  1026. if (!(R.isInteresting(V) || IE.count(Ex)))
  1027. return;
  1028. switch (Ex->getStmtClass()) {
  1029. default:
  1030. if (!isa<CastExpr>(Ex))
  1031. break;
  1032. // Fall through.
  1033. case Stmt::BinaryOperatorClass:
  1034. case Stmt::UnaryOperatorClass: {
  1035. for (const Stmt *SubStmt : Ex->children()) {
  1036. if (const Expr *child = dyn_cast_or_null<Expr>(SubStmt)) {
  1037. IE.insert(child);
  1038. SVal ChildV = State->getSVal(child, LCtx);
  1039. R.markInteresting(ChildV);
  1040. }
  1041. }
  1042. break;
  1043. }
  1044. }
  1045. R.markInteresting(V);
  1046. }
  1047. static void reversePropagateInterestingSymbols(BugReport &R,
  1048. InterestingExprs &IE,
  1049. const ProgramState *State,
  1050. const LocationContext *CalleeCtx,
  1051. const LocationContext *CallerCtx)
  1052. {
  1053. // FIXME: Handle non-CallExpr-based CallEvents.
  1054. const StackFrameContext *Callee = CalleeCtx->getCurrentStackFrame();
  1055. const Stmt *CallSite = Callee->getCallSite();
  1056. if (const CallExpr *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
  1057. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
  1058. FunctionDecl::param_const_iterator PI = FD->param_begin(),
  1059. PE = FD->param_end();
  1060. CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
  1061. for (; AI != AE && PI != PE; ++AI, ++PI) {
  1062. if (const Expr *ArgE = *AI) {
  1063. if (const ParmVarDecl *PD = *PI) {
  1064. Loc LV = State->getLValue(PD, CalleeCtx);
  1065. if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
  1066. IE.insert(ArgE);
  1067. }
  1068. }
  1069. }
  1070. }
  1071. }
  1072. }
  1073. //===----------------------------------------------------------------------===//
  1074. // Functions for determining if a loop was executed 0 times.
  1075. //===----------------------------------------------------------------------===//
  1076. static bool isLoop(const Stmt *Term) {
  1077. switch (Term->getStmtClass()) {
  1078. case Stmt::ForStmtClass:
  1079. case Stmt::WhileStmtClass:
  1080. case Stmt::ObjCForCollectionStmtClass:
  1081. case Stmt::CXXForRangeStmtClass:
  1082. return true;
  1083. default:
  1084. // Note that we intentionally do not include do..while here.
  1085. return false;
  1086. }
  1087. }
  1088. static bool isJumpToFalseBranch(const BlockEdge *BE) {
  1089. const CFGBlock *Src = BE->getSrc();
  1090. assert(Src->succ_size() == 2);
  1091. return (*(Src->succ_begin()+1) == BE->getDst());
  1092. }
  1093. /// Return true if the terminator is a loop and the destination is the
  1094. /// false branch.
  1095. static bool isLoopJumpPastBody(const Stmt *Term, const BlockEdge *BE) {
  1096. if (!isLoop(Term))
  1097. return false;
  1098. // Did we take the false branch?
  1099. return isJumpToFalseBranch(BE);
  1100. }
  1101. static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) {
  1102. while (SubS) {
  1103. if (SubS == S)
  1104. return true;
  1105. SubS = PM.getParent(SubS);
  1106. }
  1107. return false;
  1108. }
  1109. static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term,
  1110. const ExplodedNode *N) {
  1111. while (N) {
  1112. Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
  1113. if (SP) {
  1114. const Stmt *S = SP->getStmt();
  1115. if (!isContainedByStmt(PM, Term, S))
  1116. return S;
  1117. }
  1118. N = N->getFirstPred();
  1119. }
  1120. return nullptr;
  1121. }
  1122. static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) {
  1123. const Stmt *LoopBody = nullptr;
  1124. switch (Term->getStmtClass()) {
  1125. case Stmt::CXXForRangeStmtClass: {
  1126. const CXXForRangeStmt *FR = cast<CXXForRangeStmt>(Term);
  1127. if (isContainedByStmt(PM, FR->getInc(), S))
  1128. return true;
  1129. if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
  1130. return true;
  1131. LoopBody = FR->getBody();
  1132. break;
  1133. }
  1134. case Stmt::ForStmtClass: {
  1135. const ForStmt *FS = cast<ForStmt>(Term);
  1136. if (isContainedByStmt(PM, FS->getInc(), S))
  1137. return true;
  1138. LoopBody = FS->getBody();
  1139. break;
  1140. }
  1141. case Stmt::ObjCForCollectionStmtClass: {
  1142. const ObjCForCollectionStmt *FC = cast<ObjCForCollectionStmt>(Term);
  1143. LoopBody = FC->getBody();
  1144. break;
  1145. }
  1146. case Stmt::WhileStmtClass:
  1147. LoopBody = cast<WhileStmt>(Term)->getBody();
  1148. break;
  1149. default:
  1150. return false;
  1151. }
  1152. return isContainedByStmt(PM, LoopBody, S);
  1153. }
  1154. //===----------------------------------------------------------------------===//
  1155. // Top-level logic for generating extensive path diagnostics.
  1156. //===----------------------------------------------------------------------===//
  1157. static bool GenerateExtensivePathDiagnostic(
  1158. PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
  1159. LocationContextMap &LCM,
  1160. ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
  1161. EdgeBuilder EB(PD, PDB);
  1162. const SourceManager& SM = PDB.getSourceManager();
  1163. StackDiagVector CallStack;
  1164. InterestingExprs IE;
  1165. const ExplodedNode *NextNode = N->pred_empty() ? nullptr : *(N->pred_begin());
  1166. while (NextNode) {
  1167. N = NextNode;
  1168. NextNode = N->getFirstPred();
  1169. ProgramPoint P = N->getLocation();
  1170. do {
  1171. if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
  1172. if (const Expr *Ex = PS->getStmtAs<Expr>())
  1173. reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
  1174. N->getState().get(), Ex,
  1175. N->getLocationContext());
  1176. }
  1177. if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
  1178. const Stmt *S = CE->getCalleeContext()->getCallSite();
  1179. if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
  1180. reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
  1181. N->getState().get(), Ex,
  1182. N->getLocationContext());
  1183. }
  1184. PathDiagnosticCallPiece *C =
  1185. PathDiagnosticCallPiece::construct(N, *CE, SM);
  1186. LCM[&C->path] = CE->getCalleeContext();
  1187. EB.addEdge(C->callReturn, /*AlwaysAdd=*/true, /*IsPostJump=*/true);
  1188. EB.flushLocations();
  1189. PD.getActivePath().push_front(C);
  1190. PD.pushActivePath(&C->path);
  1191. CallStack.push_back(StackDiagPair(C, N));
  1192. break;
  1193. }
  1194. // Pop the call hierarchy if we are done walking the contents
  1195. // of a function call.
  1196. if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
  1197. // Add an edge to the start of the function.
  1198. const Decl *D = CE->getCalleeContext()->getDecl();
  1199. PathDiagnosticLocation pos =
  1200. PathDiagnosticLocation::createBegin(D, SM);
  1201. EB.addEdge(pos);
  1202. // Flush all locations, and pop the active path.
  1203. bool VisitedEntireCall = PD.isWithinCall();
  1204. EB.flushLocations();
  1205. PD.popActivePath();
  1206. PDB.LC = N->getLocationContext();
  1207. // Either we just added a bunch of stuff to the top-level path, or
  1208. // we have a previous CallExitEnd. If the former, it means that the
  1209. // path terminated within a function call. We must then take the
  1210. // current contents of the active path and place it within
  1211. // a new PathDiagnosticCallPiece.
  1212. PathDiagnosticCallPiece *C;
  1213. if (VisitedEntireCall) {
  1214. C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front());
  1215. } else {
  1216. const Decl *Caller = CE->getLocationContext()->getDecl();
  1217. C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
  1218. LCM[&C->path] = CE->getCalleeContext();
  1219. }
  1220. C->setCallee(*CE, SM);
  1221. EB.addContext(C->getLocation());
  1222. if (!CallStack.empty()) {
  1223. assert(CallStack.back().first == C);
  1224. CallStack.pop_back();
  1225. }
  1226. break;
  1227. }
  1228. // Note that is important that we update the LocationContext
  1229. // after looking at CallExits. CallExit basically adds an
  1230. // edge in the *caller*, so we don't want to update the LocationContext
  1231. // too soon.
  1232. PDB.LC = N->getLocationContext();
  1233. // Block edges.
  1234. if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
  1235. // Does this represent entering a call? If so, look at propagating
  1236. // interesting symbols across call boundaries.
  1237. if (NextNode) {
  1238. const LocationContext *CallerCtx = NextNode->getLocationContext();
  1239. const LocationContext *CalleeCtx = PDB.LC;
  1240. if (CallerCtx != CalleeCtx) {
  1241. reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
  1242. N->getState().get(),
  1243. CalleeCtx, CallerCtx);
  1244. }
  1245. }
  1246. // Are we jumping to the head of a loop? Add a special diagnostic.
  1247. if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
  1248. PathDiagnosticLocation L(Loop, SM, PDB.LC);
  1249. const CompoundStmt *CS = nullptr;
  1250. if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
  1251. CS = dyn_cast<CompoundStmt>(FS->getBody());
  1252. else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
  1253. CS = dyn_cast<CompoundStmt>(WS->getBody());
  1254. PathDiagnosticEventPiece *p =
  1255. new PathDiagnosticEventPiece(L,
  1256. "Looping back to the head of the loop");
  1257. p->setPrunable(true);
  1258. EB.addEdge(p->getLocation(), true);
  1259. PD.getActivePath().push_front(p);
  1260. if (CS) {
  1261. PathDiagnosticLocation BL =
  1262. PathDiagnosticLocation::createEndBrace(CS, SM);
  1263. EB.addEdge(BL);
  1264. }
  1265. }
  1266. const CFGBlock *BSrc = BE->getSrc();
  1267. ParentMap &PM = PDB.getParentMap();
  1268. if (const Stmt *Term = BSrc->getTerminator()) {
  1269. // Are we jumping past the loop body without ever executing the
  1270. // loop (because the condition was false)?
  1271. if (isLoopJumpPastBody(Term, &*BE) &&
  1272. !isInLoopBody(PM,
  1273. getStmtBeforeCond(PM,
  1274. BSrc->getTerminatorCondition(),
  1275. N),
  1276. Term)) {
  1277. PathDiagnosticLocation L(Term, SM, PDB.LC);
  1278. PathDiagnosticEventPiece *PE =
  1279. new PathDiagnosticEventPiece(L, "Loop body executed 0 times");
  1280. PE->setPrunable(true);
  1281. EB.addEdge(PE->getLocation(), true);
  1282. PD.getActivePath().push_front(PE);
  1283. }
  1284. // In any case, add the terminator as the current statement
  1285. // context for control edges.
  1286. EB.addContext(Term);
  1287. }
  1288. break;
  1289. }
  1290. if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
  1291. Optional<CFGElement> First = BE->getFirstElement();
  1292. if (Optional<CFGStmt> S = First ? First->getAs<CFGStmt>() : None) {
  1293. const Stmt *stmt = S->getStmt();
  1294. if (IsControlFlowExpr(stmt)) {
  1295. // Add the proper context for '&&', '||', and '?'.
  1296. EB.addContext(stmt);
  1297. }
  1298. else
  1299. EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
  1300. }
  1301. break;
  1302. }
  1303. } while (0);
  1304. if (!NextNode)
  1305. continue;
  1306. // Add pieces from custom visitors.
  1307. BugReport *R = PDB.getBugReport();
  1308. for (auto &V : visitors) {
  1309. if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *R)) {
  1310. const PathDiagnosticLocation &Loc = p->getLocation();
  1311. EB.addEdge(Loc, true);
  1312. PD.getActivePath().push_front(p);
  1313. updateStackPiecesWithMessage(p, CallStack);
  1314. if (const Stmt *S = Loc.asStmt())
  1315. EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
  1316. }
  1317. }
  1318. }
  1319. return PDB.getBugReport()->isValid();
  1320. }
  1321. /// \brief Adds a sanitized control-flow diagnostic edge to a path.
  1322. static void addEdgeToPath(PathPieces &path,
  1323. PathDiagnosticLocation &PrevLoc,
  1324. PathDiagnosticLocation NewLoc,
  1325. const LocationContext *LC) {
  1326. if (!NewLoc.isValid())
  1327. return;
  1328. SourceLocation NewLocL = NewLoc.asLocation();
  1329. if (NewLocL.isInvalid())
  1330. return;
  1331. if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) {
  1332. PrevLoc = NewLoc;
  1333. return;
  1334. }
  1335. // Ignore self-edges, which occur when there are multiple nodes at the same
  1336. // statement.
  1337. if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt())
  1338. return;
  1339. path.push_front(new PathDiagnosticControlFlowPiece(NewLoc,
  1340. PrevLoc));
  1341. PrevLoc = NewLoc;
  1342. }
  1343. /// A customized wrapper for CFGBlock::getTerminatorCondition()
  1344. /// which returns the element for ObjCForCollectionStmts.
  1345. static const Stmt *getTerminatorCondition(const CFGBlock *B) {
  1346. const Stmt *S = B->getTerminatorCondition();
  1347. if (const ObjCForCollectionStmt *FS =
  1348. dyn_cast_or_null<ObjCForCollectionStmt>(S))
  1349. return FS->getElement();
  1350. return S;
  1351. }
  1352. static const char StrEnteringLoop[] = "Entering loop body";
  1353. static const char StrLoopBodyZero[] = "Loop body executed 0 times";
  1354. static const char StrLoopRangeEmpty[] =
  1355. "Loop body skipped when range is empty";
  1356. static const char StrLoopCollectionEmpty[] =
  1357. "Loop body skipped when collection is empty";
  1358. static bool GenerateAlternateExtensivePathDiagnostic(
  1359. PathDiagnostic &PD, PathDiagnosticBuilder &PDB, const ExplodedNode *N,
  1360. LocationContextMap &LCM,
  1361. ArrayRef<std::unique_ptr<BugReporterVisitor>> visitors) {
  1362. BugReport *report = PDB.getBugReport();
  1363. const SourceManager& SM = PDB.getSourceManager();
  1364. StackDiagVector CallStack;
  1365. InterestingExprs IE;
  1366. PathDiagnosticLocation PrevLoc = PD.getLocation();
  1367. const ExplodedNode *NextNode = N->getFirstPred();
  1368. while (NextNode) {
  1369. N = NextNode;
  1370. NextNode = N->getFirstPred();
  1371. ProgramPoint P = N->getLocation();
  1372. do {
  1373. // Have we encountered an entrance to a call? It may be
  1374. // the case that we have not encountered a matching
  1375. // call exit before this point. This means that the path
  1376. // terminated within the call itself.
  1377. if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
  1378. // Add an edge to the start of the function.
  1379. const StackFrameContext *CalleeLC = CE->getCalleeContext();
  1380. const Decl *D = CalleeLC->getDecl();
  1381. addEdgeToPath(PD.getActivePath(), PrevLoc,
  1382. PathDiagnosticLocation::createBegin(D, SM),
  1383. CalleeLC);
  1384. // Did we visit an entire call?
  1385. bool VisitedEntireCall = PD.isWithinCall();
  1386. PD.popActivePath();
  1387. PathDiagnosticCallPiece *C;
  1388. if (VisitedEntireCall) {
  1389. PathDiagnosticPiece *P = PD.getActivePath().front().get();
  1390. C = cast<PathDiagnosticCallPiece>(P);
  1391. } else {
  1392. const Decl *Caller = CE->getLocationContext()->getDecl();
  1393. C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
  1394. // Since we just transferred the path over to the call piece,
  1395. // reset the mapping from active to location context.
  1396. assert(PD.getActivePath().size() == 1 &&
  1397. PD.getActivePath().front() == C);
  1398. LCM[&PD.getActivePath()] = nullptr;
  1399. // Record the location context mapping for the path within
  1400. // the call.
  1401. assert(LCM[&C->path] == nullptr ||
  1402. LCM[&C->path] == CE->getCalleeContext());
  1403. LCM[&C->path] = CE->getCalleeContext();
  1404. // If this is the first item in the active path, record
  1405. // the new mapping from active path to location context.
  1406. const LocationContext *&NewLC = LCM[&PD.getActivePath()];
  1407. if (!NewLC)
  1408. NewLC = N->getLocationContext();
  1409. PDB.LC = NewLC;
  1410. }
  1411. C->setCallee(*CE, SM);
  1412. // Update the previous location in the active path.
  1413. PrevLoc = C->getLocation();
  1414. if (!CallStack.empty()) {
  1415. assert(CallStack.back().first == C);
  1416. CallStack.pop_back();
  1417. }
  1418. break;
  1419. }
  1420. // Query the location context here and the previous location
  1421. // as processing CallEnter may change the active path.
  1422. PDB.LC = N->getLocationContext();
  1423. // Record the mapping from the active path to the location
  1424. // context.
  1425. assert(!LCM[&PD.getActivePath()] ||
  1426. LCM[&PD.getActivePath()] == PDB.LC);
  1427. LCM[&PD.getActivePath()] = PDB.LC;
  1428. // Have we encountered an exit from a function call?
  1429. if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
  1430. const Stmt *S = CE->getCalleeContext()->getCallSite();
  1431. // Propagate the interesting symbols accordingly.
  1432. if (const Expr *Ex = dyn_cast_or_null<Expr>(S)) {
  1433. reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
  1434. N->getState().get(), Ex,
  1435. N->getLocationContext());
  1436. }
  1437. // We are descending into a call (backwards). Construct
  1438. // a new call piece to contain the path pieces for that call.
  1439. PathDiagnosticCallPiece *C =
  1440. PathDiagnosticCallPiece::construct(N, *CE, SM);
  1441. // Record the location context for this call piece.
  1442. LCM[&C->path] = CE->getCalleeContext();
  1443. // Add the edge to the return site.
  1444. addEdgeToPath(PD.getActivePath(), PrevLoc, C->callReturn, PDB.LC);
  1445. PD.getActivePath().push_front(C);
  1446. PrevLoc.invalidate();
  1447. // Make the contents of the call the active path for now.
  1448. PD.pushActivePath(&C->path);
  1449. CallStack.push_back(StackDiagPair(C, N));
  1450. break;
  1451. }
  1452. if (Optional<PostStmt> PS = P.getAs<PostStmt>()) {
  1453. // For expressions, make sure we propagate the
  1454. // interesting symbols correctly.
  1455. if (const Expr *Ex = PS->getStmtAs<Expr>())
  1456. reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
  1457. N->getState().get(), Ex,
  1458. N->getLocationContext());
  1459. // Add an edge. If this is an ObjCForCollectionStmt do
  1460. // not add an edge here as it appears in the CFG both
  1461. // as a terminator and as a terminator condition.
  1462. if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
  1463. PathDiagnosticLocation L =
  1464. PathDiagnosticLocation(PS->getStmt(), SM, PDB.LC);
  1465. addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC);
  1466. }
  1467. break;
  1468. }
  1469. // Block edges.
  1470. if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
  1471. // Does this represent entering a call? If so, look at propagating
  1472. // interesting symbols across call boundaries.
  1473. if (NextNode) {
  1474. const LocationContext *CallerCtx = NextNode->getLocationContext();
  1475. const LocationContext *CalleeCtx = PDB.LC;
  1476. if (CallerCtx != CalleeCtx) {
  1477. reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
  1478. N->getState().get(),
  1479. CalleeCtx, CallerCtx);
  1480. }
  1481. }
  1482. // Are we jumping to the head of a loop? Add a special diagnostic.
  1483. if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
  1484. PathDiagnosticLocation L(Loop, SM, PDB.LC);
  1485. const Stmt *Body = nullptr;
  1486. if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
  1487. Body = FS->getBody();
  1488. else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
  1489. Body = WS->getBody();
  1490. else if (const ObjCForCollectionStmt *OFS =
  1491. dyn_cast<ObjCForCollectionStmt>(Loop)) {
  1492. Body = OFS->getBody();
  1493. } else if (const CXXForRangeStmt *FRS =
  1494. dyn_cast<CXXForRangeStmt>(Loop)) {
  1495. Body = FRS->getBody();
  1496. }
  1497. // do-while statements are explicitly excluded here
  1498. PathDiagnosticEventPiece *p =
  1499. new PathDiagnosticEventPiece(L, "Looping back to the head "
  1500. "of the loop");
  1501. p->setPrunable(true);
  1502. addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC);
  1503. PD.getActivePath().push_front(p);
  1504. if (const CompoundStmt *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  1505. addEdgeToPath(PD.getActivePath(), PrevLoc,
  1506. PathDiagnosticLocation::createEndBrace(CS, SM),
  1507. PDB.LC);
  1508. }
  1509. }
  1510. const CFGBlock *BSrc = BE->getSrc();
  1511. ParentMap &PM = PDB.getParentMap();
  1512. if (const Stmt *Term = BSrc->getTerminator()) {
  1513. // Are we jumping past the loop body without ever executing the
  1514. // loop (because the condition was false)?
  1515. if (isLoop(Term)) {
  1516. const Stmt *TermCond = getTerminatorCondition(BSrc);
  1517. bool IsInLoopBody =
  1518. isInLoopBody(PM, getStmtBeforeCond(PM, TermCond, N), Term);
  1519. const char *str = nullptr;
  1520. if (isJumpToFalseBranch(&*BE)) {
  1521. if (!IsInLoopBody) {
  1522. if (isa<ObjCForCollectionStmt>(Term)) {
  1523. str = StrLoopCollectionEmpty;
  1524. } else if (isa<CXXForRangeStmt>(Term)) {
  1525. str = StrLoopRangeEmpty;
  1526. } else {
  1527. str = StrLoopBodyZero;
  1528. }
  1529. }
  1530. } else {
  1531. str = StrEnteringLoop;
  1532. }
  1533. if (str) {
  1534. PathDiagnosticLocation L(TermCond ? TermCond : Term, SM, PDB.LC);
  1535. PathDiagnosticEventPiece *PE =
  1536. new PathDiagnosticEventPiece(L, str);
  1537. PE->setPrunable(true);
  1538. addEdgeToPath(PD.getActivePath(), PrevLoc,
  1539. PE->getLocation(), PDB.LC);
  1540. PD.getActivePath().push_front(PE);
  1541. }
  1542. } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
  1543. isa<GotoStmt>(Term)) {
  1544. PathDiagnosticLocation L(Term, SM, PDB.LC);
  1545. addEdgeToPath(PD.getActivePath(), PrevLoc, L, PDB.LC);
  1546. }
  1547. }
  1548. break;
  1549. }
  1550. } while (0);
  1551. if (!NextNode)
  1552. continue;
  1553. // Add pieces from custom visitors.
  1554. for (auto &V : visitors) {
  1555. if (PathDiagnosticPiece *p = V->VisitNode(N, NextNode, PDB, *report)) {
  1556. addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation(), PDB.LC);
  1557. PD.getActivePath().push_front(p);
  1558. updateStackPiecesWithMessage(p, CallStack);
  1559. }
  1560. }
  1561. }
  1562. // Add an edge to the start of the function.
  1563. // We'll prune it out later, but it helps make diagnostics more uniform.
  1564. const StackFrameContext *CalleeLC = PDB.LC->getCurrentStackFrame();
  1565. const Decl *D = CalleeLC->getDecl();
  1566. addEdgeToPath(PD.getActivePath(), PrevLoc,
  1567. PathDiagnosticLocation::createBegin(D, SM),
  1568. CalleeLC);
  1569. return report->isValid();
  1570. }
  1571. static const Stmt *getLocStmt(PathDiagnosticLocation L) {
  1572. if (!L.isValid())
  1573. return nullptr;
  1574. return L.asStmt();
  1575. }
  1576. static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
  1577. if (!S)
  1578. return nullptr;
  1579. while (true) {
  1580. S = PM.getParentIgnoreParens(S);
  1581. if (!S)
  1582. break;
  1583. if (isa<ExprWithCleanups>(S) ||
  1584. isa<CXXBindTemporaryExpr>(S) ||
  1585. isa<SubstNonTypeTemplateParmExpr>(S))
  1586. continue;
  1587. break;
  1588. }
  1589. return S;
  1590. }
  1591. static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
  1592. switch (S->getStmtClass()) {
  1593. case Stmt::BinaryOperatorClass: {
  1594. const BinaryOperator *BO = cast<BinaryOperator>(S);
  1595. if (!BO->isLogicalOp())
  1596. return false;
  1597. return BO->getLHS() == Cond || BO->getRHS() == Cond;
  1598. }
  1599. case Stmt::IfStmtClass:
  1600. return cast<IfStmt>(S)->getCond() == Cond;
  1601. case Stmt::ForStmtClass:
  1602. return cast<ForStmt>(S)->getCond() == Cond;
  1603. case Stmt::WhileStmtClass:
  1604. return cast<WhileStmt>(S)->getCond() == Cond;
  1605. case Stmt::DoStmtClass:
  1606. return cast<DoStmt>(S)->getCond() == Cond;
  1607. case Stmt::ChooseExprClass:
  1608. return cast<ChooseExpr>(S)->getCond() == Cond;
  1609. case Stmt::IndirectGotoStmtClass:
  1610. return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
  1611. case Stmt::SwitchStmtClass:
  1612. return cast<SwitchStmt>(S)->getCond() == Cond;
  1613. case Stmt::BinaryConditionalOperatorClass:
  1614. return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
  1615. case Stmt::ConditionalOperatorClass: {
  1616. const ConditionalOperator *CO = cast<ConditionalOperator>(S);
  1617. return CO->getCond() == Cond ||
  1618. CO->getLHS() == Cond ||
  1619. CO->getRHS() == Cond;
  1620. }
  1621. case Stmt::ObjCForCollectionStmtClass:
  1622. return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
  1623. case Stmt::CXXForRangeStmtClass: {
  1624. const CXXForRangeStmt *FRS = cast<CXXForRangeStmt>(S);
  1625. return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
  1626. }
  1627. default:
  1628. return false;
  1629. }
  1630. }
  1631. static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
  1632. if (const ForStmt *FS = dyn_cast<ForStmt>(FL))
  1633. return FS->getInc() == S || FS->getInit() == S;
  1634. if (const CXXForRangeStmt *FRS = dyn_cast<CXXForRangeStmt>(FL))
  1635. return FRS->getInc() == S || FRS->getRangeStmt() == S ||
  1636. FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
  1637. return false;
  1638. }
  1639. typedef llvm::DenseSet<const PathDiagnosticCallPiece *>
  1640. OptimizedCallsSet;
  1641. /// Adds synthetic edges from top-level statements to their subexpressions.
  1642. ///
  1643. /// This avoids a "swoosh" effect, where an edge from a top-level statement A
  1644. /// points to a sub-expression B.1 that's not at the start of B. In these cases,
  1645. /// we'd like to see an edge from A to B, then another one from B to B.1.
  1646. static void addContextEdges(PathPieces &pieces, SourceManager &SM,
  1647. const ParentMap &PM, const LocationContext *LCtx) {
  1648. PathPieces::iterator Prev = pieces.end();
  1649. for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
  1650. Prev = I, ++I) {
  1651. PathDiagnosticControlFlowPiece *Piece =
  1652. dyn_cast<PathDiagnosticControlFlowPiece>(*I);
  1653. if (!Piece)
  1654. continue;
  1655. PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
  1656. SmallVector<PathDiagnosticLocation, 4> SrcContexts;
  1657. PathDiagnosticLocation NextSrcContext = SrcLoc;
  1658. const Stmt *InnerStmt = nullptr;
  1659. while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
  1660. SrcContexts.push_back(NextSrcContext);
  1661. InnerStmt = NextSrcContext.asStmt();
  1662. NextSrcContext = getEnclosingStmtLocation(InnerStmt, SM, PM, LCtx,
  1663. /*allowNested=*/true);
  1664. }
  1665. // Repeatedly split the edge as necessary.
  1666. // This is important for nested logical expressions (||, &&, ?:) where we
  1667. // want to show all the levels of context.
  1668. while (true) {
  1669. const Stmt *Dst = getLocStmt(Piece->getEndLocation());
  1670. // We are looking at an edge. Is the destination within a larger
  1671. // expression?
  1672. PathDiagnosticLocation DstContext =
  1673. getEnclosingStmtLocation(Dst, SM, PM, LCtx, /*allowNested=*/true);
  1674. if (!DstContext.isValid() || DstContext.asStmt() == Dst)
  1675. break;
  1676. // If the source is in the same context, we're already good.
  1677. if (std::find(SrcContexts.begin(), SrcContexts.end(), DstContext) !=
  1678. SrcContexts.end())
  1679. break;
  1680. // Update the subexpression node to point to the context edge.
  1681. Piece->setStartLocation(DstContext);
  1682. // Try to extend the previous edge if it's at the same level as the source
  1683. // context.
  1684. if (Prev != E) {
  1685. PathDiagnosticControlFlowPiece *PrevPiece =
  1686. dyn_cast<PathDiagnosticControlFlowPiece>(*Prev);
  1687. if (PrevPiece) {
  1688. if (const Stmt *PrevSrc = getLocStmt(PrevPiece->getStartLocation())) {
  1689. const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
  1690. if (PrevSrcParent == getStmtParent(getLocStmt(DstContext), PM)) {
  1691. PrevPiece->setEndLocation(DstContext);
  1692. break;
  1693. }
  1694. }
  1695. }
  1696. }
  1697. // Otherwise, split the current edge into a context edge and a
  1698. // subexpression edge. Note that the context statement may itself have
  1699. // context.
  1700. Piece = new PathDiagnosticControlFlowPiece(SrcLoc, DstContext);
  1701. I = pieces.insert(I, Piece);
  1702. }
  1703. }
  1704. }
  1705. /// \brief Move edges from a branch condition to a branch target
  1706. /// when the condition is simple.
  1707. ///
  1708. /// This restructures some of the work of addContextEdges. That function
  1709. /// creates edges this may destroy, but they work together to create a more
  1710. /// aesthetically set of edges around branches. After the call to
  1711. /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
  1712. /// the branch to the branch condition, and (3) an edge from the branch
  1713. /// condition to the branch target. We keep (1), but may wish to remove (2)
  1714. /// and move the source of (3) to the branch if the branch condition is simple.
  1715. ///
  1716. static void simplifySimpleBranches(PathPieces &pieces) {
  1717. for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
  1718. PathDiagnosticControlFlowPiece *PieceI =
  1719. dyn_cast<PathDiagnosticControlFlowPiece>(*I);
  1720. if (!PieceI)
  1721. continue;
  1722. const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
  1723. const Stmt *s1End = getLocStmt(PieceI->getEndLocation());
  1724. if (!s1Start || !s1End)
  1725. continue;
  1726. PathPieces::iterator NextI = I; ++NextI;
  1727. if (NextI == E)
  1728. break;
  1729. PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
  1730. while (true) {
  1731. if (NextI == E)
  1732. break;
  1733. PathDiagnosticEventPiece *EV = dyn_cast<PathDiagnosticEventPiece>(*NextI);
  1734. if (EV) {
  1735. StringRef S = EV->getString();
  1736. if (S == StrEnteringLoop || S == StrLoopBodyZero ||
  1737. S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
  1738. ++NextI;
  1739. continue;
  1740. }
  1741. break;
  1742. }
  1743. PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
  1744. break;
  1745. }
  1746. if (!PieceNextI)
  1747. continue;
  1748. const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
  1749. const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation());
  1750. if (!s2Start || !s2End || s1End != s2Start)
  1751. continue;
  1752. // We only perform this transformation for specific branch kinds.
  1753. // We don't want to do this for do..while, for example.
  1754. if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) ||
  1755. isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) ||
  1756. isa<CXXForRangeStmt>(s1Start)))
  1757. continue;
  1758. // Is s1End the branch condition?
  1759. if (!isConditionForTerminator(s1Start, s1End))
  1760. continue;
  1761. // Perform the hoisting by eliminating (2) and changing the start
  1762. // location of (3).
  1763. PieceNextI->setStartLocation(PieceI->getStartLocation());
  1764. I = pieces.erase(I);
  1765. }
  1766. }
  1767. /// Returns the number of bytes in the given (character-based) SourceRange.
  1768. ///
  1769. /// If the locations in the range are not on the same line, returns None.
  1770. ///
  1771. /// Note that this does not do a precise user-visible character or column count.
  1772. static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
  1773. SourceRange Range) {
  1774. SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
  1775. SM.getExpansionRange(Range.getEnd()).second);
  1776. FileID FID = SM.getFileID(ExpansionRange.getBegin());
  1777. if (FID != SM.getFileID(ExpansionRange.getEnd()))
  1778. return None;
  1779. bool Invalid;
  1780. const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid);
  1781. if (Invalid)
  1782. return None;
  1783. unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
  1784. unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
  1785. StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
  1786. // We're searching the raw bytes of the buffer here, which might include
  1787. // escaped newlines and such. That's okay; we're trying to decide whether the
  1788. // SourceRange is covering a large or small amount of space in the user's
  1789. // editor.
  1790. if (Snippet.find_first_of("\r\n") != StringRef::npos)
  1791. return None;
  1792. // This isn't Unicode-aware, but it doesn't need to be.
  1793. return Snippet.size();
  1794. }
  1795. /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
  1796. static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
  1797. const Stmt *S) {
  1798. return getLengthOnSingleLine(SM, S->getSourceRange());
  1799. }
  1800. /// Eliminate two-edge cycles created by addContextEdges().
  1801. ///
  1802. /// Once all the context edges are in place, there are plenty of cases where
  1803. /// there's a single edge from a top-level statement to a subexpression,
  1804. /// followed by a single path note, and then a reverse edge to get back out to
  1805. /// the top level. If the statement is simple enough, the subexpression edges
  1806. /// just add noise and make it harder to understand what's going on.
  1807. ///
  1808. /// This function only removes edges in pairs, because removing only one edge
  1809. /// might leave other edges dangling.
  1810. ///
  1811. /// This will not remove edges in more complicated situations:
  1812. /// - if there is more than one "hop" leading to or from a subexpression.
  1813. /// - if there is an inlined call between the edges instead of a single event.
  1814. /// - if the whole statement is large enough that having subexpression arrows
  1815. /// might be helpful.
  1816. static void removeContextCycles(PathPieces &Path, SourceManager &SM,
  1817. ParentMap &PM) {
  1818. for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
  1819. // Pattern match the current piece and its successor.
  1820. PathDiagnosticControlFlowPiece *PieceI =
  1821. dyn_cast<PathDiagnosticControlFlowPiece>(*I);
  1822. if (!PieceI) {
  1823. ++I;
  1824. continue;
  1825. }
  1826. const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
  1827. const Stmt *s1End = getLocStmt(PieceI->getEndLocation());
  1828. PathPieces::iterator NextI = I; ++NextI;
  1829. if (NextI == E)
  1830. break;
  1831. PathDiagnosticControlFlowPiece *PieceNextI =
  1832. dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
  1833. if (!PieceNextI) {
  1834. if (isa<PathDiagnosticEventPiece>(*NextI)) {
  1835. ++NextI;
  1836. if (NextI == E)
  1837. break;
  1838. PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
  1839. }
  1840. if (!PieceNextI) {
  1841. ++I;
  1842. continue;
  1843. }
  1844. }
  1845. const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
  1846. const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation());
  1847. if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
  1848. const size_t MAX_SHORT_LINE_LENGTH = 80;
  1849. Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
  1850. if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
  1851. Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
  1852. if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
  1853. Path.erase(I);
  1854. I = Path.erase(NextI);
  1855. continue;
  1856. }
  1857. }
  1858. }
  1859. ++I;
  1860. }
  1861. }
  1862. /// \brief Return true if X is contained by Y.
  1863. static bool lexicalContains(ParentMap &PM,
  1864. const Stmt *X,
  1865. const Stmt *Y) {
  1866. while (X) {
  1867. if (X == Y)
  1868. return true;
  1869. X = PM.getParent(X);
  1870. }
  1871. return false;
  1872. }
  1873. // Remove short edges on the same line less than 3 columns in difference.
  1874. static void removePunyEdges(PathPieces &path,
  1875. SourceManager &SM,
  1876. ParentMap &PM) {
  1877. bool erased = false;
  1878. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
  1879. erased ? I : ++I) {
  1880. erased = false;
  1881. PathDiagnosticControlFlowPiece *PieceI =
  1882. dyn_cast<PathDiagnosticControlFlowPiece>(*I);
  1883. if (!PieceI)
  1884. continue;
  1885. const Stmt *start = getLocStmt(PieceI->getStartLocation());
  1886. const Stmt *end = getLocStmt(PieceI->getEndLocation());
  1887. if (!start || !end)
  1888. continue;
  1889. const Stmt *endParent = PM.getParent(end);
  1890. if (!endParent)
  1891. continue;
  1892. if (isConditionForTerminator(end, endParent))
  1893. continue;
  1894. SourceLocation FirstLoc = start->getLocStart();
  1895. SourceLocation SecondLoc = end->getLocStart();
  1896. if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
  1897. continue;
  1898. if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
  1899. std::swap(SecondLoc, FirstLoc);
  1900. SourceRange EdgeRange(FirstLoc, SecondLoc);
  1901. Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
  1902. // If the statements are on different lines, continue.
  1903. if (!ByteWidth)
  1904. continue;
  1905. const size_t MAX_PUNY_EDGE_LENGTH = 2;
  1906. if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
  1907. // FIXME: There are enough /bytes/ between the endpoints of the edge, but
  1908. // there might not be enough /columns/. A proper user-visible column count
  1909. // is probably too expensive, though.
  1910. I = path.erase(I);
  1911. erased = true;
  1912. continue;
  1913. }
  1914. }
  1915. }
  1916. static void removeIdenticalEvents(PathPieces &path) {
  1917. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
  1918. PathDiagnosticEventPiece *PieceI =
  1919. dyn_cast<PathDiagnosticEventPiece>(*I);
  1920. if (!PieceI)
  1921. continue;
  1922. PathPieces::iterator NextI = I; ++NextI;
  1923. if (NextI == E)
  1924. return;
  1925. PathDiagnosticEventPiece *PieceNextI =
  1926. dyn_cast<PathDiagnosticEventPiece>(*NextI);
  1927. if (!PieceNextI)
  1928. continue;
  1929. // Erase the second piece if it has the same exact message text.
  1930. if (PieceI->getString() == PieceNextI->getString()) {
  1931. path.erase(NextI);
  1932. }
  1933. }
  1934. }
  1935. static bool optimizeEdges(PathPieces &path, SourceManager &SM,
  1936. OptimizedCallsSet &OCS,
  1937. LocationContextMap &LCM) {
  1938. bool hasChanges = false;
  1939. const LocationContext *LC = LCM[&path];
  1940. assert(LC);
  1941. ParentMap &PM = LC->getParentMap();
  1942. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
  1943. // Optimize subpaths.
  1944. if (PathDiagnosticCallPiece *CallI = dyn_cast<PathDiagnosticCallPiece>(*I)){
  1945. // Record the fact that a call has been optimized so we only do the
  1946. // effort once.
  1947. if (!OCS.count(CallI)) {
  1948. while (optimizeEdges(CallI->path, SM, OCS, LCM)) {}
  1949. OCS.insert(CallI);
  1950. }
  1951. ++I;
  1952. continue;
  1953. }
  1954. // Pattern match the current piece and its successor.
  1955. PathDiagnosticControlFlowPiece *PieceI =
  1956. dyn_cast<PathDiagnosticControlFlowPiece>(*I);
  1957. if (!PieceI) {
  1958. ++I;
  1959. continue;
  1960. }
  1961. const Stmt *s1Start = getLocStmt(PieceI->getStartLocation());
  1962. const Stmt *s1End = getLocStmt(PieceI->getEndLocation());
  1963. const Stmt *level1 = getStmtParent(s1Start, PM);
  1964. const Stmt *level2 = getStmtParent(s1End, PM);
  1965. PathPieces::iterator NextI = I; ++NextI;
  1966. if (NextI == E)
  1967. break;
  1968. PathDiagnosticControlFlowPiece *PieceNextI =
  1969. dyn_cast<PathDiagnosticControlFlowPiece>(*NextI);
  1970. if (!PieceNextI) {
  1971. ++I;
  1972. continue;
  1973. }
  1974. const Stmt *s2Start = getLocStmt(PieceNextI->getStartLocation());
  1975. const Stmt *s2End = getLocStmt(PieceNextI->getEndLocation());
  1976. const Stmt *level3 = getStmtParent(s2Start, PM);
  1977. const Stmt *level4 = getStmtParent(s2End, PM);
  1978. // Rule I.
  1979. //
  1980. // If we have two consecutive control edges whose end/begin locations
  1981. // are at the same level (e.g. statements or top-level expressions within
  1982. // a compound statement, or siblings share a single ancestor expression),
  1983. // then merge them if they have no interesting intermediate event.
  1984. //
  1985. // For example:
  1986. //
  1987. // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
  1988. // parent is '1'. Here 'x.y.z' represents the hierarchy of statements.
  1989. //
  1990. // NOTE: this will be limited later in cases where we add barriers
  1991. // to prevent this optimization.
  1992. //
  1993. if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
  1994. PieceI->setEndLocation(PieceNextI->getEndLocation());
  1995. path.erase(NextI);
  1996. hasChanges = true;
  1997. continue;
  1998. }
  1999. // Rule II.
  2000. //
  2001. // Eliminate edges between subexpressions and parent expressions
  2002. // when the subexpression is consumed.
  2003. //
  2004. // NOTE: this will be limited later in cases where we add barriers
  2005. // to prevent this optimization.
  2006. //
  2007. if (s1End && s1End == s2Start && level2) {
  2008. bool removeEdge = false;
  2009. // Remove edges into the increment or initialization of a
  2010. // loop that have no interleaving event. This means that
  2011. // they aren't interesting.
  2012. if (isIncrementOrInitInForLoop(s1End, level2))
  2013. removeEdge = true;
  2014. // Next only consider edges that are not anchored on
  2015. // the condition of a terminator. This are intermediate edges
  2016. // that we might want to trim.
  2017. else if (!isConditionForTerminator(level2, s1End)) {
  2018. // Trim edges on expressions that are consumed by
  2019. // the parent expression.
  2020. if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
  2021. removeEdge = true;
  2022. }
  2023. // Trim edges where a lexical containment doesn't exist.
  2024. // For example:
  2025. //
  2026. // X -> Y -> Z
  2027. //
  2028. // If 'Z' lexically contains Y (it is an ancestor) and
  2029. // 'X' does not lexically contain Y (it is a descendant OR
  2030. // it has no lexical relationship at all) then trim.
  2031. //
  2032. // This can eliminate edges where we dive into a subexpression
  2033. // and then pop back out, etc.
  2034. else if (s1Start && s2End &&
  2035. lexicalContains(PM, s2Start, s2End) &&
  2036. !lexicalContains(PM, s1End, s1Start)) {
  2037. removeEdge = true;
  2038. }
  2039. // Trim edges from a subexpression back to the top level if the
  2040. // subexpression is on a different line.
  2041. //
  2042. // A.1 -> A -> B
  2043. // becomes
  2044. // A.1 -> B
  2045. //
  2046. // These edges just look ugly and don't usually add anything.
  2047. else if (s1Start && s2End &&
  2048. lexicalContains(PM, s1Start, s1End)) {
  2049. SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
  2050. PieceI->getStartLocation().asLocation());
  2051. if (!getLengthOnSingleLine(SM, EdgeRange).hasValue())
  2052. removeEdge = true;
  2053. }
  2054. }
  2055. if (removeEdge) {
  2056. PieceI->setEndLocation(PieceNextI->getEndLocation());
  2057. path.erase(NextI);
  2058. hasChanges = true;
  2059. continue;
  2060. }
  2061. }
  2062. // Optimize edges for ObjC fast-enumeration loops.
  2063. //
  2064. // (X -> collection) -> (collection -> element)
  2065. //
  2066. // becomes:
  2067. //
  2068. // (X -> element)
  2069. if (s1End == s2Start) {
  2070. const ObjCForCollectionStmt *FS =
  2071. dyn_cast_or_null<ObjCForCollectionStmt>(level3);
  2072. if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
  2073. s2End == FS->getElement()) {
  2074. PieceI->setEndLocation(PieceNextI->getEndLocation());
  2075. path.erase(NextI);
  2076. hasChanges = true;
  2077. continue;
  2078. }
  2079. }
  2080. // No changes at this index? Move to the next one.
  2081. ++I;
  2082. }
  2083. if (!hasChanges) {
  2084. // Adjust edges into subexpressions to make them more uniform
  2085. // and aesthetically pleasing.
  2086. addContextEdges(path, SM, PM, LC);
  2087. // Remove "cyclical" edges that include one or more context edges.
  2088. removeContextCycles(path, SM, PM);
  2089. // Hoist edges originating from branch conditions to branches
  2090. // for simple branches.
  2091. simplifySimpleBranches(path);
  2092. // Remove any puny edges left over after primary optimization pass.
  2093. removePunyEdges(path, SM, PM);
  2094. // Remove identical events.
  2095. removeIdenticalEvents(path);
  2096. }
  2097. return hasChanges;
  2098. }
  2099. /// Drop the very first edge in a path, which should be a function entry edge.
  2100. ///
  2101. /// If the first edge is not a function entry edge (say, because the first
  2102. /// statement had an invalid source location), this function does nothing.
  2103. // FIXME: We should just generate invalid edges anyway and have the optimizer
  2104. // deal with them.
  2105. static void dropFunctionEntryEdge(PathPieces &Path,
  2106. LocationContextMap &LCM,
  2107. SourceManager &SM) {
  2108. const PathDiagnosticControlFlowPiece *FirstEdge =
  2109. dyn_cast<PathDiagnosticControlFlowPiece>(Path.front());
  2110. if (!FirstEdge)
  2111. return;
  2112. const Decl *D = LCM[&Path]->getDecl();
  2113. PathDiagnosticLocation EntryLoc = PathDiagnosticLocation::createBegin(D, SM);
  2114. if (FirstEdge->getStartLocation() != EntryLoc)
  2115. return;
  2116. Path.pop_front();
  2117. }
  2118. //===----------------------------------------------------------------------===//
  2119. // Methods for BugType and subclasses.
  2120. //===----------------------------------------------------------------------===//
  2121. void BugType::anchor() { }
  2122. void BugType::FlushReports(BugReporter &BR) {}
  2123. void BuiltinBug::anchor() {}
  2124. //===----------------------------------------------------------------------===//
  2125. // Methods for BugReport and subclasses.
  2126. //===----------------------------------------------------------------------===//
  2127. void BugReport::NodeResolver::anchor() {}
  2128. void BugReport::addVisitor(std::unique_ptr<BugReporterVisitor> visitor) {
  2129. if (!visitor)
  2130. return;
  2131. llvm::FoldingSetNodeID ID;
  2132. visitor->Profile(ID);
  2133. void *InsertPos;
  2134. if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos))
  2135. return;
  2136. CallbacksSet.InsertNode(visitor.get(), InsertPos);
  2137. Callbacks.push_back(std::move(visitor));
  2138. ++ConfigurationChangeToken;
  2139. }
  2140. BugReport::~BugReport() {
  2141. while (!interestingSymbols.empty()) {
  2142. popInterestingSymbolsAndRegions();
  2143. }
  2144. }
  2145. const Decl *BugReport::getDeclWithIssue() const {
  2146. if (DeclWithIssue)
  2147. return DeclWithIssue;
  2148. const ExplodedNode *N = getErrorNode();
  2149. if (!N)
  2150. return nullptr;
  2151. const LocationContext *LC = N->getLocationContext();
  2152. return LC->getCurrentStackFrame()->getDecl();
  2153. }
  2154. void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
  2155. hash.AddPointer(&BT);
  2156. hash.AddString(Description);
  2157. PathDiagnosticLocation UL = getUniqueingLocation();
  2158. if (UL.isValid()) {
  2159. UL.Profile(hash);
  2160. } else if (Location.isValid()) {
  2161. Location.Profile(hash);
  2162. } else {
  2163. assert(ErrorNode);
  2164. hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
  2165. }
  2166. for (SmallVectorImpl<SourceRange>::const_iterator I =
  2167. Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  2168. const SourceRange range = *I;
  2169. if (!range.isValid())
  2170. continue;
  2171. hash.AddInteger(range.getBegin().getRawEncoding());
  2172. hash.AddInteger(range.getEnd().getRawEncoding());
  2173. }
  2174. }
  2175. void BugReport::markInteresting(SymbolRef sym) {
  2176. if (!sym)
  2177. return;
  2178. // If the symbol wasn't already in our set, note a configuration change.
  2179. if (getInterestingSymbols().insert(sym).second)
  2180. ++ConfigurationChangeToken;
  2181. if (const SymbolMetadata *meta = dyn_cast<SymbolMetadata>(sym))
  2182. getInterestingRegions().insert(meta->getRegion());
  2183. }
  2184. void BugReport::markInteresting(const MemRegion *R) {
  2185. if (!R)
  2186. return;
  2187. // If the base region wasn't already in our set, note a configuration change.
  2188. R = R->getBaseRegion();
  2189. if (getInterestingRegions().insert(R).second)
  2190. ++ConfigurationChangeToken;
  2191. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
  2192. getInterestingSymbols().insert(SR->getSymbol());
  2193. }
  2194. void BugReport::markInteresting(SVal V) {
  2195. markInteresting(V.getAsRegion());
  2196. markInteresting(V.getAsSymbol());
  2197. }
  2198. void BugReport::markInteresting(const LocationContext *LC) {
  2199. if (!LC)
  2200. return;
  2201. InterestingLocationContexts.insert(LC);
  2202. }
  2203. bool BugReport::isInteresting(SVal V) {
  2204. return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
  2205. }
  2206. bool BugReport::isInteresting(SymbolRef sym) {
  2207. if (!sym)
  2208. return false;
  2209. // We don't currently consider metadata symbols to be interesting
  2210. // even if we know their region is interesting. Is that correct behavior?
  2211. return getInterestingSymbols().count(sym);
  2212. }
  2213. bool BugReport::isInteresting(const MemRegion *R) {
  2214. if (!R)
  2215. return false;
  2216. R = R->getBaseRegion();
  2217. bool b = getInterestingRegions().count(R);
  2218. if (b)
  2219. return true;
  2220. if (const SymbolicRegion *SR = dyn_cast<SymbolicRegion>(R))
  2221. return getInterestingSymbols().count(SR->getSymbol());
  2222. return false;
  2223. }
  2224. bool BugReport::isInteresting(const LocationContext *LC) {
  2225. if (!LC)
  2226. return false;
  2227. return InterestingLocationContexts.count(LC);
  2228. }
  2229. void BugReport::lazyInitializeInterestingSets() {
  2230. if (interestingSymbols.empty()) {
  2231. interestingSymbols.push_back(new Symbols());
  2232. interestingRegions.push_back(new Regions());
  2233. }
  2234. }
  2235. BugReport::Symbols &BugReport::getInterestingSymbols() {
  2236. lazyInitializeInterestingSets();
  2237. return *interestingSymbols.back();
  2238. }
  2239. BugReport::Regions &BugReport::getInterestingRegions() {
  2240. lazyInitializeInterestingSets();
  2241. return *interestingRegions.back();
  2242. }
  2243. void BugReport::pushInterestingSymbolsAndRegions() {
  2244. interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
  2245. interestingRegions.push_back(new Regions(getInterestingRegions()));
  2246. }
  2247. void BugReport::popInterestingSymbolsAndRegions() {
  2248. delete interestingSymbols.pop_back_val();
  2249. delete interestingRegions.pop_back_val();
  2250. }
  2251. const Stmt *BugReport::getStmt() const {
  2252. if (!ErrorNode)
  2253. return nullptr;
  2254. ProgramPoint ProgP = ErrorNode->getLocation();
  2255. const Stmt *S = nullptr;
  2256. if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
  2257. CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
  2258. if (BE->getBlock() == &Exit)
  2259. S = GetPreviousStmt(ErrorNode);
  2260. }
  2261. if (!S)
  2262. S = PathDiagnosticLocation::getStmt(ErrorNode);
  2263. return S;
  2264. }
  2265. llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() {
  2266. // If no custom ranges, add the range of the statement corresponding to
  2267. // the error node.
  2268. if (Ranges.empty()) {
  2269. if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
  2270. addRange(E->getSourceRange());
  2271. else
  2272. return llvm::make_range(ranges_iterator(), ranges_iterator());
  2273. }
  2274. // User-specified absence of range info.
  2275. if (Ranges.size() == 1 && !Ranges.begin()->isValid())
  2276. return llvm::make_range(ranges_iterator(), ranges_iterator());
  2277. return llvm::iterator_range<BugReport::ranges_iterator>(Ranges.begin(),
  2278. Ranges.end());
  2279. }
  2280. PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
  2281. if (ErrorNode) {
  2282. assert(!Location.isValid() &&
  2283. "Either Location or ErrorNode should be specified but not both.");
  2284. return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
  2285. }
  2286. assert(Location.isValid());
  2287. return Location;
  2288. }
  2289. //===----------------------------------------------------------------------===//
  2290. // Methods for BugReporter and subclasses.
  2291. //===----------------------------------------------------------------------===//
  2292. BugReportEquivClass::~BugReportEquivClass() { }
  2293. GRBugReporter::~GRBugReporter() { }
  2294. BugReporterData::~BugReporterData() {}
  2295. ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
  2296. ProgramStateManager&
  2297. GRBugReporter::getStateManager() { return Eng.getStateManager(); }
  2298. BugReporter::~BugReporter() {
  2299. FlushReports();
  2300. // Free the bug reports we are tracking.
  2301. typedef std::vector<BugReportEquivClass *> ContTy;
  2302. for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
  2303. I != E; ++I) {
  2304. delete *I;
  2305. }
  2306. }
  2307. void BugReporter::FlushReports() {
  2308. if (BugTypes.isEmpty())
  2309. return;
  2310. // First flush the warnings for each BugType. This may end up creating new
  2311. // warnings and new BugTypes.
  2312. // FIXME: Only NSErrorChecker needs BugType's FlushReports.
  2313. // Turn NSErrorChecker into a proper checker and remove this.
  2314. SmallVector<const BugType *, 16> bugTypes(BugTypes.begin(), BugTypes.end());
  2315. for (SmallVectorImpl<const BugType *>::iterator
  2316. I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
  2317. const_cast<BugType*>(*I)->FlushReports(*this);
  2318. // We need to flush reports in deterministic order to ensure the order
  2319. // of the reports is consistent between runs.
  2320. typedef std::vector<BugReportEquivClass *> ContVecTy;
  2321. for (ContVecTy::iterator EI=EQClassesVector.begin(), EE=EQClassesVector.end();
  2322. EI != EE; ++EI){
  2323. BugReportEquivClass& EQ = **EI;
  2324. FlushReport(EQ);
  2325. }
  2326. // BugReporter owns and deletes only BugTypes created implicitly through
  2327. // EmitBasicReport.
  2328. // FIXME: There are leaks from checkers that assume that the BugTypes they
  2329. // create will be destroyed by the BugReporter.
  2330. llvm::DeleteContainerSeconds(StrBugTypes);
  2331. // Remove all references to the BugType objects.
  2332. BugTypes = F.getEmptySet();
  2333. }
  2334. //===----------------------------------------------------------------------===//
  2335. // PathDiagnostics generation.
  2336. //===----------------------------------------------------------------------===//
  2337. namespace {
  2338. /// A wrapper around a report graph, which contains only a single path, and its
  2339. /// node maps.
  2340. class ReportGraph {
  2341. public:
  2342. InterExplodedGraphMap BackMap;
  2343. std::unique_ptr<ExplodedGraph> Graph;
  2344. const ExplodedNode *ErrorNode;
  2345. size_t Index;
  2346. };
  2347. /// A wrapper around a trimmed graph and its node maps.
  2348. class TrimmedGraph {
  2349. InterExplodedGraphMap InverseMap;
  2350. typedef llvm::DenseMap<const ExplodedNode *, unsigned> PriorityMapTy;
  2351. PriorityMapTy PriorityMap;
  2352. typedef std::pair<const ExplodedNode *, size_t> NodeIndexPair;
  2353. SmallVector<NodeIndexPair, 32> ReportNodes;
  2354. std::unique_ptr<ExplodedGraph> G;
  2355. /// A helper class for sorting ExplodedNodes by priority.
  2356. template <bool Descending>
  2357. class PriorityCompare {
  2358. const PriorityMapTy &PriorityMap;
  2359. public:
  2360. PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
  2361. bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
  2362. PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
  2363. PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
  2364. PriorityMapTy::const_iterator E = PriorityMap.end();
  2365. if (LI == E)
  2366. return Descending;
  2367. if (RI == E)
  2368. return !Descending;
  2369. return Descending ? LI->second > RI->second
  2370. : LI->second < RI->second;
  2371. }
  2372. bool operator()(const NodeIndexPair &LHS, const NodeIndexPair &RHS) const {
  2373. return (*this)(LHS.first, RHS.first);
  2374. }
  2375. };
  2376. public:
  2377. TrimmedGraph(const ExplodedGraph *OriginalGraph,
  2378. ArrayRef<const ExplodedNode *> Nodes);
  2379. bool popNextReportGraph(ReportGraph &GraphWrapper);
  2380. };
  2381. }
  2382. TrimmedGraph::TrimmedGraph(const ExplodedGraph *OriginalGraph,
  2383. ArrayRef<const ExplodedNode *> Nodes) {
  2384. // The trimmed graph is created in the body of the constructor to ensure
  2385. // that the DenseMaps have been initialized already.
  2386. InterExplodedGraphMap ForwardMap;
  2387. G = OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap);
  2388. // Find the (first) error node in the trimmed graph. We just need to consult
  2389. // the node map which maps from nodes in the original graph to nodes
  2390. // in the new graph.
  2391. llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
  2392. for (unsigned i = 0, count = Nodes.size(); i < count; ++i) {
  2393. if (const ExplodedNode *NewNode = ForwardMap.lookup(Nodes[i])) {
  2394. ReportNodes.push_back(std::make_pair(NewNode, i));
  2395. RemainingNodes.insert(NewNode);
  2396. }
  2397. }
  2398. assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
  2399. // Perform a forward BFS to find all the shortest paths.
  2400. std::queue<const ExplodedNode *> WS;
  2401. assert(G->num_roots() == 1);
  2402. WS.push(*G->roots_begin());
  2403. unsigned Priority = 0;
  2404. while (!WS.empty()) {
  2405. const ExplodedNode *Node = WS.front();
  2406. WS.pop();
  2407. PriorityMapTy::iterator PriorityEntry;
  2408. bool IsNew;
  2409. std::tie(PriorityEntry, IsNew) =
  2410. PriorityMap.insert(std::make_pair(Node, Priority));
  2411. ++Priority;
  2412. if (!IsNew) {
  2413. assert(PriorityEntry->second <= Priority);
  2414. continue;
  2415. }
  2416. if (RemainingNodes.erase(Node))
  2417. if (RemainingNodes.empty())
  2418. break;
  2419. for (ExplodedNode::const_pred_iterator I = Node->succ_begin(),
  2420. E = Node->succ_end();
  2421. I != E; ++I)
  2422. WS.push(*I);
  2423. }
  2424. // Sort the error paths from longest to shortest.
  2425. std::sort(ReportNodes.begin(), ReportNodes.end(),
  2426. PriorityCompare<true>(PriorityMap));
  2427. }
  2428. bool TrimmedGraph::popNextReportGraph(ReportGraph &GraphWrapper) {
  2429. if (ReportNodes.empty())
  2430. return false;
  2431. const ExplodedNode *OrigN;
  2432. std::tie(OrigN, GraphWrapper.Index) = ReportNodes.pop_back_val();
  2433. assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
  2434. "error node not accessible from root");
  2435. // Create a new graph with a single path. This is the graph
  2436. // that will be returned to the caller.
  2437. auto GNew = llvm::make_unique<ExplodedGraph>();
  2438. GraphWrapper.BackMap.clear();
  2439. // Now walk from the error node up the BFS path, always taking the
  2440. // predeccessor with the lowest number.
  2441. ExplodedNode *Succ = nullptr;
  2442. while (true) {
  2443. // Create the equivalent node in the new graph with the same state
  2444. // and location.
  2445. ExplodedNode *NewN = GNew->getNode(OrigN->getLocation(), OrigN->getState(),
  2446. OrigN->isSink());
  2447. // Store the mapping to the original node.
  2448. InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN);
  2449. assert(IMitr != InverseMap.end() && "No mapping to original node.");
  2450. GraphWrapper.BackMap[NewN] = IMitr->second;
  2451. // Link up the new node with the previous node.
  2452. if (Succ)
  2453. Succ->addPredecessor(NewN, *GNew);
  2454. else
  2455. GraphWrapper.ErrorNode = NewN;
  2456. Succ = NewN;
  2457. // Are we at the final node?
  2458. if (OrigN->pred_empty()) {
  2459. GNew->addRoot(NewN);
  2460. break;
  2461. }
  2462. // Find the next predeccessor node. We choose the node that is marked
  2463. // with the lowest BFS number.
  2464. OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
  2465. PriorityCompare<false>(PriorityMap));
  2466. }
  2467. GraphWrapper.Graph = std::move(GNew);
  2468. return true;
  2469. }
  2470. /// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
  2471. /// and collapses PathDiagosticPieces that are expanded by macros.
  2472. static void CompactPathDiagnostic(PathPieces &path, const SourceManager& SM) {
  2473. typedef std::vector<std::pair<IntrusiveRefCntPtr<PathDiagnosticMacroPiece>,
  2474. SourceLocation> > MacroStackTy;
  2475. typedef std::vector<IntrusiveRefCntPtr<PathDiagnosticPiece> >
  2476. PiecesTy;
  2477. MacroStackTy MacroStack;
  2478. PiecesTy Pieces;
  2479. for (PathPieces::const_iterator I = path.begin(), E = path.end();
  2480. I!=E; ++I) {
  2481. PathDiagnosticPiece *piece = I->get();
  2482. // Recursively compact calls.
  2483. if (PathDiagnosticCallPiece *call=dyn_cast<PathDiagnosticCallPiece>(piece)){
  2484. CompactPathDiagnostic(call->path, SM);
  2485. }
  2486. // Get the location of the PathDiagnosticPiece.
  2487. const FullSourceLoc Loc = piece->getLocation().asLocation();
  2488. // Determine the instantiation location, which is the location we group
  2489. // related PathDiagnosticPieces.
  2490. SourceLocation InstantiationLoc = Loc.isMacroID() ?
  2491. SM.getExpansionLoc(Loc) :
  2492. SourceLocation();
  2493. if (Loc.isFileID()) {
  2494. MacroStack.clear();
  2495. Pieces.push_back(piece);
  2496. continue;
  2497. }
  2498. assert(Loc.isMacroID());
  2499. // Is the PathDiagnosticPiece within the same macro group?
  2500. if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
  2501. MacroStack.back().first->subPieces.push_back(piece);
  2502. continue;
  2503. }
  2504. // We aren't in the same group. Are we descending into a new macro
  2505. // or are part of an old one?
  2506. IntrusiveRefCntPtr<PathDiagnosticMacroPiece> MacroGroup;
  2507. SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
  2508. SM.getExpansionLoc(Loc) :
  2509. SourceLocation();
  2510. // Walk the entire macro stack.
  2511. while (!MacroStack.empty()) {
  2512. if (InstantiationLoc == MacroStack.back().second) {
  2513. MacroGroup = MacroStack.back().first;
  2514. break;
  2515. }
  2516. if (ParentInstantiationLoc == MacroStack.back().second) {
  2517. MacroGroup = MacroStack.back().first;
  2518. break;
  2519. }
  2520. MacroStack.pop_back();
  2521. }
  2522. if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
  2523. // Create a new macro group and add it to the stack.
  2524. PathDiagnosticMacroPiece *NewGroup =
  2525. new PathDiagnosticMacroPiece(
  2526. PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
  2527. if (MacroGroup)
  2528. MacroGroup->subPieces.push_back(NewGroup);
  2529. else {
  2530. assert(InstantiationLoc.isFileID());
  2531. Pieces.push_back(NewGroup);
  2532. }
  2533. MacroGroup = NewGroup;
  2534. MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
  2535. }
  2536. // Finally, add the PathDiagnosticPiece to the group.
  2537. MacroGroup->subPieces.push_back(piece);
  2538. }
  2539. // Now take the pieces and construct a new PathDiagnostic.
  2540. path.clear();
  2541. path.insert(path.end(), Pieces.begin(), Pieces.end());
  2542. }
  2543. bool GRBugReporter::generatePathDiagnostic(PathDiagnostic& PD,
  2544. PathDiagnosticConsumer &PC,
  2545. ArrayRef<BugReport *> &bugReports) {
  2546. assert(!bugReports.empty());
  2547. bool HasValid = false;
  2548. bool HasInvalid = false;
  2549. SmallVector<const ExplodedNode *, 32> errorNodes;
  2550. for (ArrayRef<BugReport*>::iterator I = bugReports.begin(),
  2551. E = bugReports.end(); I != E; ++I) {
  2552. if ((*I)->isValid()) {
  2553. HasValid = true;
  2554. errorNodes.push_back((*I)->getErrorNode());
  2555. } else {
  2556. // Keep the errorNodes list in sync with the bugReports list.
  2557. HasInvalid = true;
  2558. errorNodes.push_back(nullptr);
  2559. }
  2560. }
  2561. // If all the reports have been marked invalid by a previous path generation,
  2562. // we're done.
  2563. if (!HasValid)
  2564. return false;
  2565. typedef PathDiagnosticConsumer::PathGenerationScheme PathGenerationScheme;
  2566. PathGenerationScheme ActiveScheme = PC.getGenerationScheme();
  2567. if (ActiveScheme == PathDiagnosticConsumer::Extensive) {
  2568. AnalyzerOptions &options = getAnalyzerOptions();
  2569. if (options.getBooleanOption("path-diagnostics-alternate", true)) {
  2570. ActiveScheme = PathDiagnosticConsumer::AlternateExtensive;
  2571. }
  2572. }
  2573. TrimmedGraph TrimG(&getGraph(), errorNodes);
  2574. ReportGraph ErrorGraph;
  2575. while (TrimG.popNextReportGraph(ErrorGraph)) {
  2576. // Find the BugReport with the original location.
  2577. assert(ErrorGraph.Index < bugReports.size());
  2578. BugReport *R = bugReports[ErrorGraph.Index];
  2579. assert(R && "No original report found for sliced graph.");
  2580. assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
  2581. // Start building the path diagnostic...
  2582. PathDiagnosticBuilder PDB(*this, R, ErrorGraph.BackMap, &PC);
  2583. const ExplodedNode *N = ErrorGraph.ErrorNode;
  2584. // Register additional node visitors.
  2585. R->addVisitor(llvm::make_unique<NilReceiverBRVisitor>());
  2586. R->addVisitor(llvm::make_unique<ConditionBRVisitor>());
  2587. R->addVisitor(llvm::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
  2588. BugReport::VisitorList visitors;
  2589. unsigned origReportConfigToken, finalReportConfigToken;
  2590. LocationContextMap LCM;
  2591. // While generating diagnostics, it's possible the visitors will decide
  2592. // new symbols and regions are interesting, or add other visitors based on
  2593. // the information they find. If they do, we need to regenerate the path
  2594. // based on our new report configuration.
  2595. do {
  2596. // Get a clean copy of all the visitors.
  2597. for (BugReport::visitor_iterator I = R->visitor_begin(),
  2598. E = R->visitor_end(); I != E; ++I)
  2599. visitors.push_back((*I)->clone());
  2600. // Clear out the active path from any previous work.
  2601. PD.resetPath();
  2602. origReportConfigToken = R->getConfigurationChangeToken();
  2603. // Generate the very last diagnostic piece - the piece is visible before
  2604. // the trace is expanded.
  2605. std::unique_ptr<PathDiagnosticPiece> LastPiece;
  2606. for (BugReport::visitor_iterator I = visitors.begin(), E = visitors.end();
  2607. I != E; ++I) {
  2608. if (std::unique_ptr<PathDiagnosticPiece> Piece =
  2609. (*I)->getEndPath(PDB, N, *R)) {
  2610. assert (!LastPiece &&
  2611. "There can only be one final piece in a diagnostic.");
  2612. LastPiece = std::move(Piece);
  2613. }
  2614. }
  2615. if (ActiveScheme != PathDiagnosticConsumer::None) {
  2616. if (!LastPiece)
  2617. LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
  2618. assert(LastPiece);
  2619. PD.setEndOfPath(std::move(LastPiece));
  2620. }
  2621. // Make sure we get a clean location context map so we don't
  2622. // hold onto old mappings.
  2623. LCM.clear();
  2624. switch (ActiveScheme) {
  2625. case PathDiagnosticConsumer::AlternateExtensive:
  2626. GenerateAlternateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors);
  2627. break;
  2628. case PathDiagnosticConsumer::Extensive:
  2629. GenerateExtensivePathDiagnostic(PD, PDB, N, LCM, visitors);
  2630. break;
  2631. case PathDiagnosticConsumer::Minimal:
  2632. GenerateMinimalPathDiagnostic(PD, PDB, N, LCM, visitors);
  2633. break;
  2634. case PathDiagnosticConsumer::None:
  2635. GenerateVisitorsOnlyPathDiagnostic(PD, PDB, N, visitors);
  2636. break;
  2637. }
  2638. // Clean up the visitors we used.
  2639. visitors.clear();
  2640. // Did anything change while generating this path?
  2641. finalReportConfigToken = R->getConfigurationChangeToken();
  2642. } while (finalReportConfigToken != origReportConfigToken);
  2643. if (!R->isValid())
  2644. continue;
  2645. // Finally, prune the diagnostic path of uninteresting stuff.
  2646. if (!PD.path.empty()) {
  2647. if (R->shouldPrunePath() && getAnalyzerOptions().shouldPrunePaths()) {
  2648. bool stillHasNotes = removeUnneededCalls(PD.getMutablePieces(), R, LCM);
  2649. assert(stillHasNotes);
  2650. (void)stillHasNotes;
  2651. }
  2652. // Redirect all call pieces to have valid locations.
  2653. adjustCallLocations(PD.getMutablePieces());
  2654. removePiecesWithInvalidLocations(PD.getMutablePieces());
  2655. if (ActiveScheme == PathDiagnosticConsumer::AlternateExtensive) {
  2656. SourceManager &SM = getSourceManager();
  2657. // Reduce the number of edges from a very conservative set
  2658. // to an aesthetically pleasing subset that conveys the
  2659. // necessary information.
  2660. OptimizedCallsSet OCS;
  2661. while (optimizeEdges(PD.getMutablePieces(), SM, OCS, LCM)) {}
  2662. // Drop the very first function-entry edge. It's not really necessary
  2663. // for top-level functions.
  2664. dropFunctionEntryEdge(PD.getMutablePieces(), LCM, SM);
  2665. }
  2666. // Remove messages that are basically the same, and edges that may not
  2667. // make sense.
  2668. // We have to do this after edge optimization in the Extensive mode.
  2669. removeRedundantMsgs(PD.getMutablePieces());
  2670. removeEdgesToDefaultInitializers(PD.getMutablePieces());
  2671. }
  2672. // We found a report and didn't suppress it.
  2673. return true;
  2674. }
  2675. // We suppressed all the reports in this equivalence class.
  2676. assert(!HasInvalid && "Inconsistent suppression");
  2677. (void)HasInvalid;
  2678. return false;
  2679. }
  2680. void BugReporter::Register(BugType *BT) {
  2681. BugTypes = F.add(BugTypes, BT);
  2682. }
  2683. void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
  2684. if (const ExplodedNode *E = R->getErrorNode()) {
  2685. const AnalysisDeclContext *DeclCtx =
  2686. E->getLocationContext()->getAnalysisDeclContext();
  2687. // The source of autosynthesized body can be handcrafted AST or a model
  2688. // file. The locations from handcrafted ASTs have no valid source locations
  2689. // and have to be discarded. Locations from model files should be preserved
  2690. // for processing and reporting.
  2691. if (DeclCtx->isBodyAutosynthesized() &&
  2692. !DeclCtx->isBodyAutosynthesizedFromModelFile())
  2693. return;
  2694. }
  2695. bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
  2696. assert(ValidSourceLoc);
  2697. // If we mess up in a release build, we'd still prefer to just drop the bug
  2698. // instead of trying to go on.
  2699. if (!ValidSourceLoc)
  2700. return;
  2701. // Compute the bug report's hash to determine its equivalence class.
  2702. llvm::FoldingSetNodeID ID;
  2703. R->Profile(ID);
  2704. // Lookup the equivance class. If there isn't one, create it.
  2705. BugType& BT = R->getBugType();
  2706. Register(&BT);
  2707. void *InsertPos;
  2708. BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
  2709. if (!EQ) {
  2710. EQ = new BugReportEquivClass(std::move(R));
  2711. EQClasses.InsertNode(EQ, InsertPos);
  2712. EQClassesVector.push_back(EQ);
  2713. } else
  2714. EQ->AddReport(std::move(R));
  2715. }
  2716. //===----------------------------------------------------------------------===//
  2717. // Emitting reports in equivalence classes.
  2718. //===----------------------------------------------------------------------===//
  2719. namespace {
  2720. struct FRIEC_WLItem {
  2721. const ExplodedNode *N;
  2722. ExplodedNode::const_succ_iterator I, E;
  2723. FRIEC_WLItem(const ExplodedNode *n)
  2724. : N(n), I(N->succ_begin()), E(N->succ_end()) {}
  2725. };
  2726. }
  2727. static BugReport *
  2728. FindReportInEquivalenceClass(BugReportEquivClass& EQ,
  2729. SmallVectorImpl<BugReport*> &bugReports) {
  2730. BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
  2731. assert(I != E);
  2732. BugType& BT = I->getBugType();
  2733. // If we don't need to suppress any of the nodes because they are
  2734. // post-dominated by a sink, simply add all the nodes in the equivalence class
  2735. // to 'Nodes'. Any of the reports will serve as a "representative" report.
  2736. if (!BT.isSuppressOnSink()) {
  2737. BugReport *R = I;
  2738. for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
  2739. const ExplodedNode *N = I->getErrorNode();
  2740. if (N) {
  2741. R = I;
  2742. bugReports.push_back(R);
  2743. }
  2744. }
  2745. return R;
  2746. }
  2747. // For bug reports that should be suppressed when all paths are post-dominated
  2748. // by a sink node, iterate through the reports in the equivalence class
  2749. // until we find one that isn't post-dominated (if one exists). We use a
  2750. // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
  2751. // this as a recursive function, but we don't want to risk blowing out the
  2752. // stack for very long paths.
  2753. BugReport *exampleReport = nullptr;
  2754. for (; I != E; ++I) {
  2755. const ExplodedNode *errorNode = I->getErrorNode();
  2756. if (!errorNode)
  2757. continue;
  2758. if (errorNode->isSink()) {
  2759. llvm_unreachable(
  2760. "BugType::isSuppressSink() should not be 'true' for sink end nodes");
  2761. }
  2762. // No successors? By definition this nodes isn't post-dominated by a sink.
  2763. if (errorNode->succ_empty()) {
  2764. bugReports.push_back(I);
  2765. if (!exampleReport)
  2766. exampleReport = I;
  2767. continue;
  2768. }
  2769. // At this point we know that 'N' is not a sink and it has at least one
  2770. // successor. Use a DFS worklist to find a non-sink end-of-path node.
  2771. typedef FRIEC_WLItem WLItem;
  2772. typedef SmallVector<WLItem, 10> DFSWorkList;
  2773. llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
  2774. DFSWorkList WL;
  2775. WL.push_back(errorNode);
  2776. Visited[errorNode] = 1;
  2777. while (!WL.empty()) {
  2778. WLItem &WI = WL.back();
  2779. assert(!WI.N->succ_empty());
  2780. for (; WI.I != WI.E; ++WI.I) {
  2781. const ExplodedNode *Succ = *WI.I;
  2782. // End-of-path node?
  2783. if (Succ->succ_empty()) {
  2784. // If we found an end-of-path node that is not a sink.
  2785. if (!Succ->isSink()) {
  2786. bugReports.push_back(I);
  2787. if (!exampleReport)
  2788. exampleReport = I;
  2789. WL.clear();
  2790. break;
  2791. }
  2792. // Found a sink? Continue on to the next successor.
  2793. continue;
  2794. }
  2795. // Mark the successor as visited. If it hasn't been explored,
  2796. // enqueue it to the DFS worklist.
  2797. unsigned &mark = Visited[Succ];
  2798. if (!mark) {
  2799. mark = 1;
  2800. WL.push_back(Succ);
  2801. break;
  2802. }
  2803. }
  2804. // The worklist may have been cleared at this point. First
  2805. // check if it is empty before checking the last item.
  2806. if (!WL.empty() && &WL.back() == &WI)
  2807. WL.pop_back();
  2808. }
  2809. }
  2810. // ExampleReport will be NULL if all the nodes in the equivalence class
  2811. // were post-dominated by sinks.
  2812. return exampleReport;
  2813. }
  2814. void BugReporter::FlushReport(BugReportEquivClass& EQ) {
  2815. SmallVector<BugReport*, 10> bugReports;
  2816. BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
  2817. if (exampleReport) {
  2818. for (PathDiagnosticConsumer *PDC : getPathDiagnosticConsumers()) {
  2819. FlushReport(exampleReport, *PDC, bugReports);
  2820. }
  2821. }
  2822. }
  2823. void BugReporter::FlushReport(BugReport *exampleReport,
  2824. PathDiagnosticConsumer &PD,
  2825. ArrayRef<BugReport*> bugReports) {
  2826. // FIXME: Make sure we use the 'R' for the path that was actually used.
  2827. // Probably doesn't make a difference in practice.
  2828. BugType& BT = exampleReport->getBugType();
  2829. std::unique_ptr<PathDiagnostic> D(new PathDiagnostic(
  2830. exampleReport->getBugType().getCheckName(),
  2831. exampleReport->getDeclWithIssue(), exampleReport->getBugType().getName(),
  2832. exampleReport->getDescription(),
  2833. exampleReport->getShortDescription(/*Fallback=*/false), BT.getCategory(),
  2834. exampleReport->getUniqueingLocation(),
  2835. exampleReport->getUniqueingDecl()));
  2836. MaxBugClassSize = std::max(bugReports.size(),
  2837. static_cast<size_t>(MaxBugClassSize));
  2838. // Generate the full path diagnostic, using the generation scheme
  2839. // specified by the PathDiagnosticConsumer. Note that we have to generate
  2840. // path diagnostics even for consumers which do not support paths, because
  2841. // the BugReporterVisitors may mark this bug as a false positive.
  2842. if (!bugReports.empty())
  2843. if (!generatePathDiagnostic(*D.get(), PD, bugReports))
  2844. return;
  2845. MaxValidBugClassSize = std::max(bugReports.size(),
  2846. static_cast<size_t>(MaxValidBugClassSize));
  2847. // Examine the report and see if the last piece is in a header. Reset the
  2848. // report location to the last piece in the main source file.
  2849. AnalyzerOptions& Opts = getAnalyzerOptions();
  2850. if (Opts.shouldReportIssuesInMainSourceFile() && !Opts.AnalyzeAll)
  2851. D->resetDiagnosticLocationToMainFile();
  2852. // If the path is empty, generate a single step path with the location
  2853. // of the issue.
  2854. if (D->path.empty()) {
  2855. PathDiagnosticLocation L = exampleReport->getLocation(getSourceManager());
  2856. auto piece = llvm::make_unique<PathDiagnosticEventPiece>(
  2857. L, exampleReport->getDescription());
  2858. for (const SourceRange &Range : exampleReport->getRanges())
  2859. piece->addRange(Range);
  2860. D->setEndOfPath(std::move(piece));
  2861. }
  2862. // Get the meta data.
  2863. const BugReport::ExtraTextList &Meta = exampleReport->getExtraText();
  2864. for (BugReport::ExtraTextList::const_iterator i = Meta.begin(),
  2865. e = Meta.end(); i != e; ++i) {
  2866. D->addMeta(*i);
  2867. }
  2868. PD.HandlePathDiagnostic(std::move(D));
  2869. }
  2870. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  2871. const CheckerBase *Checker,
  2872. StringRef Name, StringRef Category,
  2873. StringRef Str, PathDiagnosticLocation Loc,
  2874. ArrayRef<SourceRange> Ranges) {
  2875. EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
  2876. Loc, Ranges);
  2877. }
  2878. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  2879. CheckName CheckName,
  2880. StringRef name, StringRef category,
  2881. StringRef str, PathDiagnosticLocation Loc,
  2882. ArrayRef<SourceRange> Ranges) {
  2883. // 'BT' is owned by BugReporter.
  2884. BugType *BT = getBugTypeForName(CheckName, name, category);
  2885. auto R = llvm::make_unique<BugReport>(*BT, str, Loc);
  2886. R->setDeclWithIssue(DeclWithIssue);
  2887. for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
  2888. I != E; ++I)
  2889. R->addRange(*I);
  2890. emitReport(std::move(R));
  2891. }
  2892. BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
  2893. StringRef category) {
  2894. SmallString<136> fullDesc;
  2895. llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
  2896. << ":" << category;
  2897. BugType *&BT = StrBugTypes[fullDesc];
  2898. if (!BT)
  2899. BT = new BugType(CheckName, name, category);
  2900. return BT;
  2901. }
  2902. LLVM_DUMP_METHOD void PathPieces::dump() const {
  2903. unsigned index = 0;
  2904. for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I) {
  2905. llvm::errs() << "[" << index++ << "] ";
  2906. (*I)->dump();
  2907. llvm::errs() << "\n";
  2908. }
  2909. }
  2910. void PathDiagnosticCallPiece::dump() const {
  2911. llvm::errs() << "CALL\n--------------\n";
  2912. if (const Stmt *SLoc = getLocStmt(getLocation()))
  2913. SLoc->dump();
  2914. else if (const NamedDecl *ND = dyn_cast<NamedDecl>(getCallee()))
  2915. llvm::errs() << *ND << "\n";
  2916. else
  2917. getLocation().dump();
  2918. }
  2919. void PathDiagnosticEventPiece::dump() const {
  2920. llvm::errs() << "EVENT\n--------------\n";
  2921. llvm::errs() << getString() << "\n";
  2922. llvm::errs() << " ---- at ----\n";
  2923. getLocation().dump();
  2924. }
  2925. void PathDiagnosticControlFlowPiece::dump() const {
  2926. llvm::errs() << "CONTROL\n--------------\n";
  2927. getStartLocation().dump();
  2928. llvm::errs() << " ---- to ----\n";
  2929. getEndLocation().dump();
  2930. }
  2931. void PathDiagnosticMacroPiece::dump() const {
  2932. llvm::errs() << "MACRO\n--------------\n";
  2933. // FIXME: Print which macro is being invoked.
  2934. }
  2935. void PathDiagnosticLocation::dump() const {
  2936. if (!isValid()) {
  2937. llvm::errs() << "<INVALID>\n";
  2938. return;
  2939. }
  2940. switch (K) {
  2941. case RangeK:
  2942. // FIXME: actually print the range.
  2943. llvm::errs() << "<range>\n";
  2944. break;
  2945. case SingleLocK:
  2946. asLocation().dump();
  2947. llvm::errs() << "\n";
  2948. break;
  2949. case StmtK:
  2950. if (S)
  2951. S->dump();
  2952. else
  2953. llvm::errs() << "<NULL STMT>\n";
  2954. break;
  2955. case DeclK:
  2956. if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(D))
  2957. llvm::errs() << *ND << "\n";
  2958. else if (isa<BlockDecl>(D))
  2959. // FIXME: Make this nicer.
  2960. llvm::errs() << "<block>\n";
  2961. else if (D)
  2962. llvm::errs() << "<unknown decl>\n";
  2963. else
  2964. llvm::errs() << "<NULL DECL>\n";
  2965. break;
  2966. }
  2967. }