AnalysisBasedWarnings.cpp 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282
  1. //=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
  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 analysis_warnings::[Policy,Executor].
  10. // Together they are used by Sema to issue warnings based on inexpensive
  11. // static analysis algorithms in libAnalysis.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Sema/AnalysisBasedWarnings.h"
  15. #include "clang/AST/DeclCXX.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/EvaluatedExprVisitor.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ExprObjC.h"
  20. #include "clang/AST/ParentMap.h"
  21. #include "clang/AST/RecursiveASTVisitor.h"
  22. #include "clang/AST/StmtCXX.h"
  23. #include "clang/AST/StmtObjC.h"
  24. #include "clang/AST/StmtVisitor.h"
  25. #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
  26. #include "clang/Analysis/Analyses/Consumed.h"
  27. #include "clang/Analysis/Analyses/ReachableCode.h"
  28. #include "clang/Analysis/Analyses/ThreadSafety.h"
  29. #include "clang/Analysis/Analyses/UninitializedValues.h"
  30. #include "clang/Analysis/AnalysisDeclContext.h"
  31. #include "clang/Analysis/CFG.h"
  32. #include "clang/Analysis/CFGStmtMap.h"
  33. #include "clang/Basic/SourceLocation.h"
  34. #include "clang/Basic/SourceManager.h"
  35. #include "clang/Lex/Preprocessor.h"
  36. #include "clang/Sema/ScopeInfo.h"
  37. #include "clang/Sema/SemaInternal.h"
  38. #include "llvm/ADT/BitVector.h"
  39. #include "llvm/ADT/MapVector.h"
  40. #include "llvm/ADT/SmallString.h"
  41. #include "llvm/ADT/SmallVector.h"
  42. #include "llvm/ADT/StringRef.h"
  43. #include "llvm/Support/Casting.h"
  44. #include <algorithm>
  45. #include <deque>
  46. #include <iterator>
  47. using namespace clang;
  48. //===----------------------------------------------------------------------===//
  49. // Unreachable code analysis.
  50. //===----------------------------------------------------------------------===//
  51. namespace {
  52. class UnreachableCodeHandler : public reachable_code::Callback {
  53. Sema &S;
  54. SourceRange PreviousSilenceableCondVal;
  55. public:
  56. UnreachableCodeHandler(Sema &s) : S(s) {}
  57. void HandleUnreachable(reachable_code::UnreachableKind UK,
  58. SourceLocation L,
  59. SourceRange SilenceableCondVal,
  60. SourceRange R1,
  61. SourceRange R2) override {
  62. // Avoid reporting multiple unreachable code diagnostics that are
  63. // triggered by the same conditional value.
  64. if (PreviousSilenceableCondVal.isValid() &&
  65. SilenceableCondVal.isValid() &&
  66. PreviousSilenceableCondVal == SilenceableCondVal)
  67. return;
  68. PreviousSilenceableCondVal = SilenceableCondVal;
  69. unsigned diag = diag::warn_unreachable;
  70. switch (UK) {
  71. case reachable_code::UK_Break:
  72. diag = diag::warn_unreachable_break;
  73. break;
  74. case reachable_code::UK_Return:
  75. diag = diag::warn_unreachable_return;
  76. break;
  77. case reachable_code::UK_Loop_Increment:
  78. diag = diag::warn_unreachable_loop_increment;
  79. break;
  80. case reachable_code::UK_Other:
  81. break;
  82. }
  83. S.Diag(L, diag) << R1 << R2;
  84. SourceLocation Open = SilenceableCondVal.getBegin();
  85. if (Open.isValid()) {
  86. SourceLocation Close = SilenceableCondVal.getEnd();
  87. Close = S.getLocForEndOfToken(Close);
  88. if (Close.isValid()) {
  89. S.Diag(Open, diag::note_unreachable_silence)
  90. << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
  91. << FixItHint::CreateInsertion(Close, ")");
  92. }
  93. }
  94. }
  95. };
  96. } // anonymous namespace
  97. /// CheckUnreachable - Check for unreachable code.
  98. static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
  99. // As a heuristic prune all diagnostics not in the main file. Currently
  100. // the majority of warnings in headers are false positives. These
  101. // are largely caused by configuration state, e.g. preprocessor
  102. // defined code, etc.
  103. //
  104. // Note that this is also a performance optimization. Analyzing
  105. // headers many times can be expensive.
  106. if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc()))
  107. return;
  108. UnreachableCodeHandler UC(S);
  109. reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
  110. }
  111. namespace {
  112. /// Warn on logical operator errors in CFGBuilder
  113. class LogicalErrorHandler : public CFGCallback {
  114. Sema &S;
  115. public:
  116. LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
  117. static bool HasMacroID(const Expr *E) {
  118. if (E->getExprLoc().isMacroID())
  119. return true;
  120. // Recurse to children.
  121. for (const Stmt *SubStmt : E->children())
  122. if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
  123. if (HasMacroID(SubExpr))
  124. return true;
  125. return false;
  126. }
  127. void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
  128. if (HasMacroID(B))
  129. return;
  130. SourceRange DiagRange = B->getSourceRange();
  131. S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
  132. << DiagRange << isAlwaysTrue;
  133. }
  134. void compareBitwiseEquality(const BinaryOperator *B,
  135. bool isAlwaysTrue) override {
  136. if (HasMacroID(B))
  137. return;
  138. SourceRange DiagRange = B->getSourceRange();
  139. S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
  140. << DiagRange << isAlwaysTrue;
  141. }
  142. };
  143. } // anonymous namespace
  144. //===----------------------------------------------------------------------===//
  145. // Check for infinite self-recursion in functions
  146. //===----------------------------------------------------------------------===//
  147. // Returns true if the function is called anywhere within the CFGBlock.
  148. // For member functions, the additional condition of being call from the
  149. // this pointer is required.
  150. static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
  151. // Process all the Stmt's in this block to find any calls to FD.
  152. for (const auto &B : Block) {
  153. if (B.getKind() != CFGElement::Statement)
  154. continue;
  155. const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
  156. if (!CE || !CE->getCalleeDecl() ||
  157. CE->getCalleeDecl()->getCanonicalDecl() != FD)
  158. continue;
  159. // Skip function calls which are qualified with a templated class.
  160. if (const DeclRefExpr *DRE =
  161. dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
  162. if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
  163. if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
  164. isa<TemplateSpecializationType>(NNS->getAsType())) {
  165. continue;
  166. }
  167. }
  168. }
  169. const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
  170. if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
  171. !MCE->getMethodDecl()->isVirtual())
  172. return true;
  173. }
  174. return false;
  175. }
  176. // Returns true if every path from the entry block passes through a call to FD.
  177. static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
  178. llvm::SmallPtrSet<CFGBlock *, 16> Visited;
  179. llvm::SmallVector<CFGBlock *, 16> WorkList;
  180. // Keep track of whether we found at least one recursive path.
  181. bool foundRecursion = false;
  182. const unsigned ExitID = cfg->getExit().getBlockID();
  183. // Seed the work list with the entry block.
  184. WorkList.push_back(&cfg->getEntry());
  185. while (!WorkList.empty()) {
  186. CFGBlock *Block = WorkList.pop_back_val();
  187. for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
  188. if (CFGBlock *SuccBlock = *I) {
  189. if (!Visited.insert(SuccBlock).second)
  190. continue;
  191. // Found a path to the exit node without a recursive call.
  192. if (ExitID == SuccBlock->getBlockID())
  193. return false;
  194. // If the successor block contains a recursive call, end analysis there.
  195. if (hasRecursiveCallInPath(FD, *SuccBlock)) {
  196. foundRecursion = true;
  197. continue;
  198. }
  199. WorkList.push_back(SuccBlock);
  200. }
  201. }
  202. }
  203. return foundRecursion;
  204. }
  205. static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
  206. const Stmt *Body, AnalysisDeclContext &AC) {
  207. FD = FD->getCanonicalDecl();
  208. // Only run on non-templated functions and non-templated members of
  209. // templated classes.
  210. if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
  211. FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
  212. return;
  213. CFG *cfg = AC.getCFG();
  214. if (!cfg) return;
  215. // If the exit block is unreachable, skip processing the function.
  216. if (cfg->getExit().pred_empty())
  217. return;
  218. // Emit diagnostic if a recursive function call is detected for all paths.
  219. if (checkForRecursiveFunctionCall(FD, cfg))
  220. S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function);
  221. }
  222. //===----------------------------------------------------------------------===//
  223. // Check for throw in a non-throwing function.
  224. //===----------------------------------------------------------------------===//
  225. /// Determine whether an exception thrown by E, unwinding from ThrowBlock,
  226. /// can reach ExitBlock.
  227. static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
  228. CFG *Body) {
  229. SmallVector<CFGBlock *, 16> Stack;
  230. llvm::BitVector Queued(Body->getNumBlockIDs());
  231. Stack.push_back(&ThrowBlock);
  232. Queued[ThrowBlock.getBlockID()] = true;
  233. while (!Stack.empty()) {
  234. CFGBlock &UnwindBlock = *Stack.back();
  235. Stack.pop_back();
  236. for (auto &Succ : UnwindBlock.succs()) {
  237. if (!Succ.isReachable() || Queued[Succ->getBlockID()])
  238. continue;
  239. if (Succ->getBlockID() == Body->getExit().getBlockID())
  240. return true;
  241. if (auto *Catch =
  242. dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
  243. QualType Caught = Catch->getCaughtType();
  244. if (Caught.isNull() || // catch (...) catches everything
  245. !E->getSubExpr() || // throw; is considered cuaght by any handler
  246. S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
  247. // Exception doesn't escape via this path.
  248. break;
  249. } else {
  250. Stack.push_back(Succ);
  251. Queued[Succ->getBlockID()] = true;
  252. }
  253. }
  254. }
  255. return false;
  256. }
  257. static void visitReachableThrows(
  258. CFG *BodyCFG,
  259. llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
  260. llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
  261. clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
  262. for (CFGBlock *B : *BodyCFG) {
  263. if (!Reachable[B->getBlockID()])
  264. continue;
  265. for (CFGElement &E : *B) {
  266. Optional<CFGStmt> S = E.getAs<CFGStmt>();
  267. if (!S)
  268. continue;
  269. if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
  270. Visit(Throw, *B);
  271. }
  272. }
  273. }
  274. static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
  275. const FunctionDecl *FD) {
  276. if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
  277. FD->getTypeSourceInfo()) {
  278. S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
  279. if (S.getLangOpts().CPlusPlus11 &&
  280. (isa<CXXDestructorDecl>(FD) ||
  281. FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
  282. FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
  283. if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
  284. getAs<FunctionProtoType>())
  285. S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
  286. << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
  287. << FD->getExceptionSpecSourceRange();
  288. } else
  289. S.Diag(FD->getLocation(), diag::note_throw_in_function)
  290. << FD->getExceptionSpecSourceRange();
  291. }
  292. }
  293. static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
  294. AnalysisDeclContext &AC) {
  295. CFG *BodyCFG = AC.getCFG();
  296. if (!BodyCFG)
  297. return;
  298. if (BodyCFG->getExit().pred_empty())
  299. return;
  300. visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
  301. if (throwEscapes(S, Throw, Block, BodyCFG))
  302. EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
  303. });
  304. }
  305. static bool isNoexcept(const FunctionDecl *FD) {
  306. const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  307. if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
  308. return true;
  309. return false;
  310. }
  311. //===----------------------------------------------------------------------===//
  312. // Check for missing return value.
  313. //===----------------------------------------------------------------------===//
  314. enum ControlFlowKind {
  315. UnknownFallThrough,
  316. NeverFallThrough,
  317. MaybeFallThrough,
  318. AlwaysFallThrough,
  319. NeverFallThroughOrReturn
  320. };
  321. /// CheckFallThrough - Check that we don't fall off the end of a
  322. /// Statement that should return a value.
  323. ///
  324. /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
  325. /// MaybeFallThrough iff we might or might not fall off the end,
  326. /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
  327. /// return. We assume NeverFallThrough iff we never fall off the end of the
  328. /// statement but we may return. We assume that functions not marked noreturn
  329. /// will return.
  330. static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
  331. CFG *cfg = AC.getCFG();
  332. if (!cfg) return UnknownFallThrough;
  333. // The CFG leaves in dead things, and we don't want the dead code paths to
  334. // confuse us, so we mark all live things first.
  335. llvm::BitVector live(cfg->getNumBlockIDs());
  336. unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
  337. live);
  338. bool AddEHEdges = AC.getAddEHEdges();
  339. if (!AddEHEdges && count != cfg->getNumBlockIDs())
  340. // When there are things remaining dead, and we didn't add EH edges
  341. // from CallExprs to the catch clauses, we have to go back and
  342. // mark them as live.
  343. for (const auto *B : *cfg) {
  344. if (!live[B->getBlockID()]) {
  345. if (B->pred_begin() == B->pred_end()) {
  346. const Stmt *Term = B->getTerminatorStmt();
  347. if (Term && isa<CXXTryStmt>(Term))
  348. // When not adding EH edges from calls, catch clauses
  349. // can otherwise seem dead. Avoid noting them as dead.
  350. count += reachable_code::ScanReachableFromBlock(B, live);
  351. continue;
  352. }
  353. }
  354. }
  355. // Now we know what is live, we check the live precessors of the exit block
  356. // and look for fall through paths, being careful to ignore normal returns,
  357. // and exceptional paths.
  358. bool HasLiveReturn = false;
  359. bool HasFakeEdge = false;
  360. bool HasPlainEdge = false;
  361. bool HasAbnormalEdge = false;
  362. // Ignore default cases that aren't likely to be reachable because all
  363. // enums in a switch(X) have explicit case statements.
  364. CFGBlock::FilterOptions FO;
  365. FO.IgnoreDefaultsWithCoveredEnums = 1;
  366. for (CFGBlock::filtered_pred_iterator I =
  367. cfg->getExit().filtered_pred_start_end(FO);
  368. I.hasMore(); ++I) {
  369. const CFGBlock &B = **I;
  370. if (!live[B.getBlockID()])
  371. continue;
  372. // Skip blocks which contain an element marked as no-return. They don't
  373. // represent actually viable edges into the exit block, so mark them as
  374. // abnormal.
  375. if (B.hasNoReturnElement()) {
  376. HasAbnormalEdge = true;
  377. continue;
  378. }
  379. // Destructors can appear after the 'return' in the CFG. This is
  380. // normal. We need to look pass the destructors for the return
  381. // statement (if it exists).
  382. CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
  383. for ( ; ri != re ; ++ri)
  384. if (ri->getAs<CFGStmt>())
  385. break;
  386. // No more CFGElements in the block?
  387. if (ri == re) {
  388. const Stmt *Term = B.getTerminatorStmt();
  389. if (Term && isa<CXXTryStmt>(Term)) {
  390. HasAbnormalEdge = true;
  391. continue;
  392. }
  393. // A labeled empty statement, or the entry block...
  394. HasPlainEdge = true;
  395. continue;
  396. }
  397. CFGStmt CS = ri->castAs<CFGStmt>();
  398. const Stmt *S = CS.getStmt();
  399. if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
  400. HasLiveReturn = true;
  401. continue;
  402. }
  403. if (isa<ObjCAtThrowStmt>(S)) {
  404. HasFakeEdge = true;
  405. continue;
  406. }
  407. if (isa<CXXThrowExpr>(S)) {
  408. HasFakeEdge = true;
  409. continue;
  410. }
  411. if (isa<MSAsmStmt>(S)) {
  412. // TODO: Verify this is correct.
  413. HasFakeEdge = true;
  414. HasLiveReturn = true;
  415. continue;
  416. }
  417. if (isa<CXXTryStmt>(S)) {
  418. HasAbnormalEdge = true;
  419. continue;
  420. }
  421. if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
  422. == B.succ_end()) {
  423. HasAbnormalEdge = true;
  424. continue;
  425. }
  426. HasPlainEdge = true;
  427. }
  428. if (!HasPlainEdge) {
  429. if (HasLiveReturn)
  430. return NeverFallThrough;
  431. return NeverFallThroughOrReturn;
  432. }
  433. if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
  434. return MaybeFallThrough;
  435. // This says AlwaysFallThrough for calls to functions that are not marked
  436. // noreturn, that don't return. If people would like this warning to be more
  437. // accurate, such functions should be marked as noreturn.
  438. return AlwaysFallThrough;
  439. }
  440. namespace {
  441. struct CheckFallThroughDiagnostics {
  442. unsigned diag_MaybeFallThrough_HasNoReturn;
  443. unsigned diag_MaybeFallThrough_ReturnsNonVoid;
  444. unsigned diag_AlwaysFallThrough_HasNoReturn;
  445. unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
  446. unsigned diag_NeverFallThroughOrReturn;
  447. enum { Function, Block, Lambda, Coroutine } funMode;
  448. SourceLocation FuncLoc;
  449. static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
  450. CheckFallThroughDiagnostics D;
  451. D.FuncLoc = Func->getLocation();
  452. D.diag_MaybeFallThrough_HasNoReturn =
  453. diag::warn_falloff_noreturn_function;
  454. D.diag_MaybeFallThrough_ReturnsNonVoid =
  455. diag::warn_maybe_falloff_nonvoid_function;
  456. D.diag_AlwaysFallThrough_HasNoReturn =
  457. diag::warn_falloff_noreturn_function;
  458. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  459. diag::warn_falloff_nonvoid_function;
  460. // Don't suggest that virtual functions be marked "noreturn", since they
  461. // might be overridden by non-noreturn functions.
  462. bool isVirtualMethod = false;
  463. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
  464. isVirtualMethod = Method->isVirtual();
  465. // Don't suggest that template instantiations be marked "noreturn"
  466. bool isTemplateInstantiation = false;
  467. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
  468. isTemplateInstantiation = Function->isTemplateInstantiation();
  469. if (!isVirtualMethod && !isTemplateInstantiation)
  470. D.diag_NeverFallThroughOrReturn =
  471. diag::warn_suggest_noreturn_function;
  472. else
  473. D.diag_NeverFallThroughOrReturn = 0;
  474. D.funMode = Function;
  475. return D;
  476. }
  477. static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
  478. CheckFallThroughDiagnostics D;
  479. D.FuncLoc = Func->getLocation();
  480. D.diag_MaybeFallThrough_HasNoReturn = 0;
  481. D.diag_MaybeFallThrough_ReturnsNonVoid =
  482. diag::warn_maybe_falloff_nonvoid_coroutine;
  483. D.diag_AlwaysFallThrough_HasNoReturn = 0;
  484. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  485. diag::warn_falloff_nonvoid_coroutine;
  486. D.funMode = Coroutine;
  487. return D;
  488. }
  489. static CheckFallThroughDiagnostics MakeForBlock() {
  490. CheckFallThroughDiagnostics D;
  491. D.diag_MaybeFallThrough_HasNoReturn =
  492. diag::err_noreturn_block_has_return_expr;
  493. D.diag_MaybeFallThrough_ReturnsNonVoid =
  494. diag::err_maybe_falloff_nonvoid_block;
  495. D.diag_AlwaysFallThrough_HasNoReturn =
  496. diag::err_noreturn_block_has_return_expr;
  497. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  498. diag::err_falloff_nonvoid_block;
  499. D.diag_NeverFallThroughOrReturn = 0;
  500. D.funMode = Block;
  501. return D;
  502. }
  503. static CheckFallThroughDiagnostics MakeForLambda() {
  504. CheckFallThroughDiagnostics D;
  505. D.diag_MaybeFallThrough_HasNoReturn =
  506. diag::err_noreturn_lambda_has_return_expr;
  507. D.diag_MaybeFallThrough_ReturnsNonVoid =
  508. diag::warn_maybe_falloff_nonvoid_lambda;
  509. D.diag_AlwaysFallThrough_HasNoReturn =
  510. diag::err_noreturn_lambda_has_return_expr;
  511. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  512. diag::warn_falloff_nonvoid_lambda;
  513. D.diag_NeverFallThroughOrReturn = 0;
  514. D.funMode = Lambda;
  515. return D;
  516. }
  517. bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
  518. bool HasNoReturn) const {
  519. if (funMode == Function) {
  520. return (ReturnsVoid ||
  521. D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
  522. FuncLoc)) &&
  523. (!HasNoReturn ||
  524. D.isIgnored(diag::warn_noreturn_function_has_return_expr,
  525. FuncLoc)) &&
  526. (!ReturnsVoid ||
  527. D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
  528. }
  529. if (funMode == Coroutine) {
  530. return (ReturnsVoid ||
  531. D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
  532. D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
  533. FuncLoc)) &&
  534. (!HasNoReturn);
  535. }
  536. // For blocks / lambdas.
  537. return ReturnsVoid && !HasNoReturn;
  538. }
  539. };
  540. } // anonymous namespace
  541. /// CheckFallThroughForBody - Check that we don't fall off the end of a
  542. /// function that should return a value. Check that we don't fall off the end
  543. /// of a noreturn function. We assume that functions and blocks not marked
  544. /// noreturn will return.
  545. static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
  546. QualType BlockType,
  547. const CheckFallThroughDiagnostics &CD,
  548. AnalysisDeclContext &AC,
  549. sema::FunctionScopeInfo *FSI) {
  550. bool ReturnsVoid = false;
  551. bool HasNoReturn = false;
  552. bool IsCoroutine = FSI->isCoroutine();
  553. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  554. if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
  555. ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
  556. else
  557. ReturnsVoid = FD->getReturnType()->isVoidType();
  558. HasNoReturn = FD->isNoReturn();
  559. }
  560. else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  561. ReturnsVoid = MD->getReturnType()->isVoidType();
  562. HasNoReturn = MD->hasAttr<NoReturnAttr>();
  563. }
  564. else if (isa<BlockDecl>(D)) {
  565. if (const FunctionType *FT =
  566. BlockType->getPointeeType()->getAs<FunctionType>()) {
  567. if (FT->getReturnType()->isVoidType())
  568. ReturnsVoid = true;
  569. if (FT->getNoReturnAttr())
  570. HasNoReturn = true;
  571. }
  572. }
  573. DiagnosticsEngine &Diags = S.getDiagnostics();
  574. // Short circuit for compilation speed.
  575. if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
  576. return;
  577. SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc();
  578. auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
  579. if (IsCoroutine)
  580. S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
  581. else
  582. S.Diag(Loc, DiagID);
  583. };
  584. // cpu_dispatch functions permit empty function bodies for ICC compatibility.
  585. if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
  586. return;
  587. // Either in a function body compound statement, or a function-try-block.
  588. switch (CheckFallThrough(AC)) {
  589. case UnknownFallThrough:
  590. break;
  591. case MaybeFallThrough:
  592. if (HasNoReturn)
  593. EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
  594. else if (!ReturnsVoid)
  595. EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
  596. break;
  597. case AlwaysFallThrough:
  598. if (HasNoReturn)
  599. EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
  600. else if (!ReturnsVoid)
  601. EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
  602. break;
  603. case NeverFallThroughOrReturn:
  604. if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
  605. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  606. S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
  607. } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  608. S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
  609. } else {
  610. S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
  611. }
  612. }
  613. break;
  614. case NeverFallThrough:
  615. break;
  616. }
  617. }
  618. //===----------------------------------------------------------------------===//
  619. // -Wuninitialized
  620. //===----------------------------------------------------------------------===//
  621. namespace {
  622. /// ContainsReference - A visitor class to search for references to
  623. /// a particular declaration (the needle) within any evaluated component of an
  624. /// expression (recursively).
  625. class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
  626. bool FoundReference;
  627. const DeclRefExpr *Needle;
  628. public:
  629. typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
  630. ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
  631. : Inherited(Context), FoundReference(false), Needle(Needle) {}
  632. void VisitExpr(const Expr *E) {
  633. // Stop evaluating if we already have a reference.
  634. if (FoundReference)
  635. return;
  636. Inherited::VisitExpr(E);
  637. }
  638. void VisitDeclRefExpr(const DeclRefExpr *E) {
  639. if (E == Needle)
  640. FoundReference = true;
  641. else
  642. Inherited::VisitDeclRefExpr(E);
  643. }
  644. bool doesContainReference() const { return FoundReference; }
  645. };
  646. } // anonymous namespace
  647. static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
  648. QualType VariableTy = VD->getType().getCanonicalType();
  649. if (VariableTy->isBlockPointerType() &&
  650. !VD->hasAttr<BlocksAttr>()) {
  651. S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
  652. << VD->getDeclName()
  653. << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
  654. return true;
  655. }
  656. // Don't issue a fixit if there is already an initializer.
  657. if (VD->getInit())
  658. return false;
  659. // Don't suggest a fixit inside macros.
  660. if (VD->getEndLoc().isMacroID())
  661. return false;
  662. SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
  663. // Suggest possible initialization (if any).
  664. std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
  665. if (Init.empty())
  666. return false;
  667. S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
  668. << FixItHint::CreateInsertion(Loc, Init);
  669. return true;
  670. }
  671. /// Create a fixit to remove an if-like statement, on the assumption that its
  672. /// condition is CondVal.
  673. static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
  674. const Stmt *Else, bool CondVal,
  675. FixItHint &Fixit1, FixItHint &Fixit2) {
  676. if (CondVal) {
  677. // If condition is always true, remove all but the 'then'.
  678. Fixit1 = FixItHint::CreateRemoval(
  679. CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc()));
  680. if (Else) {
  681. SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc());
  682. Fixit2 =
  683. FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc()));
  684. }
  685. } else {
  686. // If condition is always false, remove all but the 'else'.
  687. if (Else)
  688. Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange(
  689. If->getBeginLoc(), Else->getBeginLoc()));
  690. else
  691. Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
  692. }
  693. }
  694. /// DiagUninitUse -- Helper function to produce a diagnostic for an
  695. /// uninitialized use of a variable.
  696. static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
  697. bool IsCapturedByBlock) {
  698. bool Diagnosed = false;
  699. switch (Use.getKind()) {
  700. case UninitUse::Always:
  701. S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var)
  702. << VD->getDeclName() << IsCapturedByBlock
  703. << Use.getUser()->getSourceRange();
  704. return;
  705. case UninitUse::AfterDecl:
  706. case UninitUse::AfterCall:
  707. S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
  708. << VD->getDeclName() << IsCapturedByBlock
  709. << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
  710. << const_cast<DeclContext*>(VD->getLexicalDeclContext())
  711. << VD->getSourceRange();
  712. S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use)
  713. << IsCapturedByBlock << Use.getUser()->getSourceRange();
  714. return;
  715. case UninitUse::Maybe:
  716. case UninitUse::Sometimes:
  717. // Carry on to report sometimes-uninitialized branches, if possible,
  718. // or a 'may be used uninitialized' diagnostic otherwise.
  719. break;
  720. }
  721. // Diagnose each branch which leads to a sometimes-uninitialized use.
  722. for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
  723. I != E; ++I) {
  724. assert(Use.getKind() == UninitUse::Sometimes);
  725. const Expr *User = Use.getUser();
  726. const Stmt *Term = I->Terminator;
  727. // Information used when building the diagnostic.
  728. unsigned DiagKind;
  729. StringRef Str;
  730. SourceRange Range;
  731. // FixIts to suppress the diagnostic by removing the dead condition.
  732. // For all binary terminators, branch 0 is taken if the condition is true,
  733. // and branch 1 is taken if the condition is false.
  734. int RemoveDiagKind = -1;
  735. const char *FixitStr =
  736. S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
  737. : (I->Output ? "1" : "0");
  738. FixItHint Fixit1, Fixit2;
  739. switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
  740. default:
  741. // Don't know how to report this. Just fall back to 'may be used
  742. // uninitialized'. FIXME: Can this happen?
  743. continue;
  744. // "condition is true / condition is false".
  745. case Stmt::IfStmtClass: {
  746. const IfStmt *IS = cast<IfStmt>(Term);
  747. DiagKind = 0;
  748. Str = "if";
  749. Range = IS->getCond()->getSourceRange();
  750. RemoveDiagKind = 0;
  751. CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
  752. I->Output, Fixit1, Fixit2);
  753. break;
  754. }
  755. case Stmt::ConditionalOperatorClass: {
  756. const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
  757. DiagKind = 0;
  758. Str = "?:";
  759. Range = CO->getCond()->getSourceRange();
  760. RemoveDiagKind = 0;
  761. CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
  762. I->Output, Fixit1, Fixit2);
  763. break;
  764. }
  765. case Stmt::BinaryOperatorClass: {
  766. const BinaryOperator *BO = cast<BinaryOperator>(Term);
  767. if (!BO->isLogicalOp())
  768. continue;
  769. DiagKind = 0;
  770. Str = BO->getOpcodeStr();
  771. Range = BO->getLHS()->getSourceRange();
  772. RemoveDiagKind = 0;
  773. if ((BO->getOpcode() == BO_LAnd && I->Output) ||
  774. (BO->getOpcode() == BO_LOr && !I->Output))
  775. // true && y -> y, false || y -> y.
  776. Fixit1 = FixItHint::CreateRemoval(
  777. SourceRange(BO->getBeginLoc(), BO->getOperatorLoc()));
  778. else
  779. // false && y -> false, true || y -> true.
  780. Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
  781. break;
  782. }
  783. // "loop is entered / loop is exited".
  784. case Stmt::WhileStmtClass:
  785. DiagKind = 1;
  786. Str = "while";
  787. Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
  788. RemoveDiagKind = 1;
  789. Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
  790. break;
  791. case Stmt::ForStmtClass:
  792. DiagKind = 1;
  793. Str = "for";
  794. Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
  795. RemoveDiagKind = 1;
  796. if (I->Output)
  797. Fixit1 = FixItHint::CreateRemoval(Range);
  798. else
  799. Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
  800. break;
  801. case Stmt::CXXForRangeStmtClass:
  802. if (I->Output == 1) {
  803. // The use occurs if a range-based for loop's body never executes.
  804. // That may be impossible, and there's no syntactic fix for this,
  805. // so treat it as a 'may be uninitialized' case.
  806. continue;
  807. }
  808. DiagKind = 1;
  809. Str = "for";
  810. Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
  811. break;
  812. // "condition is true / loop is exited".
  813. case Stmt::DoStmtClass:
  814. DiagKind = 2;
  815. Str = "do";
  816. Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
  817. RemoveDiagKind = 1;
  818. Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
  819. break;
  820. // "switch case is taken".
  821. case Stmt::CaseStmtClass:
  822. DiagKind = 3;
  823. Str = "case";
  824. Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
  825. break;
  826. case Stmt::DefaultStmtClass:
  827. DiagKind = 3;
  828. Str = "default";
  829. Range = cast<DefaultStmt>(Term)->getDefaultLoc();
  830. break;
  831. }
  832. S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
  833. << VD->getDeclName() << IsCapturedByBlock << DiagKind
  834. << Str << I->Output << Range;
  835. S.Diag(User->getBeginLoc(), diag::note_uninit_var_use)
  836. << IsCapturedByBlock << User->getSourceRange();
  837. if (RemoveDiagKind != -1)
  838. S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
  839. << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
  840. Diagnosed = true;
  841. }
  842. if (!Diagnosed)
  843. S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var)
  844. << VD->getDeclName() << IsCapturedByBlock
  845. << Use.getUser()->getSourceRange();
  846. }
  847. /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
  848. /// uninitialized variable. This manages the different forms of diagnostic
  849. /// emitted for particular types of uses. Returns true if the use was diagnosed
  850. /// as a warning. If a particular use is one we omit warnings for, returns
  851. /// false.
  852. static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
  853. const UninitUse &Use,
  854. bool alwaysReportSelfInit = false) {
  855. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
  856. // Inspect the initializer of the variable declaration which is
  857. // being referenced prior to its initialization. We emit
  858. // specialized diagnostics for self-initialization, and we
  859. // specifically avoid warning about self references which take the
  860. // form of:
  861. //
  862. // int x = x;
  863. //
  864. // This is used to indicate to GCC that 'x' is intentionally left
  865. // uninitialized. Proven code paths which access 'x' in
  866. // an uninitialized state after this will still warn.
  867. if (const Expr *Initializer = VD->getInit()) {
  868. if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
  869. return false;
  870. ContainsReference CR(S.Context, DRE);
  871. CR.Visit(Initializer);
  872. if (CR.doesContainReference()) {
  873. S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init)
  874. << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
  875. return true;
  876. }
  877. }
  878. DiagUninitUse(S, VD, Use, false);
  879. } else {
  880. const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
  881. if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
  882. S.Diag(BE->getBeginLoc(),
  883. diag::warn_uninit_byref_blockvar_captured_by_block)
  884. << VD->getDeclName()
  885. << VD->getType().getQualifiers().hasObjCLifetime();
  886. else
  887. DiagUninitUse(S, VD, Use, true);
  888. }
  889. // Report where the variable was declared when the use wasn't within
  890. // the initializer of that declaration & we didn't already suggest
  891. // an initialization fixit.
  892. if (!SuggestInitializationFixit(S, VD))
  893. S.Diag(VD->getBeginLoc(), diag::note_var_declared_here)
  894. << VD->getDeclName();
  895. return true;
  896. }
  897. namespace {
  898. class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
  899. public:
  900. FallthroughMapper(Sema &S)
  901. : FoundSwitchStatements(false),
  902. S(S) {
  903. }
  904. bool foundSwitchStatements() const { return FoundSwitchStatements; }
  905. void markFallthroughVisited(const AttributedStmt *Stmt) {
  906. bool Found = FallthroughStmts.erase(Stmt);
  907. assert(Found);
  908. (void)Found;
  909. }
  910. typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
  911. const AttrStmts &getFallthroughStmts() const {
  912. return FallthroughStmts;
  913. }
  914. void fillReachableBlocks(CFG *Cfg) {
  915. assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
  916. std::deque<const CFGBlock *> BlockQueue;
  917. ReachableBlocks.insert(&Cfg->getEntry());
  918. BlockQueue.push_back(&Cfg->getEntry());
  919. // Mark all case blocks reachable to avoid problems with switching on
  920. // constants, covered enums, etc.
  921. // These blocks can contain fall-through annotations, and we don't want to
  922. // issue a warn_fallthrough_attr_unreachable for them.
  923. for (const auto *B : *Cfg) {
  924. const Stmt *L = B->getLabel();
  925. if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
  926. BlockQueue.push_back(B);
  927. }
  928. while (!BlockQueue.empty()) {
  929. const CFGBlock *P = BlockQueue.front();
  930. BlockQueue.pop_front();
  931. for (CFGBlock::const_succ_iterator I = P->succ_begin(),
  932. E = P->succ_end();
  933. I != E; ++I) {
  934. if (*I && ReachableBlocks.insert(*I).second)
  935. BlockQueue.push_back(*I);
  936. }
  937. }
  938. }
  939. bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
  940. bool IsTemplateInstantiation) {
  941. assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
  942. int UnannotatedCnt = 0;
  943. AnnotatedCnt = 0;
  944. std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
  945. while (!BlockQueue.empty()) {
  946. const CFGBlock *P = BlockQueue.front();
  947. BlockQueue.pop_front();
  948. if (!P) continue;
  949. const Stmt *Term = P->getTerminatorStmt();
  950. if (Term && isa<SwitchStmt>(Term))
  951. continue; // Switch statement, good.
  952. const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
  953. if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
  954. continue; // Previous case label has no statements, good.
  955. const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
  956. if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
  957. continue; // Case label is preceded with a normal label, good.
  958. if (!ReachableBlocks.count(P)) {
  959. for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
  960. ElemEnd = P->rend();
  961. ElemIt != ElemEnd; ++ElemIt) {
  962. if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
  963. if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
  964. // Don't issue a warning for an unreachable fallthrough
  965. // attribute in template instantiations as it may not be
  966. // unreachable in all instantiations of the template.
  967. if (!IsTemplateInstantiation)
  968. S.Diag(AS->getBeginLoc(),
  969. diag::warn_fallthrough_attr_unreachable);
  970. markFallthroughVisited(AS);
  971. ++AnnotatedCnt;
  972. break;
  973. }
  974. // Don't care about other unreachable statements.
  975. }
  976. }
  977. // If there are no unreachable statements, this may be a special
  978. // case in CFG:
  979. // case X: {
  980. // A a; // A has a destructor.
  981. // break;
  982. // }
  983. // // <<<< This place is represented by a 'hanging' CFG block.
  984. // case Y:
  985. continue;
  986. }
  987. const Stmt *LastStmt = getLastStmt(*P);
  988. if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
  989. markFallthroughVisited(AS);
  990. ++AnnotatedCnt;
  991. continue; // Fallthrough annotation, good.
  992. }
  993. if (!LastStmt) { // This block contains no executable statements.
  994. // Traverse its predecessors.
  995. std::copy(P->pred_begin(), P->pred_end(),
  996. std::back_inserter(BlockQueue));
  997. continue;
  998. }
  999. ++UnannotatedCnt;
  1000. }
  1001. return !!UnannotatedCnt;
  1002. }
  1003. // RecursiveASTVisitor setup.
  1004. bool shouldWalkTypesOfTypeLocs() const { return false; }
  1005. bool VisitAttributedStmt(AttributedStmt *S) {
  1006. if (asFallThroughAttr(S))
  1007. FallthroughStmts.insert(S);
  1008. return true;
  1009. }
  1010. bool VisitSwitchStmt(SwitchStmt *S) {
  1011. FoundSwitchStatements = true;
  1012. return true;
  1013. }
  1014. // We don't want to traverse local type declarations. We analyze their
  1015. // methods separately.
  1016. bool TraverseDecl(Decl *D) { return true; }
  1017. // We analyze lambda bodies separately. Skip them here.
  1018. bool TraverseLambdaExpr(LambdaExpr *LE) {
  1019. // Traverse the captures, but not the body.
  1020. for (const auto &C : zip(LE->captures(), LE->capture_inits()))
  1021. TraverseLambdaCapture(LE, &std::get<0>(C), std::get<1>(C));
  1022. return true;
  1023. }
  1024. private:
  1025. static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
  1026. if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
  1027. if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
  1028. return AS;
  1029. }
  1030. return nullptr;
  1031. }
  1032. static const Stmt *getLastStmt(const CFGBlock &B) {
  1033. if (const Stmt *Term = B.getTerminatorStmt())
  1034. return Term;
  1035. for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
  1036. ElemEnd = B.rend();
  1037. ElemIt != ElemEnd; ++ElemIt) {
  1038. if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
  1039. return CS->getStmt();
  1040. }
  1041. // Workaround to detect a statement thrown out by CFGBuilder:
  1042. // case X: {} case Y:
  1043. // case X: ; case Y:
  1044. if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
  1045. if (!isa<SwitchCase>(SW->getSubStmt()))
  1046. return SW->getSubStmt();
  1047. return nullptr;
  1048. }
  1049. bool FoundSwitchStatements;
  1050. AttrStmts FallthroughStmts;
  1051. Sema &S;
  1052. llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
  1053. };
  1054. } // anonymous namespace
  1055. static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
  1056. SourceLocation Loc) {
  1057. TokenValue FallthroughTokens[] = {
  1058. tok::l_square, tok::l_square,
  1059. PP.getIdentifierInfo("fallthrough"),
  1060. tok::r_square, tok::r_square
  1061. };
  1062. TokenValue ClangFallthroughTokens[] = {
  1063. tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
  1064. tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
  1065. tok::r_square, tok::r_square
  1066. };
  1067. bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
  1068. StringRef MacroName;
  1069. if (PreferClangAttr)
  1070. MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
  1071. if (MacroName.empty())
  1072. MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
  1073. if (MacroName.empty() && !PreferClangAttr)
  1074. MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
  1075. if (MacroName.empty())
  1076. MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
  1077. return MacroName;
  1078. }
  1079. static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
  1080. bool PerFunction) {
  1081. // Only perform this analysis when using [[]] attributes. There is no good
  1082. // workflow for this warning when not using C++11. There is no good way to
  1083. // silence the warning (no attribute is available) unless we are using
  1084. // [[]] attributes. One could use pragmas to silence the warning, but as a
  1085. // general solution that is gross and not in the spirit of this warning.
  1086. //
  1087. // NOTE: This an intermediate solution. There are on-going discussions on
  1088. // how to properly support this warning outside of C++11 with an annotation.
  1089. if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
  1090. return;
  1091. FallthroughMapper FM(S);
  1092. FM.TraverseStmt(AC.getBody());
  1093. if (!FM.foundSwitchStatements())
  1094. return;
  1095. if (PerFunction && FM.getFallthroughStmts().empty())
  1096. return;
  1097. CFG *Cfg = AC.getCFG();
  1098. if (!Cfg)
  1099. return;
  1100. FM.fillReachableBlocks(Cfg);
  1101. for (const CFGBlock *B : llvm::reverse(*Cfg)) {
  1102. const Stmt *Label = B->getLabel();
  1103. if (!Label || !isa<SwitchCase>(Label))
  1104. continue;
  1105. int AnnotatedCnt;
  1106. bool IsTemplateInstantiation = false;
  1107. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
  1108. IsTemplateInstantiation = Function->isTemplateInstantiation();
  1109. if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
  1110. IsTemplateInstantiation))
  1111. continue;
  1112. S.Diag(Label->getBeginLoc(),
  1113. PerFunction ? diag::warn_unannotated_fallthrough_per_function
  1114. : diag::warn_unannotated_fallthrough);
  1115. if (!AnnotatedCnt) {
  1116. SourceLocation L = Label->getBeginLoc();
  1117. if (L.isMacroID())
  1118. continue;
  1119. if (S.getLangOpts().CPlusPlus11) {
  1120. const Stmt *Term = B->getTerminatorStmt();
  1121. // Skip empty cases.
  1122. while (B->empty() && !Term && B->succ_size() == 1) {
  1123. B = *B->succ_begin();
  1124. Term = B->getTerminatorStmt();
  1125. }
  1126. if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
  1127. Preprocessor &PP = S.getPreprocessor();
  1128. StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
  1129. SmallString<64> TextToInsert(AnnotationSpelling);
  1130. TextToInsert += "; ";
  1131. S.Diag(L, diag::note_insert_fallthrough_fixit) <<
  1132. AnnotationSpelling <<
  1133. FixItHint::CreateInsertion(L, TextToInsert);
  1134. }
  1135. }
  1136. S.Diag(L, diag::note_insert_break_fixit) <<
  1137. FixItHint::CreateInsertion(L, "break; ");
  1138. }
  1139. }
  1140. for (const auto *F : FM.getFallthroughStmts())
  1141. S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement);
  1142. }
  1143. static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
  1144. const Stmt *S) {
  1145. assert(S);
  1146. do {
  1147. switch (S->getStmtClass()) {
  1148. case Stmt::ForStmtClass:
  1149. case Stmt::WhileStmtClass:
  1150. case Stmt::CXXForRangeStmtClass:
  1151. case Stmt::ObjCForCollectionStmtClass:
  1152. return true;
  1153. case Stmt::DoStmtClass: {
  1154. Expr::EvalResult Result;
  1155. if (!cast<DoStmt>(S)->getCond()->EvaluateAsInt(Result, Ctx))
  1156. return true;
  1157. return Result.Val.getInt().getBoolValue();
  1158. }
  1159. default:
  1160. break;
  1161. }
  1162. } while ((S = PM.getParent(S)));
  1163. return false;
  1164. }
  1165. static void diagnoseRepeatedUseOfWeak(Sema &S,
  1166. const sema::FunctionScopeInfo *CurFn,
  1167. const Decl *D,
  1168. const ParentMap &PM) {
  1169. typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
  1170. typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
  1171. typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
  1172. typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
  1173. StmtUsesPair;
  1174. ASTContext &Ctx = S.getASTContext();
  1175. const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
  1176. // Extract all weak objects that are referenced more than once.
  1177. SmallVector<StmtUsesPair, 8> UsesByStmt;
  1178. for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
  1179. I != E; ++I) {
  1180. const WeakUseVector &Uses = I->second;
  1181. // Find the first read of the weak object.
  1182. WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
  1183. for ( ; UI != UE; ++UI) {
  1184. if (UI->isUnsafe())
  1185. break;
  1186. }
  1187. // If there were only writes to this object, don't warn.
  1188. if (UI == UE)
  1189. continue;
  1190. // If there was only one read, followed by any number of writes, and the
  1191. // read is not within a loop, don't warn. Additionally, don't warn in a
  1192. // loop if the base object is a local variable -- local variables are often
  1193. // changed in loops.
  1194. if (UI == Uses.begin()) {
  1195. WeakUseVector::const_iterator UI2 = UI;
  1196. for (++UI2; UI2 != UE; ++UI2)
  1197. if (UI2->isUnsafe())
  1198. break;
  1199. if (UI2 == UE) {
  1200. if (!isInLoop(Ctx, PM, UI->getUseExpr()))
  1201. continue;
  1202. const WeakObjectProfileTy &Profile = I->first;
  1203. if (!Profile.isExactProfile())
  1204. continue;
  1205. const NamedDecl *Base = Profile.getBase();
  1206. if (!Base)
  1207. Base = Profile.getProperty();
  1208. assert(Base && "A profile always has a base or property.");
  1209. if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
  1210. if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
  1211. continue;
  1212. }
  1213. }
  1214. UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
  1215. }
  1216. if (UsesByStmt.empty())
  1217. return;
  1218. // Sort by first use so that we emit the warnings in a deterministic order.
  1219. SourceManager &SM = S.getSourceManager();
  1220. llvm::sort(UsesByStmt,
  1221. [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
  1222. return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(),
  1223. RHS.first->getBeginLoc());
  1224. });
  1225. // Classify the current code body for better warning text.
  1226. // This enum should stay in sync with the cases in
  1227. // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
  1228. // FIXME: Should we use a common classification enum and the same set of
  1229. // possibilities all throughout Sema?
  1230. enum {
  1231. Function,
  1232. Method,
  1233. Block,
  1234. Lambda
  1235. } FunctionKind;
  1236. if (isa<sema::BlockScopeInfo>(CurFn))
  1237. FunctionKind = Block;
  1238. else if (isa<sema::LambdaScopeInfo>(CurFn))
  1239. FunctionKind = Lambda;
  1240. else if (isa<ObjCMethodDecl>(D))
  1241. FunctionKind = Method;
  1242. else
  1243. FunctionKind = Function;
  1244. // Iterate through the sorted problems and emit warnings for each.
  1245. for (const auto &P : UsesByStmt) {
  1246. const Stmt *FirstRead = P.first;
  1247. const WeakObjectProfileTy &Key = P.second->first;
  1248. const WeakUseVector &Uses = P.second->second;
  1249. // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
  1250. // may not contain enough information to determine that these are different
  1251. // properties. We can only be 100% sure of a repeated use in certain cases,
  1252. // and we adjust the diagnostic kind accordingly so that the less certain
  1253. // case can be turned off if it is too noisy.
  1254. unsigned DiagKind;
  1255. if (Key.isExactProfile())
  1256. DiagKind = diag::warn_arc_repeated_use_of_weak;
  1257. else
  1258. DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
  1259. // Classify the weak object being accessed for better warning text.
  1260. // This enum should stay in sync with the cases in
  1261. // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
  1262. enum {
  1263. Variable,
  1264. Property,
  1265. ImplicitProperty,
  1266. Ivar
  1267. } ObjectKind;
  1268. const NamedDecl *KeyProp = Key.getProperty();
  1269. if (isa<VarDecl>(KeyProp))
  1270. ObjectKind = Variable;
  1271. else if (isa<ObjCPropertyDecl>(KeyProp))
  1272. ObjectKind = Property;
  1273. else if (isa<ObjCMethodDecl>(KeyProp))
  1274. ObjectKind = ImplicitProperty;
  1275. else if (isa<ObjCIvarDecl>(KeyProp))
  1276. ObjectKind = Ivar;
  1277. else
  1278. llvm_unreachable("Unexpected weak object kind!");
  1279. // Do not warn about IBOutlet weak property receivers being set to null
  1280. // since they are typically only used from the main thread.
  1281. if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
  1282. if (Prop->hasAttr<IBOutletAttr>())
  1283. continue;
  1284. // Show the first time the object was read.
  1285. S.Diag(FirstRead->getBeginLoc(), DiagKind)
  1286. << int(ObjectKind) << KeyProp << int(FunctionKind)
  1287. << FirstRead->getSourceRange();
  1288. // Print all the other accesses as notes.
  1289. for (const auto &Use : Uses) {
  1290. if (Use.getUseExpr() == FirstRead)
  1291. continue;
  1292. S.Diag(Use.getUseExpr()->getBeginLoc(),
  1293. diag::note_arc_weak_also_accessed_here)
  1294. << Use.getUseExpr()->getSourceRange();
  1295. }
  1296. }
  1297. }
  1298. namespace {
  1299. class UninitValsDiagReporter : public UninitVariablesHandler {
  1300. Sema &S;
  1301. typedef SmallVector<UninitUse, 2> UsesVec;
  1302. typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
  1303. // Prefer using MapVector to DenseMap, so that iteration order will be
  1304. // the same as insertion order. This is needed to obtain a deterministic
  1305. // order of diagnostics when calling flushDiagnostics().
  1306. typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
  1307. UsesMap uses;
  1308. public:
  1309. UninitValsDiagReporter(Sema &S) : S(S) {}
  1310. ~UninitValsDiagReporter() override { flushDiagnostics(); }
  1311. MappedType &getUses(const VarDecl *vd) {
  1312. MappedType &V = uses[vd];
  1313. if (!V.getPointer())
  1314. V.setPointer(new UsesVec());
  1315. return V;
  1316. }
  1317. void handleUseOfUninitVariable(const VarDecl *vd,
  1318. const UninitUse &use) override {
  1319. getUses(vd).getPointer()->push_back(use);
  1320. }
  1321. void handleSelfInit(const VarDecl *vd) override {
  1322. getUses(vd).setInt(true);
  1323. }
  1324. void flushDiagnostics() {
  1325. for (const auto &P : uses) {
  1326. const VarDecl *vd = P.first;
  1327. const MappedType &V = P.second;
  1328. UsesVec *vec = V.getPointer();
  1329. bool hasSelfInit = V.getInt();
  1330. // Specially handle the case where we have uses of an uninitialized
  1331. // variable, but the root cause is an idiomatic self-init. We want
  1332. // to report the diagnostic at the self-init since that is the root cause.
  1333. if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
  1334. DiagnoseUninitializedUse(S, vd,
  1335. UninitUse(vd->getInit()->IgnoreParenCasts(),
  1336. /* isAlwaysUninit */ true),
  1337. /* alwaysReportSelfInit */ true);
  1338. else {
  1339. // Sort the uses by their SourceLocations. While not strictly
  1340. // guaranteed to produce them in line/column order, this will provide
  1341. // a stable ordering.
  1342. llvm::sort(vec->begin(), vec->end(),
  1343. [](const UninitUse &a, const UninitUse &b) {
  1344. // Prefer a more confident report over a less confident one.
  1345. if (a.getKind() != b.getKind())
  1346. return a.getKind() > b.getKind();
  1347. return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc();
  1348. });
  1349. for (const auto &U : *vec) {
  1350. // If we have self-init, downgrade all uses to 'may be uninitialized'.
  1351. UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
  1352. if (DiagnoseUninitializedUse(S, vd, Use))
  1353. // Skip further diagnostics for this variable. We try to warn only
  1354. // on the first point at which a variable is used uninitialized.
  1355. break;
  1356. }
  1357. }
  1358. // Release the uses vector.
  1359. delete vec;
  1360. }
  1361. uses.clear();
  1362. }
  1363. private:
  1364. static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
  1365. return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
  1366. return U.getKind() == UninitUse::Always ||
  1367. U.getKind() == UninitUse::AfterCall ||
  1368. U.getKind() == UninitUse::AfterDecl;
  1369. });
  1370. }
  1371. };
  1372. } // anonymous namespace
  1373. namespace clang {
  1374. namespace {
  1375. typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
  1376. typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
  1377. typedef std::list<DelayedDiag> DiagList;
  1378. struct SortDiagBySourceLocation {
  1379. SourceManager &SM;
  1380. SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
  1381. bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
  1382. // Although this call will be slow, this is only called when outputting
  1383. // multiple warnings.
  1384. return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
  1385. }
  1386. };
  1387. } // anonymous namespace
  1388. } // namespace clang
  1389. //===----------------------------------------------------------------------===//
  1390. // -Wthread-safety
  1391. //===----------------------------------------------------------------------===//
  1392. namespace clang {
  1393. namespace threadSafety {
  1394. namespace {
  1395. class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
  1396. Sema &S;
  1397. DiagList Warnings;
  1398. SourceLocation FunLocation, FunEndLocation;
  1399. const FunctionDecl *CurrentFunction;
  1400. bool Verbose;
  1401. OptionalNotes getNotes() const {
  1402. if (Verbose && CurrentFunction) {
  1403. PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
  1404. S.PDiag(diag::note_thread_warning_in_fun)
  1405. << CurrentFunction);
  1406. return OptionalNotes(1, FNote);
  1407. }
  1408. return OptionalNotes();
  1409. }
  1410. OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
  1411. OptionalNotes ONS(1, Note);
  1412. if (Verbose && CurrentFunction) {
  1413. PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
  1414. S.PDiag(diag::note_thread_warning_in_fun)
  1415. << CurrentFunction);
  1416. ONS.push_back(std::move(FNote));
  1417. }
  1418. return ONS;
  1419. }
  1420. OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
  1421. const PartialDiagnosticAt &Note2) const {
  1422. OptionalNotes ONS;
  1423. ONS.push_back(Note1);
  1424. ONS.push_back(Note2);
  1425. if (Verbose && CurrentFunction) {
  1426. PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
  1427. S.PDiag(diag::note_thread_warning_in_fun)
  1428. << CurrentFunction);
  1429. ONS.push_back(std::move(FNote));
  1430. }
  1431. return ONS;
  1432. }
  1433. OptionalNotes makeLockedHereNote(SourceLocation LocLocked, StringRef Kind) {
  1434. return LocLocked.isValid()
  1435. ? getNotes(PartialDiagnosticAt(
  1436. LocLocked, S.PDiag(diag::note_locked_here) << Kind))
  1437. : getNotes();
  1438. }
  1439. public:
  1440. ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
  1441. : S(S), FunLocation(FL), FunEndLocation(FEL),
  1442. CurrentFunction(nullptr), Verbose(false) {}
  1443. void setVerbose(bool b) { Verbose = b; }
  1444. /// Emit all buffered diagnostics in order of sourcelocation.
  1445. /// We need to output diagnostics produced while iterating through
  1446. /// the lockset in deterministic order, so this function orders diagnostics
  1447. /// and outputs them.
  1448. void emitDiagnostics() {
  1449. Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
  1450. for (const auto &Diag : Warnings) {
  1451. S.Diag(Diag.first.first, Diag.first.second);
  1452. for (const auto &Note : Diag.second)
  1453. S.Diag(Note.first, Note.second);
  1454. }
  1455. }
  1456. void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
  1457. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
  1458. << Loc);
  1459. Warnings.emplace_back(std::move(Warning), getNotes());
  1460. }
  1461. void handleUnmatchedUnlock(StringRef Kind, Name LockName,
  1462. SourceLocation Loc) override {
  1463. if (Loc.isInvalid())
  1464. Loc = FunLocation;
  1465. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_but_no_lock)
  1466. << Kind << LockName);
  1467. Warnings.emplace_back(std::move(Warning), getNotes());
  1468. }
  1469. void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
  1470. LockKind Expected, LockKind Received,
  1471. SourceLocation LocLocked,
  1472. SourceLocation LocUnlock) override {
  1473. if (LocUnlock.isInvalid())
  1474. LocUnlock = FunLocation;
  1475. PartialDiagnosticAt Warning(
  1476. LocUnlock, S.PDiag(diag::warn_unlock_kind_mismatch)
  1477. << Kind << LockName << Received << Expected);
  1478. Warnings.emplace_back(std::move(Warning),
  1479. makeLockedHereNote(LocLocked, Kind));
  1480. }
  1481. void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation LocLocked,
  1482. SourceLocation LocDoubleLock) override {
  1483. if (LocDoubleLock.isInvalid())
  1484. LocDoubleLock = FunLocation;
  1485. PartialDiagnosticAt Warning(LocDoubleLock, S.PDiag(diag::warn_double_lock)
  1486. << Kind << LockName);
  1487. Warnings.emplace_back(std::move(Warning),
  1488. makeLockedHereNote(LocLocked, Kind));
  1489. }
  1490. void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
  1491. SourceLocation LocLocked,
  1492. SourceLocation LocEndOfScope,
  1493. LockErrorKind LEK) override {
  1494. unsigned DiagID = 0;
  1495. switch (LEK) {
  1496. case LEK_LockedSomePredecessors:
  1497. DiagID = diag::warn_lock_some_predecessors;
  1498. break;
  1499. case LEK_LockedSomeLoopIterations:
  1500. DiagID = diag::warn_expecting_lock_held_on_loop;
  1501. break;
  1502. case LEK_LockedAtEndOfFunction:
  1503. DiagID = diag::warn_no_unlock;
  1504. break;
  1505. case LEK_NotLockedAtEndOfFunction:
  1506. DiagID = diag::warn_expecting_locked;
  1507. break;
  1508. }
  1509. if (LocEndOfScope.isInvalid())
  1510. LocEndOfScope = FunEndLocation;
  1511. PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
  1512. << LockName);
  1513. Warnings.emplace_back(std::move(Warning),
  1514. makeLockedHereNote(LocLocked, Kind));
  1515. }
  1516. void handleExclusiveAndShared(StringRef Kind, Name LockName,
  1517. SourceLocation Loc1,
  1518. SourceLocation Loc2) override {
  1519. PartialDiagnosticAt Warning(Loc1,
  1520. S.PDiag(diag::warn_lock_exclusive_and_shared)
  1521. << Kind << LockName);
  1522. PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
  1523. << Kind << LockName);
  1524. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1525. }
  1526. void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
  1527. ProtectedOperationKind POK, AccessKind AK,
  1528. SourceLocation Loc) override {
  1529. assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
  1530. "Only works for variables");
  1531. unsigned DiagID = POK == POK_VarAccess?
  1532. diag::warn_variable_requires_any_lock:
  1533. diag::warn_var_deref_requires_any_lock;
  1534. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
  1535. << D << getLockKindFromAccessKind(AK));
  1536. Warnings.emplace_back(std::move(Warning), getNotes());
  1537. }
  1538. void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
  1539. ProtectedOperationKind POK, Name LockName,
  1540. LockKind LK, SourceLocation Loc,
  1541. Name *PossibleMatch) override {
  1542. unsigned DiagID = 0;
  1543. if (PossibleMatch) {
  1544. switch (POK) {
  1545. case POK_VarAccess:
  1546. DiagID = diag::warn_variable_requires_lock_precise;
  1547. break;
  1548. case POK_VarDereference:
  1549. DiagID = diag::warn_var_deref_requires_lock_precise;
  1550. break;
  1551. case POK_FunctionCall:
  1552. DiagID = diag::warn_fun_requires_lock_precise;
  1553. break;
  1554. case POK_PassByRef:
  1555. DiagID = diag::warn_guarded_pass_by_reference;
  1556. break;
  1557. case POK_PtPassByRef:
  1558. DiagID = diag::warn_pt_guarded_pass_by_reference;
  1559. break;
  1560. }
  1561. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
  1562. << D
  1563. << LockName << LK);
  1564. PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
  1565. << *PossibleMatch);
  1566. if (Verbose && POK == POK_VarAccess) {
  1567. PartialDiagnosticAt VNote(D->getLocation(),
  1568. S.PDiag(diag::note_guarded_by_declared_here)
  1569. << D->getNameAsString());
  1570. Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
  1571. } else
  1572. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1573. } else {
  1574. switch (POK) {
  1575. case POK_VarAccess:
  1576. DiagID = diag::warn_variable_requires_lock;
  1577. break;
  1578. case POK_VarDereference:
  1579. DiagID = diag::warn_var_deref_requires_lock;
  1580. break;
  1581. case POK_FunctionCall:
  1582. DiagID = diag::warn_fun_requires_lock;
  1583. break;
  1584. case POK_PassByRef:
  1585. DiagID = diag::warn_guarded_pass_by_reference;
  1586. break;
  1587. case POK_PtPassByRef:
  1588. DiagID = diag::warn_pt_guarded_pass_by_reference;
  1589. break;
  1590. }
  1591. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
  1592. << D
  1593. << LockName << LK);
  1594. if (Verbose && POK == POK_VarAccess) {
  1595. PartialDiagnosticAt Note(D->getLocation(),
  1596. S.PDiag(diag::note_guarded_by_declared_here));
  1597. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1598. } else
  1599. Warnings.emplace_back(std::move(Warning), getNotes());
  1600. }
  1601. }
  1602. void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
  1603. SourceLocation Loc) override {
  1604. PartialDiagnosticAt Warning(Loc,
  1605. S.PDiag(diag::warn_acquire_requires_negative_cap)
  1606. << Kind << LockName << Neg);
  1607. Warnings.emplace_back(std::move(Warning), getNotes());
  1608. }
  1609. void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
  1610. SourceLocation Loc) override {
  1611. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
  1612. << Kind << FunName << LockName);
  1613. Warnings.emplace_back(std::move(Warning), getNotes());
  1614. }
  1615. void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
  1616. SourceLocation Loc) override {
  1617. PartialDiagnosticAt Warning(Loc,
  1618. S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
  1619. Warnings.emplace_back(std::move(Warning), getNotes());
  1620. }
  1621. void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
  1622. PartialDiagnosticAt Warning(Loc,
  1623. S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
  1624. Warnings.emplace_back(std::move(Warning), getNotes());
  1625. }
  1626. void enterFunction(const FunctionDecl* FD) override {
  1627. CurrentFunction = FD;
  1628. }
  1629. void leaveFunction(const FunctionDecl* FD) override {
  1630. CurrentFunction = nullptr;
  1631. }
  1632. };
  1633. } // anonymous namespace
  1634. } // namespace threadSafety
  1635. } // namespace clang
  1636. //===----------------------------------------------------------------------===//
  1637. // -Wconsumed
  1638. //===----------------------------------------------------------------------===//
  1639. namespace clang {
  1640. namespace consumed {
  1641. namespace {
  1642. class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
  1643. Sema &S;
  1644. DiagList Warnings;
  1645. public:
  1646. ConsumedWarningsHandler(Sema &S) : S(S) {}
  1647. void emitDiagnostics() override {
  1648. Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
  1649. for (const auto &Diag : Warnings) {
  1650. S.Diag(Diag.first.first, Diag.first.second);
  1651. for (const auto &Note : Diag.second)
  1652. S.Diag(Note.first, Note.second);
  1653. }
  1654. }
  1655. void warnLoopStateMismatch(SourceLocation Loc,
  1656. StringRef VariableName) override {
  1657. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
  1658. VariableName);
  1659. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1660. }
  1661. void warnParamReturnTypestateMismatch(SourceLocation Loc,
  1662. StringRef VariableName,
  1663. StringRef ExpectedState,
  1664. StringRef ObservedState) override {
  1665. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1666. diag::warn_param_return_typestate_mismatch) << VariableName <<
  1667. ExpectedState << ObservedState);
  1668. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1669. }
  1670. void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
  1671. StringRef ObservedState) override {
  1672. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1673. diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
  1674. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1675. }
  1676. void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
  1677. StringRef TypeName) override {
  1678. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1679. diag::warn_return_typestate_for_unconsumable_type) << TypeName);
  1680. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1681. }
  1682. void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
  1683. StringRef ObservedState) override {
  1684. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1685. diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
  1686. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1687. }
  1688. void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
  1689. SourceLocation Loc) override {
  1690. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1691. diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
  1692. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1693. }
  1694. void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
  1695. StringRef State, SourceLocation Loc) override {
  1696. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
  1697. MethodName << VariableName << State);
  1698. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1699. }
  1700. };
  1701. } // anonymous namespace
  1702. } // namespace consumed
  1703. } // namespace clang
  1704. //===----------------------------------------------------------------------===//
  1705. // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
  1706. // warnings on a function, method, or block.
  1707. //===----------------------------------------------------------------------===//
  1708. clang::sema::AnalysisBasedWarnings::Policy::Policy() {
  1709. enableCheckFallThrough = 1;
  1710. enableCheckUnreachable = 0;
  1711. enableThreadSafetyAnalysis = 0;
  1712. enableConsumedAnalysis = 0;
  1713. }
  1714. static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
  1715. return (unsigned)!D.isIgnored(diag, SourceLocation());
  1716. }
  1717. clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
  1718. : S(s),
  1719. NumFunctionsAnalyzed(0),
  1720. NumFunctionsWithBadCFGs(0),
  1721. NumCFGBlocks(0),
  1722. MaxCFGBlocksPerFunction(0),
  1723. NumUninitAnalysisFunctions(0),
  1724. NumUninitAnalysisVariables(0),
  1725. MaxUninitAnalysisVariablesPerFunction(0),
  1726. NumUninitAnalysisBlockVisits(0),
  1727. MaxUninitAnalysisBlockVisitsPerFunction(0) {
  1728. using namespace diag;
  1729. DiagnosticsEngine &D = S.getDiagnostics();
  1730. DefaultPolicy.enableCheckUnreachable =
  1731. isEnabled(D, warn_unreachable) ||
  1732. isEnabled(D, warn_unreachable_break) ||
  1733. isEnabled(D, warn_unreachable_return) ||
  1734. isEnabled(D, warn_unreachable_loop_increment);
  1735. DefaultPolicy.enableThreadSafetyAnalysis =
  1736. isEnabled(D, warn_double_lock);
  1737. DefaultPolicy.enableConsumedAnalysis =
  1738. isEnabled(D, warn_use_in_invalid_state);
  1739. }
  1740. static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
  1741. for (const auto &D : fscope->PossiblyUnreachableDiags)
  1742. S.Diag(D.Loc, D.PD);
  1743. }
  1744. void clang::sema::
  1745. AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
  1746. sema::FunctionScopeInfo *fscope,
  1747. const Decl *D, QualType BlockType) {
  1748. // We avoid doing analysis-based warnings when there are errors for
  1749. // two reasons:
  1750. // (1) The CFGs often can't be constructed (if the body is invalid), so
  1751. // don't bother trying.
  1752. // (2) The code already has problems; running the analysis just takes more
  1753. // time.
  1754. DiagnosticsEngine &Diags = S.getDiagnostics();
  1755. // Do not do any analysis if we are going to just ignore them.
  1756. if (Diags.getIgnoreAllWarnings() ||
  1757. (Diags.getSuppressSystemWarnings() &&
  1758. S.SourceMgr.isInSystemHeader(D->getLocation())))
  1759. return;
  1760. // For code in dependent contexts, we'll do this at instantiation time.
  1761. if (cast<DeclContext>(D)->isDependentContext())
  1762. return;
  1763. if (Diags.hasUncompilableErrorOccurred()) {
  1764. // Flush out any possibly unreachable diagnostics.
  1765. flushDiagnostics(S, fscope);
  1766. return;
  1767. }
  1768. const Stmt *Body = D->getBody();
  1769. assert(Body);
  1770. // Construct the analysis context with the specified CFG build options.
  1771. AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
  1772. // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
  1773. // explosion for destructors that can result and the compile time hit.
  1774. AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
  1775. AC.getCFGBuildOptions().AddEHEdges = false;
  1776. AC.getCFGBuildOptions().AddInitializers = true;
  1777. AC.getCFGBuildOptions().AddImplicitDtors = true;
  1778. AC.getCFGBuildOptions().AddTemporaryDtors = true;
  1779. AC.getCFGBuildOptions().AddCXXNewAllocator = false;
  1780. AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
  1781. // Force that certain expressions appear as CFGElements in the CFG. This
  1782. // is used to speed up various analyses.
  1783. // FIXME: This isn't the right factoring. This is here for initial
  1784. // prototyping, but we need a way for analyses to say what expressions they
  1785. // expect to always be CFGElements and then fill in the BuildOptions
  1786. // appropriately. This is essentially a layering violation.
  1787. if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
  1788. P.enableConsumedAnalysis) {
  1789. // Unreachable code analysis and thread safety require a linearized CFG.
  1790. AC.getCFGBuildOptions().setAllAlwaysAdd();
  1791. }
  1792. else {
  1793. AC.getCFGBuildOptions()
  1794. .setAlwaysAdd(Stmt::BinaryOperatorClass)
  1795. .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
  1796. .setAlwaysAdd(Stmt::BlockExprClass)
  1797. .setAlwaysAdd(Stmt::CStyleCastExprClass)
  1798. .setAlwaysAdd(Stmt::DeclRefExprClass)
  1799. .setAlwaysAdd(Stmt::ImplicitCastExprClass)
  1800. .setAlwaysAdd(Stmt::UnaryOperatorClass)
  1801. .setAlwaysAdd(Stmt::AttributedStmtClass);
  1802. }
  1803. // Install the logical handler for -Wtautological-overlap-compare
  1804. llvm::Optional<LogicalErrorHandler> LEH;
  1805. if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
  1806. D->getBeginLoc())) {
  1807. LEH.emplace(S);
  1808. AC.getCFGBuildOptions().Observer = &*LEH;
  1809. }
  1810. // Emit delayed diagnostics.
  1811. if (!fscope->PossiblyUnreachableDiags.empty()) {
  1812. bool analyzed = false;
  1813. // Register the expressions with the CFGBuilder.
  1814. for (const auto &D : fscope->PossiblyUnreachableDiags) {
  1815. for (const Stmt *S : D.Stmts)
  1816. AC.registerForcedBlockExpression(S);
  1817. }
  1818. if (AC.getCFG()) {
  1819. analyzed = true;
  1820. for (const auto &D : fscope->PossiblyUnreachableDiags) {
  1821. bool AllReachable = true;
  1822. for (const Stmt *S : D.Stmts) {
  1823. const CFGBlock *block = AC.getBlockForRegisteredExpression(S);
  1824. CFGReverseBlockReachabilityAnalysis *cra =
  1825. AC.getCFGReachablityAnalysis();
  1826. // FIXME: We should be able to assert that block is non-null, but
  1827. // the CFG analysis can skip potentially-evaluated expressions in
  1828. // edge cases; see test/Sema/vla-2.c.
  1829. if (block && cra) {
  1830. // Can this block be reached from the entrance?
  1831. if (!cra->isReachable(&AC.getCFG()->getEntry(), block)) {
  1832. AllReachable = false;
  1833. break;
  1834. }
  1835. }
  1836. // If we cannot map to a basic block, assume the statement is
  1837. // reachable.
  1838. }
  1839. if (AllReachable)
  1840. S.Diag(D.Loc, D.PD);
  1841. }
  1842. }
  1843. if (!analyzed)
  1844. flushDiagnostics(S, fscope);
  1845. }
  1846. // Warning: check missing 'return'
  1847. if (P.enableCheckFallThrough) {
  1848. const CheckFallThroughDiagnostics &CD =
  1849. (isa<BlockDecl>(D)
  1850. ? CheckFallThroughDiagnostics::MakeForBlock()
  1851. : (isa<CXXMethodDecl>(D) &&
  1852. cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
  1853. cast<CXXMethodDecl>(D)->getParent()->isLambda())
  1854. ? CheckFallThroughDiagnostics::MakeForLambda()
  1855. : (fscope->isCoroutine()
  1856. ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
  1857. : CheckFallThroughDiagnostics::MakeForFunction(D)));
  1858. CheckFallThroughForBody(S, D, Body, BlockType, CD, AC, fscope);
  1859. }
  1860. // Warning: check for unreachable code
  1861. if (P.enableCheckUnreachable) {
  1862. // Only check for unreachable code on non-template instantiations.
  1863. // Different template instantiations can effectively change the control-flow
  1864. // and it is very difficult to prove that a snippet of code in a template
  1865. // is unreachable for all instantiations.
  1866. bool isTemplateInstantiation = false;
  1867. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
  1868. isTemplateInstantiation = Function->isTemplateInstantiation();
  1869. if (!isTemplateInstantiation)
  1870. CheckUnreachable(S, AC);
  1871. }
  1872. // Check for thread safety violations
  1873. if (P.enableThreadSafetyAnalysis) {
  1874. SourceLocation FL = AC.getDecl()->getLocation();
  1875. SourceLocation FEL = AC.getDecl()->getEndLoc();
  1876. threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
  1877. if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc()))
  1878. Reporter.setIssueBetaWarnings(true);
  1879. if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc()))
  1880. Reporter.setVerbose(true);
  1881. threadSafety::runThreadSafetyAnalysis(AC, Reporter,
  1882. &S.ThreadSafetyDeclCache);
  1883. Reporter.emitDiagnostics();
  1884. }
  1885. // Check for violations of consumed properties.
  1886. if (P.enableConsumedAnalysis) {
  1887. consumed::ConsumedWarningsHandler WarningHandler(S);
  1888. consumed::ConsumedAnalyzer Analyzer(WarningHandler);
  1889. Analyzer.run(AC);
  1890. }
  1891. if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) ||
  1892. !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc()) ||
  1893. !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc())) {
  1894. if (CFG *cfg = AC.getCFG()) {
  1895. UninitValsDiagReporter reporter(S);
  1896. UninitVariablesAnalysisStats stats;
  1897. std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
  1898. runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
  1899. reporter, stats);
  1900. if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
  1901. ++NumUninitAnalysisFunctions;
  1902. NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
  1903. NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
  1904. MaxUninitAnalysisVariablesPerFunction =
  1905. std::max(MaxUninitAnalysisVariablesPerFunction,
  1906. stats.NumVariablesAnalyzed);
  1907. MaxUninitAnalysisBlockVisitsPerFunction =
  1908. std::max(MaxUninitAnalysisBlockVisitsPerFunction,
  1909. stats.NumBlockVisits);
  1910. }
  1911. }
  1912. }
  1913. bool FallThroughDiagFull =
  1914. !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc());
  1915. bool FallThroughDiagPerFunction = !Diags.isIgnored(
  1916. diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc());
  1917. if (FallThroughDiagFull || FallThroughDiagPerFunction ||
  1918. fscope->HasFallthroughStmt) {
  1919. DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
  1920. }
  1921. if (S.getLangOpts().ObjCWeak &&
  1922. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc()))
  1923. diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
  1924. // Check for infinite self-recursion in functions
  1925. if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
  1926. D->getBeginLoc())) {
  1927. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1928. checkRecursiveFunction(S, FD, Body, AC);
  1929. }
  1930. }
  1931. // Check for throw out of non-throwing function.
  1932. if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc()))
  1933. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  1934. if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
  1935. checkThrowInNonThrowingFunc(S, FD, AC);
  1936. // If none of the previous checks caused a CFG build, trigger one here
  1937. // for -Wtautological-overlap-compare
  1938. if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
  1939. D->getBeginLoc())) {
  1940. AC.getCFG();
  1941. }
  1942. // Collect statistics about the CFG if it was built.
  1943. if (S.CollectStats && AC.isCFGBuilt()) {
  1944. ++NumFunctionsAnalyzed;
  1945. if (CFG *cfg = AC.getCFG()) {
  1946. // If we successfully built a CFG for this context, record some more
  1947. // detail information about it.
  1948. NumCFGBlocks += cfg->getNumBlockIDs();
  1949. MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
  1950. cfg->getNumBlockIDs());
  1951. } else {
  1952. ++NumFunctionsWithBadCFGs;
  1953. }
  1954. }
  1955. }
  1956. void clang::sema::AnalysisBasedWarnings::PrintStats() const {
  1957. llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
  1958. unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
  1959. unsigned AvgCFGBlocksPerFunction =
  1960. !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
  1961. llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
  1962. << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
  1963. << " " << NumCFGBlocks << " CFG blocks built.\n"
  1964. << " " << AvgCFGBlocksPerFunction
  1965. << " average CFG blocks per function.\n"
  1966. << " " << MaxCFGBlocksPerFunction
  1967. << " max CFG blocks per function.\n";
  1968. unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
  1969. : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
  1970. unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
  1971. : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
  1972. llvm::errs() << NumUninitAnalysisFunctions
  1973. << " functions analyzed for uninitialiazed variables\n"
  1974. << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
  1975. << " " << AvgUninitVariablesPerFunction
  1976. << " average variables per function.\n"
  1977. << " " << MaxUninitAnalysisVariablesPerFunction
  1978. << " max variables per function.\n"
  1979. << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
  1980. << " " << AvgUninitBlockVisitsPerFunction
  1981. << " average block visits per function.\n"
  1982. << " " << MaxUninitAnalysisBlockVisitsPerFunction
  1983. << " max block visits per function.\n";
  1984. }