PathDiagnostic.cpp 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463
  1. //===- PathDiagnostic.cpp - Path-Specific Diagnostic Handling -------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the PathDiagnostic-related interfaces.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  13. #include "clang/AST/Decl.h"
  14. #include "clang/AST/DeclBase.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/OperationKinds.h"
  21. #include "clang/AST/ParentMap.h"
  22. #include "clang/AST/Stmt.h"
  23. #include "clang/AST/Type.h"
  24. #include "clang/Analysis/AnalysisDeclContext.h"
  25. #include "clang/Analysis/CFG.h"
  26. #include "clang/Analysis/ProgramPoint.h"
  27. #include "clang/Basic/FileManager.h"
  28. #include "clang/Basic/LLVM.h"
  29. #include "clang/Basic/SourceLocation.h"
  30. #include "clang/Basic/SourceManager.h"
  31. #include "clang/StaticAnalyzer/Core/PathSensitive/AnalysisManager.h"
  32. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  33. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  34. #include "llvm/ADT/ArrayRef.h"
  35. #include "llvm/ADT/FoldingSet.h"
  36. #include "llvm/ADT/None.h"
  37. #include "llvm/ADT/Optional.h"
  38. #include "llvm/ADT/STLExtras.h"
  39. #include "llvm/ADT/SmallString.h"
  40. #include "llvm/ADT/SmallVector.h"
  41. #include "llvm/ADT/StringExtras.h"
  42. #include "llvm/ADT/StringRef.h"
  43. #include "llvm/Support/Casting.h"
  44. #include "llvm/Support/ErrorHandling.h"
  45. #include "llvm/Support/raw_ostream.h"
  46. #include <cassert>
  47. #include <cstring>
  48. #include <memory>
  49. #include <utility>
  50. #include <vector>
  51. using namespace clang;
  52. using namespace ento;
  53. bool PathDiagnosticMacroPiece::containsEvent() const {
  54. for (const auto &P : subPieces) {
  55. if (isa<PathDiagnosticEventPiece>(*P))
  56. return true;
  57. if (const auto *MP = dyn_cast<PathDiagnosticMacroPiece>(P.get()))
  58. if (MP->containsEvent())
  59. return true;
  60. }
  61. return false;
  62. }
  63. static StringRef StripTrailingDots(StringRef s) {
  64. for (StringRef::size_type i = s.size(); i != 0; --i)
  65. if (s[i - 1] != '.')
  66. return s.substr(0, i);
  67. return {};
  68. }
  69. PathDiagnosticPiece::PathDiagnosticPiece(StringRef s,
  70. Kind k, DisplayHint hint)
  71. : str(StripTrailingDots(s)), kind(k), Hint(hint) {}
  72. PathDiagnosticPiece::PathDiagnosticPiece(Kind k, DisplayHint hint)
  73. : kind(k), Hint(hint) {}
  74. PathDiagnosticPiece::~PathDiagnosticPiece() = default;
  75. PathDiagnosticEventPiece::~PathDiagnosticEventPiece() = default;
  76. PathDiagnosticCallPiece::~PathDiagnosticCallPiece() = default;
  77. PathDiagnosticControlFlowPiece::~PathDiagnosticControlFlowPiece() = default;
  78. PathDiagnosticMacroPiece::~PathDiagnosticMacroPiece() = default;
  79. PathDiagnosticNotePiece::~PathDiagnosticNotePiece() = default;
  80. PathDiagnosticPopUpPiece::~PathDiagnosticPopUpPiece() = default;
  81. void PathPieces::flattenTo(PathPieces &Primary, PathPieces &Current,
  82. bool ShouldFlattenMacros) const {
  83. for (auto &Piece : *this) {
  84. switch (Piece->getKind()) {
  85. case PathDiagnosticPiece::Call: {
  86. auto &Call = cast<PathDiagnosticCallPiece>(*Piece);
  87. if (auto CallEnter = Call.getCallEnterEvent())
  88. Current.push_back(std::move(CallEnter));
  89. Call.path.flattenTo(Primary, Primary, ShouldFlattenMacros);
  90. if (auto callExit = Call.getCallExitEvent())
  91. Current.push_back(std::move(callExit));
  92. break;
  93. }
  94. case PathDiagnosticPiece::Macro: {
  95. auto &Macro = cast<PathDiagnosticMacroPiece>(*Piece);
  96. if (ShouldFlattenMacros) {
  97. Macro.subPieces.flattenTo(Primary, Primary, ShouldFlattenMacros);
  98. } else {
  99. Current.push_back(Piece);
  100. PathPieces NewPath;
  101. Macro.subPieces.flattenTo(Primary, NewPath, ShouldFlattenMacros);
  102. // FIXME: This probably shouldn't mutate the original path piece.
  103. Macro.subPieces = NewPath;
  104. }
  105. break;
  106. }
  107. case PathDiagnosticPiece::Event:
  108. case PathDiagnosticPiece::ControlFlow:
  109. case PathDiagnosticPiece::Note:
  110. case PathDiagnosticPiece::PopUp:
  111. Current.push_back(Piece);
  112. break;
  113. }
  114. }
  115. }
  116. PathDiagnostic::~PathDiagnostic() = default;
  117. PathDiagnostic::PathDiagnostic(
  118. StringRef CheckName, const Decl *declWithIssue, StringRef bugtype,
  119. StringRef verboseDesc, StringRef shortDesc, StringRef category,
  120. PathDiagnosticLocation LocationToUnique, const Decl *DeclToUnique,
  121. std::unique_ptr<FilesToLineNumsMap> ExecutedLines)
  122. : CheckName(CheckName), DeclWithIssue(declWithIssue),
  123. BugType(StripTrailingDots(bugtype)),
  124. VerboseDesc(StripTrailingDots(verboseDesc)),
  125. ShortDesc(StripTrailingDots(shortDesc)),
  126. Category(StripTrailingDots(category)), UniqueingLoc(LocationToUnique),
  127. UniqueingDecl(DeclToUnique), ExecutedLines(std::move(ExecutedLines)),
  128. path(pathImpl) {}
  129. static PathDiagnosticCallPiece *
  130. getFirstStackedCallToHeaderFile(PathDiagnosticCallPiece *CP,
  131. const SourceManager &SMgr) {
  132. SourceLocation CallLoc = CP->callEnter.asLocation();
  133. // If the call is within a macro, don't do anything (for now).
  134. if (CallLoc.isMacroID())
  135. return nullptr;
  136. assert(AnalysisManager::isInCodeFile(CallLoc, SMgr) &&
  137. "The call piece should not be in a header file.");
  138. // Check if CP represents a path through a function outside of the main file.
  139. if (!AnalysisManager::isInCodeFile(CP->callEnterWithin.asLocation(), SMgr))
  140. return CP;
  141. const PathPieces &Path = CP->path;
  142. if (Path.empty())
  143. return nullptr;
  144. // Check if the last piece in the callee path is a call to a function outside
  145. // of the main file.
  146. if (auto *CPInner = dyn_cast<PathDiagnosticCallPiece>(Path.back().get()))
  147. return getFirstStackedCallToHeaderFile(CPInner, SMgr);
  148. // Otherwise, the last piece is in the main file.
  149. return nullptr;
  150. }
  151. void PathDiagnostic::resetDiagnosticLocationToMainFile() {
  152. if (path.empty())
  153. return;
  154. PathDiagnosticPiece *LastP = path.back().get();
  155. assert(LastP);
  156. const SourceManager &SMgr = LastP->getLocation().getManager();
  157. // We only need to check if the report ends inside headers, if the last piece
  158. // is a call piece.
  159. if (auto *CP = dyn_cast<PathDiagnosticCallPiece>(LastP)) {
  160. CP = getFirstStackedCallToHeaderFile(CP, SMgr);
  161. if (CP) {
  162. // Mark the piece.
  163. CP->setAsLastInMainSourceFile();
  164. // Update the path diagnostic message.
  165. const auto *ND = dyn_cast<NamedDecl>(CP->getCallee());
  166. if (ND) {
  167. SmallString<200> buf;
  168. llvm::raw_svector_ostream os(buf);
  169. os << " (within a call to '" << ND->getDeclName() << "')";
  170. appendToDesc(os.str());
  171. }
  172. // Reset the report containing declaration and location.
  173. DeclWithIssue = CP->getCaller();
  174. Loc = CP->getLocation();
  175. return;
  176. }
  177. }
  178. }
  179. void PathDiagnosticConsumer::anchor() {}
  180. PathDiagnosticConsumer::~PathDiagnosticConsumer() {
  181. // Delete the contents of the FoldingSet if it isn't empty already.
  182. for (auto &Diag : Diags)
  183. delete &Diag;
  184. }
  185. void PathDiagnosticConsumer::HandlePathDiagnostic(
  186. std::unique_ptr<PathDiagnostic> D) {
  187. if (!D || D->path.empty())
  188. return;
  189. // We need to flatten the locations (convert Stmt* to locations) because
  190. // the referenced statements may be freed by the time the diagnostics
  191. // are emitted.
  192. D->flattenLocations();
  193. // If the PathDiagnosticConsumer does not support diagnostics that
  194. // cross file boundaries, prune out such diagnostics now.
  195. if (!supportsCrossFileDiagnostics()) {
  196. // Verify that the entire path is from the same FileID.
  197. FileID FID;
  198. const SourceManager &SMgr = D->path.front()->getLocation().getManager();
  199. SmallVector<const PathPieces *, 5> WorkList;
  200. WorkList.push_back(&D->path);
  201. SmallString<128> buf;
  202. llvm::raw_svector_ostream warning(buf);
  203. warning << "warning: Path diagnostic report is not generated. Current "
  204. << "output format does not support diagnostics that cross file "
  205. << "boundaries. Refer to --analyzer-output for valid output "
  206. << "formats\n";
  207. while (!WorkList.empty()) {
  208. const PathPieces &path = *WorkList.pop_back_val();
  209. for (const auto &I : path) {
  210. const PathDiagnosticPiece *piece = I.get();
  211. FullSourceLoc L = piece->getLocation().asLocation().getExpansionLoc();
  212. if (FID.isInvalid()) {
  213. FID = SMgr.getFileID(L);
  214. } else if (SMgr.getFileID(L) != FID) {
  215. llvm::errs() << warning.str();
  216. return;
  217. }
  218. // Check the source ranges.
  219. ArrayRef<SourceRange> Ranges = piece->getRanges();
  220. for (const auto &I : Ranges) {
  221. SourceLocation L = SMgr.getExpansionLoc(I.getBegin());
  222. if (!L.isFileID() || SMgr.getFileID(L) != FID) {
  223. llvm::errs() << warning.str();
  224. return;
  225. }
  226. L = SMgr.getExpansionLoc(I.getEnd());
  227. if (!L.isFileID() || SMgr.getFileID(L) != FID) {
  228. llvm::errs() << warning.str();
  229. return;
  230. }
  231. }
  232. if (const auto *call = dyn_cast<PathDiagnosticCallPiece>(piece))
  233. WorkList.push_back(&call->path);
  234. else if (const auto *macro = dyn_cast<PathDiagnosticMacroPiece>(piece))
  235. WorkList.push_back(&macro->subPieces);
  236. }
  237. }
  238. if (FID.isInvalid())
  239. return; // FIXME: Emit a warning?
  240. }
  241. // Profile the node to see if we already have something matching it
  242. llvm::FoldingSetNodeID profile;
  243. D->Profile(profile);
  244. void *InsertPos = nullptr;
  245. if (PathDiagnostic *orig = Diags.FindNodeOrInsertPos(profile, InsertPos)) {
  246. // Keep the PathDiagnostic with the shorter path.
  247. // Note, the enclosing routine is called in deterministic order, so the
  248. // results will be consistent between runs (no reason to break ties if the
  249. // size is the same).
  250. const unsigned orig_size = orig->full_size();
  251. const unsigned new_size = D->full_size();
  252. if (orig_size <= new_size)
  253. return;
  254. assert(orig != D.get());
  255. Diags.RemoveNode(orig);
  256. delete orig;
  257. }
  258. Diags.InsertNode(D.release());
  259. }
  260. static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y);
  261. static Optional<bool>
  262. compareControlFlow(const PathDiagnosticControlFlowPiece &X,
  263. const PathDiagnosticControlFlowPiece &Y) {
  264. FullSourceLoc XSL = X.getStartLocation().asLocation();
  265. FullSourceLoc YSL = Y.getStartLocation().asLocation();
  266. if (XSL != YSL)
  267. return XSL.isBeforeInTranslationUnitThan(YSL);
  268. FullSourceLoc XEL = X.getEndLocation().asLocation();
  269. FullSourceLoc YEL = Y.getEndLocation().asLocation();
  270. if (XEL != YEL)
  271. return XEL.isBeforeInTranslationUnitThan(YEL);
  272. return None;
  273. }
  274. static Optional<bool> compareMacro(const PathDiagnosticMacroPiece &X,
  275. const PathDiagnosticMacroPiece &Y) {
  276. return comparePath(X.subPieces, Y.subPieces);
  277. }
  278. static Optional<bool> compareCall(const PathDiagnosticCallPiece &X,
  279. const PathDiagnosticCallPiece &Y) {
  280. FullSourceLoc X_CEL = X.callEnter.asLocation();
  281. FullSourceLoc Y_CEL = Y.callEnter.asLocation();
  282. if (X_CEL != Y_CEL)
  283. return X_CEL.isBeforeInTranslationUnitThan(Y_CEL);
  284. FullSourceLoc X_CEWL = X.callEnterWithin.asLocation();
  285. FullSourceLoc Y_CEWL = Y.callEnterWithin.asLocation();
  286. if (X_CEWL != Y_CEWL)
  287. return X_CEWL.isBeforeInTranslationUnitThan(Y_CEWL);
  288. FullSourceLoc X_CRL = X.callReturn.asLocation();
  289. FullSourceLoc Y_CRL = Y.callReturn.asLocation();
  290. if (X_CRL != Y_CRL)
  291. return X_CRL.isBeforeInTranslationUnitThan(Y_CRL);
  292. return comparePath(X.path, Y.path);
  293. }
  294. static Optional<bool> comparePiece(const PathDiagnosticPiece &X,
  295. const PathDiagnosticPiece &Y) {
  296. if (X.getKind() != Y.getKind())
  297. return X.getKind() < Y.getKind();
  298. FullSourceLoc XL = X.getLocation().asLocation();
  299. FullSourceLoc YL = Y.getLocation().asLocation();
  300. if (XL != YL)
  301. return XL.isBeforeInTranslationUnitThan(YL);
  302. if (X.getString() != Y.getString())
  303. return X.getString() < Y.getString();
  304. if (X.getRanges().size() != Y.getRanges().size())
  305. return X.getRanges().size() < Y.getRanges().size();
  306. const SourceManager &SM = XL.getManager();
  307. for (unsigned i = 0, n = X.getRanges().size(); i < n; ++i) {
  308. SourceRange XR = X.getRanges()[i];
  309. SourceRange YR = Y.getRanges()[i];
  310. if (XR != YR) {
  311. if (XR.getBegin() != YR.getBegin())
  312. return SM.isBeforeInTranslationUnit(XR.getBegin(), YR.getBegin());
  313. return SM.isBeforeInTranslationUnit(XR.getEnd(), YR.getEnd());
  314. }
  315. }
  316. switch (X.getKind()) {
  317. case PathDiagnosticPiece::ControlFlow:
  318. return compareControlFlow(cast<PathDiagnosticControlFlowPiece>(X),
  319. cast<PathDiagnosticControlFlowPiece>(Y));
  320. case PathDiagnosticPiece::Macro:
  321. return compareMacro(cast<PathDiagnosticMacroPiece>(X),
  322. cast<PathDiagnosticMacroPiece>(Y));
  323. case PathDiagnosticPiece::Call:
  324. return compareCall(cast<PathDiagnosticCallPiece>(X),
  325. cast<PathDiagnosticCallPiece>(Y));
  326. case PathDiagnosticPiece::Event:
  327. case PathDiagnosticPiece::Note:
  328. case PathDiagnosticPiece::PopUp:
  329. return None;
  330. }
  331. llvm_unreachable("all cases handled");
  332. }
  333. static Optional<bool> comparePath(const PathPieces &X, const PathPieces &Y) {
  334. if (X.size() != Y.size())
  335. return X.size() < Y.size();
  336. PathPieces::const_iterator X_I = X.begin(), X_end = X.end();
  337. PathPieces::const_iterator Y_I = Y.begin(), Y_end = Y.end();
  338. for ( ; X_I != X_end && Y_I != Y_end; ++X_I, ++Y_I) {
  339. Optional<bool> b = comparePiece(**X_I, **Y_I);
  340. if (b.hasValue())
  341. return b.getValue();
  342. }
  343. return None;
  344. }
  345. static bool compareCrossTUSourceLocs(FullSourceLoc XL, FullSourceLoc YL) {
  346. std::pair<FileID, unsigned> XOffs = XL.getDecomposedLoc();
  347. std::pair<FileID, unsigned> YOffs = YL.getDecomposedLoc();
  348. const SourceManager &SM = XL.getManager();
  349. std::pair<bool, bool> InSameTU = SM.isInTheSameTranslationUnit(XOffs, YOffs);
  350. if (InSameTU.first)
  351. return XL.isBeforeInTranslationUnitThan(YL);
  352. const FileEntry *XFE = SM.getFileEntryForID(XL.getSpellingLoc().getFileID());
  353. const FileEntry *YFE = SM.getFileEntryForID(YL.getSpellingLoc().getFileID());
  354. if (!XFE || !YFE)
  355. return XFE && !YFE;
  356. int NameCmp = XFE->getName().compare(YFE->getName());
  357. if (NameCmp != 0)
  358. return NameCmp == -1;
  359. // Last resort: Compare raw file IDs that are possibly expansions.
  360. return XL.getFileID() < YL.getFileID();
  361. }
  362. static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y) {
  363. FullSourceLoc XL = X.getLocation().asLocation();
  364. FullSourceLoc YL = Y.getLocation().asLocation();
  365. if (XL != YL)
  366. return compareCrossTUSourceLocs(XL, YL);
  367. if (X.getBugType() != Y.getBugType())
  368. return X.getBugType() < Y.getBugType();
  369. if (X.getCategory() != Y.getCategory())
  370. return X.getCategory() < Y.getCategory();
  371. if (X.getVerboseDescription() != Y.getVerboseDescription())
  372. return X.getVerboseDescription() < Y.getVerboseDescription();
  373. if (X.getShortDescription() != Y.getShortDescription())
  374. return X.getShortDescription() < Y.getShortDescription();
  375. if (X.getDeclWithIssue() != Y.getDeclWithIssue()) {
  376. const Decl *XD = X.getDeclWithIssue();
  377. if (!XD)
  378. return true;
  379. const Decl *YD = Y.getDeclWithIssue();
  380. if (!YD)
  381. return false;
  382. SourceLocation XDL = XD->getLocation();
  383. SourceLocation YDL = YD->getLocation();
  384. if (XDL != YDL) {
  385. const SourceManager &SM = XL.getManager();
  386. return compareCrossTUSourceLocs(FullSourceLoc(XDL, SM),
  387. FullSourceLoc(YDL, SM));
  388. }
  389. }
  390. PathDiagnostic::meta_iterator XI = X.meta_begin(), XE = X.meta_end();
  391. PathDiagnostic::meta_iterator YI = Y.meta_begin(), YE = Y.meta_end();
  392. if (XE - XI != YE - YI)
  393. return (XE - XI) < (YE - YI);
  394. for ( ; XI != XE ; ++XI, ++YI) {
  395. if (*XI != *YI)
  396. return (*XI) < (*YI);
  397. }
  398. Optional<bool> b = comparePath(X.path, Y.path);
  399. assert(b.hasValue());
  400. return b.getValue();
  401. }
  402. void PathDiagnosticConsumer::FlushDiagnostics(
  403. PathDiagnosticConsumer::FilesMade *Files) {
  404. if (flushed)
  405. return;
  406. flushed = true;
  407. std::vector<const PathDiagnostic *> BatchDiags;
  408. for (const auto &D : Diags)
  409. BatchDiags.push_back(&D);
  410. // Sort the diagnostics so that they are always emitted in a deterministic
  411. // order.
  412. int (*Comp)(const PathDiagnostic *const *, const PathDiagnostic *const *) =
  413. [](const PathDiagnostic *const *X, const PathDiagnostic *const *Y) {
  414. assert(*X != *Y && "PathDiagnostics not uniqued!");
  415. if (compare(**X, **Y))
  416. return -1;
  417. assert(compare(**Y, **X) && "Not a total order!");
  418. return 1;
  419. };
  420. array_pod_sort(BatchDiags.begin(), BatchDiags.end(), Comp);
  421. FlushDiagnosticsImpl(BatchDiags, Files);
  422. // Delete the flushed diagnostics.
  423. for (const auto D : BatchDiags)
  424. delete D;
  425. // Clear out the FoldingSet.
  426. Diags.clear();
  427. }
  428. PathDiagnosticConsumer::FilesMade::~FilesMade() {
  429. for (PDFileEntry &Entry : Set)
  430. Entry.~PDFileEntry();
  431. }
  432. void PathDiagnosticConsumer::FilesMade::addDiagnostic(const PathDiagnostic &PD,
  433. StringRef ConsumerName,
  434. StringRef FileName) {
  435. llvm::FoldingSetNodeID NodeID;
  436. NodeID.Add(PD);
  437. void *InsertPos;
  438. PDFileEntry *Entry = Set.FindNodeOrInsertPos(NodeID, InsertPos);
  439. if (!Entry) {
  440. Entry = Alloc.Allocate<PDFileEntry>();
  441. Entry = new (Entry) PDFileEntry(NodeID);
  442. Set.InsertNode(Entry, InsertPos);
  443. }
  444. // Allocate persistent storage for the file name.
  445. char *FileName_cstr = (char*) Alloc.Allocate(FileName.size(), 1);
  446. memcpy(FileName_cstr, FileName.data(), FileName.size());
  447. Entry->files.push_back(std::make_pair(ConsumerName,
  448. StringRef(FileName_cstr,
  449. FileName.size())));
  450. }
  451. PathDiagnosticConsumer::PDFileEntry::ConsumerFiles *
  452. PathDiagnosticConsumer::FilesMade::getFiles(const PathDiagnostic &PD) {
  453. llvm::FoldingSetNodeID NodeID;
  454. NodeID.Add(PD);
  455. void *InsertPos;
  456. PDFileEntry *Entry = Set.FindNodeOrInsertPos(NodeID, InsertPos);
  457. if (!Entry)
  458. return nullptr;
  459. return &Entry->files;
  460. }
  461. //===----------------------------------------------------------------------===//
  462. // PathDiagnosticLocation methods.
  463. //===----------------------------------------------------------------------===//
  464. static SourceLocation getValidSourceLocation(const Stmt* S,
  465. LocationOrAnalysisDeclContext LAC,
  466. bool UseEnd = false) {
  467. SourceLocation L = UseEnd ? S->getEndLoc() : S->getBeginLoc();
  468. assert(!LAC.isNull() && "A valid LocationContext or AnalysisDeclContext should "
  469. "be passed to PathDiagnosticLocation upon creation.");
  470. // S might be a temporary statement that does not have a location in the
  471. // source code, so find an enclosing statement and use its location.
  472. if (!L.isValid()) {
  473. AnalysisDeclContext *ADC;
  474. if (LAC.is<const LocationContext*>())
  475. ADC = LAC.get<const LocationContext*>()->getAnalysisDeclContext();
  476. else
  477. ADC = LAC.get<AnalysisDeclContext*>();
  478. ParentMap &PM = ADC->getParentMap();
  479. const Stmt *Parent = S;
  480. do {
  481. Parent = PM.getParent(Parent);
  482. // In rare cases, we have implicit top-level expressions,
  483. // such as arguments for implicit member initializers.
  484. // In this case, fall back to the start of the body (even if we were
  485. // asked for the statement end location).
  486. if (!Parent) {
  487. const Stmt *Body = ADC->getBody();
  488. if (Body)
  489. L = Body->getBeginLoc();
  490. else
  491. L = ADC->getDecl()->getEndLoc();
  492. break;
  493. }
  494. L = UseEnd ? Parent->getEndLoc() : Parent->getBeginLoc();
  495. } while (!L.isValid());
  496. }
  497. // FIXME: Ironically, this assert actually fails in some cases.
  498. //assert(L.isValid());
  499. return L;
  500. }
  501. static PathDiagnosticLocation
  502. getLocationForCaller(const StackFrameContext *SFC,
  503. const LocationContext *CallerCtx,
  504. const SourceManager &SM) {
  505. const CFGBlock &Block = *SFC->getCallSiteBlock();
  506. CFGElement Source = Block[SFC->getIndex()];
  507. switch (Source.getKind()) {
  508. case CFGElement::Statement:
  509. case CFGElement::Constructor:
  510. case CFGElement::CXXRecordTypedCall:
  511. return PathDiagnosticLocation(Source.castAs<CFGStmt>().getStmt(),
  512. SM, CallerCtx);
  513. case CFGElement::Initializer: {
  514. const CFGInitializer &Init = Source.castAs<CFGInitializer>();
  515. return PathDiagnosticLocation(Init.getInitializer()->getInit(),
  516. SM, CallerCtx);
  517. }
  518. case CFGElement::AutomaticObjectDtor: {
  519. const CFGAutomaticObjDtor &Dtor = Source.castAs<CFGAutomaticObjDtor>();
  520. return PathDiagnosticLocation::createEnd(Dtor.getTriggerStmt(),
  521. SM, CallerCtx);
  522. }
  523. case CFGElement::DeleteDtor: {
  524. const CFGDeleteDtor &Dtor = Source.castAs<CFGDeleteDtor>();
  525. return PathDiagnosticLocation(Dtor.getDeleteExpr(), SM, CallerCtx);
  526. }
  527. case CFGElement::BaseDtor:
  528. case CFGElement::MemberDtor: {
  529. const AnalysisDeclContext *CallerInfo = CallerCtx->getAnalysisDeclContext();
  530. if (const Stmt *CallerBody = CallerInfo->getBody())
  531. return PathDiagnosticLocation::createEnd(CallerBody, SM, CallerCtx);
  532. return PathDiagnosticLocation::create(CallerInfo->getDecl(), SM);
  533. }
  534. case CFGElement::NewAllocator: {
  535. const CFGNewAllocator &Alloc = Source.castAs<CFGNewAllocator>();
  536. return PathDiagnosticLocation(Alloc.getAllocatorExpr(), SM, CallerCtx);
  537. }
  538. case CFGElement::TemporaryDtor: {
  539. // Temporary destructors are for temporaries. They die immediately at around
  540. // the location of CXXBindTemporaryExpr. If they are lifetime-extended,
  541. // they'd be dealt with via an AutomaticObjectDtor instead.
  542. const auto &Dtor = Source.castAs<CFGTemporaryDtor>();
  543. return PathDiagnosticLocation::createEnd(Dtor.getBindTemporaryExpr(), SM,
  544. CallerCtx);
  545. }
  546. case CFGElement::ScopeBegin:
  547. case CFGElement::ScopeEnd:
  548. llvm_unreachable("not yet implemented!");
  549. case CFGElement::LifetimeEnds:
  550. case CFGElement::LoopExit:
  551. llvm_unreachable("CFGElement kind should not be on callsite!");
  552. }
  553. llvm_unreachable("Unknown CFGElement kind");
  554. }
  555. PathDiagnosticLocation
  556. PathDiagnosticLocation::createBegin(const Decl *D,
  557. const SourceManager &SM) {
  558. return PathDiagnosticLocation(D->getBeginLoc(), SM, SingleLocK);
  559. }
  560. PathDiagnosticLocation
  561. PathDiagnosticLocation::createBegin(const Stmt *S,
  562. const SourceManager &SM,
  563. LocationOrAnalysisDeclContext LAC) {
  564. return PathDiagnosticLocation(getValidSourceLocation(S, LAC),
  565. SM, SingleLocK);
  566. }
  567. PathDiagnosticLocation
  568. PathDiagnosticLocation::createEnd(const Stmt *S,
  569. const SourceManager &SM,
  570. LocationOrAnalysisDeclContext LAC) {
  571. if (const auto *CS = dyn_cast<CompoundStmt>(S))
  572. return createEndBrace(CS, SM);
  573. return PathDiagnosticLocation(getValidSourceLocation(S, LAC, /*End=*/true),
  574. SM, SingleLocK);
  575. }
  576. PathDiagnosticLocation
  577. PathDiagnosticLocation::createOperatorLoc(const BinaryOperator *BO,
  578. const SourceManager &SM) {
  579. return PathDiagnosticLocation(BO->getOperatorLoc(), SM, SingleLocK);
  580. }
  581. PathDiagnosticLocation
  582. PathDiagnosticLocation::createConditionalColonLoc(
  583. const ConditionalOperator *CO,
  584. const SourceManager &SM) {
  585. return PathDiagnosticLocation(CO->getColonLoc(), SM, SingleLocK);
  586. }
  587. PathDiagnosticLocation
  588. PathDiagnosticLocation::createMemberLoc(const MemberExpr *ME,
  589. const SourceManager &SM) {
  590. assert(ME->getMemberLoc().isValid() || ME->getBeginLoc().isValid());
  591. // In some cases, getMemberLoc isn't valid -- in this case we'll return with
  592. // some other related valid SourceLocation.
  593. if (ME->getMemberLoc().isValid())
  594. return PathDiagnosticLocation(ME->getMemberLoc(), SM, SingleLocK);
  595. return PathDiagnosticLocation(ME->getBeginLoc(), SM, SingleLocK);
  596. }
  597. PathDiagnosticLocation
  598. PathDiagnosticLocation::createBeginBrace(const CompoundStmt *CS,
  599. const SourceManager &SM) {
  600. SourceLocation L = CS->getLBracLoc();
  601. return PathDiagnosticLocation(L, SM, SingleLocK);
  602. }
  603. PathDiagnosticLocation
  604. PathDiagnosticLocation::createEndBrace(const CompoundStmt *CS,
  605. const SourceManager &SM) {
  606. SourceLocation L = CS->getRBracLoc();
  607. return PathDiagnosticLocation(L, SM, SingleLocK);
  608. }
  609. PathDiagnosticLocation
  610. PathDiagnosticLocation::createDeclBegin(const LocationContext *LC,
  611. const SourceManager &SM) {
  612. // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
  613. if (const auto *CS = dyn_cast_or_null<CompoundStmt>(LC->getDecl()->getBody()))
  614. if (!CS->body_empty()) {
  615. SourceLocation Loc = (*CS->body_begin())->getBeginLoc();
  616. return PathDiagnosticLocation(Loc, SM, SingleLocK);
  617. }
  618. return PathDiagnosticLocation();
  619. }
  620. PathDiagnosticLocation
  621. PathDiagnosticLocation::createDeclEnd(const LocationContext *LC,
  622. const SourceManager &SM) {
  623. SourceLocation L = LC->getDecl()->getBodyRBrace();
  624. return PathDiagnosticLocation(L, SM, SingleLocK);
  625. }
  626. PathDiagnosticLocation
  627. PathDiagnosticLocation::create(const ProgramPoint& P,
  628. const SourceManager &SMng) {
  629. const Stmt* S = nullptr;
  630. if (Optional<BlockEdge> BE = P.getAs<BlockEdge>()) {
  631. const CFGBlock *BSrc = BE->getSrc();
  632. if (BSrc->getTerminator().isVirtualBaseBranch()) {
  633. // TODO: VirtualBaseBranches should also appear for destructors.
  634. // In this case we should put the diagnostic at the end of decl.
  635. return PathDiagnosticLocation::createBegin(
  636. P.getLocationContext()->getDecl(), SMng);
  637. } else {
  638. S = BSrc->getTerminatorCondition();
  639. if (!S) {
  640. // If the BlockEdge has no terminator condition statement but its
  641. // source is the entry of the CFG (e.g. a checker crated the branch at
  642. // the beginning of a function), use the function's declaration instead.
  643. assert(BSrc == &BSrc->getParent()->getEntry() && "CFGBlock has no "
  644. "TerminatorCondition and is not the enrty block of the CFG");
  645. return PathDiagnosticLocation::createBegin(
  646. P.getLocationContext()->getDecl(), SMng);
  647. }
  648. }
  649. } else if (Optional<StmtPoint> SP = P.getAs<StmtPoint>()) {
  650. S = SP->getStmt();
  651. if (P.getAs<PostStmtPurgeDeadSymbols>())
  652. return PathDiagnosticLocation::createEnd(S, SMng, P.getLocationContext());
  653. } else if (Optional<PostInitializer> PIP = P.getAs<PostInitializer>()) {
  654. return PathDiagnosticLocation(PIP->getInitializer()->getSourceLocation(),
  655. SMng);
  656. } else if (Optional<PreImplicitCall> PIC = P.getAs<PreImplicitCall>()) {
  657. return PathDiagnosticLocation(PIC->getLocation(), SMng);
  658. } else if (Optional<PostImplicitCall> PIE = P.getAs<PostImplicitCall>()) {
  659. return PathDiagnosticLocation(PIE->getLocation(), SMng);
  660. } else if (Optional<CallEnter> CE = P.getAs<CallEnter>()) {
  661. return getLocationForCaller(CE->getCalleeContext(),
  662. CE->getLocationContext(),
  663. SMng);
  664. } else if (Optional<CallExitEnd> CEE = P.getAs<CallExitEnd>()) {
  665. return getLocationForCaller(CEE->getCalleeContext(),
  666. CEE->getLocationContext(),
  667. SMng);
  668. } else if (auto CEB = P.getAs<CallExitBegin>()) {
  669. if (const ReturnStmt *RS = CEB->getReturnStmt())
  670. return PathDiagnosticLocation::createBegin(RS, SMng,
  671. CEB->getLocationContext());
  672. return PathDiagnosticLocation(
  673. CEB->getLocationContext()->getDecl()->getSourceRange().getEnd(), SMng);
  674. } else if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>()) {
  675. CFGElement BlockFront = BE->getBlock()->front();
  676. if (auto StmtElt = BlockFront.getAs<CFGStmt>()) {
  677. return PathDiagnosticLocation(StmtElt->getStmt()->getBeginLoc(), SMng);
  678. } else if (auto NewAllocElt = BlockFront.getAs<CFGNewAllocator>()) {
  679. return PathDiagnosticLocation(
  680. NewAllocElt->getAllocatorExpr()->getBeginLoc(), SMng);
  681. }
  682. llvm_unreachable("Unexpected CFG element at front of block");
  683. } else {
  684. llvm_unreachable("Unexpected ProgramPoint");
  685. }
  686. return PathDiagnosticLocation(S, SMng, P.getLocationContext());
  687. }
  688. static const LocationContext *
  689. findTopAutosynthesizedParentContext(const LocationContext *LC) {
  690. assert(LC->getAnalysisDeclContext()->isBodyAutosynthesized());
  691. const LocationContext *ParentLC = LC->getParent();
  692. assert(ParentLC && "We don't start analysis from autosynthesized code");
  693. while (ParentLC->getAnalysisDeclContext()->isBodyAutosynthesized()) {
  694. LC = ParentLC;
  695. ParentLC = LC->getParent();
  696. assert(ParentLC && "We don't start analysis from autosynthesized code");
  697. }
  698. return LC;
  699. }
  700. const Stmt *PathDiagnosticLocation::getStmt(const ExplodedNode *N) {
  701. // We cannot place diagnostics on autosynthesized code.
  702. // Put them onto the call site through which we jumped into autosynthesized
  703. // code for the first time.
  704. const LocationContext *LC = N->getLocationContext();
  705. if (LC->getAnalysisDeclContext()->isBodyAutosynthesized()) {
  706. // It must be a stack frame because we only autosynthesize functions.
  707. return cast<StackFrameContext>(findTopAutosynthesizedParentContext(LC))
  708. ->getCallSite();
  709. }
  710. // Otherwise, see if the node's program point directly points to a statement.
  711. ProgramPoint P = N->getLocation();
  712. if (auto SP = P.getAs<StmtPoint>())
  713. return SP->getStmt();
  714. if (auto BE = P.getAs<BlockEdge>())
  715. return BE->getSrc()->getTerminatorStmt();
  716. if (auto CE = P.getAs<CallEnter>())
  717. return CE->getCallExpr();
  718. if (auto CEE = P.getAs<CallExitEnd>())
  719. return CEE->getCalleeContext()->getCallSite();
  720. if (auto PIPP = P.getAs<PostInitializer>())
  721. return PIPP->getInitializer()->getInit();
  722. if (auto CEB = P.getAs<CallExitBegin>())
  723. return CEB->getReturnStmt();
  724. if (auto FEP = P.getAs<FunctionExitPoint>())
  725. return FEP->getStmt();
  726. return nullptr;
  727. }
  728. const Stmt *PathDiagnosticLocation::getNextStmt(const ExplodedNode *N) {
  729. for (N = N->getFirstSucc(); N; N = N->getFirstSucc()) {
  730. if (const Stmt *S = getStmt(N)) {
  731. // Check if the statement is '?' or '&&'/'||'. These are "merges",
  732. // not actual statement points.
  733. switch (S->getStmtClass()) {
  734. case Stmt::ChooseExprClass:
  735. case Stmt::BinaryConditionalOperatorClass:
  736. case Stmt::ConditionalOperatorClass:
  737. continue;
  738. case Stmt::BinaryOperatorClass: {
  739. BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
  740. if (Op == BO_LAnd || Op == BO_LOr)
  741. continue;
  742. break;
  743. }
  744. default:
  745. break;
  746. }
  747. // We found the statement, so return it.
  748. return S;
  749. }
  750. }
  751. return nullptr;
  752. }
  753. PathDiagnosticLocation
  754. PathDiagnosticLocation::createEndOfPath(const ExplodedNode *N,
  755. const SourceManager &SM) {
  756. assert(N && "Cannot create a location with a null node.");
  757. const Stmt *S = getStmt(N);
  758. const LocationContext *LC = N->getLocationContext();
  759. if (!S) {
  760. // If this is an implicit call, return the implicit call point location.
  761. if (Optional<PreImplicitCall> PIE = N->getLocationAs<PreImplicitCall>())
  762. return PathDiagnosticLocation(PIE->getLocation(), SM);
  763. if (auto FE = N->getLocationAs<FunctionExitPoint>()) {
  764. if (const ReturnStmt *RS = FE->getStmt())
  765. return PathDiagnosticLocation::createBegin(RS, SM, LC);
  766. }
  767. S = getNextStmt(N);
  768. }
  769. if (S) {
  770. ProgramPoint P = N->getLocation();
  771. // For member expressions, return the location of the '.' or '->'.
  772. if (const auto *ME = dyn_cast<MemberExpr>(S))
  773. return PathDiagnosticLocation::createMemberLoc(ME, SM);
  774. // For binary operators, return the location of the operator.
  775. if (const auto *B = dyn_cast<BinaryOperator>(S))
  776. return PathDiagnosticLocation::createOperatorLoc(B, SM);
  777. if (P.getAs<PostStmtPurgeDeadSymbols>())
  778. return PathDiagnosticLocation::createEnd(S, SM, LC);
  779. if (S->getBeginLoc().isValid())
  780. return PathDiagnosticLocation(S, SM, LC);
  781. return PathDiagnosticLocation(getValidSourceLocation(S, LC), SM);
  782. }
  783. return createDeclEnd(N->getLocationContext(), SM);
  784. }
  785. PathDiagnosticLocation PathDiagnosticLocation::createSingleLocation(
  786. const PathDiagnosticLocation &PDL) {
  787. FullSourceLoc L = PDL.asLocation();
  788. return PathDiagnosticLocation(L, L.getManager(), SingleLocK);
  789. }
  790. FullSourceLoc
  791. PathDiagnosticLocation::genLocation(SourceLocation L,
  792. LocationOrAnalysisDeclContext LAC) const {
  793. assert(isValid());
  794. // Note that we want a 'switch' here so that the compiler can warn us in
  795. // case we add more cases.
  796. switch (K) {
  797. case SingleLocK:
  798. case RangeK:
  799. break;
  800. case StmtK:
  801. // Defensive checking.
  802. if (!S)
  803. break;
  804. return FullSourceLoc(getValidSourceLocation(S, LAC),
  805. const_cast<SourceManager&>(*SM));
  806. case DeclK:
  807. // Defensive checking.
  808. if (!D)
  809. break;
  810. return FullSourceLoc(D->getLocation(), const_cast<SourceManager&>(*SM));
  811. }
  812. return FullSourceLoc(L, const_cast<SourceManager&>(*SM));
  813. }
  814. PathDiagnosticRange
  815. PathDiagnosticLocation::genRange(LocationOrAnalysisDeclContext LAC) const {
  816. assert(isValid());
  817. // Note that we want a 'switch' here so that the compiler can warn us in
  818. // case we add more cases.
  819. switch (K) {
  820. case SingleLocK:
  821. return PathDiagnosticRange(SourceRange(Loc,Loc), true);
  822. case RangeK:
  823. break;
  824. case StmtK: {
  825. const Stmt *S = asStmt();
  826. switch (S->getStmtClass()) {
  827. default:
  828. break;
  829. case Stmt::DeclStmtClass: {
  830. const auto *DS = cast<DeclStmt>(S);
  831. if (DS->isSingleDecl()) {
  832. // Should always be the case, but we'll be defensive.
  833. return SourceRange(DS->getBeginLoc(),
  834. DS->getSingleDecl()->getLocation());
  835. }
  836. break;
  837. }
  838. // FIXME: Provide better range information for different
  839. // terminators.
  840. case Stmt::IfStmtClass:
  841. case Stmt::WhileStmtClass:
  842. case Stmt::DoStmtClass:
  843. case Stmt::ForStmtClass:
  844. case Stmt::ChooseExprClass:
  845. case Stmt::IndirectGotoStmtClass:
  846. case Stmt::SwitchStmtClass:
  847. case Stmt::BinaryConditionalOperatorClass:
  848. case Stmt::ConditionalOperatorClass:
  849. case Stmt::ObjCForCollectionStmtClass: {
  850. SourceLocation L = getValidSourceLocation(S, LAC);
  851. return SourceRange(L, L);
  852. }
  853. }
  854. SourceRange R = S->getSourceRange();
  855. if (R.isValid())
  856. return R;
  857. break;
  858. }
  859. case DeclK:
  860. if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
  861. return MD->getSourceRange();
  862. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  863. if (Stmt *Body = FD->getBody())
  864. return Body->getSourceRange();
  865. }
  866. else {
  867. SourceLocation L = D->getLocation();
  868. return PathDiagnosticRange(SourceRange(L, L), true);
  869. }
  870. }
  871. return SourceRange(Loc, Loc);
  872. }
  873. void PathDiagnosticLocation::flatten() {
  874. if (K == StmtK) {
  875. K = RangeK;
  876. S = nullptr;
  877. D = nullptr;
  878. }
  879. else if (K == DeclK) {
  880. K = SingleLocK;
  881. S = nullptr;
  882. D = nullptr;
  883. }
  884. }
  885. //===----------------------------------------------------------------------===//
  886. // Manipulation of PathDiagnosticCallPieces.
  887. //===----------------------------------------------------------------------===//
  888. std::shared_ptr<PathDiagnosticCallPiece>
  889. PathDiagnosticCallPiece::construct(const CallExitEnd &CE,
  890. const SourceManager &SM) {
  891. const Decl *caller = CE.getLocationContext()->getDecl();
  892. PathDiagnosticLocation pos = getLocationForCaller(CE.getCalleeContext(),
  893. CE.getLocationContext(),
  894. SM);
  895. return std::shared_ptr<PathDiagnosticCallPiece>(
  896. new PathDiagnosticCallPiece(caller, pos));
  897. }
  898. PathDiagnosticCallPiece *
  899. PathDiagnosticCallPiece::construct(PathPieces &path,
  900. const Decl *caller) {
  901. std::shared_ptr<PathDiagnosticCallPiece> C(
  902. new PathDiagnosticCallPiece(path, caller));
  903. path.clear();
  904. auto *R = C.get();
  905. path.push_front(std::move(C));
  906. return R;
  907. }
  908. void PathDiagnosticCallPiece::setCallee(const CallEnter &CE,
  909. const SourceManager &SM) {
  910. const StackFrameContext *CalleeCtx = CE.getCalleeContext();
  911. Callee = CalleeCtx->getDecl();
  912. callEnterWithin = PathDiagnosticLocation::createBegin(Callee, SM);
  913. callEnter = getLocationForCaller(CalleeCtx, CE.getLocationContext(), SM);
  914. // Autosynthesized property accessors are special because we'd never
  915. // pop back up to non-autosynthesized code until we leave them.
  916. // This is not generally true for autosynthesized callees, which may call
  917. // non-autosynthesized callbacks.
  918. // Unless set here, the IsCalleeAnAutosynthesizedPropertyAccessor flag
  919. // defaults to false.
  920. if (const auto *MD = dyn_cast<ObjCMethodDecl>(Callee))
  921. IsCalleeAnAutosynthesizedPropertyAccessor = (
  922. MD->isPropertyAccessor() &&
  923. CalleeCtx->getAnalysisDeclContext()->isBodyAutosynthesized());
  924. }
  925. static void describeTemplateParameters(raw_ostream &Out,
  926. const ArrayRef<TemplateArgument> TAList,
  927. const LangOptions &LO,
  928. StringRef Prefix = StringRef(),
  929. StringRef Postfix = StringRef());
  930. static void describeTemplateParameter(raw_ostream &Out,
  931. const TemplateArgument &TArg,
  932. const LangOptions &LO) {
  933. if (TArg.getKind() == TemplateArgument::ArgKind::Pack) {
  934. describeTemplateParameters(Out, TArg.getPackAsArray(), LO);
  935. } else {
  936. TArg.print(PrintingPolicy(LO), Out);
  937. }
  938. }
  939. static void describeTemplateParameters(raw_ostream &Out,
  940. const ArrayRef<TemplateArgument> TAList,
  941. const LangOptions &LO,
  942. StringRef Prefix, StringRef Postfix) {
  943. if (TAList.empty())
  944. return;
  945. Out << Prefix;
  946. for (int I = 0, Last = TAList.size() - 1; I != Last; ++I) {
  947. describeTemplateParameter(Out, TAList[I], LO);
  948. Out << ", ";
  949. }
  950. describeTemplateParameter(Out, TAList[TAList.size() - 1], LO);
  951. Out << Postfix;
  952. }
  953. static void describeClass(raw_ostream &Out, const CXXRecordDecl *D,
  954. StringRef Prefix = StringRef()) {
  955. if (!D->getIdentifier())
  956. return;
  957. Out << Prefix << '\'' << *D;
  958. if (const auto T = dyn_cast<ClassTemplateSpecializationDecl>(D))
  959. describeTemplateParameters(Out, T->getTemplateArgs().asArray(),
  960. D->getASTContext().getLangOpts(), "<", ">");
  961. Out << '\'';
  962. }
  963. static bool describeCodeDecl(raw_ostream &Out, const Decl *D,
  964. bool ExtendedDescription,
  965. StringRef Prefix = StringRef()) {
  966. if (!D)
  967. return false;
  968. if (isa<BlockDecl>(D)) {
  969. if (ExtendedDescription)
  970. Out << Prefix << "anonymous block";
  971. return ExtendedDescription;
  972. }
  973. if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
  974. Out << Prefix;
  975. if (ExtendedDescription && !MD->isUserProvided()) {
  976. if (MD->isExplicitlyDefaulted())
  977. Out << "defaulted ";
  978. else
  979. Out << "implicit ";
  980. }
  981. if (const auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
  982. if (CD->isDefaultConstructor())
  983. Out << "default ";
  984. else if (CD->isCopyConstructor())
  985. Out << "copy ";
  986. else if (CD->isMoveConstructor())
  987. Out << "move ";
  988. Out << "constructor";
  989. describeClass(Out, MD->getParent(), " for ");
  990. } else if (isa<CXXDestructorDecl>(MD)) {
  991. if (!MD->isUserProvided()) {
  992. Out << "destructor";
  993. describeClass(Out, MD->getParent(), " for ");
  994. } else {
  995. // Use ~Foo for explicitly-written destructors.
  996. Out << "'" << *MD << "'";
  997. }
  998. } else if (MD->isCopyAssignmentOperator()) {
  999. Out << "copy assignment operator";
  1000. describeClass(Out, MD->getParent(), " for ");
  1001. } else if (MD->isMoveAssignmentOperator()) {
  1002. Out << "move assignment operator";
  1003. describeClass(Out, MD->getParent(), " for ");
  1004. } else {
  1005. if (MD->getParent()->getIdentifier())
  1006. Out << "'" << *MD->getParent() << "::" << *MD << "'";
  1007. else
  1008. Out << "'" << *MD << "'";
  1009. }
  1010. return true;
  1011. }
  1012. Out << Prefix << '\'' << cast<NamedDecl>(*D);
  1013. // Adding template parameters.
  1014. if (const auto FD = dyn_cast<FunctionDecl>(D))
  1015. if (const TemplateArgumentList *TAList =
  1016. FD->getTemplateSpecializationArgs())
  1017. describeTemplateParameters(Out, TAList->asArray(),
  1018. FD->getASTContext().getLangOpts(), "<", ">");
  1019. Out << '\'';
  1020. return true;
  1021. }
  1022. std::shared_ptr<PathDiagnosticEventPiece>
  1023. PathDiagnosticCallPiece::getCallEnterEvent() const {
  1024. // We do not produce call enters and call exits for autosynthesized property
  1025. // accessors. We do generally produce them for other functions coming from
  1026. // the body farm because they may call callbacks that bring us back into
  1027. // visible code.
  1028. if (!Callee || IsCalleeAnAutosynthesizedPropertyAccessor)
  1029. return nullptr;
  1030. SmallString<256> buf;
  1031. llvm::raw_svector_ostream Out(buf);
  1032. Out << "Calling ";
  1033. describeCodeDecl(Out, Callee, /*ExtendedDescription=*/true);
  1034. assert(callEnter.asLocation().isValid());
  1035. return std::make_shared<PathDiagnosticEventPiece>(callEnter, Out.str());
  1036. }
  1037. std::shared_ptr<PathDiagnosticEventPiece>
  1038. PathDiagnosticCallPiece::getCallEnterWithinCallerEvent() const {
  1039. if (!callEnterWithin.asLocation().isValid())
  1040. return nullptr;
  1041. if (Callee->isImplicit() || !Callee->hasBody())
  1042. return nullptr;
  1043. if (const auto *MD = dyn_cast<CXXMethodDecl>(Callee))
  1044. if (MD->isDefaulted())
  1045. return nullptr;
  1046. SmallString<256> buf;
  1047. llvm::raw_svector_ostream Out(buf);
  1048. Out << "Entered call";
  1049. describeCodeDecl(Out, Caller, /*ExtendedDescription=*/false, " from ");
  1050. return std::make_shared<PathDiagnosticEventPiece>(callEnterWithin, Out.str());
  1051. }
  1052. std::shared_ptr<PathDiagnosticEventPiece>
  1053. PathDiagnosticCallPiece::getCallExitEvent() const {
  1054. // We do not produce call enters and call exits for autosynthesized property
  1055. // accessors. We do generally produce them for other functions coming from
  1056. // the body farm because they may call callbacks that bring us back into
  1057. // visible code.
  1058. if (NoExit || IsCalleeAnAutosynthesizedPropertyAccessor)
  1059. return nullptr;
  1060. SmallString<256> buf;
  1061. llvm::raw_svector_ostream Out(buf);
  1062. if (!CallStackMessage.empty()) {
  1063. Out << CallStackMessage;
  1064. } else {
  1065. bool DidDescribe = describeCodeDecl(Out, Callee,
  1066. /*ExtendedDescription=*/false,
  1067. "Returning from ");
  1068. if (!DidDescribe)
  1069. Out << "Returning to caller";
  1070. }
  1071. assert(callReturn.asLocation().isValid());
  1072. return std::make_shared<PathDiagnosticEventPiece>(callReturn, Out.str());
  1073. }
  1074. static void compute_path_size(const PathPieces &pieces, unsigned &size) {
  1075. for (const auto &I : pieces) {
  1076. const PathDiagnosticPiece *piece = I.get();
  1077. if (const auto *cp = dyn_cast<PathDiagnosticCallPiece>(piece))
  1078. compute_path_size(cp->path, size);
  1079. else
  1080. ++size;
  1081. }
  1082. }
  1083. unsigned PathDiagnostic::full_size() {
  1084. unsigned size = 0;
  1085. compute_path_size(path, size);
  1086. return size;
  1087. }
  1088. //===----------------------------------------------------------------------===//
  1089. // FoldingSet profiling methods.
  1090. //===----------------------------------------------------------------------===//
  1091. void PathDiagnosticLocation::Profile(llvm::FoldingSetNodeID &ID) const {
  1092. ID.AddInteger(Range.getBegin().getRawEncoding());
  1093. ID.AddInteger(Range.getEnd().getRawEncoding());
  1094. ID.AddInteger(Loc.getRawEncoding());
  1095. }
  1096. void PathDiagnosticPiece::Profile(llvm::FoldingSetNodeID &ID) const {
  1097. ID.AddInteger((unsigned) getKind());
  1098. ID.AddString(str);
  1099. // FIXME: Add profiling support for code hints.
  1100. ID.AddInteger((unsigned) getDisplayHint());
  1101. ArrayRef<SourceRange> Ranges = getRanges();
  1102. for (const auto &I : Ranges) {
  1103. ID.AddInteger(I.getBegin().getRawEncoding());
  1104. ID.AddInteger(I.getEnd().getRawEncoding());
  1105. }
  1106. }
  1107. void PathDiagnosticCallPiece::Profile(llvm::FoldingSetNodeID &ID) const {
  1108. PathDiagnosticPiece::Profile(ID);
  1109. for (const auto &I : path)
  1110. ID.Add(*I);
  1111. }
  1112. void PathDiagnosticSpotPiece::Profile(llvm::FoldingSetNodeID &ID) const {
  1113. PathDiagnosticPiece::Profile(ID);
  1114. ID.Add(Pos);
  1115. }
  1116. void PathDiagnosticControlFlowPiece::Profile(llvm::FoldingSetNodeID &ID) const {
  1117. PathDiagnosticPiece::Profile(ID);
  1118. for (const auto &I : *this)
  1119. ID.Add(I);
  1120. }
  1121. void PathDiagnosticMacroPiece::Profile(llvm::FoldingSetNodeID &ID) const {
  1122. PathDiagnosticSpotPiece::Profile(ID);
  1123. for (const auto &I : subPieces)
  1124. ID.Add(*I);
  1125. }
  1126. void PathDiagnosticNotePiece::Profile(llvm::FoldingSetNodeID &ID) const {
  1127. PathDiagnosticSpotPiece::Profile(ID);
  1128. }
  1129. void PathDiagnosticPopUpPiece::Profile(llvm::FoldingSetNodeID &ID) const {
  1130. PathDiagnosticSpotPiece::Profile(ID);
  1131. }
  1132. void PathDiagnostic::Profile(llvm::FoldingSetNodeID &ID) const {
  1133. ID.Add(getLocation());
  1134. ID.AddString(BugType);
  1135. ID.AddString(VerboseDesc);
  1136. ID.AddString(Category);
  1137. }
  1138. void PathDiagnostic::FullProfile(llvm::FoldingSetNodeID &ID) const {
  1139. Profile(ID);
  1140. for (const auto &I : path)
  1141. ID.Add(*I);
  1142. for (meta_iterator I = meta_begin(), E = meta_end(); I != E; ++I)
  1143. ID.AddString(*I);
  1144. }
  1145. StackHintGenerator::~StackHintGenerator() = default;
  1146. std::string StackHintGeneratorForSymbol::getMessage(const ExplodedNode *N){
  1147. if (!N)
  1148. return getMessageForSymbolNotFound();
  1149. ProgramPoint P = N->getLocation();
  1150. CallExitEnd CExit = P.castAs<CallExitEnd>();
  1151. // FIXME: Use CallEvent to abstract this over all calls.
  1152. const Stmt *CallSite = CExit.getCalleeContext()->getCallSite();
  1153. const auto *CE = dyn_cast_or_null<CallExpr>(CallSite);
  1154. if (!CE)
  1155. return {};
  1156. // Check if one of the parameters are set to the interesting symbol.
  1157. unsigned ArgIndex = 0;
  1158. for (CallExpr::const_arg_iterator I = CE->arg_begin(),
  1159. E = CE->arg_end(); I != E; ++I, ++ArgIndex){
  1160. SVal SV = N->getSVal(*I);
  1161. // Check if the variable corresponding to the symbol is passed by value.
  1162. SymbolRef AS = SV.getAsLocSymbol();
  1163. if (AS == Sym) {
  1164. return getMessageForArg(*I, ArgIndex);
  1165. }
  1166. // Check if the parameter is a pointer to the symbol.
  1167. if (Optional<loc::MemRegionVal> Reg = SV.getAs<loc::MemRegionVal>()) {
  1168. // Do not attempt to dereference void*.
  1169. if ((*I)->getType()->isVoidPointerType())
  1170. continue;
  1171. SVal PSV = N->getState()->getSVal(Reg->getRegion());
  1172. SymbolRef AS = PSV.getAsLocSymbol();
  1173. if (AS == Sym) {
  1174. return getMessageForArg(*I, ArgIndex);
  1175. }
  1176. }
  1177. }
  1178. // Check if we are returning the interesting symbol.
  1179. SVal SV = N->getSVal(CE);
  1180. SymbolRef RetSym = SV.getAsLocSymbol();
  1181. if (RetSym == Sym) {
  1182. return getMessageForReturn(CE);
  1183. }
  1184. return getMessageForSymbolNotFound();
  1185. }
  1186. std::string StackHintGeneratorForSymbol::getMessageForArg(const Expr *ArgE,
  1187. unsigned ArgIndex) {
  1188. // Printed parameters start at 1, not 0.
  1189. ++ArgIndex;
  1190. SmallString<200> buf;
  1191. llvm::raw_svector_ostream os(buf);
  1192. os << Msg << " via " << ArgIndex << llvm::getOrdinalSuffix(ArgIndex)
  1193. << " parameter";
  1194. return os.str();
  1195. }
  1196. LLVM_DUMP_METHOD void PathPieces::dump() const {
  1197. unsigned index = 0;
  1198. for (PathPieces::const_iterator I = begin(), E = end(); I != E; ++I) {
  1199. llvm::errs() << "[" << index++ << "] ";
  1200. (*I)->dump();
  1201. llvm::errs() << "\n";
  1202. }
  1203. }
  1204. LLVM_DUMP_METHOD void PathDiagnosticCallPiece::dump() const {
  1205. llvm::errs() << "CALL\n--------------\n";
  1206. if (const Stmt *SLoc = getLocation().getStmtOrNull())
  1207. SLoc->dump();
  1208. else if (const auto *ND = dyn_cast_or_null<NamedDecl>(getCallee()))
  1209. llvm::errs() << *ND << "\n";
  1210. else
  1211. getLocation().dump();
  1212. }
  1213. LLVM_DUMP_METHOD void PathDiagnosticEventPiece::dump() const {
  1214. llvm::errs() << "EVENT\n--------------\n";
  1215. llvm::errs() << getString() << "\n";
  1216. llvm::errs() << " ---- at ----\n";
  1217. getLocation().dump();
  1218. }
  1219. LLVM_DUMP_METHOD void PathDiagnosticControlFlowPiece::dump() const {
  1220. llvm::errs() << "CONTROL\n--------------\n";
  1221. getStartLocation().dump();
  1222. llvm::errs() << " ---- to ----\n";
  1223. getEndLocation().dump();
  1224. }
  1225. LLVM_DUMP_METHOD void PathDiagnosticMacroPiece::dump() const {
  1226. llvm::errs() << "MACRO\n--------------\n";
  1227. // FIXME: Print which macro is being invoked.
  1228. }
  1229. LLVM_DUMP_METHOD void PathDiagnosticNotePiece::dump() const {
  1230. llvm::errs() << "NOTE\n--------------\n";
  1231. llvm::errs() << getString() << "\n";
  1232. llvm::errs() << " ---- at ----\n";
  1233. getLocation().dump();
  1234. }
  1235. LLVM_DUMP_METHOD void PathDiagnosticPopUpPiece::dump() const {
  1236. llvm::errs() << "POP-UP\n--------------\n";
  1237. llvm::errs() << getString() << "\n";
  1238. llvm::errs() << " ---- at ----\n";
  1239. getLocation().dump();
  1240. }
  1241. LLVM_DUMP_METHOD void PathDiagnosticLocation::dump() const {
  1242. if (!isValid()) {
  1243. llvm::errs() << "<INVALID>\n";
  1244. return;
  1245. }
  1246. switch (K) {
  1247. case RangeK:
  1248. // FIXME: actually print the range.
  1249. llvm::errs() << "<range>\n";
  1250. break;
  1251. case SingleLocK:
  1252. asLocation().dump();
  1253. llvm::errs() << "\n";
  1254. break;
  1255. case StmtK:
  1256. if (S)
  1257. S->dump();
  1258. else
  1259. llvm::errs() << "<NULL STMT>\n";
  1260. break;
  1261. case DeclK:
  1262. if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
  1263. llvm::errs() << *ND << "\n";
  1264. else if (isa<BlockDecl>(D))
  1265. // FIXME: Make this nicer.
  1266. llvm::errs() << "<block>\n";
  1267. else if (D)
  1268. llvm::errs() << "<unknown decl>\n";
  1269. else
  1270. llvm::errs() << "<NULL DECL>\n";
  1271. break;
  1272. }
  1273. }