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