BugReporter.cpp 120 KB

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